index
int64
0
100k
blob_id
stringlengths
40
40
code
stringlengths
7
7.27M
steps
listlengths
1
1.25k
error
bool
2 classes
98,700
013c59462ddc35d0ce6f5ffbece93de00c3369d4
import math from functional.pipeline import Sequence def dot_product(xs: Sequence, ys: Sequence) -> float: return xs \ .zip(ys) \ .map(lambda t: t[0] * t[1]) \ .sum() def euclidean_distance(xs: Sequence, ys: Sequence) -> float: s = xs \ .zip(ys) \ .map(lambda t: (t[0] - t[1]) * (t[0] - t[1])) \ .sum() return math.sqrt(s) def root_mean_square_error_d(y_hat: Sequence, y: Sequence) -> float: d = euclidean_distance(y_hat, y) return d * d def root_mean_square_error(y_hats_with_ys: Sequence) -> float: (n, s) = y_hats_with_ys \ .map(lambda t: root_mean_square_error_d(t[0], t[1])) \ .fold_left((0, 0.0), lambda acc, x: (acc[0] + 1, acc[1] + x)) return math.sqrt(s / n)
[ "import math\n\nfrom functional.pipeline import Sequence\n\n\ndef dot_product(xs: Sequence, ys: Sequence) -> float:\n return xs \\\n .zip(ys) \\\n .map(lambda t: t[0] * t[1]) \\\n .sum()\n\n\ndef euclidean_distance(xs: Sequence, ys: Sequence) -> float:\n s = xs \\\n .zip(ys) \\\n .map(lambda t: (t[0] - t[1]) * (t[0] - t[1])) \\\n .sum()\n return math.sqrt(s)\n\n\ndef root_mean_square_error_d(y_hat: Sequence, y: Sequence) -> float:\n d = euclidean_distance(y_hat, y)\n return d * d\n\n\ndef root_mean_square_error(y_hats_with_ys: Sequence) -> float:\n (n, s) = y_hats_with_ys \\\n .map(lambda t: root_mean_square_error_d(t[0], t[1])) \\\n .fold_left((0, 0.0), lambda acc, x: (acc[0] + 1, acc[1] + x))\n return math.sqrt(s / n)\n", "import math\nfrom functional.pipeline import Sequence\n\n\ndef dot_product(xs: Sequence, ys: Sequence) ->float:\n return xs.zip(ys).map(lambda t: t[0] * t[1]).sum()\n\n\ndef euclidean_distance(xs: Sequence, ys: Sequence) ->float:\n s = xs.zip(ys).map(lambda t: (t[0] - t[1]) * (t[0] - t[1])).sum()\n return math.sqrt(s)\n\n\ndef root_mean_square_error_d(y_hat: Sequence, y: Sequence) ->float:\n d = euclidean_distance(y_hat, y)\n return d * d\n\n\ndef root_mean_square_error(y_hats_with_ys: Sequence) ->float:\n n, s = y_hats_with_ys.map(lambda t: root_mean_square_error_d(t[0], t[1])\n ).fold_left((0, 0.0), lambda acc, x: (acc[0] + 1, acc[1] + x))\n return math.sqrt(s / n)\n", "<import token>\n\n\ndef dot_product(xs: Sequence, ys: Sequence) ->float:\n return xs.zip(ys).map(lambda t: t[0] * t[1]).sum()\n\n\ndef euclidean_distance(xs: Sequence, ys: Sequence) ->float:\n s = xs.zip(ys).map(lambda t: (t[0] - t[1]) * (t[0] - t[1])).sum()\n return math.sqrt(s)\n\n\ndef root_mean_square_error_d(y_hat: Sequence, y: Sequence) ->float:\n d = euclidean_distance(y_hat, y)\n return d * d\n\n\ndef root_mean_square_error(y_hats_with_ys: Sequence) ->float:\n n, s = y_hats_with_ys.map(lambda t: root_mean_square_error_d(t[0], t[1])\n ).fold_left((0, 0.0), lambda acc, x: (acc[0] + 1, acc[1] + x))\n return math.sqrt(s / n)\n", "<import token>\n\n\ndef dot_product(xs: Sequence, ys: Sequence) ->float:\n return xs.zip(ys).map(lambda t: t[0] * t[1]).sum()\n\n\ndef euclidean_distance(xs: Sequence, ys: Sequence) ->float:\n s = xs.zip(ys).map(lambda t: (t[0] - t[1]) * (t[0] - t[1])).sum()\n return math.sqrt(s)\n\n\ndef root_mean_square_error_d(y_hat: Sequence, y: Sequence) ->float:\n d = euclidean_distance(y_hat, y)\n return d * d\n\n\n<function token>\n", "<import token>\n<function token>\n\n\ndef euclidean_distance(xs: Sequence, ys: Sequence) ->float:\n s = xs.zip(ys).map(lambda t: (t[0] - t[1]) * (t[0] - t[1])).sum()\n return math.sqrt(s)\n\n\ndef root_mean_square_error_d(y_hat: Sequence, y: Sequence) ->float:\n d = euclidean_distance(y_hat, y)\n return d * d\n\n\n<function token>\n", "<import token>\n<function token>\n\n\ndef euclidean_distance(xs: Sequence, ys: Sequence) ->float:\n s = xs.zip(ys).map(lambda t: (t[0] - t[1]) * (t[0] - t[1])).sum()\n return math.sqrt(s)\n\n\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n" ]
false
98,701
80ed00de885686f1a017dd3a23d7a1903ec07139
"""TVM operator upsampling compute.""" from __future__ import absolute_import import tvm from .. import util def upsampling(data, scale, layout="NCHW"): """Perform nearest neighbor upsampling on the data. Bilinear upsampling is not supported. Parameters ---------- data : tvm.Tensor 4-D with shape [batch, channel, in_height, in_width] or [batch, in_height, in_width, channel] scale: int upsampling scaling factor layout: string either "NCHW" or "NHWC" Returns ------- output : tvm.Tensor 4-D with shape [batch, channel, in_height*scale, in_width*scale] or [batch, in_height*scale, in_width*scale, channel] """ if layout == "NCHW": return upsampling_nchw(data, scale) elif layout == "NHWC": return upsampling_nhwc(data, scale) else: raise ValueError("not support this layout {} yet".format(layout)) def upsampling_nchw(data, scale): """Perform nearest neighor upsampling on NCHW layout input. Parameters ---------- data : tvm.Tensor 4-D with shape [batch, channel, in_height, in_width] scale: int upsampling scaling factor Returns ------- output : tvm.Tensor 4-D with shape [batch, channel, in_height*scale, in_width*scale] """ batch, channel, height, width = data.shape out_height = util.simplify(height * scale) out_width = util.simplify(width * scale) return tvm.compute((batch, channel, out_height, out_width), \ lambda n, c, h, w: data[n, c, h/scale, w/scale]) def upsampling_nhwc(data, scale): """Perform nearest neighor upsampling on NHWC layout input. Parameters ---------- data : tvm.Tensor 4-D with shape [batch, in_height, in_width, channel] scale: int upsampling scaling factor """ batch, height, width, channel = data.shape out_height = util.simplify(height * scale) out_width = util.simplify(width * scale) return tvm.compute((batch, out_height, out_width, channel), \ lambda n, h, w, c: data[n, h/scale, w/scale, c])
[ "\"\"\"TVM operator upsampling compute.\"\"\"\nfrom __future__ import absolute_import\nimport tvm\nfrom .. import util\n\n\ndef upsampling(data, scale, layout=\"NCHW\"):\n \"\"\"Perform nearest neighbor upsampling on the data.\n Bilinear upsampling is not supported.\n\n Parameters\n ----------\n data : tvm.Tensor\n 4-D with shape [batch, channel, in_height, in_width]\n or [batch, in_height, in_width, channel]\n\n scale: int\n upsampling scaling factor\n\n layout: string\n either \"NCHW\" or \"NHWC\"\n\n Returns\n -------\n output : tvm.Tensor\n 4-D with shape [batch, channel, in_height*scale, in_width*scale]\n or [batch, in_height*scale, in_width*scale, channel]\n \"\"\"\n\n if layout == \"NCHW\":\n return upsampling_nchw(data, scale)\n elif layout == \"NHWC\":\n return upsampling_nhwc(data, scale)\n else:\n raise ValueError(\"not support this layout {} yet\".format(layout))\n\n\ndef upsampling_nchw(data, scale):\n \"\"\"Perform nearest neighor upsampling on NCHW layout input.\n\n Parameters\n ----------\n data : tvm.Tensor\n 4-D with shape [batch, channel, in_height, in_width]\n\n scale: int\n upsampling scaling factor\n\n Returns\n -------\n output : tvm.Tensor\n 4-D with shape [batch, channel, in_height*scale, in_width*scale]\n \"\"\"\n batch, channel, height, width = data.shape\n out_height = util.simplify(height * scale)\n out_width = util.simplify(width * scale)\n\n return tvm.compute((batch, channel, out_height, out_width), \\\n lambda n, c, h, w: data[n, c, h/scale, w/scale])\n\n\ndef upsampling_nhwc(data, scale):\n \"\"\"Perform nearest neighor upsampling on NHWC layout input.\n\n Parameters\n ----------\n data : tvm.Tensor\n 4-D with shape [batch, in_height, in_width, channel]\n\n scale: int\n upsampling scaling factor\n\n \"\"\"\n\n batch, height, width, channel = data.shape\n out_height = util.simplify(height * scale)\n out_width = util.simplify(width * scale)\n\n return tvm.compute((batch, out_height, out_width, channel), \\\n lambda n, h, w, c: data[n, h/scale, w/scale, c])\n", "<docstring token>\nfrom __future__ import absolute_import\nimport tvm\nfrom .. import util\n\n\ndef upsampling(data, scale, layout='NCHW'):\n \"\"\"Perform nearest neighbor upsampling on the data.\n Bilinear upsampling is not supported.\n\n Parameters\n ----------\n data : tvm.Tensor\n 4-D with shape [batch, channel, in_height, in_width]\n or [batch, in_height, in_width, channel]\n\n scale: int\n upsampling scaling factor\n\n layout: string\n either \"NCHW\" or \"NHWC\"\n\n Returns\n -------\n output : tvm.Tensor\n 4-D with shape [batch, channel, in_height*scale, in_width*scale]\n or [batch, in_height*scale, in_width*scale, channel]\n \"\"\"\n if layout == 'NCHW':\n return upsampling_nchw(data, scale)\n elif layout == 'NHWC':\n return upsampling_nhwc(data, scale)\n else:\n raise ValueError('not support this layout {} yet'.format(layout))\n\n\ndef upsampling_nchw(data, scale):\n \"\"\"Perform nearest neighor upsampling on NCHW layout input.\n\n Parameters\n ----------\n data : tvm.Tensor\n 4-D with shape [batch, channel, in_height, in_width]\n\n scale: int\n upsampling scaling factor\n\n Returns\n -------\n output : tvm.Tensor\n 4-D with shape [batch, channel, in_height*scale, in_width*scale]\n \"\"\"\n batch, channel, height, width = data.shape\n out_height = util.simplify(height * scale)\n out_width = util.simplify(width * scale)\n return tvm.compute((batch, channel, out_height, out_width), lambda n, c,\n h, w: data[n, c, h / scale, w / scale])\n\n\ndef upsampling_nhwc(data, scale):\n \"\"\"Perform nearest neighor upsampling on NHWC layout input.\n\n Parameters\n ----------\n data : tvm.Tensor\n 4-D with shape [batch, in_height, in_width, channel]\n\n scale: int\n upsampling scaling factor\n\n \"\"\"\n batch, height, width, channel = data.shape\n out_height = util.simplify(height * scale)\n out_width = util.simplify(width * scale)\n return tvm.compute((batch, out_height, out_width, channel), lambda n, h,\n w, c: data[n, h / scale, w / scale, c])\n", "<docstring token>\n<import token>\n\n\ndef upsampling(data, scale, layout='NCHW'):\n \"\"\"Perform nearest neighbor upsampling on the data.\n Bilinear upsampling is not supported.\n\n Parameters\n ----------\n data : tvm.Tensor\n 4-D with shape [batch, channel, in_height, in_width]\n or [batch, in_height, in_width, channel]\n\n scale: int\n upsampling scaling factor\n\n layout: string\n either \"NCHW\" or \"NHWC\"\n\n Returns\n -------\n output : tvm.Tensor\n 4-D with shape [batch, channel, in_height*scale, in_width*scale]\n or [batch, in_height*scale, in_width*scale, channel]\n \"\"\"\n if layout == 'NCHW':\n return upsampling_nchw(data, scale)\n elif layout == 'NHWC':\n return upsampling_nhwc(data, scale)\n else:\n raise ValueError('not support this layout {} yet'.format(layout))\n\n\ndef upsampling_nchw(data, scale):\n \"\"\"Perform nearest neighor upsampling on NCHW layout input.\n\n Parameters\n ----------\n data : tvm.Tensor\n 4-D with shape [batch, channel, in_height, in_width]\n\n scale: int\n upsampling scaling factor\n\n Returns\n -------\n output : tvm.Tensor\n 4-D with shape [batch, channel, in_height*scale, in_width*scale]\n \"\"\"\n batch, channel, height, width = data.shape\n out_height = util.simplify(height * scale)\n out_width = util.simplify(width * scale)\n return tvm.compute((batch, channel, out_height, out_width), lambda n, c,\n h, w: data[n, c, h / scale, w / scale])\n\n\ndef upsampling_nhwc(data, scale):\n \"\"\"Perform nearest neighor upsampling on NHWC layout input.\n\n Parameters\n ----------\n data : tvm.Tensor\n 4-D with shape [batch, in_height, in_width, channel]\n\n scale: int\n upsampling scaling factor\n\n \"\"\"\n batch, height, width, channel = data.shape\n out_height = util.simplify(height * scale)\n out_width = util.simplify(width * scale)\n return tvm.compute((batch, out_height, out_width, channel), lambda n, h,\n w, c: data[n, h / scale, w / scale, c])\n", "<docstring token>\n<import token>\n\n\ndef upsampling(data, scale, layout='NCHW'):\n \"\"\"Perform nearest neighbor upsampling on the data.\n Bilinear upsampling is not supported.\n\n Parameters\n ----------\n data : tvm.Tensor\n 4-D with shape [batch, channel, in_height, in_width]\n or [batch, in_height, in_width, channel]\n\n scale: int\n upsampling scaling factor\n\n layout: string\n either \"NCHW\" or \"NHWC\"\n\n Returns\n -------\n output : tvm.Tensor\n 4-D with shape [batch, channel, in_height*scale, in_width*scale]\n or [batch, in_height*scale, in_width*scale, channel]\n \"\"\"\n if layout == 'NCHW':\n return upsampling_nchw(data, scale)\n elif layout == 'NHWC':\n return upsampling_nhwc(data, scale)\n else:\n raise ValueError('not support this layout {} yet'.format(layout))\n\n\ndef upsampling_nchw(data, scale):\n \"\"\"Perform nearest neighor upsampling on NCHW layout input.\n\n Parameters\n ----------\n data : tvm.Tensor\n 4-D with shape [batch, channel, in_height, in_width]\n\n scale: int\n upsampling scaling factor\n\n Returns\n -------\n output : tvm.Tensor\n 4-D with shape [batch, channel, in_height*scale, in_width*scale]\n \"\"\"\n batch, channel, height, width = data.shape\n out_height = util.simplify(height * scale)\n out_width = util.simplify(width * scale)\n return tvm.compute((batch, channel, out_height, out_width), lambda n, c,\n h, w: data[n, c, h / scale, w / scale])\n\n\n<function token>\n", "<docstring token>\n<import token>\n<function token>\n\n\ndef upsampling_nchw(data, scale):\n \"\"\"Perform nearest neighor upsampling on NCHW layout input.\n\n Parameters\n ----------\n data : tvm.Tensor\n 4-D with shape [batch, channel, in_height, in_width]\n\n scale: int\n upsampling scaling factor\n\n Returns\n -------\n output : tvm.Tensor\n 4-D with shape [batch, channel, in_height*scale, in_width*scale]\n \"\"\"\n batch, channel, height, width = data.shape\n out_height = util.simplify(height * scale)\n out_width = util.simplify(width * scale)\n return tvm.compute((batch, channel, out_height, out_width), lambda n, c,\n h, w: data[n, c, h / scale, w / scale])\n\n\n<function token>\n", "<docstring token>\n<import token>\n<function token>\n<function token>\n<function token>\n" ]
false
98,702
490b7043fb91993d21ffa8b1d946bb10bebe3cb4
from common import getinput, bothparts, noop from typing import List, Dict, Set import re from pathlib import Path from os import sep DIR = str(Path(__file__).parent) + sep class IDProfiler: __slots__ = ["hastwo", "hasthree", "rawstr"] def __init__(self, rawstr: str = "") -> None: self.rawstr: str = rawstr self.hastwo: bool = False self.hasthree: bool = False counts: Dict[str, int] = dict() for letter in rawstr: if letter not in counts: counts[letter] = 0 counts[letter] += 1 for key, val in counts.items(): if val == 2: self.hastwo = True elif val == 3: self.hasthree = True def sharedletters(self, idprofiler: "IDProfiler") -> str: """ Return the shared in-order letters between self and idprofiler """ shared: str = "" for i in range(len(self.rawstr)): if self.rawstr[i] is idprofiler.rawstr[i]: shared += self.rawstr[i] return shared def getidlist(data: str = None) -> List[IDProfiler]: """ Return a list of IDProfilers from provided data or input.txt """ boxids: str = getinput(directory=DIR) if data is None else data idlist: List[IDProfiler] = list(map(IDProfiler, boxids.split("\n"))) return idlist def part1(data: str = None) -> int: """ Return the checksum """ idlist: List[IDProfiler] = getidlist(data) hastwo: List[IDProfiler] = list(filter(lambda a: a.hastwo is True, idlist)) hasthree: List[IDProfiler] = list(filter(lambda a: a.hasthree is True, idlist)) return len(hastwo) * len(hasthree) def part2(data: str = None) -> str: """ Return the shared letters between two in which there is only one discrepancy """ idlist: List[IDProfiler] = getidlist(data) for i in range(len(idlist)): for j in range(i + 1, len(idlist)): shared: str = idlist[i].sharedletters(idlist[j]) if len(shared) is len(idlist[i].rawstr) - 1: return shared def minpart1(data: str = open(DIR+"input.txt", "r").read()) -> int: """ Return the checksum (minified version of part1) """ lines: List[str] = data.split("\n") sets: List[Set[str]] = list(map(lambda a: set(), range(len(lines[0]) + 1))) for i in range(ord("a"), ord("z") + 1): for line in lines: sets[len(re.findall(f"{chr(i)}", line))].add(line) return len(sets[2]) * len(sets[3]) def minpart2(d: str = open(DIR+"input.txt", "r").read(), s: Set[str] = None, a: int = 0, b: int = 1, p: int = 0) -> str: """ Return the shared letters between two in which there is only one discrepancy (minified version of part2) (longer runtime) """ seen: Set[str] = s if s is not None else set() lines: List[str] = d.split("\n") if p >= len(lines[a]) or b >= len(lines) or f"{a}-{b}-{p}" in seen or "found" in seen: return "" seen.add(f"{a}-{b}-{p}") if lines[a][:p] + lines[a][p + 1:] == lines[b][:p] + lines[b][p + 1:] and seen.add("found") is None: return lines[a][:p] + lines[a][p + 1:] return max(minpart2(d, seen, a, b + 1, p), minpart2(d, seen, a + 1, b + 1, p), minpart2(d, seen, a, b, p + 1)) if __name__ == '__main__': # pragma: no cover bothparts(part1, part2) noop()
[ "from common import getinput, bothparts, noop\nfrom typing import List, Dict, Set\nimport re\nfrom pathlib import Path\nfrom os import sep\n\nDIR = str(Path(__file__).parent) + sep\n\n\nclass IDProfiler:\n __slots__ = [\"hastwo\", \"hasthree\", \"rawstr\"]\n\n def __init__(self, rawstr: str = \"\") -> None:\n self.rawstr: str = rawstr\n self.hastwo: bool = False\n self.hasthree: bool = False\n counts: Dict[str, int] = dict()\n for letter in rawstr:\n if letter not in counts:\n counts[letter] = 0\n counts[letter] += 1\n for key, val in counts.items():\n if val == 2:\n self.hastwo = True\n elif val == 3:\n self.hasthree = True\n\n def sharedletters(self, idprofiler: \"IDProfiler\") -> str:\n \"\"\" Return the shared in-order letters between self and idprofiler \"\"\"\n shared: str = \"\"\n for i in range(len(self.rawstr)):\n if self.rawstr[i] is idprofiler.rawstr[i]:\n shared += self.rawstr[i]\n return shared\n\n\ndef getidlist(data: str = None) -> List[IDProfiler]:\n \"\"\" Return a list of IDProfilers from provided data or input.txt \"\"\"\n boxids: str = getinput(directory=DIR) if data is None else data\n idlist: List[IDProfiler] = list(map(IDProfiler, boxids.split(\"\\n\")))\n return idlist\n\n\ndef part1(data: str = None) -> int:\n \"\"\" Return the checksum \"\"\"\n idlist: List[IDProfiler] = getidlist(data)\n hastwo: List[IDProfiler] = list(filter(lambda a: a.hastwo is True, idlist))\n hasthree: List[IDProfiler] = list(filter(lambda a: a.hasthree is True, idlist))\n return len(hastwo) * len(hasthree)\n\n\ndef part2(data: str = None) -> str:\n \"\"\" Return the shared letters between two in which there is only one discrepancy \"\"\"\n idlist: List[IDProfiler] = getidlist(data)\n for i in range(len(idlist)):\n for j in range(i + 1, len(idlist)):\n shared: str = idlist[i].sharedletters(idlist[j])\n if len(shared) is len(idlist[i].rawstr) - 1:\n return shared\n\n\ndef minpart1(data: str = open(DIR+\"input.txt\", \"r\").read()) -> int:\n \"\"\" Return the checksum (minified version of part1) \"\"\"\n lines: List[str] = data.split(\"\\n\")\n sets: List[Set[str]] = list(map(lambda a: set(), range(len(lines[0]) + 1)))\n for i in range(ord(\"a\"), ord(\"z\") + 1):\n for line in lines:\n sets[len(re.findall(f\"{chr(i)}\", line))].add(line)\n return len(sets[2]) * len(sets[3])\n\n\ndef minpart2(d: str = open(DIR+\"input.txt\", \"r\").read(), s: Set[str] = None, a: int = 0, b: int = 1, p: int = 0) -> str:\n \"\"\"\n Return the shared letters between two in which there is only one discrepancy\n (minified version of part2) (longer runtime)\n \"\"\"\n seen: Set[str] = s if s is not None else set()\n lines: List[str] = d.split(\"\\n\")\n if p >= len(lines[a]) or b >= len(lines) or f\"{a}-{b}-{p}\" in seen or \"found\" in seen:\n return \"\"\n seen.add(f\"{a}-{b}-{p}\")\n if lines[a][:p] + lines[a][p + 1:] == lines[b][:p] + lines[b][p + 1:] and seen.add(\"found\") is None:\n return lines[a][:p] + lines[a][p + 1:]\n return max(minpart2(d, seen, a, b + 1, p), minpart2(d, seen, a + 1, b + 1, p), minpart2(d, seen, a, b, p + 1))\n\n\nif __name__ == '__main__': # pragma: no cover\n bothparts(part1, part2)\n noop()\n", "from common import getinput, bothparts, noop\nfrom typing import List, Dict, Set\nimport re\nfrom pathlib import Path\nfrom os import sep\nDIR = str(Path(__file__).parent) + sep\n\n\nclass IDProfiler:\n __slots__ = ['hastwo', 'hasthree', 'rawstr']\n\n def __init__(self, rawstr: str='') ->None:\n self.rawstr: str = rawstr\n self.hastwo: bool = False\n self.hasthree: bool = False\n counts: Dict[str, int] = dict()\n for letter in rawstr:\n if letter not in counts:\n counts[letter] = 0\n counts[letter] += 1\n for key, val in counts.items():\n if val == 2:\n self.hastwo = True\n elif val == 3:\n self.hasthree = True\n\n def sharedletters(self, idprofiler: 'IDProfiler') ->str:\n \"\"\" Return the shared in-order letters between self and idprofiler \"\"\"\n shared: str = ''\n for i in range(len(self.rawstr)):\n if self.rawstr[i] is idprofiler.rawstr[i]:\n shared += self.rawstr[i]\n return shared\n\n\ndef getidlist(data: str=None) ->List[IDProfiler]:\n \"\"\" Return a list of IDProfilers from provided data or input.txt \"\"\"\n boxids: str = getinput(directory=DIR) if data is None else data\n idlist: List[IDProfiler] = list(map(IDProfiler, boxids.split('\\n')))\n return idlist\n\n\ndef part1(data: str=None) ->int:\n \"\"\" Return the checksum \"\"\"\n idlist: List[IDProfiler] = getidlist(data)\n hastwo: List[IDProfiler] = list(filter(lambda a: a.hastwo is True, idlist))\n hasthree: List[IDProfiler] = list(filter(lambda a: a.hasthree is True,\n idlist))\n return len(hastwo) * len(hasthree)\n\n\ndef part2(data: str=None) ->str:\n \"\"\" Return the shared letters between two in which there is only one discrepancy \"\"\"\n idlist: List[IDProfiler] = getidlist(data)\n for i in range(len(idlist)):\n for j in range(i + 1, len(idlist)):\n shared: str = idlist[i].sharedletters(idlist[j])\n if len(shared) is len(idlist[i].rawstr) - 1:\n return shared\n\n\ndef minpart1(data: str=open(DIR + 'input.txt', 'r').read()) ->int:\n \"\"\" Return the checksum (minified version of part1) \"\"\"\n lines: List[str] = data.split('\\n')\n sets: List[Set[str]] = list(map(lambda a: set(), range(len(lines[0]) + 1)))\n for i in range(ord('a'), ord('z') + 1):\n for line in lines:\n sets[len(re.findall(f'{chr(i)}', line))].add(line)\n return len(sets[2]) * len(sets[3])\n\n\ndef minpart2(d: str=open(DIR + 'input.txt', 'r').read(), s: Set[str]=None,\n a: int=0, b: int=1, p: int=0) ->str:\n \"\"\"\n Return the shared letters between two in which there is only one discrepancy\n (minified version of part2) (longer runtime)\n \"\"\"\n seen: Set[str] = s if s is not None else set()\n lines: List[str] = d.split('\\n')\n if p >= len(lines[a]) or b >= len(lines\n ) or f'{a}-{b}-{p}' in seen or 'found' in seen:\n return ''\n seen.add(f'{a}-{b}-{p}')\n if lines[a][:p] + lines[a][p + 1:] == lines[b][:p] + lines[b][p + 1:\n ] and seen.add('found') is None:\n return lines[a][:p] + lines[a][p + 1:]\n return max(minpart2(d, seen, a, b + 1, p), minpart2(d, seen, a + 1, b +\n 1, p), minpart2(d, seen, a, b, p + 1))\n\n\nif __name__ == '__main__':\n bothparts(part1, part2)\n noop()\n", "<import token>\nDIR = str(Path(__file__).parent) + sep\n\n\nclass IDProfiler:\n __slots__ = ['hastwo', 'hasthree', 'rawstr']\n\n def __init__(self, rawstr: str='') ->None:\n self.rawstr: str = rawstr\n self.hastwo: bool = False\n self.hasthree: bool = False\n counts: Dict[str, int] = dict()\n for letter in rawstr:\n if letter not in counts:\n counts[letter] = 0\n counts[letter] += 1\n for key, val in counts.items():\n if val == 2:\n self.hastwo = True\n elif val == 3:\n self.hasthree = True\n\n def sharedletters(self, idprofiler: 'IDProfiler') ->str:\n \"\"\" Return the shared in-order letters between self and idprofiler \"\"\"\n shared: str = ''\n for i in range(len(self.rawstr)):\n if self.rawstr[i] is idprofiler.rawstr[i]:\n shared += self.rawstr[i]\n return shared\n\n\ndef getidlist(data: str=None) ->List[IDProfiler]:\n \"\"\" Return a list of IDProfilers from provided data or input.txt \"\"\"\n boxids: str = getinput(directory=DIR) if data is None else data\n idlist: List[IDProfiler] = list(map(IDProfiler, boxids.split('\\n')))\n return idlist\n\n\ndef part1(data: str=None) ->int:\n \"\"\" Return the checksum \"\"\"\n idlist: List[IDProfiler] = getidlist(data)\n hastwo: List[IDProfiler] = list(filter(lambda a: a.hastwo is True, idlist))\n hasthree: List[IDProfiler] = list(filter(lambda a: a.hasthree is True,\n idlist))\n return len(hastwo) * len(hasthree)\n\n\ndef part2(data: str=None) ->str:\n \"\"\" Return the shared letters between two in which there is only one discrepancy \"\"\"\n idlist: List[IDProfiler] = getidlist(data)\n for i in range(len(idlist)):\n for j in range(i + 1, len(idlist)):\n shared: str = idlist[i].sharedletters(idlist[j])\n if len(shared) is len(idlist[i].rawstr) - 1:\n return shared\n\n\ndef minpart1(data: str=open(DIR + 'input.txt', 'r').read()) ->int:\n \"\"\" Return the checksum (minified version of part1) \"\"\"\n lines: List[str] = data.split('\\n')\n sets: List[Set[str]] = list(map(lambda a: set(), range(len(lines[0]) + 1)))\n for i in range(ord('a'), ord('z') + 1):\n for line in lines:\n sets[len(re.findall(f'{chr(i)}', line))].add(line)\n return len(sets[2]) * len(sets[3])\n\n\ndef minpart2(d: str=open(DIR + 'input.txt', 'r').read(), s: Set[str]=None,\n a: int=0, b: int=1, p: int=0) ->str:\n \"\"\"\n Return the shared letters between two in which there is only one discrepancy\n (minified version of part2) (longer runtime)\n \"\"\"\n seen: Set[str] = s if s is not None else set()\n lines: List[str] = d.split('\\n')\n if p >= len(lines[a]) or b >= len(lines\n ) or f'{a}-{b}-{p}' in seen or 'found' in seen:\n return ''\n seen.add(f'{a}-{b}-{p}')\n if lines[a][:p] + lines[a][p + 1:] == lines[b][:p] + lines[b][p + 1:\n ] and seen.add('found') is None:\n return lines[a][:p] + lines[a][p + 1:]\n return max(minpart2(d, seen, a, b + 1, p), minpart2(d, seen, a + 1, b +\n 1, p), minpart2(d, seen, a, b, p + 1))\n\n\nif __name__ == '__main__':\n bothparts(part1, part2)\n noop()\n", "<import token>\n<assignment token>\n\n\nclass IDProfiler:\n __slots__ = ['hastwo', 'hasthree', 'rawstr']\n\n def __init__(self, rawstr: str='') ->None:\n self.rawstr: str = rawstr\n self.hastwo: bool = False\n self.hasthree: bool = False\n counts: Dict[str, int] = dict()\n for letter in rawstr:\n if letter not in counts:\n counts[letter] = 0\n counts[letter] += 1\n for key, val in counts.items():\n if val == 2:\n self.hastwo = True\n elif val == 3:\n self.hasthree = True\n\n def sharedletters(self, idprofiler: 'IDProfiler') ->str:\n \"\"\" Return the shared in-order letters between self and idprofiler \"\"\"\n shared: str = ''\n for i in range(len(self.rawstr)):\n if self.rawstr[i] is idprofiler.rawstr[i]:\n shared += self.rawstr[i]\n return shared\n\n\ndef getidlist(data: str=None) ->List[IDProfiler]:\n \"\"\" Return a list of IDProfilers from provided data or input.txt \"\"\"\n boxids: str = getinput(directory=DIR) if data is None else data\n idlist: List[IDProfiler] = list(map(IDProfiler, boxids.split('\\n')))\n return idlist\n\n\ndef part1(data: str=None) ->int:\n \"\"\" Return the checksum \"\"\"\n idlist: List[IDProfiler] = getidlist(data)\n hastwo: List[IDProfiler] = list(filter(lambda a: a.hastwo is True, idlist))\n hasthree: List[IDProfiler] = list(filter(lambda a: a.hasthree is True,\n idlist))\n return len(hastwo) * len(hasthree)\n\n\ndef part2(data: str=None) ->str:\n \"\"\" Return the shared letters between two in which there is only one discrepancy \"\"\"\n idlist: List[IDProfiler] = getidlist(data)\n for i in range(len(idlist)):\n for j in range(i + 1, len(idlist)):\n shared: str = idlist[i].sharedletters(idlist[j])\n if len(shared) is len(idlist[i].rawstr) - 1:\n return shared\n\n\ndef minpart1(data: str=open(DIR + 'input.txt', 'r').read()) ->int:\n \"\"\" Return the checksum (minified version of part1) \"\"\"\n lines: List[str] = data.split('\\n')\n sets: List[Set[str]] = list(map(lambda a: set(), range(len(lines[0]) + 1)))\n for i in range(ord('a'), ord('z') + 1):\n for line in lines:\n sets[len(re.findall(f'{chr(i)}', line))].add(line)\n return len(sets[2]) * len(sets[3])\n\n\ndef minpart2(d: str=open(DIR + 'input.txt', 'r').read(), s: Set[str]=None,\n a: int=0, b: int=1, p: int=0) ->str:\n \"\"\"\n Return the shared letters between two in which there is only one discrepancy\n (minified version of part2) (longer runtime)\n \"\"\"\n seen: Set[str] = s if s is not None else set()\n lines: List[str] = d.split('\\n')\n if p >= len(lines[a]) or b >= len(lines\n ) or f'{a}-{b}-{p}' in seen or 'found' in seen:\n return ''\n seen.add(f'{a}-{b}-{p}')\n if lines[a][:p] + lines[a][p + 1:] == lines[b][:p] + lines[b][p + 1:\n ] and seen.add('found') is None:\n return lines[a][:p] + lines[a][p + 1:]\n return max(minpart2(d, seen, a, b + 1, p), minpart2(d, seen, a + 1, b +\n 1, p), minpart2(d, seen, a, b, p + 1))\n\n\nif __name__ == '__main__':\n bothparts(part1, part2)\n noop()\n", "<import token>\n<assignment token>\n\n\nclass IDProfiler:\n __slots__ = ['hastwo', 'hasthree', 'rawstr']\n\n def __init__(self, rawstr: str='') ->None:\n self.rawstr: str = rawstr\n self.hastwo: bool = False\n self.hasthree: bool = False\n counts: Dict[str, int] = dict()\n for letter in rawstr:\n if letter not in counts:\n counts[letter] = 0\n counts[letter] += 1\n for key, val in counts.items():\n if val == 2:\n self.hastwo = True\n elif val == 3:\n self.hasthree = True\n\n def sharedletters(self, idprofiler: 'IDProfiler') ->str:\n \"\"\" Return the shared in-order letters between self and idprofiler \"\"\"\n shared: str = ''\n for i in range(len(self.rawstr)):\n if self.rawstr[i] is idprofiler.rawstr[i]:\n shared += self.rawstr[i]\n return shared\n\n\ndef getidlist(data: str=None) ->List[IDProfiler]:\n \"\"\" Return a list of IDProfilers from provided data or input.txt \"\"\"\n boxids: str = getinput(directory=DIR) if data is None else data\n idlist: List[IDProfiler] = list(map(IDProfiler, boxids.split('\\n')))\n return idlist\n\n\ndef part1(data: str=None) ->int:\n \"\"\" Return the checksum \"\"\"\n idlist: List[IDProfiler] = getidlist(data)\n hastwo: List[IDProfiler] = list(filter(lambda a: a.hastwo is True, idlist))\n hasthree: List[IDProfiler] = list(filter(lambda a: a.hasthree is True,\n idlist))\n return len(hastwo) * len(hasthree)\n\n\ndef part2(data: str=None) ->str:\n \"\"\" Return the shared letters between two in which there is only one discrepancy \"\"\"\n idlist: List[IDProfiler] = getidlist(data)\n for i in range(len(idlist)):\n for j in range(i + 1, len(idlist)):\n shared: str = idlist[i].sharedletters(idlist[j])\n if len(shared) is len(idlist[i].rawstr) - 1:\n return shared\n\n\ndef minpart1(data: str=open(DIR + 'input.txt', 'r').read()) ->int:\n \"\"\" Return the checksum (minified version of part1) \"\"\"\n lines: List[str] = data.split('\\n')\n sets: List[Set[str]] = list(map(lambda a: set(), range(len(lines[0]) + 1)))\n for i in range(ord('a'), ord('z') + 1):\n for line in lines:\n sets[len(re.findall(f'{chr(i)}', line))].add(line)\n return len(sets[2]) * len(sets[3])\n\n\ndef minpart2(d: str=open(DIR + 'input.txt', 'r').read(), s: Set[str]=None,\n a: int=0, b: int=1, p: int=0) ->str:\n \"\"\"\n Return the shared letters between two in which there is only one discrepancy\n (minified version of part2) (longer runtime)\n \"\"\"\n seen: Set[str] = s if s is not None else set()\n lines: List[str] = d.split('\\n')\n if p >= len(lines[a]) or b >= len(lines\n ) or f'{a}-{b}-{p}' in seen or 'found' in seen:\n return ''\n seen.add(f'{a}-{b}-{p}')\n if lines[a][:p] + lines[a][p + 1:] == lines[b][:p] + lines[b][p + 1:\n ] and seen.add('found') is None:\n return lines[a][:p] + lines[a][p + 1:]\n return max(minpart2(d, seen, a, b + 1, p), minpart2(d, seen, a + 1, b +\n 1, p), minpart2(d, seen, a, b, p + 1))\n\n\n<code token>\n", "<import token>\n<assignment token>\n\n\nclass IDProfiler:\n __slots__ = ['hastwo', 'hasthree', 'rawstr']\n\n def __init__(self, rawstr: str='') ->None:\n self.rawstr: str = rawstr\n self.hastwo: bool = False\n self.hasthree: bool = False\n counts: Dict[str, int] = dict()\n for letter in rawstr:\n if letter not in counts:\n counts[letter] = 0\n counts[letter] += 1\n for key, val in counts.items():\n if val == 2:\n self.hastwo = True\n elif val == 3:\n self.hasthree = True\n\n def sharedletters(self, idprofiler: 'IDProfiler') ->str:\n \"\"\" Return the shared in-order letters between self and idprofiler \"\"\"\n shared: str = ''\n for i in range(len(self.rawstr)):\n if self.rawstr[i] is idprofiler.rawstr[i]:\n shared += self.rawstr[i]\n return shared\n\n\ndef getidlist(data: str=None) ->List[IDProfiler]:\n \"\"\" Return a list of IDProfilers from provided data or input.txt \"\"\"\n boxids: str = getinput(directory=DIR) if data is None else data\n idlist: List[IDProfiler] = list(map(IDProfiler, boxids.split('\\n')))\n return idlist\n\n\n<function token>\n\n\ndef part2(data: str=None) ->str:\n \"\"\" Return the shared letters between two in which there is only one discrepancy \"\"\"\n idlist: List[IDProfiler] = getidlist(data)\n for i in range(len(idlist)):\n for j in range(i + 1, len(idlist)):\n shared: str = idlist[i].sharedletters(idlist[j])\n if len(shared) is len(idlist[i].rawstr) - 1:\n return shared\n\n\ndef minpart1(data: str=open(DIR + 'input.txt', 'r').read()) ->int:\n \"\"\" Return the checksum (minified version of part1) \"\"\"\n lines: List[str] = data.split('\\n')\n sets: List[Set[str]] = list(map(lambda a: set(), range(len(lines[0]) + 1)))\n for i in range(ord('a'), ord('z') + 1):\n for line in lines:\n sets[len(re.findall(f'{chr(i)}', line))].add(line)\n return len(sets[2]) * len(sets[3])\n\n\ndef minpart2(d: str=open(DIR + 'input.txt', 'r').read(), s: Set[str]=None,\n a: int=0, b: int=1, p: int=0) ->str:\n \"\"\"\n Return the shared letters between two in which there is only one discrepancy\n (minified version of part2) (longer runtime)\n \"\"\"\n seen: Set[str] = s if s is not None else set()\n lines: List[str] = d.split('\\n')\n if p >= len(lines[a]) or b >= len(lines\n ) or f'{a}-{b}-{p}' in seen or 'found' in seen:\n return ''\n seen.add(f'{a}-{b}-{p}')\n if lines[a][:p] + lines[a][p + 1:] == lines[b][:p] + lines[b][p + 1:\n ] and seen.add('found') is None:\n return lines[a][:p] + lines[a][p + 1:]\n return max(minpart2(d, seen, a, b + 1, p), minpart2(d, seen, a + 1, b +\n 1, p), minpart2(d, seen, a, b, p + 1))\n\n\n<code token>\n", "<import token>\n<assignment token>\n\n\nclass IDProfiler:\n __slots__ = ['hastwo', 'hasthree', 'rawstr']\n\n def __init__(self, rawstr: str='') ->None:\n self.rawstr: str = rawstr\n self.hastwo: bool = False\n self.hasthree: bool = False\n counts: Dict[str, int] = dict()\n for letter in rawstr:\n if letter not in counts:\n counts[letter] = 0\n counts[letter] += 1\n for key, val in counts.items():\n if val == 2:\n self.hastwo = True\n elif val == 3:\n self.hasthree = True\n\n def sharedletters(self, idprofiler: 'IDProfiler') ->str:\n \"\"\" Return the shared in-order letters between self and idprofiler \"\"\"\n shared: str = ''\n for i in range(len(self.rawstr)):\n if self.rawstr[i] is idprofiler.rawstr[i]:\n shared += self.rawstr[i]\n return shared\n\n\ndef getidlist(data: str=None) ->List[IDProfiler]:\n \"\"\" Return a list of IDProfilers from provided data or input.txt \"\"\"\n boxids: str = getinput(directory=DIR) if data is None else data\n idlist: List[IDProfiler] = list(map(IDProfiler, boxids.split('\\n')))\n return idlist\n\n\n<function token>\n\n\ndef part2(data: str=None) ->str:\n \"\"\" Return the shared letters between two in which there is only one discrepancy \"\"\"\n idlist: List[IDProfiler] = getidlist(data)\n for i in range(len(idlist)):\n for j in range(i + 1, len(idlist)):\n shared: str = idlist[i].sharedletters(idlist[j])\n if len(shared) is len(idlist[i].rawstr) - 1:\n return shared\n\n\ndef minpart1(data: str=open(DIR + 'input.txt', 'r').read()) ->int:\n \"\"\" Return the checksum (minified version of part1) \"\"\"\n lines: List[str] = data.split('\\n')\n sets: List[Set[str]] = list(map(lambda a: set(), range(len(lines[0]) + 1)))\n for i in range(ord('a'), ord('z') + 1):\n for line in lines:\n sets[len(re.findall(f'{chr(i)}', line))].add(line)\n return len(sets[2]) * len(sets[3])\n\n\n<function token>\n<code token>\n", "<import token>\n<assignment token>\n\n\nclass IDProfiler:\n __slots__ = ['hastwo', 'hasthree', 'rawstr']\n\n def __init__(self, rawstr: str='') ->None:\n self.rawstr: str = rawstr\n self.hastwo: bool = False\n self.hasthree: bool = False\n counts: Dict[str, int] = dict()\n for letter in rawstr:\n if letter not in counts:\n counts[letter] = 0\n counts[letter] += 1\n for key, val in counts.items():\n if val == 2:\n self.hastwo = True\n elif val == 3:\n self.hasthree = True\n\n def sharedletters(self, idprofiler: 'IDProfiler') ->str:\n \"\"\" Return the shared in-order letters between self and idprofiler \"\"\"\n shared: str = ''\n for i in range(len(self.rawstr)):\n if self.rawstr[i] is idprofiler.rawstr[i]:\n shared += self.rawstr[i]\n return shared\n\n\ndef getidlist(data: str=None) ->List[IDProfiler]:\n \"\"\" Return a list of IDProfilers from provided data or input.txt \"\"\"\n boxids: str = getinput(directory=DIR) if data is None else data\n idlist: List[IDProfiler] = list(map(IDProfiler, boxids.split('\\n')))\n return idlist\n\n\n<function token>\n\n\ndef part2(data: str=None) ->str:\n \"\"\" Return the shared letters between two in which there is only one discrepancy \"\"\"\n idlist: List[IDProfiler] = getidlist(data)\n for i in range(len(idlist)):\n for j in range(i + 1, len(idlist)):\n shared: str = idlist[i].sharedletters(idlist[j])\n if len(shared) is len(idlist[i].rawstr) - 1:\n return shared\n\n\n<function token>\n<function token>\n<code token>\n", "<import token>\n<assignment token>\n\n\nclass IDProfiler:\n __slots__ = ['hastwo', 'hasthree', 'rawstr']\n\n def __init__(self, rawstr: str='') ->None:\n self.rawstr: str = rawstr\n self.hastwo: bool = False\n self.hasthree: bool = False\n counts: Dict[str, int] = dict()\n for letter in rawstr:\n if letter not in counts:\n counts[letter] = 0\n counts[letter] += 1\n for key, val in counts.items():\n if val == 2:\n self.hastwo = True\n elif val == 3:\n self.hasthree = True\n\n def sharedletters(self, idprofiler: 'IDProfiler') ->str:\n \"\"\" Return the shared in-order letters between self and idprofiler \"\"\"\n shared: str = ''\n for i in range(len(self.rawstr)):\n if self.rawstr[i] is idprofiler.rawstr[i]:\n shared += self.rawstr[i]\n return shared\n\n\n<function token>\n<function token>\n\n\ndef part2(data: str=None) ->str:\n \"\"\" Return the shared letters between two in which there is only one discrepancy \"\"\"\n idlist: List[IDProfiler] = getidlist(data)\n for i in range(len(idlist)):\n for j in range(i + 1, len(idlist)):\n shared: str = idlist[i].sharedletters(idlist[j])\n if len(shared) is len(idlist[i].rawstr) - 1:\n return shared\n\n\n<function token>\n<function token>\n<code token>\n", "<import token>\n<assignment token>\n\n\nclass IDProfiler:\n __slots__ = ['hastwo', 'hasthree', 'rawstr']\n\n def __init__(self, rawstr: str='') ->None:\n self.rawstr: str = rawstr\n self.hastwo: bool = False\n self.hasthree: bool = False\n counts: Dict[str, int] = dict()\n for letter in rawstr:\n if letter not in counts:\n counts[letter] = 0\n counts[letter] += 1\n for key, val in counts.items():\n if val == 2:\n self.hastwo = True\n elif val == 3:\n self.hasthree = True\n\n def sharedletters(self, idprofiler: 'IDProfiler') ->str:\n \"\"\" Return the shared in-order letters between self and idprofiler \"\"\"\n shared: str = ''\n for i in range(len(self.rawstr)):\n if self.rawstr[i] is idprofiler.rawstr[i]:\n shared += self.rawstr[i]\n return shared\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n", "<import token>\n<assignment token>\n\n\nclass IDProfiler:\n <assignment token>\n\n def __init__(self, rawstr: str='') ->None:\n self.rawstr: str = rawstr\n self.hastwo: bool = False\n self.hasthree: bool = False\n counts: Dict[str, int] = dict()\n for letter in rawstr:\n if letter not in counts:\n counts[letter] = 0\n counts[letter] += 1\n for key, val in counts.items():\n if val == 2:\n self.hastwo = True\n elif val == 3:\n self.hasthree = True\n\n def sharedletters(self, idprofiler: 'IDProfiler') ->str:\n \"\"\" Return the shared in-order letters between self and idprofiler \"\"\"\n shared: str = ''\n for i in range(len(self.rawstr)):\n if self.rawstr[i] is idprofiler.rawstr[i]:\n shared += self.rawstr[i]\n return shared\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n", "<import token>\n<assignment token>\n\n\nclass IDProfiler:\n <assignment token>\n\n def __init__(self, rawstr: str='') ->None:\n self.rawstr: str = rawstr\n self.hastwo: bool = False\n self.hasthree: bool = False\n counts: Dict[str, int] = dict()\n for letter in rawstr:\n if letter not in counts:\n counts[letter] = 0\n counts[letter] += 1\n for key, val in counts.items():\n if val == 2:\n self.hastwo = True\n elif val == 3:\n self.hasthree = True\n <function token>\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n", "<import token>\n<assignment token>\n\n\nclass IDProfiler:\n <assignment token>\n <function token>\n <function token>\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n", "<import token>\n<assignment token>\n<class token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n" ]
false
98,703
2b49e98dde6a975422d2d804a7b7faf45b985702
colors = ["black", "red", "green", "yellow", "blue", "magenta", "cyan", "white"] def make_colors(start): res = {} for i in range(len(colors)): res[colors[i]] = '\033[' + str(start+i) + 'm' return res foreground_normal = make_colors(30) foreground_bright = make_colors(90) def color(s, c, scheme = None): if (scheme == None): scheme = foreground_bright return scheme[c] + s + '\033[0m' def bold(s): return '\033[1m' + s + '\033[0m'
[ "\ncolors = [\"black\", \"red\", \"green\", \"yellow\", \"blue\", \"magenta\", \"cyan\", \"white\"]\n\ndef make_colors(start):\n res = {}\n for i in range(len(colors)):\n res[colors[i]] = '\\033[' + str(start+i) + 'm'\n return res\n\nforeground_normal = make_colors(30)\nforeground_bright = make_colors(90)\n\ndef color(s, c, scheme = None):\n if (scheme == None):\n scheme = foreground_bright\n return scheme[c] + s + '\\033[0m'\n\ndef bold(s):\n return '\\033[1m' + s + '\\033[0m'\n\n", "colors = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'\n ]\n\n\ndef make_colors(start):\n res = {}\n for i in range(len(colors)):\n res[colors[i]] = '\\x1b[' + str(start + i) + 'm'\n return res\n\n\nforeground_normal = make_colors(30)\nforeground_bright = make_colors(90)\n\n\ndef color(s, c, scheme=None):\n if scheme == None:\n scheme = foreground_bright\n return scheme[c] + s + '\\x1b[0m'\n\n\ndef bold(s):\n return '\\x1b[1m' + s + '\\x1b[0m'\n", "<assignment token>\n\n\ndef make_colors(start):\n res = {}\n for i in range(len(colors)):\n res[colors[i]] = '\\x1b[' + str(start + i) + 'm'\n return res\n\n\n<assignment token>\n\n\ndef color(s, c, scheme=None):\n if scheme == None:\n scheme = foreground_bright\n return scheme[c] + s + '\\x1b[0m'\n\n\ndef bold(s):\n return '\\x1b[1m' + s + '\\x1b[0m'\n", "<assignment token>\n<function token>\n<assignment token>\n\n\ndef color(s, c, scheme=None):\n if scheme == None:\n scheme = foreground_bright\n return scheme[c] + s + '\\x1b[0m'\n\n\ndef bold(s):\n return '\\x1b[1m' + s + '\\x1b[0m'\n", "<assignment token>\n<function token>\n<assignment token>\n\n\ndef color(s, c, scheme=None):\n if scheme == None:\n scheme = foreground_bright\n return scheme[c] + s + '\\x1b[0m'\n\n\n<function token>\n", "<assignment token>\n<function token>\n<assignment token>\n<function token>\n<function token>\n" ]
false
98,704
38ea60f0b933720cfaa87c007031f82e2841625b
import grpc import calculator_pb2, calculator_pb2_grpc def print_results(request, response, procedure_name) -> None: """ Prints results of a fulfilled request. """ procedure_names_dict = { 'SquareRoot': calculator_pb2_grpc.CalculatorServicer.SquareRoot.__name__, 'Square': calculator_pb2_grpc.CalculatorServicer.Square.__name__, } print_string = f"Request: {procedure_names_dict[procedure_name]} for {request.value}.\nResponse: {response.value}.\n" print(print_string) # open a gRPC channel channel = grpc.insecure_channel("localhost:50051") # create a stub: converts parameters passed between client and server during a remote procedure call stub = calculator_pb2_grpc.CalculatorStub(channel) # create a valid request message request = calculator_pb2.Number(value=9) # make the remote procedure call (rpc) response = stub.SquareRoot(request) print_results(request, response, 'SquareRoot') # make new requests and fulfill request = calculator_pb2.Number(value=16) response = stub.SquareRoot(request) print_results(request, response, 'SquareRoot') # request: square request = calculator_pb2.Number(value=5) response = stub.Square(request) print_results(request, response, 'Square')
[ "import grpc\n\nimport calculator_pb2, calculator_pb2_grpc\n\ndef print_results(request, response, procedure_name) -> None:\n \"\"\"\n Prints results of a fulfilled request.\n \"\"\"\n procedure_names_dict = {\n 'SquareRoot': calculator_pb2_grpc.CalculatorServicer.SquareRoot.__name__,\n 'Square': calculator_pb2_grpc.CalculatorServicer.Square.__name__,\n }\n print_string = f\"Request: {procedure_names_dict[procedure_name]} for {request.value}.\\nResponse: {response.value}.\\n\"\n print(print_string)\n\n\n# open a gRPC channel\nchannel = grpc.insecure_channel(\"localhost:50051\")\n\n# create a stub: converts parameters passed between client and server during a remote procedure call\nstub = calculator_pb2_grpc.CalculatorStub(channel)\n\n# create a valid request message\nrequest = calculator_pb2.Number(value=9)\n\n# make the remote procedure call (rpc)\nresponse = stub.SquareRoot(request)\n\nprint_results(request, response, 'SquareRoot')\n\n\n# make new requests and fulfill\nrequest = calculator_pb2.Number(value=16)\nresponse = stub.SquareRoot(request)\nprint_results(request, response, 'SquareRoot')\n\n\n# request: square\nrequest = calculator_pb2.Number(value=5)\nresponse = stub.Square(request)\nprint_results(request, response, 'Square')\n", "import grpc\nimport calculator_pb2, calculator_pb2_grpc\n\n\ndef print_results(request, response, procedure_name) ->None:\n \"\"\"\n Prints results of a fulfilled request.\n \"\"\"\n procedure_names_dict = {'SquareRoot': calculator_pb2_grpc.\n CalculatorServicer.SquareRoot.__name__, 'Square':\n calculator_pb2_grpc.CalculatorServicer.Square.__name__}\n print_string = f\"\"\"Request: {procedure_names_dict[procedure_name]} for {request.value}.\nResponse: {response.value}.\n\"\"\"\n print(print_string)\n\n\nchannel = grpc.insecure_channel('localhost:50051')\nstub = calculator_pb2_grpc.CalculatorStub(channel)\nrequest = calculator_pb2.Number(value=9)\nresponse = stub.SquareRoot(request)\nprint_results(request, response, 'SquareRoot')\nrequest = calculator_pb2.Number(value=16)\nresponse = stub.SquareRoot(request)\nprint_results(request, response, 'SquareRoot')\nrequest = calculator_pb2.Number(value=5)\nresponse = stub.Square(request)\nprint_results(request, response, 'Square')\n", "<import token>\n\n\ndef print_results(request, response, procedure_name) ->None:\n \"\"\"\n Prints results of a fulfilled request.\n \"\"\"\n procedure_names_dict = {'SquareRoot': calculator_pb2_grpc.\n CalculatorServicer.SquareRoot.__name__, 'Square':\n calculator_pb2_grpc.CalculatorServicer.Square.__name__}\n print_string = f\"\"\"Request: {procedure_names_dict[procedure_name]} for {request.value}.\nResponse: {response.value}.\n\"\"\"\n print(print_string)\n\n\nchannel = grpc.insecure_channel('localhost:50051')\nstub = calculator_pb2_grpc.CalculatorStub(channel)\nrequest = calculator_pb2.Number(value=9)\nresponse = stub.SquareRoot(request)\nprint_results(request, response, 'SquareRoot')\nrequest = calculator_pb2.Number(value=16)\nresponse = stub.SquareRoot(request)\nprint_results(request, response, 'SquareRoot')\nrequest = calculator_pb2.Number(value=5)\nresponse = stub.Square(request)\nprint_results(request, response, 'Square')\n", "<import token>\n\n\ndef print_results(request, response, procedure_name) ->None:\n \"\"\"\n Prints results of a fulfilled request.\n \"\"\"\n procedure_names_dict = {'SquareRoot': calculator_pb2_grpc.\n CalculatorServicer.SquareRoot.__name__, 'Square':\n calculator_pb2_grpc.CalculatorServicer.Square.__name__}\n print_string = f\"\"\"Request: {procedure_names_dict[procedure_name]} for {request.value}.\nResponse: {response.value}.\n\"\"\"\n print(print_string)\n\n\n<assignment token>\nprint_results(request, response, 'SquareRoot')\n<assignment token>\nprint_results(request, response, 'SquareRoot')\n<assignment token>\nprint_results(request, response, 'Square')\n", "<import token>\n\n\ndef print_results(request, response, procedure_name) ->None:\n \"\"\"\n Prints results of a fulfilled request.\n \"\"\"\n procedure_names_dict = {'SquareRoot': calculator_pb2_grpc.\n CalculatorServicer.SquareRoot.__name__, 'Square':\n calculator_pb2_grpc.CalculatorServicer.Square.__name__}\n print_string = f\"\"\"Request: {procedure_names_dict[procedure_name]} for {request.value}.\nResponse: {response.value}.\n\"\"\"\n print(print_string)\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<function token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
98,705
11e8b835f13d141d1766363f1fd9a0117d43b9ac
def s1r0 (text,key): output = "" for char in text: if (65 <= ord(char) and ord(char) <= 90) or (97 <= ord(char) and ord(char) <= 122): case = 97 if (97 <= ord(char) and ord(char) <= 122) else 65 shift = (chr(((ord(char)+(ord((key[(len(output) % len(key))]).lower()))-97-case) % 26)+ case)) output = output + shift else: output = output+char return output;
[ "def s1r0 (text,key):\n output = \"\"\n for char in text: \n if (65 <= ord(char) and ord(char) <= 90) or (97 <= ord(char) and ord(char) <= 122):\n case = 97 if (97 <= ord(char) and ord(char) <= 122) else 65\n shift = (chr(((ord(char)+(ord((key[(len(output) % len(key))]).lower()))-97-case) % 26)+ case))\n output = output + shift\n else:\n output = output+char\n return output;\n ", "def s1r0(text, key):\n output = ''\n for char in text:\n if 65 <= ord(char) and ord(char) <= 90 or 97 <= ord(char) and ord(char\n ) <= 122:\n case = 97 if 97 <= ord(char) and ord(char) <= 122 else 65\n shift = chr((ord(char) + ord(key[len(output) % len(key)].lower(\n )) - 97 - case) % 26 + case)\n output = output + shift\n else:\n output = output + char\n return output\n", "<function token>\n" ]
false
98,706
4292d2ec35dfb6f9d04823511443eadf85dd87c9
# -*- coding: utf-8 -*- # author: Guixinyu # create Time: 2019-10-17 18:15:39 from PyQt5.QtWidgets import * import sys import first import fileselect import shutil from first import Ui_MainWindow import AddLibraryPath import Enterlibraries from PyQt5.QtCore import * from PyQt5.QtGui import * import os import re import subprocess import time #读取log的线程 class BackendTread(QThread): setvalue = pyqtSignal(int) def __init__(self, parent=None): super(BackendTread, self).__init__(parent) self.working=True def stopSig(self): self.working=False def run(self): #cmd1 = r'''%s\bin\make -j8 all >console.log 2>&1''' % Hdir '''os.chdir(self.ProjectName_2.text() + '/Default') self.process = subprocess.call(cmd1)''' while VAL<NUM and self.working: num=0 for path,dir,files in os.walk(os.getcwd()): for file in files: if file.endswith('.o'): num=num+1 self.setvalue.emit(num) #开编译的线程 class BackendTread1(QThread): startcompile1 = pyqtSignal(str) endSig = pyqtSignal() def __init__(self, parent=None): super(BackendTread1, self).__init__(parent) def startCom(self): self.process = subprocess.Popen(cmd1) def run(self): #cmd1 = r'''%s\bin\make -j8 all >console.log 2>&1''' % Hdir '''os.chdir(self.ProjectName_2.text() + '/Default') self.process = subprocess.call(cmd1)''' f=open('conerr.err','w+') self.process = subprocess.Popen(cmd1,stdout=subprocess.PIPE,stderr=f,bufsize=1) '''self.bt=BackendTread() self.bt.startcompile.connect(self.PrintConsole) self.bt.start()''' self.sleep(3) while self.process.poll() is None: #print(1) r = self.process.stdout.readline().decode('gbk') if r: self.startcompile1.emit(r) if 'tool>pause'in r: break os.system(r"taskkill /f /t /im make.exe")#因为在做post-build的时候,al2的工具需要按回车键才能结束进程,因为在这里强制性的使其结束 self.endSig.emit() class basePage(QMainWindow,Ui_MainWindow): def __init__(self): super(basePage, self).__init__() self.setupUi(self) self.startpath=os.getcwd() self.actionbuild.triggered.connect(self.checkFLAG) #self.menuclean.triggered.connect(self.CleanProject) self.actionclean.triggered.connect(self.CleanProject) self.actionopen_project.triggered.connect(self.ChooseProDir) self.actionsave_project.triggered.connect(self.modifyFLAG) #self.quitApp.triggered.connect(QCoreApplication.instance().quit) #关闭程序的第一种方式 self.actionexit.triggered.connect(qApp.quit)#关闭程序的第二种方式 #添加工具栏:停止和退出 self.tb1=self.addToolBar('tool') actionopen1=QAction(QIcon('./Compile/file.png'),"打开工程",self) self.tb1.addAction(actionopen1) actionopen1.triggered.connect(self.ChooseProDir) self.tb1.addSeparator() actionstop=QAction(QIcon('./Compile/stop.png'),"停止",self) self.tb1.addAction(actionstop) actionstop.triggered.connect(self.KillProcess) self.tb1.addSeparator() actionExit=QAction(QIcon('./Compile/exit.png'),"退出",self) self.tb1.addAction(actionExit) actionExit.triggered.connect(qApp.quit) ##创建右键菜单 #self.includeList.setContextMenuPolicy(Qt.CustomContextMenu) #self.includeList.customContextMenuRequested.connect(self.showRightMenu) #self.includeList.customContextMenuRequested[QPoint].connect(self.remove) #单击一个选项 #self.f="" #self.includeList.clicked.connect(self.check) self.includeList.setContextMenuPolicy(Qt.CustomContextMenu) self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu) self.contextMenu=QMenu(self) self.actionA=self.contextMenu.addAction("删除") self.actionA.triggered.connect(self.remove) self.includeList.customContextMenuRequested.connect(lambda :self.showContextMenu(1)) #self.contextMenu.triggered[QAction].connect(self.remove) #self.includeList.customContextMenuRequested[QPoint].connect(self.remove1)#[]里的代表传入的参数,自带的 self.excludeList.customContextMenuRequested.connect(lambda :self.showContextMenu(2)) #self.excludeList.customContextMenuRequested[QPoint].connect(self.remove2) # []里的代表传入的参数,自带的 self.delPath1.clicked.connect(self.includeList.clear) self.delPath2.clicked.connect(self.excludeList.clear) self.addPath1.clicked.connect(lambda :self.ShowDialog(1)) self.addPath2.clicked.connect(self.AddExpath) self.fileselect = fileselect.Ui_Dialog() #初始化page self.listWidget.currentRowChanged.connect(self.display) #Library的初始化 self.initLibraryWindow() self.Llist.setSelectionMode(3) self.llist.setSelectionMode(3) #self.add2.clidken.connect(self.ShowLWindow) #状态栏的部件 self.barlabel = QLabel('barlabel') #self.initDialog() #self.fileselect.buttonBox #print(self.fileselect.treeWidget.currentItem().text(0)) def initUI(self): self.includeList.clear() self.excludeList.clear() self.Llist.clear() self.llist.clear() self.ProjectName.setText(self.DebugName) self.HithTecDir.setText(self.HighTecDir) self.GCCFLAGName.setText(self.CCFLAG) self.LINKFLAGName.setText(self.LINKFLAG) self.ProjectName_2.setText(self.PROJECTDIR) self.ProjectName_2.setEnabled(False) self.barlabel.setText('准备中') self.statusBar.addPermanentWidget(self.barlabel) self.Result.clear() if self.includepath: #a=1 self.includeList.addItems(self.includepath) if self.excludefiles: #a=1 self.excludeList.addItems(self.excludefiles) if self.LibraryPath: #a=1 self.Llist.addItems(self.LibraryPath) if self.libraties: #a=1 self.llist.addItems(self.libraties) def display(self,index): self.index=index self.stackedWidget.setCurrentIndex(index) def initLibraryWindow(self): self.LWUI=AddLibraryPath.Ui_LSelect() self.LWin=QWidget() self.LWin.setWindowModality(Qt.ApplicationModal)#设置模态对话框 self.LWUI.setupUi(self.LWin) self.LWUI.LibraryP.setText("") self.add1.clicked.connect(self.LWin.show) self.LWUI.L_Cancel.clicked.connect(self.LWin.close) self.LWUI.L_Workspace.clicked.connect(lambda: self.ShowDialog(1)) self.LWUI.L_OK.clicked.connect(self.AddLibraryPath) self.del1.clicked.connect(self.DelLibraryPath) self.lWUI = Enterlibraries.Ui_LSelect() self.lWin = QWidget() self.lWin.setWindowModality(Qt.ApplicationModal) self.lWUI.setupUi(self.lWin) self.LWUI.LibraryP.setText("") self.add2.clicked.connect(self.lWin.show) self.lWUI.l_OK.clicked.connect(self.AddLibraries) self.lWUI.l_Cancel.clicked.connect(self.lWin.close) self.del2.clicked.connect(self.DelLibraries) def KillProcess(self): #self.process.kill() #self.process.pid os.system(r"taskkill /f /t /im make.exe") self.Result.append('用户终止执行') def ChooseProDir(self): dir=QFileDialog.getExistingDirectory() dir=dir.replace('/','\\') self.ProjectName_2.setText(dir) if dir!='': os.chdir(dir) import automake_config as ac (DebugName, HighTecDir, CCFLAG, LINKFLAG, includepath, excludefiles, g_except_dir_list, g_except_file_list,LibraryPath,libraties) = ac.maininit() self.includepath=includepath self.excludefiles=excludefiles self.DebugName=DebugName self.CCFLAG=CCFLAG self.LINKFLAG=LINKFLAG self.HighTecDir=HighTecDir self.PROJECTDIR=dir self.LibraryPath=LibraryPath self.libraties=libraties #print(os.getcwd()) self.AllPath=ac.FindAllPath(dir) #print(self.AllPath) self.initDialog() #对Dialog按钮的设置 self.fileselect.buttonBox.accepted.connect(self.GetPath) self.fileselect.treeWidget.setSelectionMode(3) self.fileselect.buttonBox.rejected.connect(self.Cleartree) #self.adds(dir,self.child0) a.initUI() def initDialog(self): self.di = QDialog() fileselect1 = self.fileselect fileselect1.setupUi(self.di) # self.di.show() child0 = QTreeWidgetItem(fileselect1.treeWidget) child0.setText(0, self.DebugName) child0.setIcon(0, QIcon('./Compile/01.png')) self.adds(os.getcwd(), child0) child1 = QTreeWidgetItem(child0) child1.setText(0, 'TOOLS') child1.setIcon(0, QIcon('./Compile/01.png')) #展开所有节点 fileselect1.treeWidget.expandAll() def showContextMenu(self,id): # 如果有选中项,则显示显示菜单 #if id==1: items1 = self.includeList.selectedIndexes() #self.idRm=id #print(items) #elif id==2: items2 = self.excludeList.selectedIndexes() #self.idRm = id if items1 or items2: self.contextMenu.show() #self.f=QPoint self.contextMenu.exec_(QCursor.pos()) # 在鼠标位置显示 def remove(self): items1 = self.includeList.selectedIndexes() items2 = self.excludeList.selectedIndexes() if self.index==3: if items1: for jj in items1: self.includeList.removeItemWidget(self.includeList.takeItem(jj.row())) if self.index == 4: if items2: for jj in items2: self.excludeList.removeItemWidget(self.excludeList.takeItem(jj.row())) def EndResult(self): print(os.getcwd()) f=open('./conerr.err','r') lines=f.readlines() j=0 for ii in lines: if "error:"in ii: self.Result.append("<font color=\"#FF0000\">%s</font> "%ii) j=1 if j!=1: self.Result.append("<font color=\"#FF0000\">finished!!!!!!!!</font> ") self.barlabel.setText('已完成') f.close() os.remove('./conerr.err') self.backend.working=False self.statusBar.removeWidget(self.progressBar) self.barlabel.setText('准备中') os.chdir(self.ProjectName_2.text()) def initBar(self): global NUM self.progressBar = QProgressBar() self.Result.clear() self.barlabel.setText('正在编译:') self.statusBar.addPermanentWidget(self.progressBar, stretch=2) f = open('./Default/Default.objectlist','r') lines = f.readlines() f.close() NUM=len(lines) #self.progressBar.setGeometry(0,0,100,5) self.progressBar.setRange(0,len(lines)) global VAL VAL=0 def SetProgressBarVal(self,val): #global VAL n=VAL+val self.progressBar.setValue(n) def StartCompile(self,Hdir): global cmd1 #cmd1 = r'''%s\bin\make -j8 all >console.log 2>&1''' % Hdir cmd1 = r'''%s\bin\make -j8 all''' % Hdir #cmd1 = self.startpath+'\Compile\compile.bat '+Hdir # cmd1='cd ..' # print(includepath) # self.process =subprocess.Popen(self.startpath+ '\Compile\compile.bat ' + cmd1) os.chdir(self.ProjectName_2.text() + '/Default') #f=open('ccccc.txt','w') #self.process = subprocess.Popen(cmd1) self.backend1 = BackendTread1() self.backend1.startcompile1.connect(self.PrintConsole) self.backend1.endSig.connect(self.EndResult) #time.sleep(3) self.backend1.start() self.backend = BackendTread() self.backend.setvalue.connect(self.SetProgressBarVal) #self.backend.endSig.connect(self.EndResult) # time.sleep(3) self.backend.start() '''self.process = subprocess.call(cmd1) self.process.wait() f= open('console.log','r') lines =f.readlines() for ii in lines: if 'error:'in ii: self.Result.insertText(ii+'\n')''' #os.chdir(self.ProjectName_2.text()) def PrintConsole(self,r): #print(2222) # None表示正在执行中 #r = self.process.stdout.readline() #self.Result.append(r) self.Result.append("<font color=\"#000000\">%s</font> "%r) #self.backend.stopSig() # 可修改输出方式,比如控制台、文件等 #print(self.process.poll()) # 重定向错误输出 def checkFLAG(self): CCFLAG1 = self.GCCFLAGName.toPlainText() #CCFLAG1 = CCFLAG1[0:len(CCFLAG1) - 1] LINKFLAG1 = self.LINKFLAGName.toPlainText() #LINKFLAG1 = LINKFLAG1[0:len(LINKFLAG1) - 1] Hdir = self.HithTecDir.text() DebugName1 = self.ProjectName.text() inn=self.includeList.count() inpath=[] exn = self.excludeList.count() expath = [] for i in range(inn): inpath.append(self.includeList.item(i).text()) for i in range(exn): expath.append(self.excludeList.item(i).text()) #print(CCFLAG1) # POSTBUILD1 = pb.get() # Hdir = Hdir[0:len(Hdir) - 1] #if CCFLAG1 != self.CCFLAG or self.LINKFLAG != LINKFLAG1 or Hdir != self.HighTecDir or DebugName1 != self.DebugName or expath != self.excludefiles or inpath != self.includepath: self.modifyFLAG() '''for i in range(0,len(CCFALG)): if CCFALG1[i]!=CCFALG[i]: print(i)''' cmd=self.startpath+'\Compile\python '+self.startpath+"\Compile/automake.py "+self.startpath a=subprocess.call(cmd) self.initBar() #a.wait() #cmd1 = Hdir + r'\bin\make' #self.backend.update_date.connect(self.handleDisplay) try: self.StartCompile(Hdir) except BaseException as e: print(333333) f=open('cons.log','w') f.write(e.args) f.close() #def def modifyFLAG(self): # f=open('./TOOLS/Compile/automake_config.py','r',encoding='utf-8') CCFLAGNOW = self.GCCFLAGName.toPlainText() # CCFLAG1 = CCFLAG1[0:len(CCFLAG1) - 1] LINKFLAGNOW = self.LINKFLAGName.toPlainText() # LINKFLAG1 = LINKFLAG1[0:len(LINKFLAG1) - 1] HighTecDirNOW = self.HithTecDir.text() DebugNameNOW = self.ProjectName.text() inn = self.includeList.count() inpathNOW = [] exn = self.excludeList.count() expathNOW = [] Ln = self.Llist.count() LnNOW = [] ln = self.llist.count() lnNOW = [] try: for i in range(inn): inpathNOW.append(self.includeList.item(i).text()) for i in range(exn): expathNOW.append(self.excludeList.item(i).text()) f = open('./py.pyconfig', 'w', encoding='utf-8') # lines=f.readlines() tLink = re.split(' ',LINKFLAGNOW) Linkchange='' for iii in tLink: if '-L' not in iii and '-l:' not in iii: Linkchange+=iii+' ' for i in range(Ln): p = re.split('{workspace}/',self.Llist.item(i).text()) #print(p) if len(p)==1: Linkchange+='''-L"'''+os.path.abspath(p[0])+'''" ''' else: Linkchange += '''-L"''' + os.path.abspath(p[1]) + '''" ''' LnNOW.append(self.Llist.item(i).text()) for i in range(ln): Linkchange+='-l'+self.llist.item(i).text()+' ' lnNOW.append(self.llist.item(i).text()) f.write('CCFLAG=' + CCFLAGNOW + "\n") f.write('LINKFLAG=' + Linkchange + "\n") f.write('HighTecDir=' + HighTecDirNOW + "\n") f.write('DebugName=' + DebugNameNOW + "\n") aa = "includepath=" for a in inpathNOW: if a != "": aa += a + ',' f.write(aa + '\n') bb = "excludefiles=" for b in expathNOW: if b != "": bb += b + ',' f.write(bb + '\n') cc = "LibraryPath=" for c in LnNOW: if c != "": cc += c + ',' dd = "libraties=" for d in lnNOW: if d != "": dd += d + ',' f.write(cc + '\n') f.write(dd + '\n') f.close() self.LINKFLAGName.setText('') self.LINKFLAGName.setText(Linkchange) except: f.close() def CleanProject(self): print('Cleanning project...... ') if os.path.exists('./Default'): shutil.rmtree('./Default') if os.path.exists('./delivery'): shutil.rmtree('./delivery') QMessageBox.about(self, "消息", "Clean has finished!") #tkinter.messagebox.showinfo('提示','Clean has finished!') print('Clean has finished!') def testaa(self): print("1") def CloseTools(self): print(1) def delPath(self,id): if id==1: self.includeList.clear() if id == 2: self.excludeList.clear() def ShowDialog(self,id): #self.di=QDialog() #fileselect1 = fileselect.Ui_Dialog() #fileselect1.setupUi(self.di) self.idPath=id self.di.exec() # for path,dir,files in os.walk(os.getcwd()): # for file in files: # i=i+1 # if file.endswith('.h') and "TOOLS" not in path: # if "TOOLS" not in path: # a='child'+str(i) # a=QTreeWidgetItem(child0) def adds(self,paths, root): if os.path.isdir(paths): list = os.listdir(paths) for i in list: # j=0 # for path1 ,dirs,files in os.walk(os.path.join(paths,i)): # for file in files: # if file.endswith('.h') or file.endswith('.c'): # j=1 if 'Default' not in i and '.' not in i and '_pycache_' not in os.path.join(paths,i) and os.path.join( paths, i) in self.AllPath: # self.adds(os.path.join(paths, i),root) if os.path.isdir(os.path.join(paths, i)): childs = QTreeWidgetItem(root) childs.setText(0, i) childs.setIcon(0, QIcon('./Compile/01.png')) self.adds(os.path.join(paths, i), childs) #注意:是对QDialog对象show(),并不是自己生成的Ui_Dialog对象 show(),开始没有写self.di,弹窗总是一闪而过,类的的函数加上self之后成功 #print(QFileDialog.getExistingDirectory(None, "请选择要添加的文件", os.getcwd())) def GetPath(self): if self.index==3: pathlist = self.fileselect.treeWidget.selectedItems() # pathlist = QTreeWidgetItemIterator(self.fileselect.treeWidget) # print(pathlist.value().childCount()) tempinclude = [] for pathss in pathlist: tpathss = pathss tp = "" while 1: if tpathss.text(0)!=self.DebugName: tp = tpathss.text(0) + tp if tpathss.parent(): tpathss = tpathss.parent() tp = '/' + tp else: break if tp not in tempinclude and tp!="": tempinclude.append(tp) pathss.setSelected(False) self.includeList.addItems(sorted(tempinclude)) elif self.idPath==2: pathlist = self.fileselect.treeWidget.selectedItems() #pathlist = QTreeWidgetItemIterator(self.fileselect.treeWidget) #print(pathlist.value().childCount()) tempexclude=[] for pathss in pathlist: tpathss=pathss tp="" while 1: if tpathss.text(0) != self.DebugName: tp = tpathss.text(0)+tp if tpathss.parent(): tpathss=tpathss.parent() tp='/'+tp else: break if tp not in tempexclude and tp!="": tempexclude.append(tp) self.excludeList.addItems(sorted(tempexclude)) elif self.index==2: pathlist = self.fileselect.treeWidget.selectedItems() # pathlist = QTreeWidgetItemIterator(self.fileselect.treeWidget) # print(pathlist.value().childCount()) tempexclude = [] for pathss in pathlist: tpathss = pathss tp = "" while 1: if tpathss.text(0) != self.DebugName: tp = tpathss.text(0) + tp if tpathss.parent(): tpathss = tpathss.parent() tp = '/' + tp else: break if tp not in tempexclude and tp != "": tempexclude.append("{workspace}"+tp) pathss.setSelected(False) self.Llist.addItems(tempexclude) self.LWin.close()#如果是通过workspace选的直接关掉选择框 self.di.close() '''for selectedPath in pathlist: print(selectedPath.text(0)) print(pathlist)''' #if pathlist.value().checkState(0) == Qt.Checked: #n=self.fileselect.treeWidget.topLevelItemCount() '''while pathlist.value(): if pathlist.value().checkState(0)==Qt.Checked: print(pathlist.value.text(0)) break''' def Cleartree(self): pathlist = self.fileselect.treeWidget.selectedItems() for pathss in pathlist: pathss.setSelected(False) self.di.close() def AddExpath(self): dir1,file1 = QFileDialog.getOpenFileNames (self,'选择过滤文件',os.getcwd(),"C FILES(*.c)") #print(dir1,file1) for ii in dir1: if ii!='' : dir2 = re.split(os.getcwd().replace('\\','/'),ii)[1] self.excludeList.addItem(dir2) #Library的具体操作 def AddLibraryPath(self): txt=self.LWUI.LibraryP.text() if txt: self.Llist.addItem(txt) self.LWin.close() def AddLibraries(self): txt = self.lWUI.libraries.text() if txt: self.llist.addItem(txt) self.lWin.close() def DelLibraryPath(self): items1 = self.Llist.selectedIndexes() if items1: for jj in items1: self.Llist.removeItemWidget(self.Llist.takeItem(jj.row())) def DelLibraries(self): items1 = self.llist.selectedIndexes() if items1: for jj in items1: self.llist.removeItemWidget(self.llist.takeItem(jj.row())) if __name__ == '__main__': cmd1 = "" NUM=0 VAL=0 app = QApplication(sys.argv) app.setWindowIcon(QIcon('./Compile/mainwindowIcon.png')) a=basePage() a.ChooseProDir() a.show() #进入程序的主循环,并通过exit函数确保主循环安全结束 sys.exit(app.exec_())
[ "# -*- coding: utf-8 -*-\n\n#\tauthor:\tGuixinyu\n#\tcreate Time: 2019-10-17 18:15:39\n\nfrom PyQt5.QtWidgets import *\nimport sys\nimport first\nimport fileselect\nimport shutil\n\nfrom first import Ui_MainWindow\nimport AddLibraryPath\nimport Enterlibraries\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nimport os\nimport re\nimport subprocess\nimport time\n#读取log的线程\nclass BackendTread(QThread):\n setvalue = pyqtSignal(int)\n def __init__(self, parent=None):\n super(BackendTread, self).__init__(parent)\n self.working=True\n def stopSig(self):\n self.working=False\n def run(self):\n #cmd1 = r'''%s\\bin\\make -j8 all >console.log 2>&1''' % Hdir\n '''os.chdir(self.ProjectName_2.text() + '/Default')\n self.process = subprocess.call(cmd1)'''\n while VAL<NUM and self.working:\n num=0\n for path,dir,files in os.walk(os.getcwd()):\n for file in files:\n if file.endswith('.o'):\n num=num+1\n self.setvalue.emit(num)\n\n\n#开编译的线程\nclass BackendTread1(QThread):\n startcompile1 = pyqtSignal(str)\n endSig = pyqtSignal()\n def __init__(self, parent=None):\n super(BackendTread1, self).__init__(parent)\n\n def startCom(self):\n self.process = subprocess.Popen(cmd1)\n\n def run(self):\n #cmd1 = r'''%s\\bin\\make -j8 all >console.log 2>&1''' % Hdir\n '''os.chdir(self.ProjectName_2.text() + '/Default')\n self.process = subprocess.call(cmd1)'''\n f=open('conerr.err','w+')\n\n self.process = subprocess.Popen(cmd1,stdout=subprocess.PIPE,stderr=f,bufsize=1)\n\n '''self.bt=BackendTread()\n self.bt.startcompile.connect(self.PrintConsole)\n self.bt.start()'''\n self.sleep(3)\n\n while self.process.poll() is None:\n #print(1)\n r = self.process.stdout.readline().decode('gbk')\n if r:\n self.startcompile1.emit(r)\n if 'tool>pause'in r:\n break\n os.system(r\"taskkill /f /t /im make.exe\")#因为在做post-build的时候,al2的工具需要按回车键才能结束进程,因为在这里强制性的使其结束\n self.endSig.emit()\n\n\nclass basePage(QMainWindow,Ui_MainWindow):\n def __init__(self):\n super(basePage, self).__init__()\n self.setupUi(self)\n\n self.startpath=os.getcwd()\n self.actionbuild.triggered.connect(self.checkFLAG)\n #self.menuclean.triggered.connect(self.CleanProject)\n self.actionclean.triggered.connect(self.CleanProject)\n self.actionopen_project.triggered.connect(self.ChooseProDir)\n self.actionsave_project.triggered.connect(self.modifyFLAG)\n\n #self.quitApp.triggered.connect(QCoreApplication.instance().quit) #关闭程序的第一种方式\n self.actionexit.triggered.connect(qApp.quit)#关闭程序的第二种方式\n\n\n\n #添加工具栏:停止和退出\n self.tb1=self.addToolBar('tool')\n actionopen1=QAction(QIcon('./Compile/file.png'),\"打开工程\",self)\n self.tb1.addAction(actionopen1)\n actionopen1.triggered.connect(self.ChooseProDir)\n self.tb1.addSeparator()\n actionstop=QAction(QIcon('./Compile/stop.png'),\"停止\",self)\n self.tb1.addAction(actionstop)\n actionstop.triggered.connect(self.KillProcess)\n self.tb1.addSeparator()\n actionExit=QAction(QIcon('./Compile/exit.png'),\"退出\",self)\n self.tb1.addAction(actionExit)\n actionExit.triggered.connect(qApp.quit)\n ##创建右键菜单\n #self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n #self.includeList.customContextMenuRequested.connect(self.showRightMenu)\n #self.includeList.customContextMenuRequested[QPoint].connect(self.remove)\n #单击一个选项\n #self.f=\"\"\n #self.includeList.clicked.connect(self.check)\n self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.contextMenu=QMenu(self)\n\n\n self.actionA=self.contextMenu.addAction(\"删除\")\n self.actionA.triggered.connect(self.remove)\n\n self.includeList.customContextMenuRequested.connect(lambda :self.showContextMenu(1))\n\n #self.contextMenu.triggered[QAction].connect(self.remove)\n #self.includeList.customContextMenuRequested[QPoint].connect(self.remove1)#[]里的代表传入的参数,自带的\n\n\n self.excludeList.customContextMenuRequested.connect(lambda :self.showContextMenu(2))\n #self.excludeList.customContextMenuRequested[QPoint].connect(self.remove2) # []里的代表传入的参数,自带的\n\n\n\n self.delPath1.clicked.connect(self.includeList.clear)\n self.delPath2.clicked.connect(self.excludeList.clear)\n\n\n self.addPath1.clicked.connect(lambda :self.ShowDialog(1))\n self.addPath2.clicked.connect(self.AddExpath)\n\n\n self.fileselect = fileselect.Ui_Dialog()\n\n #初始化page\n\n self.listWidget.currentRowChanged.connect(self.display)\n\n #Library的初始化\n self.initLibraryWindow()\n self.Llist.setSelectionMode(3)\n self.llist.setSelectionMode(3)\n #self.add2.clidken.connect(self.ShowLWindow)\n #状态栏的部件\n self.barlabel = QLabel('barlabel')\n #self.initDialog()\n\n #self.fileselect.buttonBox\n #print(self.fileselect.treeWidget.currentItem().text(0))\n def initUI(self):\n self.includeList.clear()\n self.excludeList.clear()\n self.Llist.clear()\n self.llist.clear()\n self.ProjectName.setText(self.DebugName)\n self.HithTecDir.setText(self.HighTecDir)\n self.GCCFLAGName.setText(self.CCFLAG)\n self.LINKFLAGName.setText(self.LINKFLAG)\n self.ProjectName_2.setText(self.PROJECTDIR)\n self.ProjectName_2.setEnabled(False)\n\n self.barlabel.setText('准备中')\n self.statusBar.addPermanentWidget(self.barlabel)\n self.Result.clear()\n\n if self.includepath:\n #a=1\n self.includeList.addItems(self.includepath)\n\n if self.excludefiles:\n #a=1\n self.excludeList.addItems(self.excludefiles)\n\n if self.LibraryPath:\n #a=1\n self.Llist.addItems(self.LibraryPath)\n if self.libraties:\n #a=1\n self.llist.addItems(self.libraties)\n\n def display(self,index):\n self.index=index\n self.stackedWidget.setCurrentIndex(index)\n\n\n def initLibraryWindow(self):\n self.LWUI=AddLibraryPath.Ui_LSelect()\n self.LWin=QWidget()\n self.LWin.setWindowModality(Qt.ApplicationModal)#设置模态对话框\n self.LWUI.setupUi(self.LWin)\n self.LWUI.LibraryP.setText(\"\")\n self.add1.clicked.connect(self.LWin.show)\n self.LWUI.L_Cancel.clicked.connect(self.LWin.close)\n self.LWUI.L_Workspace.clicked.connect(lambda: self.ShowDialog(1))\n self.LWUI.L_OK.clicked.connect(self.AddLibraryPath)\n self.del1.clicked.connect(self.DelLibraryPath)\n\n\n self.lWUI = Enterlibraries.Ui_LSelect()\n self.lWin = QWidget()\n self.lWin.setWindowModality(Qt.ApplicationModal)\n self.lWUI.setupUi(self.lWin)\n self.LWUI.LibraryP.setText(\"\")\n self.add2.clicked.connect(self.lWin.show)\n self.lWUI.l_OK.clicked.connect(self.AddLibraries)\n self.lWUI.l_Cancel.clicked.connect(self.lWin.close)\n self.del2.clicked.connect(self.DelLibraries)\n\n\n\n\n\n def KillProcess(self):\n #self.process.kill()\n\n #self.process.pid\n os.system(r\"taskkill /f /t /im make.exe\")\n\n self.Result.append('用户终止执行')\n\n\n def ChooseProDir(self):\n dir=QFileDialog.getExistingDirectory()\n dir=dir.replace('/','\\\\')\n self.ProjectName_2.setText(dir)\n\n if dir!='':\n os.chdir(dir)\n\n import automake_config as ac\n (DebugName, HighTecDir, CCFLAG, LINKFLAG, includepath, excludefiles, g_except_dir_list,\n g_except_file_list,LibraryPath,libraties) = ac.maininit()\n self.includepath=includepath\n self.excludefiles=excludefiles\n self.DebugName=DebugName\n self.CCFLAG=CCFLAG\n self.LINKFLAG=LINKFLAG\n self.HighTecDir=HighTecDir\n self.PROJECTDIR=dir\n self.LibraryPath=LibraryPath\n self.libraties=libraties\n #print(os.getcwd())\n self.AllPath=ac.FindAllPath(dir)\n #print(self.AllPath)\n self.initDialog()\n #对Dialog按钮的设置\n self.fileselect.buttonBox.accepted.connect(self.GetPath)\n self.fileselect.treeWidget.setSelectionMode(3)\n self.fileselect.buttonBox.rejected.connect(self.Cleartree)\n\n #self.adds(dir,self.child0)\n a.initUI()\n\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n # self.di.show()\n\n\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n\n #展开所有节点\n fileselect1.treeWidget.expandAll()\n def showContextMenu(self,id):\n # 如果有选中项,则显示显示菜单\n\n #if id==1:\n items1 = self.includeList.selectedIndexes()\n\n #self.idRm=id\n #print(items)\n #elif id==2:\n items2 = self.excludeList.selectedIndexes()\n\n #self.idRm = id\n\n if items1 or items2:\n\n self.contextMenu.show()\n #self.f=QPoint\n self.contextMenu.exec_(QCursor.pos()) # 在鼠标位置显示\n\n def remove(self):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if self.index==3:\n if items1:\n for jj in items1:\n self.includeList.removeItemWidget(self.includeList.takeItem(jj.row()))\n if self.index == 4:\n if items2:\n for jj in items2:\n\n self.excludeList.removeItemWidget(self.excludeList.takeItem(jj.row()))\n\n\n\n\n def EndResult(self):\n print(os.getcwd())\n f=open('./conerr.err','r')\n lines=f.readlines()\n j=0\n for ii in lines:\n if \"error:\"in ii:\n self.Result.append(\"<font color=\\\"#FF0000\\\">%s</font> \"%ii)\n j=1\n if j!=1:\n self.Result.append(\"<font color=\\\"#FF0000\\\">finished!!!!!!!!</font> \")\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working=False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n\n\n\n\n\n def initBar(self):\n global NUM\n self.progressBar = QProgressBar()\n self.Result.clear()\n self.barlabel.setText('正在编译:')\n self.statusBar.addPermanentWidget(self.progressBar, stretch=2)\n f = open('./Default/Default.objectlist','r')\n lines = f.readlines()\n f.close()\n NUM=len(lines)\n #self.progressBar.setGeometry(0,0,100,5)\n self.progressBar.setRange(0,len(lines))\n global VAL\n VAL=0\n\n\n def SetProgressBarVal(self,val):\n #global VAL\n\n n=VAL+val\n self.progressBar.setValue(n)\n def StartCompile(self,Hdir):\n\n\n global cmd1\n #cmd1 = r'''%s\\bin\\make -j8 all >console.log 2>&1''' % Hdir\n cmd1 = r'''%s\\bin\\make -j8 all''' % Hdir\n #cmd1 = self.startpath+'\\Compile\\compile.bat '+Hdir\n # cmd1='cd ..'\n # print(includepath)\n # self.process =subprocess.Popen(self.startpath+ '\\Compile\\compile.bat ' + cmd1)\n\n os.chdir(self.ProjectName_2.text() + '/Default')\n #f=open('ccccc.txt','w')\n #self.process = subprocess.Popen(cmd1)\n\n\n self.backend1 = BackendTread1()\n self.backend1.startcompile1.connect(self.PrintConsole)\n self.backend1.endSig.connect(self.EndResult)\n #time.sleep(3)\n self.backend1.start()\n self.backend = BackendTread()\n self.backend.setvalue.connect(self.SetProgressBarVal)\n #self.backend.endSig.connect(self.EndResult)\n # time.sleep(3)\n\n self.backend.start()\n\n\n\n '''self.process = subprocess.call(cmd1)\n self.process.wait()\n f= open('console.log','r')\n lines =f.readlines()\n for ii in lines:\n if 'error:'in ii:\n self.Result.insertText(ii+'\\n')'''\n #os.chdir(self.ProjectName_2.text())\n\n\n def PrintConsole(self,r):\n #print(2222)\n # None表示正在执行中\n #r = self.process.stdout.readline()\n #self.Result.append(r)\n self.Result.append(\"<font color=\\\"#000000\\\">%s</font> \"%r)\n #self.backend.stopSig()\n # 可修改输出方式,比如控制台、文件等\n\n #print(self.process.poll())\n\n # 重定向错误输出\n\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n #CCFLAG1 = CCFLAG1[0:len(CCFLAG1) - 1]\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n #LINKFLAG1 = LINKFLAG1[0:len(LINKFLAG1) - 1]\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n\n inn=self.includeList.count()\n inpath=[]\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n\n #print(CCFLAG1)\n # POSTBUILD1 = pb.get()\n # Hdir = Hdir[0:len(Hdir) - 1]\n #if CCFLAG1 != self.CCFLAG or self.LINKFLAG != LINKFLAG1 or Hdir != self.HighTecDir or DebugName1 != self.DebugName or expath != self.excludefiles or inpath != self.includepath:\n self.modifyFLAG()\n '''for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)'''\n cmd=self.startpath+'\\Compile\\python '+self.startpath+\"\\Compile/automake.py \"+self.startpath\n a=subprocess.call(cmd)\n self.initBar()\n #a.wait()\n #cmd1 = Hdir + r'\\bin\\make'\n\n #self.backend.update_date.connect(self.handleDisplay)\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f=open('cons.log','w')\n f.write(e.args)\n f.close()\n #def\n\n\n def modifyFLAG(self):\n # f=open('./TOOLS/Compile/automake_config.py','r',encoding='utf-8')\n CCFLAGNOW = self.GCCFLAGName.toPlainText()\n # CCFLAG1 = CCFLAG1[0:len(CCFLAG1) - 1]\n LINKFLAGNOW = self.LINKFLAGName.toPlainText()\n # LINKFLAG1 = LINKFLAG1[0:len(LINKFLAG1) - 1]\n HighTecDirNOW = self.HithTecDir.text()\n DebugNameNOW = self.ProjectName.text()\n\n inn = self.includeList.count()\n inpathNOW = []\n exn = self.excludeList.count()\n expathNOW = []\n Ln = self.Llist.count()\n LnNOW = []\n ln = self.llist.count()\n lnNOW = []\n try:\n for i in range(inn):\n inpathNOW.append(self.includeList.item(i).text())\n for i in range(exn):\n expathNOW.append(self.excludeList.item(i).text())\n f = open('./py.pyconfig', 'w', encoding='utf-8')\n # lines=f.readlines()\n tLink = re.split(' ',LINKFLAGNOW)\n Linkchange=''\n for iii in tLink:\n if '-L' not in iii and '-l:' not in iii:\n Linkchange+=iii+' '\n\n for i in range(Ln):\n p = re.split('{workspace}/',self.Llist.item(i).text())\n #print(p)\n if len(p)==1:\n Linkchange+='''-L\"'''+os.path.abspath(p[0])+'''\" '''\n else:\n Linkchange += '''-L\"''' + os.path.abspath(p[1]) + '''\" '''\n LnNOW.append(self.Llist.item(i).text())\n for i in range(ln):\n Linkchange+='-l'+self.llist.item(i).text()+' '\n lnNOW.append(self.llist.item(i).text())\n\n\n f.write('CCFLAG=' + CCFLAGNOW + \"\\n\")\n f.write('LINKFLAG=' + Linkchange + \"\\n\")\n f.write('HighTecDir=' + HighTecDirNOW + \"\\n\")\n f.write('DebugName=' + DebugNameNOW + \"\\n\")\n aa = \"includepath=\"\n for a in inpathNOW:\n if a != \"\":\n aa += a + ','\n f.write(aa + '\\n')\n bb = \"excludefiles=\"\n for b in expathNOW:\n if b != \"\":\n bb += b + ','\n f.write(bb + '\\n')\n cc = \"LibraryPath=\"\n for c in LnNOW:\n if c != \"\":\n cc += c + ','\n dd = \"libraties=\"\n for d in lnNOW:\n if d != \"\":\n dd += d + ','\n f.write(cc + '\\n')\n f.write(dd + '\\n')\n f.close()\n self.LINKFLAGName.setText('')\n self.LINKFLAGName.setText(Linkchange)\n except:\n f.close()\n\n\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, \"消息\", \"Clean has finished!\")\n #tkinter.messagebox.showinfo('提示','Clean has finished!')\n print('Clean has finished!')\n\n def testaa(self):\n print(\"1\")\n\n\n def CloseTools(self):\n print(1)\n def delPath(self,id):\n if id==1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n\n\n def ShowDialog(self,id):\n #self.di=QDialog()\n #fileselect1 = fileselect.Ui_Dialog()\n #fileselect1.setupUi(self.di)\n self.idPath=id\n self.di.exec()\n\n\n\n # for path,dir,files in os.walk(os.getcwd()):\n # for file in files:\n # i=i+1\n # if file.endswith('.h') and \"TOOLS\" not in path:\n # if \"TOOLS\" not in path:\n # a='child'+str(i)\n # a=QTreeWidgetItem(child0)\n\n def adds(self,paths, root):\n\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n # j=0\n # for path1 ,dirs,files in os.walk(os.path.join(paths,i)):\n # for file in files:\n # if file.endswith('.h') or file.endswith('.c'):\n # j=1\n\n if 'Default' not in i and '.' not in i and '_pycache_' not in os.path.join(paths,i) and os.path.join(\n paths, i) in self.AllPath:\n # self.adds(os.path.join(paths, i),root)\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n\n\n\n\n #注意:是对QDialog对象show(),并不是自己生成的Ui_Dialog对象 show(),开始没有写self.di,弹窗总是一闪而过,类的的函数加上self之后成功\n #print(QFileDialog.getExistingDirectory(None, \"请选择要添加的文件\", os.getcwd()))\n def GetPath(self):\n if self.index==3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n # pathlist = QTreeWidgetItemIterator(self.fileselect.treeWidget)\n # print(pathlist.value().childCount())\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = \"\"\n while 1:\n if tpathss.text(0)!=self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp!=\"\":\n tempinclude.append(tp)\n pathss.setSelected(False)\n\n\n self.includeList.addItems(sorted(tempinclude))\n\n\n\n elif self.idPath==2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n #pathlist = QTreeWidgetItemIterator(self.fileselect.treeWidget)\n #print(pathlist.value().childCount())\n tempexclude=[]\n for pathss in pathlist:\n tpathss=pathss\n tp=\"\"\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0)+tp\n if tpathss.parent():\n tpathss=tpathss.parent()\n tp='/'+tp\n else:\n break\n if tp not in tempexclude and tp!=\"\":\n tempexclude.append(tp)\n\n self.excludeList.addItems(sorted(tempexclude))\n\n\n elif self.index==2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n # pathlist = QTreeWidgetItemIterator(self.fileselect.treeWidget)\n # print(pathlist.value().childCount())\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = \"\"\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != \"\":\n tempexclude.append(\"{workspace}\"+tp)\n pathss.setSelected(False)\n\n\n self.Llist.addItems(tempexclude)\n self.LWin.close()#如果是通过workspace选的直接关掉选择框\n\n\n\n\n self.di.close()\n '''for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)'''\n #if pathlist.value().checkState(0) == Qt.Checked:\n\n\n #n=self.fileselect.treeWidget.topLevelItemCount()\n\n\n\n '''while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break'''\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n\n def AddExpath(self):\n dir1,file1 = QFileDialog.getOpenFileNames (self,'选择过滤文件',os.getcwd(),\"C FILES(*.c)\")\n #print(dir1,file1)\n for ii in dir1:\n if ii!='' :\n dir2 = re.split(os.getcwd().replace('\\\\','/'),ii)[1]\n self.excludeList.addItem(dir2)\n\n #Library的具体操作\n def AddLibraryPath(self):\n txt=self.LWUI.LibraryP.text()\n if txt:\n self.Llist.addItem(txt)\n self.LWin.close()\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n def DelLibraryPath(self):\n items1 = self.Llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.Llist.removeItemWidget(self.Llist.takeItem(jj.row()))\n def DelLibraries(self):\n items1 = self.llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.llist.removeItemWidget(self.llist.takeItem(jj.row()))\n\nif __name__ == '__main__':\n cmd1 = \"\"\n NUM=0\n VAL=0\n app = QApplication(sys.argv)\n app.setWindowIcon(QIcon('./Compile/mainwindowIcon.png'))\n\n a=basePage()\n\n a.ChooseProDir()\n\n\n\n a.show()\n\n #进入程序的主循环,并通过exit函数确保主循环安全结束\n sys.exit(app.exec_())", "from PyQt5.QtWidgets import *\nimport sys\nimport first\nimport fileselect\nimport shutil\nfrom first import Ui_MainWindow\nimport AddLibraryPath\nimport Enterlibraries\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nimport os\nimport re\nimport subprocess\nimport time\n\n\nclass BackendTread(QThread):\n setvalue = pyqtSignal(int)\n\n def __init__(self, parent=None):\n super(BackendTread, self).__init__(parent)\n self.working = True\n\n def stopSig(self):\n self.working = False\n\n def run(self):\n \"\"\"os.chdir(self.ProjectName_2.text() + '/Default')\n self.process = subprocess.call(cmd1)\"\"\"\n while VAL < NUM and self.working:\n num = 0\n for path, dir, files in os.walk(os.getcwd()):\n for file in files:\n if file.endswith('.o'):\n num = num + 1\n self.setvalue.emit(num)\n\n\nclass BackendTread1(QThread):\n startcompile1 = pyqtSignal(str)\n endSig = pyqtSignal()\n\n def __init__(self, parent=None):\n super(BackendTread1, self).__init__(parent)\n\n def startCom(self):\n self.process = subprocess.Popen(cmd1)\n\n def run(self):\n \"\"\"os.chdir(self.ProjectName_2.text() + '/Default')\n self.process = subprocess.call(cmd1)\"\"\"\n f = open('conerr.err', 'w+')\n self.process = subprocess.Popen(cmd1, stdout=subprocess.PIPE,\n stderr=f, bufsize=1)\n \"\"\"self.bt=BackendTread()\n self.bt.startcompile.connect(self.PrintConsole)\n self.bt.start()\"\"\"\n self.sleep(3)\n while self.process.poll() is None:\n r = self.process.stdout.readline().decode('gbk')\n if r:\n self.startcompile1.emit(r)\n if 'tool>pause' in r:\n break\n os.system('taskkill /f /t /im make.exe')\n self.endSig.emit()\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n\n def __init__(self):\n super(basePage, self).__init__()\n self.setupUi(self)\n self.startpath = os.getcwd()\n self.actionbuild.triggered.connect(self.checkFLAG)\n self.actionclean.triggered.connect(self.CleanProject)\n self.actionopen_project.triggered.connect(self.ChooseProDir)\n self.actionsave_project.triggered.connect(self.modifyFLAG)\n self.actionexit.triggered.connect(qApp.quit)\n self.tb1 = self.addToolBar('tool')\n actionopen1 = QAction(QIcon('./Compile/file.png'), '打开工程', self)\n self.tb1.addAction(actionopen1)\n actionopen1.triggered.connect(self.ChooseProDir)\n self.tb1.addSeparator()\n actionstop = QAction(QIcon('./Compile/stop.png'), '停止', self)\n self.tb1.addAction(actionstop)\n actionstop.triggered.connect(self.KillProcess)\n self.tb1.addSeparator()\n actionExit = QAction(QIcon('./Compile/exit.png'), '退出', self)\n self.tb1.addAction(actionExit)\n actionExit.triggered.connect(qApp.quit)\n self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.contextMenu = QMenu(self)\n self.actionA = self.contextMenu.addAction('删除')\n self.actionA.triggered.connect(self.remove)\n self.includeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(1))\n self.excludeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(2))\n self.delPath1.clicked.connect(self.includeList.clear)\n self.delPath2.clicked.connect(self.excludeList.clear)\n self.addPath1.clicked.connect(lambda : self.ShowDialog(1))\n self.addPath2.clicked.connect(self.AddExpath)\n self.fileselect = fileselect.Ui_Dialog()\n self.listWidget.currentRowChanged.connect(self.display)\n self.initLibraryWindow()\n self.Llist.setSelectionMode(3)\n self.llist.setSelectionMode(3)\n self.barlabel = QLabel('barlabel')\n\n def initUI(self):\n self.includeList.clear()\n self.excludeList.clear()\n self.Llist.clear()\n self.llist.clear()\n self.ProjectName.setText(self.DebugName)\n self.HithTecDir.setText(self.HighTecDir)\n self.GCCFLAGName.setText(self.CCFLAG)\n self.LINKFLAGName.setText(self.LINKFLAG)\n self.ProjectName_2.setText(self.PROJECTDIR)\n self.ProjectName_2.setEnabled(False)\n self.barlabel.setText('准备中')\n self.statusBar.addPermanentWidget(self.barlabel)\n self.Result.clear()\n if self.includepath:\n self.includeList.addItems(self.includepath)\n if self.excludefiles:\n self.excludeList.addItems(self.excludefiles)\n if self.LibraryPath:\n self.Llist.addItems(self.LibraryPath)\n if self.libraties:\n self.llist.addItems(self.libraties)\n\n def display(self, index):\n self.index = index\n self.stackedWidget.setCurrentIndex(index)\n\n def initLibraryWindow(self):\n self.LWUI = AddLibraryPath.Ui_LSelect()\n self.LWin = QWidget()\n self.LWin.setWindowModality(Qt.ApplicationModal)\n self.LWUI.setupUi(self.LWin)\n self.LWUI.LibraryP.setText('')\n self.add1.clicked.connect(self.LWin.show)\n self.LWUI.L_Cancel.clicked.connect(self.LWin.close)\n self.LWUI.L_Workspace.clicked.connect(lambda : self.ShowDialog(1))\n self.LWUI.L_OK.clicked.connect(self.AddLibraryPath)\n self.del1.clicked.connect(self.DelLibraryPath)\n self.lWUI = Enterlibraries.Ui_LSelect()\n self.lWin = QWidget()\n self.lWin.setWindowModality(Qt.ApplicationModal)\n self.lWUI.setupUi(self.lWin)\n self.LWUI.LibraryP.setText('')\n self.add2.clicked.connect(self.lWin.show)\n self.lWUI.l_OK.clicked.connect(self.AddLibraries)\n self.lWUI.l_Cancel.clicked.connect(self.lWin.close)\n self.del2.clicked.connect(self.DelLibraries)\n\n def KillProcess(self):\n os.system('taskkill /f /t /im make.exe')\n self.Result.append('用户终止执行')\n\n def ChooseProDir(self):\n dir = QFileDialog.getExistingDirectory()\n dir = dir.replace('/', '\\\\')\n self.ProjectName_2.setText(dir)\n if dir != '':\n os.chdir(dir)\n import automake_config as ac\n (DebugName, HighTecDir, CCFLAG, LINKFLAG, includepath,\n excludefiles, g_except_dir_list, g_except_file_list,\n LibraryPath, libraties) = ac.maininit()\n self.includepath = includepath\n self.excludefiles = excludefiles\n self.DebugName = DebugName\n self.CCFLAG = CCFLAG\n self.LINKFLAG = LINKFLAG\n self.HighTecDir = HighTecDir\n self.PROJECTDIR = dir\n self.LibraryPath = LibraryPath\n self.libraties = libraties\n self.AllPath = ac.FindAllPath(dir)\n self.initDialog()\n self.fileselect.buttonBox.accepted.connect(self.GetPath)\n self.fileselect.treeWidget.setSelectionMode(3)\n self.fileselect.buttonBox.rejected.connect(self.Cleartree)\n a.initUI()\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n\n def remove(self):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if self.index == 3:\n if items1:\n for jj in items1:\n self.includeList.removeItemWidget(self.includeList.\n takeItem(jj.row()))\n if self.index == 4:\n if items2:\n for jj in items2:\n self.excludeList.removeItemWidget(self.excludeList.\n takeItem(jj.row()))\n\n def EndResult(self):\n print(os.getcwd())\n f = open('./conerr.err', 'r')\n lines = f.readlines()\n j = 0\n for ii in lines:\n if 'error:' in ii:\n self.Result.append('<font color=\"#FF0000\">%s</font> ' % ii)\n j = 1\n if j != 1:\n self.Result.append('<font color=\"#FF0000\">finished!!!!!!!!</font> '\n )\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working = False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n\n def initBar(self):\n global NUM\n self.progressBar = QProgressBar()\n self.Result.clear()\n self.barlabel.setText('正在编译:')\n self.statusBar.addPermanentWidget(self.progressBar, stretch=2)\n f = open('./Default/Default.objectlist', 'r')\n lines = f.readlines()\n f.close()\n NUM = len(lines)\n self.progressBar.setRange(0, len(lines))\n global VAL\n VAL = 0\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n\n def StartCompile(self, Hdir):\n global cmd1\n cmd1 = '%s\\\\bin\\\\make -j8 all' % Hdir\n os.chdir(self.ProjectName_2.text() + '/Default')\n self.backend1 = BackendTread1()\n self.backend1.startcompile1.connect(self.PrintConsole)\n self.backend1.endSig.connect(self.EndResult)\n self.backend1.start()\n self.backend = BackendTread()\n self.backend.setvalue.connect(self.SetProgressBarVal)\n self.backend.start()\n \"\"\"self.process = subprocess.call(cmd1)\n self.process.wait()\n f= open('console.log','r')\n lines =f.readlines()\n for ii in lines:\n if 'error:'in ii:\n self.Result.insertText(ii+'\n')\"\"\"\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n\n def modifyFLAG(self):\n CCFLAGNOW = self.GCCFLAGName.toPlainText()\n LINKFLAGNOW = self.LINKFLAGName.toPlainText()\n HighTecDirNOW = self.HithTecDir.text()\n DebugNameNOW = self.ProjectName.text()\n inn = self.includeList.count()\n inpathNOW = []\n exn = self.excludeList.count()\n expathNOW = []\n Ln = self.Llist.count()\n LnNOW = []\n ln = self.llist.count()\n lnNOW = []\n try:\n for i in range(inn):\n inpathNOW.append(self.includeList.item(i).text())\n for i in range(exn):\n expathNOW.append(self.excludeList.item(i).text())\n f = open('./py.pyconfig', 'w', encoding='utf-8')\n tLink = re.split(' ', LINKFLAGNOW)\n Linkchange = ''\n for iii in tLink:\n if '-L' not in iii and '-l:' not in iii:\n Linkchange += iii + ' '\n for i in range(Ln):\n p = re.split('{workspace}/', self.Llist.item(i).text())\n if len(p) == 1:\n Linkchange += '-L\"' + os.path.abspath(p[0]) + '\" '\n else:\n Linkchange += '-L\"' + os.path.abspath(p[1]) + '\" '\n LnNOW.append(self.Llist.item(i).text())\n for i in range(ln):\n Linkchange += '-l' + self.llist.item(i).text() + ' '\n lnNOW.append(self.llist.item(i).text())\n f.write('CCFLAG=' + CCFLAGNOW + '\\n')\n f.write('LINKFLAG=' + Linkchange + '\\n')\n f.write('HighTecDir=' + HighTecDirNOW + '\\n')\n f.write('DebugName=' + DebugNameNOW + '\\n')\n aa = 'includepath='\n for a in inpathNOW:\n if a != '':\n aa += a + ','\n f.write(aa + '\\n')\n bb = 'excludefiles='\n for b in expathNOW:\n if b != '':\n bb += b + ','\n f.write(bb + '\\n')\n cc = 'LibraryPath='\n for c in LnNOW:\n if c != '':\n cc += c + ','\n dd = 'libraties='\n for d in lnNOW:\n if d != '':\n dd += d + ','\n f.write(cc + '\\n')\n f.write(dd + '\\n')\n f.close()\n self.LINKFLAGName.setText('')\n self.LINKFLAGName.setText(Linkchange)\n except:\n f.close()\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n\n def testaa(self):\n print('1')\n\n def CloseTools(self):\n print(1)\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n\n def ShowDialog(self, id):\n self.idPath = id\n self.di.exec()\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n\n def AddExpath(self):\n dir1, file1 = QFileDialog.getOpenFileNames(self, '选择过滤文件', os.\n getcwd(), 'C FILES(*.c)')\n for ii in dir1:\n if ii != '':\n dir2 = re.split(os.getcwd().replace('\\\\', '/'), ii)[1]\n self.excludeList.addItem(dir2)\n\n def AddLibraryPath(self):\n txt = self.LWUI.LibraryP.text()\n if txt:\n self.Llist.addItem(txt)\n self.LWin.close()\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n\n def DelLibraryPath(self):\n items1 = self.Llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.Llist.removeItemWidget(self.Llist.takeItem(jj.row()))\n\n def DelLibraries(self):\n items1 = self.llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.llist.removeItemWidget(self.llist.takeItem(jj.row()))\n\n\nif __name__ == '__main__':\n cmd1 = ''\n NUM = 0\n VAL = 0\n app = QApplication(sys.argv)\n app.setWindowIcon(QIcon('./Compile/mainwindowIcon.png'))\n a = basePage()\n a.ChooseProDir()\n a.show()\n sys.exit(app.exec_())\n", "<import token>\n\n\nclass BackendTread(QThread):\n setvalue = pyqtSignal(int)\n\n def __init__(self, parent=None):\n super(BackendTread, self).__init__(parent)\n self.working = True\n\n def stopSig(self):\n self.working = False\n\n def run(self):\n \"\"\"os.chdir(self.ProjectName_2.text() + '/Default')\n self.process = subprocess.call(cmd1)\"\"\"\n while VAL < NUM and self.working:\n num = 0\n for path, dir, files in os.walk(os.getcwd()):\n for file in files:\n if file.endswith('.o'):\n num = num + 1\n self.setvalue.emit(num)\n\n\nclass BackendTread1(QThread):\n startcompile1 = pyqtSignal(str)\n endSig = pyqtSignal()\n\n def __init__(self, parent=None):\n super(BackendTread1, self).__init__(parent)\n\n def startCom(self):\n self.process = subprocess.Popen(cmd1)\n\n def run(self):\n \"\"\"os.chdir(self.ProjectName_2.text() + '/Default')\n self.process = subprocess.call(cmd1)\"\"\"\n f = open('conerr.err', 'w+')\n self.process = subprocess.Popen(cmd1, stdout=subprocess.PIPE,\n stderr=f, bufsize=1)\n \"\"\"self.bt=BackendTread()\n self.bt.startcompile.connect(self.PrintConsole)\n self.bt.start()\"\"\"\n self.sleep(3)\n while self.process.poll() is None:\n r = self.process.stdout.readline().decode('gbk')\n if r:\n self.startcompile1.emit(r)\n if 'tool>pause' in r:\n break\n os.system('taskkill /f /t /im make.exe')\n self.endSig.emit()\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n\n def __init__(self):\n super(basePage, self).__init__()\n self.setupUi(self)\n self.startpath = os.getcwd()\n self.actionbuild.triggered.connect(self.checkFLAG)\n self.actionclean.triggered.connect(self.CleanProject)\n self.actionopen_project.triggered.connect(self.ChooseProDir)\n self.actionsave_project.triggered.connect(self.modifyFLAG)\n self.actionexit.triggered.connect(qApp.quit)\n self.tb1 = self.addToolBar('tool')\n actionopen1 = QAction(QIcon('./Compile/file.png'), '打开工程', self)\n self.tb1.addAction(actionopen1)\n actionopen1.triggered.connect(self.ChooseProDir)\n self.tb1.addSeparator()\n actionstop = QAction(QIcon('./Compile/stop.png'), '停止', self)\n self.tb1.addAction(actionstop)\n actionstop.triggered.connect(self.KillProcess)\n self.tb1.addSeparator()\n actionExit = QAction(QIcon('./Compile/exit.png'), '退出', self)\n self.tb1.addAction(actionExit)\n actionExit.triggered.connect(qApp.quit)\n self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.contextMenu = QMenu(self)\n self.actionA = self.contextMenu.addAction('删除')\n self.actionA.triggered.connect(self.remove)\n self.includeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(1))\n self.excludeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(2))\n self.delPath1.clicked.connect(self.includeList.clear)\n self.delPath2.clicked.connect(self.excludeList.clear)\n self.addPath1.clicked.connect(lambda : self.ShowDialog(1))\n self.addPath2.clicked.connect(self.AddExpath)\n self.fileselect = fileselect.Ui_Dialog()\n self.listWidget.currentRowChanged.connect(self.display)\n self.initLibraryWindow()\n self.Llist.setSelectionMode(3)\n self.llist.setSelectionMode(3)\n self.barlabel = QLabel('barlabel')\n\n def initUI(self):\n self.includeList.clear()\n self.excludeList.clear()\n self.Llist.clear()\n self.llist.clear()\n self.ProjectName.setText(self.DebugName)\n self.HithTecDir.setText(self.HighTecDir)\n self.GCCFLAGName.setText(self.CCFLAG)\n self.LINKFLAGName.setText(self.LINKFLAG)\n self.ProjectName_2.setText(self.PROJECTDIR)\n self.ProjectName_2.setEnabled(False)\n self.barlabel.setText('准备中')\n self.statusBar.addPermanentWidget(self.barlabel)\n self.Result.clear()\n if self.includepath:\n self.includeList.addItems(self.includepath)\n if self.excludefiles:\n self.excludeList.addItems(self.excludefiles)\n if self.LibraryPath:\n self.Llist.addItems(self.LibraryPath)\n if self.libraties:\n self.llist.addItems(self.libraties)\n\n def display(self, index):\n self.index = index\n self.stackedWidget.setCurrentIndex(index)\n\n def initLibraryWindow(self):\n self.LWUI = AddLibraryPath.Ui_LSelect()\n self.LWin = QWidget()\n self.LWin.setWindowModality(Qt.ApplicationModal)\n self.LWUI.setupUi(self.LWin)\n self.LWUI.LibraryP.setText('')\n self.add1.clicked.connect(self.LWin.show)\n self.LWUI.L_Cancel.clicked.connect(self.LWin.close)\n self.LWUI.L_Workspace.clicked.connect(lambda : self.ShowDialog(1))\n self.LWUI.L_OK.clicked.connect(self.AddLibraryPath)\n self.del1.clicked.connect(self.DelLibraryPath)\n self.lWUI = Enterlibraries.Ui_LSelect()\n self.lWin = QWidget()\n self.lWin.setWindowModality(Qt.ApplicationModal)\n self.lWUI.setupUi(self.lWin)\n self.LWUI.LibraryP.setText('')\n self.add2.clicked.connect(self.lWin.show)\n self.lWUI.l_OK.clicked.connect(self.AddLibraries)\n self.lWUI.l_Cancel.clicked.connect(self.lWin.close)\n self.del2.clicked.connect(self.DelLibraries)\n\n def KillProcess(self):\n os.system('taskkill /f /t /im make.exe')\n self.Result.append('用户终止执行')\n\n def ChooseProDir(self):\n dir = QFileDialog.getExistingDirectory()\n dir = dir.replace('/', '\\\\')\n self.ProjectName_2.setText(dir)\n if dir != '':\n os.chdir(dir)\n import automake_config as ac\n (DebugName, HighTecDir, CCFLAG, LINKFLAG, includepath,\n excludefiles, g_except_dir_list, g_except_file_list,\n LibraryPath, libraties) = ac.maininit()\n self.includepath = includepath\n self.excludefiles = excludefiles\n self.DebugName = DebugName\n self.CCFLAG = CCFLAG\n self.LINKFLAG = LINKFLAG\n self.HighTecDir = HighTecDir\n self.PROJECTDIR = dir\n self.LibraryPath = LibraryPath\n self.libraties = libraties\n self.AllPath = ac.FindAllPath(dir)\n self.initDialog()\n self.fileselect.buttonBox.accepted.connect(self.GetPath)\n self.fileselect.treeWidget.setSelectionMode(3)\n self.fileselect.buttonBox.rejected.connect(self.Cleartree)\n a.initUI()\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n\n def remove(self):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if self.index == 3:\n if items1:\n for jj in items1:\n self.includeList.removeItemWidget(self.includeList.\n takeItem(jj.row()))\n if self.index == 4:\n if items2:\n for jj in items2:\n self.excludeList.removeItemWidget(self.excludeList.\n takeItem(jj.row()))\n\n def EndResult(self):\n print(os.getcwd())\n f = open('./conerr.err', 'r')\n lines = f.readlines()\n j = 0\n for ii in lines:\n if 'error:' in ii:\n self.Result.append('<font color=\"#FF0000\">%s</font> ' % ii)\n j = 1\n if j != 1:\n self.Result.append('<font color=\"#FF0000\">finished!!!!!!!!</font> '\n )\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working = False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n\n def initBar(self):\n global NUM\n self.progressBar = QProgressBar()\n self.Result.clear()\n self.barlabel.setText('正在编译:')\n self.statusBar.addPermanentWidget(self.progressBar, stretch=2)\n f = open('./Default/Default.objectlist', 'r')\n lines = f.readlines()\n f.close()\n NUM = len(lines)\n self.progressBar.setRange(0, len(lines))\n global VAL\n VAL = 0\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n\n def StartCompile(self, Hdir):\n global cmd1\n cmd1 = '%s\\\\bin\\\\make -j8 all' % Hdir\n os.chdir(self.ProjectName_2.text() + '/Default')\n self.backend1 = BackendTread1()\n self.backend1.startcompile1.connect(self.PrintConsole)\n self.backend1.endSig.connect(self.EndResult)\n self.backend1.start()\n self.backend = BackendTread()\n self.backend.setvalue.connect(self.SetProgressBarVal)\n self.backend.start()\n \"\"\"self.process = subprocess.call(cmd1)\n self.process.wait()\n f= open('console.log','r')\n lines =f.readlines()\n for ii in lines:\n if 'error:'in ii:\n self.Result.insertText(ii+'\n')\"\"\"\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n\n def modifyFLAG(self):\n CCFLAGNOW = self.GCCFLAGName.toPlainText()\n LINKFLAGNOW = self.LINKFLAGName.toPlainText()\n HighTecDirNOW = self.HithTecDir.text()\n DebugNameNOW = self.ProjectName.text()\n inn = self.includeList.count()\n inpathNOW = []\n exn = self.excludeList.count()\n expathNOW = []\n Ln = self.Llist.count()\n LnNOW = []\n ln = self.llist.count()\n lnNOW = []\n try:\n for i in range(inn):\n inpathNOW.append(self.includeList.item(i).text())\n for i in range(exn):\n expathNOW.append(self.excludeList.item(i).text())\n f = open('./py.pyconfig', 'w', encoding='utf-8')\n tLink = re.split(' ', LINKFLAGNOW)\n Linkchange = ''\n for iii in tLink:\n if '-L' not in iii and '-l:' not in iii:\n Linkchange += iii + ' '\n for i in range(Ln):\n p = re.split('{workspace}/', self.Llist.item(i).text())\n if len(p) == 1:\n Linkchange += '-L\"' + os.path.abspath(p[0]) + '\" '\n else:\n Linkchange += '-L\"' + os.path.abspath(p[1]) + '\" '\n LnNOW.append(self.Llist.item(i).text())\n for i in range(ln):\n Linkchange += '-l' + self.llist.item(i).text() + ' '\n lnNOW.append(self.llist.item(i).text())\n f.write('CCFLAG=' + CCFLAGNOW + '\\n')\n f.write('LINKFLAG=' + Linkchange + '\\n')\n f.write('HighTecDir=' + HighTecDirNOW + '\\n')\n f.write('DebugName=' + DebugNameNOW + '\\n')\n aa = 'includepath='\n for a in inpathNOW:\n if a != '':\n aa += a + ','\n f.write(aa + '\\n')\n bb = 'excludefiles='\n for b in expathNOW:\n if b != '':\n bb += b + ','\n f.write(bb + '\\n')\n cc = 'LibraryPath='\n for c in LnNOW:\n if c != '':\n cc += c + ','\n dd = 'libraties='\n for d in lnNOW:\n if d != '':\n dd += d + ','\n f.write(cc + '\\n')\n f.write(dd + '\\n')\n f.close()\n self.LINKFLAGName.setText('')\n self.LINKFLAGName.setText(Linkchange)\n except:\n f.close()\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n\n def testaa(self):\n print('1')\n\n def CloseTools(self):\n print(1)\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n\n def ShowDialog(self, id):\n self.idPath = id\n self.di.exec()\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n\n def AddExpath(self):\n dir1, file1 = QFileDialog.getOpenFileNames(self, '选择过滤文件', os.\n getcwd(), 'C FILES(*.c)')\n for ii in dir1:\n if ii != '':\n dir2 = re.split(os.getcwd().replace('\\\\', '/'), ii)[1]\n self.excludeList.addItem(dir2)\n\n def AddLibraryPath(self):\n txt = self.LWUI.LibraryP.text()\n if txt:\n self.Llist.addItem(txt)\n self.LWin.close()\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n\n def DelLibraryPath(self):\n items1 = self.Llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.Llist.removeItemWidget(self.Llist.takeItem(jj.row()))\n\n def DelLibraries(self):\n items1 = self.llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.llist.removeItemWidget(self.llist.takeItem(jj.row()))\n\n\nif __name__ == '__main__':\n cmd1 = ''\n NUM = 0\n VAL = 0\n app = QApplication(sys.argv)\n app.setWindowIcon(QIcon('./Compile/mainwindowIcon.png'))\n a = basePage()\n a.ChooseProDir()\n a.show()\n sys.exit(app.exec_())\n", "<import token>\n\n\nclass BackendTread(QThread):\n setvalue = pyqtSignal(int)\n\n def __init__(self, parent=None):\n super(BackendTread, self).__init__(parent)\n self.working = True\n\n def stopSig(self):\n self.working = False\n\n def run(self):\n \"\"\"os.chdir(self.ProjectName_2.text() + '/Default')\n self.process = subprocess.call(cmd1)\"\"\"\n while VAL < NUM and self.working:\n num = 0\n for path, dir, files in os.walk(os.getcwd()):\n for file in files:\n if file.endswith('.o'):\n num = num + 1\n self.setvalue.emit(num)\n\n\nclass BackendTread1(QThread):\n startcompile1 = pyqtSignal(str)\n endSig = pyqtSignal()\n\n def __init__(self, parent=None):\n super(BackendTread1, self).__init__(parent)\n\n def startCom(self):\n self.process = subprocess.Popen(cmd1)\n\n def run(self):\n \"\"\"os.chdir(self.ProjectName_2.text() + '/Default')\n self.process = subprocess.call(cmd1)\"\"\"\n f = open('conerr.err', 'w+')\n self.process = subprocess.Popen(cmd1, stdout=subprocess.PIPE,\n stderr=f, bufsize=1)\n \"\"\"self.bt=BackendTread()\n self.bt.startcompile.connect(self.PrintConsole)\n self.bt.start()\"\"\"\n self.sleep(3)\n while self.process.poll() is None:\n r = self.process.stdout.readline().decode('gbk')\n if r:\n self.startcompile1.emit(r)\n if 'tool>pause' in r:\n break\n os.system('taskkill /f /t /im make.exe')\n self.endSig.emit()\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n\n def __init__(self):\n super(basePage, self).__init__()\n self.setupUi(self)\n self.startpath = os.getcwd()\n self.actionbuild.triggered.connect(self.checkFLAG)\n self.actionclean.triggered.connect(self.CleanProject)\n self.actionopen_project.triggered.connect(self.ChooseProDir)\n self.actionsave_project.triggered.connect(self.modifyFLAG)\n self.actionexit.triggered.connect(qApp.quit)\n self.tb1 = self.addToolBar('tool')\n actionopen1 = QAction(QIcon('./Compile/file.png'), '打开工程', self)\n self.tb1.addAction(actionopen1)\n actionopen1.triggered.connect(self.ChooseProDir)\n self.tb1.addSeparator()\n actionstop = QAction(QIcon('./Compile/stop.png'), '停止', self)\n self.tb1.addAction(actionstop)\n actionstop.triggered.connect(self.KillProcess)\n self.tb1.addSeparator()\n actionExit = QAction(QIcon('./Compile/exit.png'), '退出', self)\n self.tb1.addAction(actionExit)\n actionExit.triggered.connect(qApp.quit)\n self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.contextMenu = QMenu(self)\n self.actionA = self.contextMenu.addAction('删除')\n self.actionA.triggered.connect(self.remove)\n self.includeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(1))\n self.excludeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(2))\n self.delPath1.clicked.connect(self.includeList.clear)\n self.delPath2.clicked.connect(self.excludeList.clear)\n self.addPath1.clicked.connect(lambda : self.ShowDialog(1))\n self.addPath2.clicked.connect(self.AddExpath)\n self.fileselect = fileselect.Ui_Dialog()\n self.listWidget.currentRowChanged.connect(self.display)\n self.initLibraryWindow()\n self.Llist.setSelectionMode(3)\n self.llist.setSelectionMode(3)\n self.barlabel = QLabel('barlabel')\n\n def initUI(self):\n self.includeList.clear()\n self.excludeList.clear()\n self.Llist.clear()\n self.llist.clear()\n self.ProjectName.setText(self.DebugName)\n self.HithTecDir.setText(self.HighTecDir)\n self.GCCFLAGName.setText(self.CCFLAG)\n self.LINKFLAGName.setText(self.LINKFLAG)\n self.ProjectName_2.setText(self.PROJECTDIR)\n self.ProjectName_2.setEnabled(False)\n self.barlabel.setText('准备中')\n self.statusBar.addPermanentWidget(self.barlabel)\n self.Result.clear()\n if self.includepath:\n self.includeList.addItems(self.includepath)\n if self.excludefiles:\n self.excludeList.addItems(self.excludefiles)\n if self.LibraryPath:\n self.Llist.addItems(self.LibraryPath)\n if self.libraties:\n self.llist.addItems(self.libraties)\n\n def display(self, index):\n self.index = index\n self.stackedWidget.setCurrentIndex(index)\n\n def initLibraryWindow(self):\n self.LWUI = AddLibraryPath.Ui_LSelect()\n self.LWin = QWidget()\n self.LWin.setWindowModality(Qt.ApplicationModal)\n self.LWUI.setupUi(self.LWin)\n self.LWUI.LibraryP.setText('')\n self.add1.clicked.connect(self.LWin.show)\n self.LWUI.L_Cancel.clicked.connect(self.LWin.close)\n self.LWUI.L_Workspace.clicked.connect(lambda : self.ShowDialog(1))\n self.LWUI.L_OK.clicked.connect(self.AddLibraryPath)\n self.del1.clicked.connect(self.DelLibraryPath)\n self.lWUI = Enterlibraries.Ui_LSelect()\n self.lWin = QWidget()\n self.lWin.setWindowModality(Qt.ApplicationModal)\n self.lWUI.setupUi(self.lWin)\n self.LWUI.LibraryP.setText('')\n self.add2.clicked.connect(self.lWin.show)\n self.lWUI.l_OK.clicked.connect(self.AddLibraries)\n self.lWUI.l_Cancel.clicked.connect(self.lWin.close)\n self.del2.clicked.connect(self.DelLibraries)\n\n def KillProcess(self):\n os.system('taskkill /f /t /im make.exe')\n self.Result.append('用户终止执行')\n\n def ChooseProDir(self):\n dir = QFileDialog.getExistingDirectory()\n dir = dir.replace('/', '\\\\')\n self.ProjectName_2.setText(dir)\n if dir != '':\n os.chdir(dir)\n import automake_config as ac\n (DebugName, HighTecDir, CCFLAG, LINKFLAG, includepath,\n excludefiles, g_except_dir_list, g_except_file_list,\n LibraryPath, libraties) = ac.maininit()\n self.includepath = includepath\n self.excludefiles = excludefiles\n self.DebugName = DebugName\n self.CCFLAG = CCFLAG\n self.LINKFLAG = LINKFLAG\n self.HighTecDir = HighTecDir\n self.PROJECTDIR = dir\n self.LibraryPath = LibraryPath\n self.libraties = libraties\n self.AllPath = ac.FindAllPath(dir)\n self.initDialog()\n self.fileselect.buttonBox.accepted.connect(self.GetPath)\n self.fileselect.treeWidget.setSelectionMode(3)\n self.fileselect.buttonBox.rejected.connect(self.Cleartree)\n a.initUI()\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n\n def remove(self):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if self.index == 3:\n if items1:\n for jj in items1:\n self.includeList.removeItemWidget(self.includeList.\n takeItem(jj.row()))\n if self.index == 4:\n if items2:\n for jj in items2:\n self.excludeList.removeItemWidget(self.excludeList.\n takeItem(jj.row()))\n\n def EndResult(self):\n print(os.getcwd())\n f = open('./conerr.err', 'r')\n lines = f.readlines()\n j = 0\n for ii in lines:\n if 'error:' in ii:\n self.Result.append('<font color=\"#FF0000\">%s</font> ' % ii)\n j = 1\n if j != 1:\n self.Result.append('<font color=\"#FF0000\">finished!!!!!!!!</font> '\n )\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working = False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n\n def initBar(self):\n global NUM\n self.progressBar = QProgressBar()\n self.Result.clear()\n self.barlabel.setText('正在编译:')\n self.statusBar.addPermanentWidget(self.progressBar, stretch=2)\n f = open('./Default/Default.objectlist', 'r')\n lines = f.readlines()\n f.close()\n NUM = len(lines)\n self.progressBar.setRange(0, len(lines))\n global VAL\n VAL = 0\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n\n def StartCompile(self, Hdir):\n global cmd1\n cmd1 = '%s\\\\bin\\\\make -j8 all' % Hdir\n os.chdir(self.ProjectName_2.text() + '/Default')\n self.backend1 = BackendTread1()\n self.backend1.startcompile1.connect(self.PrintConsole)\n self.backend1.endSig.connect(self.EndResult)\n self.backend1.start()\n self.backend = BackendTread()\n self.backend.setvalue.connect(self.SetProgressBarVal)\n self.backend.start()\n \"\"\"self.process = subprocess.call(cmd1)\n self.process.wait()\n f= open('console.log','r')\n lines =f.readlines()\n for ii in lines:\n if 'error:'in ii:\n self.Result.insertText(ii+'\n')\"\"\"\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n\n def modifyFLAG(self):\n CCFLAGNOW = self.GCCFLAGName.toPlainText()\n LINKFLAGNOW = self.LINKFLAGName.toPlainText()\n HighTecDirNOW = self.HithTecDir.text()\n DebugNameNOW = self.ProjectName.text()\n inn = self.includeList.count()\n inpathNOW = []\n exn = self.excludeList.count()\n expathNOW = []\n Ln = self.Llist.count()\n LnNOW = []\n ln = self.llist.count()\n lnNOW = []\n try:\n for i in range(inn):\n inpathNOW.append(self.includeList.item(i).text())\n for i in range(exn):\n expathNOW.append(self.excludeList.item(i).text())\n f = open('./py.pyconfig', 'w', encoding='utf-8')\n tLink = re.split(' ', LINKFLAGNOW)\n Linkchange = ''\n for iii in tLink:\n if '-L' not in iii and '-l:' not in iii:\n Linkchange += iii + ' '\n for i in range(Ln):\n p = re.split('{workspace}/', self.Llist.item(i).text())\n if len(p) == 1:\n Linkchange += '-L\"' + os.path.abspath(p[0]) + '\" '\n else:\n Linkchange += '-L\"' + os.path.abspath(p[1]) + '\" '\n LnNOW.append(self.Llist.item(i).text())\n for i in range(ln):\n Linkchange += '-l' + self.llist.item(i).text() + ' '\n lnNOW.append(self.llist.item(i).text())\n f.write('CCFLAG=' + CCFLAGNOW + '\\n')\n f.write('LINKFLAG=' + Linkchange + '\\n')\n f.write('HighTecDir=' + HighTecDirNOW + '\\n')\n f.write('DebugName=' + DebugNameNOW + '\\n')\n aa = 'includepath='\n for a in inpathNOW:\n if a != '':\n aa += a + ','\n f.write(aa + '\\n')\n bb = 'excludefiles='\n for b in expathNOW:\n if b != '':\n bb += b + ','\n f.write(bb + '\\n')\n cc = 'LibraryPath='\n for c in LnNOW:\n if c != '':\n cc += c + ','\n dd = 'libraties='\n for d in lnNOW:\n if d != '':\n dd += d + ','\n f.write(cc + '\\n')\n f.write(dd + '\\n')\n f.close()\n self.LINKFLAGName.setText('')\n self.LINKFLAGName.setText(Linkchange)\n except:\n f.close()\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n\n def testaa(self):\n print('1')\n\n def CloseTools(self):\n print(1)\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n\n def ShowDialog(self, id):\n self.idPath = id\n self.di.exec()\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n\n def AddExpath(self):\n dir1, file1 = QFileDialog.getOpenFileNames(self, '选择过滤文件', os.\n getcwd(), 'C FILES(*.c)')\n for ii in dir1:\n if ii != '':\n dir2 = re.split(os.getcwd().replace('\\\\', '/'), ii)[1]\n self.excludeList.addItem(dir2)\n\n def AddLibraryPath(self):\n txt = self.LWUI.LibraryP.text()\n if txt:\n self.Llist.addItem(txt)\n self.LWin.close()\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n\n def DelLibraryPath(self):\n items1 = self.Llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.Llist.removeItemWidget(self.Llist.takeItem(jj.row()))\n\n def DelLibraries(self):\n items1 = self.llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.llist.removeItemWidget(self.llist.takeItem(jj.row()))\n\n\n<code token>\n", "<import token>\n\n\nclass BackendTread(QThread):\n <assignment token>\n\n def __init__(self, parent=None):\n super(BackendTread, self).__init__(parent)\n self.working = True\n\n def stopSig(self):\n self.working = False\n\n def run(self):\n \"\"\"os.chdir(self.ProjectName_2.text() + '/Default')\n self.process = subprocess.call(cmd1)\"\"\"\n while VAL < NUM and self.working:\n num = 0\n for path, dir, files in os.walk(os.getcwd()):\n for file in files:\n if file.endswith('.o'):\n num = num + 1\n self.setvalue.emit(num)\n\n\nclass BackendTread1(QThread):\n startcompile1 = pyqtSignal(str)\n endSig = pyqtSignal()\n\n def __init__(self, parent=None):\n super(BackendTread1, self).__init__(parent)\n\n def startCom(self):\n self.process = subprocess.Popen(cmd1)\n\n def run(self):\n \"\"\"os.chdir(self.ProjectName_2.text() + '/Default')\n self.process = subprocess.call(cmd1)\"\"\"\n f = open('conerr.err', 'w+')\n self.process = subprocess.Popen(cmd1, stdout=subprocess.PIPE,\n stderr=f, bufsize=1)\n \"\"\"self.bt=BackendTread()\n self.bt.startcompile.connect(self.PrintConsole)\n self.bt.start()\"\"\"\n self.sleep(3)\n while self.process.poll() is None:\n r = self.process.stdout.readline().decode('gbk')\n if r:\n self.startcompile1.emit(r)\n if 'tool>pause' in r:\n break\n os.system('taskkill /f /t /im make.exe')\n self.endSig.emit()\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n\n def __init__(self):\n super(basePage, self).__init__()\n self.setupUi(self)\n self.startpath = os.getcwd()\n self.actionbuild.triggered.connect(self.checkFLAG)\n self.actionclean.triggered.connect(self.CleanProject)\n self.actionopen_project.triggered.connect(self.ChooseProDir)\n self.actionsave_project.triggered.connect(self.modifyFLAG)\n self.actionexit.triggered.connect(qApp.quit)\n self.tb1 = self.addToolBar('tool')\n actionopen1 = QAction(QIcon('./Compile/file.png'), '打开工程', self)\n self.tb1.addAction(actionopen1)\n actionopen1.triggered.connect(self.ChooseProDir)\n self.tb1.addSeparator()\n actionstop = QAction(QIcon('./Compile/stop.png'), '停止', self)\n self.tb1.addAction(actionstop)\n actionstop.triggered.connect(self.KillProcess)\n self.tb1.addSeparator()\n actionExit = QAction(QIcon('./Compile/exit.png'), '退出', self)\n self.tb1.addAction(actionExit)\n actionExit.triggered.connect(qApp.quit)\n self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.contextMenu = QMenu(self)\n self.actionA = self.contextMenu.addAction('删除')\n self.actionA.triggered.connect(self.remove)\n self.includeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(1))\n self.excludeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(2))\n self.delPath1.clicked.connect(self.includeList.clear)\n self.delPath2.clicked.connect(self.excludeList.clear)\n self.addPath1.clicked.connect(lambda : self.ShowDialog(1))\n self.addPath2.clicked.connect(self.AddExpath)\n self.fileselect = fileselect.Ui_Dialog()\n self.listWidget.currentRowChanged.connect(self.display)\n self.initLibraryWindow()\n self.Llist.setSelectionMode(3)\n self.llist.setSelectionMode(3)\n self.barlabel = QLabel('barlabel')\n\n def initUI(self):\n self.includeList.clear()\n self.excludeList.clear()\n self.Llist.clear()\n self.llist.clear()\n self.ProjectName.setText(self.DebugName)\n self.HithTecDir.setText(self.HighTecDir)\n self.GCCFLAGName.setText(self.CCFLAG)\n self.LINKFLAGName.setText(self.LINKFLAG)\n self.ProjectName_2.setText(self.PROJECTDIR)\n self.ProjectName_2.setEnabled(False)\n self.barlabel.setText('准备中')\n self.statusBar.addPermanentWidget(self.barlabel)\n self.Result.clear()\n if self.includepath:\n self.includeList.addItems(self.includepath)\n if self.excludefiles:\n self.excludeList.addItems(self.excludefiles)\n if self.LibraryPath:\n self.Llist.addItems(self.LibraryPath)\n if self.libraties:\n self.llist.addItems(self.libraties)\n\n def display(self, index):\n self.index = index\n self.stackedWidget.setCurrentIndex(index)\n\n def initLibraryWindow(self):\n self.LWUI = AddLibraryPath.Ui_LSelect()\n self.LWin = QWidget()\n self.LWin.setWindowModality(Qt.ApplicationModal)\n self.LWUI.setupUi(self.LWin)\n self.LWUI.LibraryP.setText('')\n self.add1.clicked.connect(self.LWin.show)\n self.LWUI.L_Cancel.clicked.connect(self.LWin.close)\n self.LWUI.L_Workspace.clicked.connect(lambda : self.ShowDialog(1))\n self.LWUI.L_OK.clicked.connect(self.AddLibraryPath)\n self.del1.clicked.connect(self.DelLibraryPath)\n self.lWUI = Enterlibraries.Ui_LSelect()\n self.lWin = QWidget()\n self.lWin.setWindowModality(Qt.ApplicationModal)\n self.lWUI.setupUi(self.lWin)\n self.LWUI.LibraryP.setText('')\n self.add2.clicked.connect(self.lWin.show)\n self.lWUI.l_OK.clicked.connect(self.AddLibraries)\n self.lWUI.l_Cancel.clicked.connect(self.lWin.close)\n self.del2.clicked.connect(self.DelLibraries)\n\n def KillProcess(self):\n os.system('taskkill /f /t /im make.exe')\n self.Result.append('用户终止执行')\n\n def ChooseProDir(self):\n dir = QFileDialog.getExistingDirectory()\n dir = dir.replace('/', '\\\\')\n self.ProjectName_2.setText(dir)\n if dir != '':\n os.chdir(dir)\n import automake_config as ac\n (DebugName, HighTecDir, CCFLAG, LINKFLAG, includepath,\n excludefiles, g_except_dir_list, g_except_file_list,\n LibraryPath, libraties) = ac.maininit()\n self.includepath = includepath\n self.excludefiles = excludefiles\n self.DebugName = DebugName\n self.CCFLAG = CCFLAG\n self.LINKFLAG = LINKFLAG\n self.HighTecDir = HighTecDir\n self.PROJECTDIR = dir\n self.LibraryPath = LibraryPath\n self.libraties = libraties\n self.AllPath = ac.FindAllPath(dir)\n self.initDialog()\n self.fileselect.buttonBox.accepted.connect(self.GetPath)\n self.fileselect.treeWidget.setSelectionMode(3)\n self.fileselect.buttonBox.rejected.connect(self.Cleartree)\n a.initUI()\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n\n def remove(self):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if self.index == 3:\n if items1:\n for jj in items1:\n self.includeList.removeItemWidget(self.includeList.\n takeItem(jj.row()))\n if self.index == 4:\n if items2:\n for jj in items2:\n self.excludeList.removeItemWidget(self.excludeList.\n takeItem(jj.row()))\n\n def EndResult(self):\n print(os.getcwd())\n f = open('./conerr.err', 'r')\n lines = f.readlines()\n j = 0\n for ii in lines:\n if 'error:' in ii:\n self.Result.append('<font color=\"#FF0000\">%s</font> ' % ii)\n j = 1\n if j != 1:\n self.Result.append('<font color=\"#FF0000\">finished!!!!!!!!</font> '\n )\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working = False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n\n def initBar(self):\n global NUM\n self.progressBar = QProgressBar()\n self.Result.clear()\n self.barlabel.setText('正在编译:')\n self.statusBar.addPermanentWidget(self.progressBar, stretch=2)\n f = open('./Default/Default.objectlist', 'r')\n lines = f.readlines()\n f.close()\n NUM = len(lines)\n self.progressBar.setRange(0, len(lines))\n global VAL\n VAL = 0\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n\n def StartCompile(self, Hdir):\n global cmd1\n cmd1 = '%s\\\\bin\\\\make -j8 all' % Hdir\n os.chdir(self.ProjectName_2.text() + '/Default')\n self.backend1 = BackendTread1()\n self.backend1.startcompile1.connect(self.PrintConsole)\n self.backend1.endSig.connect(self.EndResult)\n self.backend1.start()\n self.backend = BackendTread()\n self.backend.setvalue.connect(self.SetProgressBarVal)\n self.backend.start()\n \"\"\"self.process = subprocess.call(cmd1)\n self.process.wait()\n f= open('console.log','r')\n lines =f.readlines()\n for ii in lines:\n if 'error:'in ii:\n self.Result.insertText(ii+'\n')\"\"\"\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n\n def modifyFLAG(self):\n CCFLAGNOW = self.GCCFLAGName.toPlainText()\n LINKFLAGNOW = self.LINKFLAGName.toPlainText()\n HighTecDirNOW = self.HithTecDir.text()\n DebugNameNOW = self.ProjectName.text()\n inn = self.includeList.count()\n inpathNOW = []\n exn = self.excludeList.count()\n expathNOW = []\n Ln = self.Llist.count()\n LnNOW = []\n ln = self.llist.count()\n lnNOW = []\n try:\n for i in range(inn):\n inpathNOW.append(self.includeList.item(i).text())\n for i in range(exn):\n expathNOW.append(self.excludeList.item(i).text())\n f = open('./py.pyconfig', 'w', encoding='utf-8')\n tLink = re.split(' ', LINKFLAGNOW)\n Linkchange = ''\n for iii in tLink:\n if '-L' not in iii and '-l:' not in iii:\n Linkchange += iii + ' '\n for i in range(Ln):\n p = re.split('{workspace}/', self.Llist.item(i).text())\n if len(p) == 1:\n Linkchange += '-L\"' + os.path.abspath(p[0]) + '\" '\n else:\n Linkchange += '-L\"' + os.path.abspath(p[1]) + '\" '\n LnNOW.append(self.Llist.item(i).text())\n for i in range(ln):\n Linkchange += '-l' + self.llist.item(i).text() + ' '\n lnNOW.append(self.llist.item(i).text())\n f.write('CCFLAG=' + CCFLAGNOW + '\\n')\n f.write('LINKFLAG=' + Linkchange + '\\n')\n f.write('HighTecDir=' + HighTecDirNOW + '\\n')\n f.write('DebugName=' + DebugNameNOW + '\\n')\n aa = 'includepath='\n for a in inpathNOW:\n if a != '':\n aa += a + ','\n f.write(aa + '\\n')\n bb = 'excludefiles='\n for b in expathNOW:\n if b != '':\n bb += b + ','\n f.write(bb + '\\n')\n cc = 'LibraryPath='\n for c in LnNOW:\n if c != '':\n cc += c + ','\n dd = 'libraties='\n for d in lnNOW:\n if d != '':\n dd += d + ','\n f.write(cc + '\\n')\n f.write(dd + '\\n')\n f.close()\n self.LINKFLAGName.setText('')\n self.LINKFLAGName.setText(Linkchange)\n except:\n f.close()\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n\n def testaa(self):\n print('1')\n\n def CloseTools(self):\n print(1)\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n\n def ShowDialog(self, id):\n self.idPath = id\n self.di.exec()\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n\n def AddExpath(self):\n dir1, file1 = QFileDialog.getOpenFileNames(self, '选择过滤文件', os.\n getcwd(), 'C FILES(*.c)')\n for ii in dir1:\n if ii != '':\n dir2 = re.split(os.getcwd().replace('\\\\', '/'), ii)[1]\n self.excludeList.addItem(dir2)\n\n def AddLibraryPath(self):\n txt = self.LWUI.LibraryP.text()\n if txt:\n self.Llist.addItem(txt)\n self.LWin.close()\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n\n def DelLibraryPath(self):\n items1 = self.Llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.Llist.removeItemWidget(self.Llist.takeItem(jj.row()))\n\n def DelLibraries(self):\n items1 = self.llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.llist.removeItemWidget(self.llist.takeItem(jj.row()))\n\n\n<code token>\n", "<import token>\n\n\nclass BackendTread(QThread):\n <assignment token>\n\n def __init__(self, parent=None):\n super(BackendTread, self).__init__(parent)\n self.working = True\n <function token>\n\n def run(self):\n \"\"\"os.chdir(self.ProjectName_2.text() + '/Default')\n self.process = subprocess.call(cmd1)\"\"\"\n while VAL < NUM and self.working:\n num = 0\n for path, dir, files in os.walk(os.getcwd()):\n for file in files:\n if file.endswith('.o'):\n num = num + 1\n self.setvalue.emit(num)\n\n\nclass BackendTread1(QThread):\n startcompile1 = pyqtSignal(str)\n endSig = pyqtSignal()\n\n def __init__(self, parent=None):\n super(BackendTread1, self).__init__(parent)\n\n def startCom(self):\n self.process = subprocess.Popen(cmd1)\n\n def run(self):\n \"\"\"os.chdir(self.ProjectName_2.text() + '/Default')\n self.process = subprocess.call(cmd1)\"\"\"\n f = open('conerr.err', 'w+')\n self.process = subprocess.Popen(cmd1, stdout=subprocess.PIPE,\n stderr=f, bufsize=1)\n \"\"\"self.bt=BackendTread()\n self.bt.startcompile.connect(self.PrintConsole)\n self.bt.start()\"\"\"\n self.sleep(3)\n while self.process.poll() is None:\n r = self.process.stdout.readline().decode('gbk')\n if r:\n self.startcompile1.emit(r)\n if 'tool>pause' in r:\n break\n os.system('taskkill /f /t /im make.exe')\n self.endSig.emit()\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n\n def __init__(self):\n super(basePage, self).__init__()\n self.setupUi(self)\n self.startpath = os.getcwd()\n self.actionbuild.triggered.connect(self.checkFLAG)\n self.actionclean.triggered.connect(self.CleanProject)\n self.actionopen_project.triggered.connect(self.ChooseProDir)\n self.actionsave_project.triggered.connect(self.modifyFLAG)\n self.actionexit.triggered.connect(qApp.quit)\n self.tb1 = self.addToolBar('tool')\n actionopen1 = QAction(QIcon('./Compile/file.png'), '打开工程', self)\n self.tb1.addAction(actionopen1)\n actionopen1.triggered.connect(self.ChooseProDir)\n self.tb1.addSeparator()\n actionstop = QAction(QIcon('./Compile/stop.png'), '停止', self)\n self.tb1.addAction(actionstop)\n actionstop.triggered.connect(self.KillProcess)\n self.tb1.addSeparator()\n actionExit = QAction(QIcon('./Compile/exit.png'), '退出', self)\n self.tb1.addAction(actionExit)\n actionExit.triggered.connect(qApp.quit)\n self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.contextMenu = QMenu(self)\n self.actionA = self.contextMenu.addAction('删除')\n self.actionA.triggered.connect(self.remove)\n self.includeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(1))\n self.excludeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(2))\n self.delPath1.clicked.connect(self.includeList.clear)\n self.delPath2.clicked.connect(self.excludeList.clear)\n self.addPath1.clicked.connect(lambda : self.ShowDialog(1))\n self.addPath2.clicked.connect(self.AddExpath)\n self.fileselect = fileselect.Ui_Dialog()\n self.listWidget.currentRowChanged.connect(self.display)\n self.initLibraryWindow()\n self.Llist.setSelectionMode(3)\n self.llist.setSelectionMode(3)\n self.barlabel = QLabel('barlabel')\n\n def initUI(self):\n self.includeList.clear()\n self.excludeList.clear()\n self.Llist.clear()\n self.llist.clear()\n self.ProjectName.setText(self.DebugName)\n self.HithTecDir.setText(self.HighTecDir)\n self.GCCFLAGName.setText(self.CCFLAG)\n self.LINKFLAGName.setText(self.LINKFLAG)\n self.ProjectName_2.setText(self.PROJECTDIR)\n self.ProjectName_2.setEnabled(False)\n self.barlabel.setText('准备中')\n self.statusBar.addPermanentWidget(self.barlabel)\n self.Result.clear()\n if self.includepath:\n self.includeList.addItems(self.includepath)\n if self.excludefiles:\n self.excludeList.addItems(self.excludefiles)\n if self.LibraryPath:\n self.Llist.addItems(self.LibraryPath)\n if self.libraties:\n self.llist.addItems(self.libraties)\n\n def display(self, index):\n self.index = index\n self.stackedWidget.setCurrentIndex(index)\n\n def initLibraryWindow(self):\n self.LWUI = AddLibraryPath.Ui_LSelect()\n self.LWin = QWidget()\n self.LWin.setWindowModality(Qt.ApplicationModal)\n self.LWUI.setupUi(self.LWin)\n self.LWUI.LibraryP.setText('')\n self.add1.clicked.connect(self.LWin.show)\n self.LWUI.L_Cancel.clicked.connect(self.LWin.close)\n self.LWUI.L_Workspace.clicked.connect(lambda : self.ShowDialog(1))\n self.LWUI.L_OK.clicked.connect(self.AddLibraryPath)\n self.del1.clicked.connect(self.DelLibraryPath)\n self.lWUI = Enterlibraries.Ui_LSelect()\n self.lWin = QWidget()\n self.lWin.setWindowModality(Qt.ApplicationModal)\n self.lWUI.setupUi(self.lWin)\n self.LWUI.LibraryP.setText('')\n self.add2.clicked.connect(self.lWin.show)\n self.lWUI.l_OK.clicked.connect(self.AddLibraries)\n self.lWUI.l_Cancel.clicked.connect(self.lWin.close)\n self.del2.clicked.connect(self.DelLibraries)\n\n def KillProcess(self):\n os.system('taskkill /f /t /im make.exe')\n self.Result.append('用户终止执行')\n\n def ChooseProDir(self):\n dir = QFileDialog.getExistingDirectory()\n dir = dir.replace('/', '\\\\')\n self.ProjectName_2.setText(dir)\n if dir != '':\n os.chdir(dir)\n import automake_config as ac\n (DebugName, HighTecDir, CCFLAG, LINKFLAG, includepath,\n excludefiles, g_except_dir_list, g_except_file_list,\n LibraryPath, libraties) = ac.maininit()\n self.includepath = includepath\n self.excludefiles = excludefiles\n self.DebugName = DebugName\n self.CCFLAG = CCFLAG\n self.LINKFLAG = LINKFLAG\n self.HighTecDir = HighTecDir\n self.PROJECTDIR = dir\n self.LibraryPath = LibraryPath\n self.libraties = libraties\n self.AllPath = ac.FindAllPath(dir)\n self.initDialog()\n self.fileselect.buttonBox.accepted.connect(self.GetPath)\n self.fileselect.treeWidget.setSelectionMode(3)\n self.fileselect.buttonBox.rejected.connect(self.Cleartree)\n a.initUI()\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n\n def remove(self):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if self.index == 3:\n if items1:\n for jj in items1:\n self.includeList.removeItemWidget(self.includeList.\n takeItem(jj.row()))\n if self.index == 4:\n if items2:\n for jj in items2:\n self.excludeList.removeItemWidget(self.excludeList.\n takeItem(jj.row()))\n\n def EndResult(self):\n print(os.getcwd())\n f = open('./conerr.err', 'r')\n lines = f.readlines()\n j = 0\n for ii in lines:\n if 'error:' in ii:\n self.Result.append('<font color=\"#FF0000\">%s</font> ' % ii)\n j = 1\n if j != 1:\n self.Result.append('<font color=\"#FF0000\">finished!!!!!!!!</font> '\n )\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working = False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n\n def initBar(self):\n global NUM\n self.progressBar = QProgressBar()\n self.Result.clear()\n self.barlabel.setText('正在编译:')\n self.statusBar.addPermanentWidget(self.progressBar, stretch=2)\n f = open('./Default/Default.objectlist', 'r')\n lines = f.readlines()\n f.close()\n NUM = len(lines)\n self.progressBar.setRange(0, len(lines))\n global VAL\n VAL = 0\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n\n def StartCompile(self, Hdir):\n global cmd1\n cmd1 = '%s\\\\bin\\\\make -j8 all' % Hdir\n os.chdir(self.ProjectName_2.text() + '/Default')\n self.backend1 = BackendTread1()\n self.backend1.startcompile1.connect(self.PrintConsole)\n self.backend1.endSig.connect(self.EndResult)\n self.backend1.start()\n self.backend = BackendTread()\n self.backend.setvalue.connect(self.SetProgressBarVal)\n self.backend.start()\n \"\"\"self.process = subprocess.call(cmd1)\n self.process.wait()\n f= open('console.log','r')\n lines =f.readlines()\n for ii in lines:\n if 'error:'in ii:\n self.Result.insertText(ii+'\n')\"\"\"\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n\n def modifyFLAG(self):\n CCFLAGNOW = self.GCCFLAGName.toPlainText()\n LINKFLAGNOW = self.LINKFLAGName.toPlainText()\n HighTecDirNOW = self.HithTecDir.text()\n DebugNameNOW = self.ProjectName.text()\n inn = self.includeList.count()\n inpathNOW = []\n exn = self.excludeList.count()\n expathNOW = []\n Ln = self.Llist.count()\n LnNOW = []\n ln = self.llist.count()\n lnNOW = []\n try:\n for i in range(inn):\n inpathNOW.append(self.includeList.item(i).text())\n for i in range(exn):\n expathNOW.append(self.excludeList.item(i).text())\n f = open('./py.pyconfig', 'w', encoding='utf-8')\n tLink = re.split(' ', LINKFLAGNOW)\n Linkchange = ''\n for iii in tLink:\n if '-L' not in iii and '-l:' not in iii:\n Linkchange += iii + ' '\n for i in range(Ln):\n p = re.split('{workspace}/', self.Llist.item(i).text())\n if len(p) == 1:\n Linkchange += '-L\"' + os.path.abspath(p[0]) + '\" '\n else:\n Linkchange += '-L\"' + os.path.abspath(p[1]) + '\" '\n LnNOW.append(self.Llist.item(i).text())\n for i in range(ln):\n Linkchange += '-l' + self.llist.item(i).text() + ' '\n lnNOW.append(self.llist.item(i).text())\n f.write('CCFLAG=' + CCFLAGNOW + '\\n')\n f.write('LINKFLAG=' + Linkchange + '\\n')\n f.write('HighTecDir=' + HighTecDirNOW + '\\n')\n f.write('DebugName=' + DebugNameNOW + '\\n')\n aa = 'includepath='\n for a in inpathNOW:\n if a != '':\n aa += a + ','\n f.write(aa + '\\n')\n bb = 'excludefiles='\n for b in expathNOW:\n if b != '':\n bb += b + ','\n f.write(bb + '\\n')\n cc = 'LibraryPath='\n for c in LnNOW:\n if c != '':\n cc += c + ','\n dd = 'libraties='\n for d in lnNOW:\n if d != '':\n dd += d + ','\n f.write(cc + '\\n')\n f.write(dd + '\\n')\n f.close()\n self.LINKFLAGName.setText('')\n self.LINKFLAGName.setText(Linkchange)\n except:\n f.close()\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n\n def testaa(self):\n print('1')\n\n def CloseTools(self):\n print(1)\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n\n def ShowDialog(self, id):\n self.idPath = id\n self.di.exec()\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n\n def AddExpath(self):\n dir1, file1 = QFileDialog.getOpenFileNames(self, '选择过滤文件', os.\n getcwd(), 'C FILES(*.c)')\n for ii in dir1:\n if ii != '':\n dir2 = re.split(os.getcwd().replace('\\\\', '/'), ii)[1]\n self.excludeList.addItem(dir2)\n\n def AddLibraryPath(self):\n txt = self.LWUI.LibraryP.text()\n if txt:\n self.Llist.addItem(txt)\n self.LWin.close()\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n\n def DelLibraryPath(self):\n items1 = self.Llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.Llist.removeItemWidget(self.Llist.takeItem(jj.row()))\n\n def DelLibraries(self):\n items1 = self.llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.llist.removeItemWidget(self.llist.takeItem(jj.row()))\n\n\n<code token>\n", "<import token>\n\n\nclass BackendTread(QThread):\n <assignment token>\n <function token>\n <function token>\n\n def run(self):\n \"\"\"os.chdir(self.ProjectName_2.text() + '/Default')\n self.process = subprocess.call(cmd1)\"\"\"\n while VAL < NUM and self.working:\n num = 0\n for path, dir, files in os.walk(os.getcwd()):\n for file in files:\n if file.endswith('.o'):\n num = num + 1\n self.setvalue.emit(num)\n\n\nclass BackendTread1(QThread):\n startcompile1 = pyqtSignal(str)\n endSig = pyqtSignal()\n\n def __init__(self, parent=None):\n super(BackendTread1, self).__init__(parent)\n\n def startCom(self):\n self.process = subprocess.Popen(cmd1)\n\n def run(self):\n \"\"\"os.chdir(self.ProjectName_2.text() + '/Default')\n self.process = subprocess.call(cmd1)\"\"\"\n f = open('conerr.err', 'w+')\n self.process = subprocess.Popen(cmd1, stdout=subprocess.PIPE,\n stderr=f, bufsize=1)\n \"\"\"self.bt=BackendTread()\n self.bt.startcompile.connect(self.PrintConsole)\n self.bt.start()\"\"\"\n self.sleep(3)\n while self.process.poll() is None:\n r = self.process.stdout.readline().decode('gbk')\n if r:\n self.startcompile1.emit(r)\n if 'tool>pause' in r:\n break\n os.system('taskkill /f /t /im make.exe')\n self.endSig.emit()\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n\n def __init__(self):\n super(basePage, self).__init__()\n self.setupUi(self)\n self.startpath = os.getcwd()\n self.actionbuild.triggered.connect(self.checkFLAG)\n self.actionclean.triggered.connect(self.CleanProject)\n self.actionopen_project.triggered.connect(self.ChooseProDir)\n self.actionsave_project.triggered.connect(self.modifyFLAG)\n self.actionexit.triggered.connect(qApp.quit)\n self.tb1 = self.addToolBar('tool')\n actionopen1 = QAction(QIcon('./Compile/file.png'), '打开工程', self)\n self.tb1.addAction(actionopen1)\n actionopen1.triggered.connect(self.ChooseProDir)\n self.tb1.addSeparator()\n actionstop = QAction(QIcon('./Compile/stop.png'), '停止', self)\n self.tb1.addAction(actionstop)\n actionstop.triggered.connect(self.KillProcess)\n self.tb1.addSeparator()\n actionExit = QAction(QIcon('./Compile/exit.png'), '退出', self)\n self.tb1.addAction(actionExit)\n actionExit.triggered.connect(qApp.quit)\n self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.contextMenu = QMenu(self)\n self.actionA = self.contextMenu.addAction('删除')\n self.actionA.triggered.connect(self.remove)\n self.includeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(1))\n self.excludeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(2))\n self.delPath1.clicked.connect(self.includeList.clear)\n self.delPath2.clicked.connect(self.excludeList.clear)\n self.addPath1.clicked.connect(lambda : self.ShowDialog(1))\n self.addPath2.clicked.connect(self.AddExpath)\n self.fileselect = fileselect.Ui_Dialog()\n self.listWidget.currentRowChanged.connect(self.display)\n self.initLibraryWindow()\n self.Llist.setSelectionMode(3)\n self.llist.setSelectionMode(3)\n self.barlabel = QLabel('barlabel')\n\n def initUI(self):\n self.includeList.clear()\n self.excludeList.clear()\n self.Llist.clear()\n self.llist.clear()\n self.ProjectName.setText(self.DebugName)\n self.HithTecDir.setText(self.HighTecDir)\n self.GCCFLAGName.setText(self.CCFLAG)\n self.LINKFLAGName.setText(self.LINKFLAG)\n self.ProjectName_2.setText(self.PROJECTDIR)\n self.ProjectName_2.setEnabled(False)\n self.barlabel.setText('准备中')\n self.statusBar.addPermanentWidget(self.barlabel)\n self.Result.clear()\n if self.includepath:\n self.includeList.addItems(self.includepath)\n if self.excludefiles:\n self.excludeList.addItems(self.excludefiles)\n if self.LibraryPath:\n self.Llist.addItems(self.LibraryPath)\n if self.libraties:\n self.llist.addItems(self.libraties)\n\n def display(self, index):\n self.index = index\n self.stackedWidget.setCurrentIndex(index)\n\n def initLibraryWindow(self):\n self.LWUI = AddLibraryPath.Ui_LSelect()\n self.LWin = QWidget()\n self.LWin.setWindowModality(Qt.ApplicationModal)\n self.LWUI.setupUi(self.LWin)\n self.LWUI.LibraryP.setText('')\n self.add1.clicked.connect(self.LWin.show)\n self.LWUI.L_Cancel.clicked.connect(self.LWin.close)\n self.LWUI.L_Workspace.clicked.connect(lambda : self.ShowDialog(1))\n self.LWUI.L_OK.clicked.connect(self.AddLibraryPath)\n self.del1.clicked.connect(self.DelLibraryPath)\n self.lWUI = Enterlibraries.Ui_LSelect()\n self.lWin = QWidget()\n self.lWin.setWindowModality(Qt.ApplicationModal)\n self.lWUI.setupUi(self.lWin)\n self.LWUI.LibraryP.setText('')\n self.add2.clicked.connect(self.lWin.show)\n self.lWUI.l_OK.clicked.connect(self.AddLibraries)\n self.lWUI.l_Cancel.clicked.connect(self.lWin.close)\n self.del2.clicked.connect(self.DelLibraries)\n\n def KillProcess(self):\n os.system('taskkill /f /t /im make.exe')\n self.Result.append('用户终止执行')\n\n def ChooseProDir(self):\n dir = QFileDialog.getExistingDirectory()\n dir = dir.replace('/', '\\\\')\n self.ProjectName_2.setText(dir)\n if dir != '':\n os.chdir(dir)\n import automake_config as ac\n (DebugName, HighTecDir, CCFLAG, LINKFLAG, includepath,\n excludefiles, g_except_dir_list, g_except_file_list,\n LibraryPath, libraties) = ac.maininit()\n self.includepath = includepath\n self.excludefiles = excludefiles\n self.DebugName = DebugName\n self.CCFLAG = CCFLAG\n self.LINKFLAG = LINKFLAG\n self.HighTecDir = HighTecDir\n self.PROJECTDIR = dir\n self.LibraryPath = LibraryPath\n self.libraties = libraties\n self.AllPath = ac.FindAllPath(dir)\n self.initDialog()\n self.fileselect.buttonBox.accepted.connect(self.GetPath)\n self.fileselect.treeWidget.setSelectionMode(3)\n self.fileselect.buttonBox.rejected.connect(self.Cleartree)\n a.initUI()\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n\n def remove(self):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if self.index == 3:\n if items1:\n for jj in items1:\n self.includeList.removeItemWidget(self.includeList.\n takeItem(jj.row()))\n if self.index == 4:\n if items2:\n for jj in items2:\n self.excludeList.removeItemWidget(self.excludeList.\n takeItem(jj.row()))\n\n def EndResult(self):\n print(os.getcwd())\n f = open('./conerr.err', 'r')\n lines = f.readlines()\n j = 0\n for ii in lines:\n if 'error:' in ii:\n self.Result.append('<font color=\"#FF0000\">%s</font> ' % ii)\n j = 1\n if j != 1:\n self.Result.append('<font color=\"#FF0000\">finished!!!!!!!!</font> '\n )\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working = False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n\n def initBar(self):\n global NUM\n self.progressBar = QProgressBar()\n self.Result.clear()\n self.barlabel.setText('正在编译:')\n self.statusBar.addPermanentWidget(self.progressBar, stretch=2)\n f = open('./Default/Default.objectlist', 'r')\n lines = f.readlines()\n f.close()\n NUM = len(lines)\n self.progressBar.setRange(0, len(lines))\n global VAL\n VAL = 0\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n\n def StartCompile(self, Hdir):\n global cmd1\n cmd1 = '%s\\\\bin\\\\make -j8 all' % Hdir\n os.chdir(self.ProjectName_2.text() + '/Default')\n self.backend1 = BackendTread1()\n self.backend1.startcompile1.connect(self.PrintConsole)\n self.backend1.endSig.connect(self.EndResult)\n self.backend1.start()\n self.backend = BackendTread()\n self.backend.setvalue.connect(self.SetProgressBarVal)\n self.backend.start()\n \"\"\"self.process = subprocess.call(cmd1)\n self.process.wait()\n f= open('console.log','r')\n lines =f.readlines()\n for ii in lines:\n if 'error:'in ii:\n self.Result.insertText(ii+'\n')\"\"\"\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n\n def modifyFLAG(self):\n CCFLAGNOW = self.GCCFLAGName.toPlainText()\n LINKFLAGNOW = self.LINKFLAGName.toPlainText()\n HighTecDirNOW = self.HithTecDir.text()\n DebugNameNOW = self.ProjectName.text()\n inn = self.includeList.count()\n inpathNOW = []\n exn = self.excludeList.count()\n expathNOW = []\n Ln = self.Llist.count()\n LnNOW = []\n ln = self.llist.count()\n lnNOW = []\n try:\n for i in range(inn):\n inpathNOW.append(self.includeList.item(i).text())\n for i in range(exn):\n expathNOW.append(self.excludeList.item(i).text())\n f = open('./py.pyconfig', 'w', encoding='utf-8')\n tLink = re.split(' ', LINKFLAGNOW)\n Linkchange = ''\n for iii in tLink:\n if '-L' not in iii and '-l:' not in iii:\n Linkchange += iii + ' '\n for i in range(Ln):\n p = re.split('{workspace}/', self.Llist.item(i).text())\n if len(p) == 1:\n Linkchange += '-L\"' + os.path.abspath(p[0]) + '\" '\n else:\n Linkchange += '-L\"' + os.path.abspath(p[1]) + '\" '\n LnNOW.append(self.Llist.item(i).text())\n for i in range(ln):\n Linkchange += '-l' + self.llist.item(i).text() + ' '\n lnNOW.append(self.llist.item(i).text())\n f.write('CCFLAG=' + CCFLAGNOW + '\\n')\n f.write('LINKFLAG=' + Linkchange + '\\n')\n f.write('HighTecDir=' + HighTecDirNOW + '\\n')\n f.write('DebugName=' + DebugNameNOW + '\\n')\n aa = 'includepath='\n for a in inpathNOW:\n if a != '':\n aa += a + ','\n f.write(aa + '\\n')\n bb = 'excludefiles='\n for b in expathNOW:\n if b != '':\n bb += b + ','\n f.write(bb + '\\n')\n cc = 'LibraryPath='\n for c in LnNOW:\n if c != '':\n cc += c + ','\n dd = 'libraties='\n for d in lnNOW:\n if d != '':\n dd += d + ','\n f.write(cc + '\\n')\n f.write(dd + '\\n')\n f.close()\n self.LINKFLAGName.setText('')\n self.LINKFLAGName.setText(Linkchange)\n except:\n f.close()\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n\n def testaa(self):\n print('1')\n\n def CloseTools(self):\n print(1)\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n\n def ShowDialog(self, id):\n self.idPath = id\n self.di.exec()\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n\n def AddExpath(self):\n dir1, file1 = QFileDialog.getOpenFileNames(self, '选择过滤文件', os.\n getcwd(), 'C FILES(*.c)')\n for ii in dir1:\n if ii != '':\n dir2 = re.split(os.getcwd().replace('\\\\', '/'), ii)[1]\n self.excludeList.addItem(dir2)\n\n def AddLibraryPath(self):\n txt = self.LWUI.LibraryP.text()\n if txt:\n self.Llist.addItem(txt)\n self.LWin.close()\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n\n def DelLibraryPath(self):\n items1 = self.Llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.Llist.removeItemWidget(self.Llist.takeItem(jj.row()))\n\n def DelLibraries(self):\n items1 = self.llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.llist.removeItemWidget(self.llist.takeItem(jj.row()))\n\n\n<code token>\n", "<import token>\n\n\nclass BackendTread(QThread):\n <assignment token>\n <function token>\n <function token>\n <function token>\n\n\nclass BackendTread1(QThread):\n startcompile1 = pyqtSignal(str)\n endSig = pyqtSignal()\n\n def __init__(self, parent=None):\n super(BackendTread1, self).__init__(parent)\n\n def startCom(self):\n self.process = subprocess.Popen(cmd1)\n\n def run(self):\n \"\"\"os.chdir(self.ProjectName_2.text() + '/Default')\n self.process = subprocess.call(cmd1)\"\"\"\n f = open('conerr.err', 'w+')\n self.process = subprocess.Popen(cmd1, stdout=subprocess.PIPE,\n stderr=f, bufsize=1)\n \"\"\"self.bt=BackendTread()\n self.bt.startcompile.connect(self.PrintConsole)\n self.bt.start()\"\"\"\n self.sleep(3)\n while self.process.poll() is None:\n r = self.process.stdout.readline().decode('gbk')\n if r:\n self.startcompile1.emit(r)\n if 'tool>pause' in r:\n break\n os.system('taskkill /f /t /im make.exe')\n self.endSig.emit()\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n\n def __init__(self):\n super(basePage, self).__init__()\n self.setupUi(self)\n self.startpath = os.getcwd()\n self.actionbuild.triggered.connect(self.checkFLAG)\n self.actionclean.triggered.connect(self.CleanProject)\n self.actionopen_project.triggered.connect(self.ChooseProDir)\n self.actionsave_project.triggered.connect(self.modifyFLAG)\n self.actionexit.triggered.connect(qApp.quit)\n self.tb1 = self.addToolBar('tool')\n actionopen1 = QAction(QIcon('./Compile/file.png'), '打开工程', self)\n self.tb1.addAction(actionopen1)\n actionopen1.triggered.connect(self.ChooseProDir)\n self.tb1.addSeparator()\n actionstop = QAction(QIcon('./Compile/stop.png'), '停止', self)\n self.tb1.addAction(actionstop)\n actionstop.triggered.connect(self.KillProcess)\n self.tb1.addSeparator()\n actionExit = QAction(QIcon('./Compile/exit.png'), '退出', self)\n self.tb1.addAction(actionExit)\n actionExit.triggered.connect(qApp.quit)\n self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.contextMenu = QMenu(self)\n self.actionA = self.contextMenu.addAction('删除')\n self.actionA.triggered.connect(self.remove)\n self.includeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(1))\n self.excludeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(2))\n self.delPath1.clicked.connect(self.includeList.clear)\n self.delPath2.clicked.connect(self.excludeList.clear)\n self.addPath1.clicked.connect(lambda : self.ShowDialog(1))\n self.addPath2.clicked.connect(self.AddExpath)\n self.fileselect = fileselect.Ui_Dialog()\n self.listWidget.currentRowChanged.connect(self.display)\n self.initLibraryWindow()\n self.Llist.setSelectionMode(3)\n self.llist.setSelectionMode(3)\n self.barlabel = QLabel('barlabel')\n\n def initUI(self):\n self.includeList.clear()\n self.excludeList.clear()\n self.Llist.clear()\n self.llist.clear()\n self.ProjectName.setText(self.DebugName)\n self.HithTecDir.setText(self.HighTecDir)\n self.GCCFLAGName.setText(self.CCFLAG)\n self.LINKFLAGName.setText(self.LINKFLAG)\n self.ProjectName_2.setText(self.PROJECTDIR)\n self.ProjectName_2.setEnabled(False)\n self.barlabel.setText('准备中')\n self.statusBar.addPermanentWidget(self.barlabel)\n self.Result.clear()\n if self.includepath:\n self.includeList.addItems(self.includepath)\n if self.excludefiles:\n self.excludeList.addItems(self.excludefiles)\n if self.LibraryPath:\n self.Llist.addItems(self.LibraryPath)\n if self.libraties:\n self.llist.addItems(self.libraties)\n\n def display(self, index):\n self.index = index\n self.stackedWidget.setCurrentIndex(index)\n\n def initLibraryWindow(self):\n self.LWUI = AddLibraryPath.Ui_LSelect()\n self.LWin = QWidget()\n self.LWin.setWindowModality(Qt.ApplicationModal)\n self.LWUI.setupUi(self.LWin)\n self.LWUI.LibraryP.setText('')\n self.add1.clicked.connect(self.LWin.show)\n self.LWUI.L_Cancel.clicked.connect(self.LWin.close)\n self.LWUI.L_Workspace.clicked.connect(lambda : self.ShowDialog(1))\n self.LWUI.L_OK.clicked.connect(self.AddLibraryPath)\n self.del1.clicked.connect(self.DelLibraryPath)\n self.lWUI = Enterlibraries.Ui_LSelect()\n self.lWin = QWidget()\n self.lWin.setWindowModality(Qt.ApplicationModal)\n self.lWUI.setupUi(self.lWin)\n self.LWUI.LibraryP.setText('')\n self.add2.clicked.connect(self.lWin.show)\n self.lWUI.l_OK.clicked.connect(self.AddLibraries)\n self.lWUI.l_Cancel.clicked.connect(self.lWin.close)\n self.del2.clicked.connect(self.DelLibraries)\n\n def KillProcess(self):\n os.system('taskkill /f /t /im make.exe')\n self.Result.append('用户终止执行')\n\n def ChooseProDir(self):\n dir = QFileDialog.getExistingDirectory()\n dir = dir.replace('/', '\\\\')\n self.ProjectName_2.setText(dir)\n if dir != '':\n os.chdir(dir)\n import automake_config as ac\n (DebugName, HighTecDir, CCFLAG, LINKFLAG, includepath,\n excludefiles, g_except_dir_list, g_except_file_list,\n LibraryPath, libraties) = ac.maininit()\n self.includepath = includepath\n self.excludefiles = excludefiles\n self.DebugName = DebugName\n self.CCFLAG = CCFLAG\n self.LINKFLAG = LINKFLAG\n self.HighTecDir = HighTecDir\n self.PROJECTDIR = dir\n self.LibraryPath = LibraryPath\n self.libraties = libraties\n self.AllPath = ac.FindAllPath(dir)\n self.initDialog()\n self.fileselect.buttonBox.accepted.connect(self.GetPath)\n self.fileselect.treeWidget.setSelectionMode(3)\n self.fileselect.buttonBox.rejected.connect(self.Cleartree)\n a.initUI()\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n\n def remove(self):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if self.index == 3:\n if items1:\n for jj in items1:\n self.includeList.removeItemWidget(self.includeList.\n takeItem(jj.row()))\n if self.index == 4:\n if items2:\n for jj in items2:\n self.excludeList.removeItemWidget(self.excludeList.\n takeItem(jj.row()))\n\n def EndResult(self):\n print(os.getcwd())\n f = open('./conerr.err', 'r')\n lines = f.readlines()\n j = 0\n for ii in lines:\n if 'error:' in ii:\n self.Result.append('<font color=\"#FF0000\">%s</font> ' % ii)\n j = 1\n if j != 1:\n self.Result.append('<font color=\"#FF0000\">finished!!!!!!!!</font> '\n )\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working = False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n\n def initBar(self):\n global NUM\n self.progressBar = QProgressBar()\n self.Result.clear()\n self.barlabel.setText('正在编译:')\n self.statusBar.addPermanentWidget(self.progressBar, stretch=2)\n f = open('./Default/Default.objectlist', 'r')\n lines = f.readlines()\n f.close()\n NUM = len(lines)\n self.progressBar.setRange(0, len(lines))\n global VAL\n VAL = 0\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n\n def StartCompile(self, Hdir):\n global cmd1\n cmd1 = '%s\\\\bin\\\\make -j8 all' % Hdir\n os.chdir(self.ProjectName_2.text() + '/Default')\n self.backend1 = BackendTread1()\n self.backend1.startcompile1.connect(self.PrintConsole)\n self.backend1.endSig.connect(self.EndResult)\n self.backend1.start()\n self.backend = BackendTread()\n self.backend.setvalue.connect(self.SetProgressBarVal)\n self.backend.start()\n \"\"\"self.process = subprocess.call(cmd1)\n self.process.wait()\n f= open('console.log','r')\n lines =f.readlines()\n for ii in lines:\n if 'error:'in ii:\n self.Result.insertText(ii+'\n')\"\"\"\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n\n def modifyFLAG(self):\n CCFLAGNOW = self.GCCFLAGName.toPlainText()\n LINKFLAGNOW = self.LINKFLAGName.toPlainText()\n HighTecDirNOW = self.HithTecDir.text()\n DebugNameNOW = self.ProjectName.text()\n inn = self.includeList.count()\n inpathNOW = []\n exn = self.excludeList.count()\n expathNOW = []\n Ln = self.Llist.count()\n LnNOW = []\n ln = self.llist.count()\n lnNOW = []\n try:\n for i in range(inn):\n inpathNOW.append(self.includeList.item(i).text())\n for i in range(exn):\n expathNOW.append(self.excludeList.item(i).text())\n f = open('./py.pyconfig', 'w', encoding='utf-8')\n tLink = re.split(' ', LINKFLAGNOW)\n Linkchange = ''\n for iii in tLink:\n if '-L' not in iii and '-l:' not in iii:\n Linkchange += iii + ' '\n for i in range(Ln):\n p = re.split('{workspace}/', self.Llist.item(i).text())\n if len(p) == 1:\n Linkchange += '-L\"' + os.path.abspath(p[0]) + '\" '\n else:\n Linkchange += '-L\"' + os.path.abspath(p[1]) + '\" '\n LnNOW.append(self.Llist.item(i).text())\n for i in range(ln):\n Linkchange += '-l' + self.llist.item(i).text() + ' '\n lnNOW.append(self.llist.item(i).text())\n f.write('CCFLAG=' + CCFLAGNOW + '\\n')\n f.write('LINKFLAG=' + Linkchange + '\\n')\n f.write('HighTecDir=' + HighTecDirNOW + '\\n')\n f.write('DebugName=' + DebugNameNOW + '\\n')\n aa = 'includepath='\n for a in inpathNOW:\n if a != '':\n aa += a + ','\n f.write(aa + '\\n')\n bb = 'excludefiles='\n for b in expathNOW:\n if b != '':\n bb += b + ','\n f.write(bb + '\\n')\n cc = 'LibraryPath='\n for c in LnNOW:\n if c != '':\n cc += c + ','\n dd = 'libraties='\n for d in lnNOW:\n if d != '':\n dd += d + ','\n f.write(cc + '\\n')\n f.write(dd + '\\n')\n f.close()\n self.LINKFLAGName.setText('')\n self.LINKFLAGName.setText(Linkchange)\n except:\n f.close()\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n\n def testaa(self):\n print('1')\n\n def CloseTools(self):\n print(1)\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n\n def ShowDialog(self, id):\n self.idPath = id\n self.di.exec()\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n\n def AddExpath(self):\n dir1, file1 = QFileDialog.getOpenFileNames(self, '选择过滤文件', os.\n getcwd(), 'C FILES(*.c)')\n for ii in dir1:\n if ii != '':\n dir2 = re.split(os.getcwd().replace('\\\\', '/'), ii)[1]\n self.excludeList.addItem(dir2)\n\n def AddLibraryPath(self):\n txt = self.LWUI.LibraryP.text()\n if txt:\n self.Llist.addItem(txt)\n self.LWin.close()\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n\n def DelLibraryPath(self):\n items1 = self.Llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.Llist.removeItemWidget(self.Llist.takeItem(jj.row()))\n\n def DelLibraries(self):\n items1 = self.llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.llist.removeItemWidget(self.llist.takeItem(jj.row()))\n\n\n<code token>\n", "<import token>\n<class token>\n\n\nclass BackendTread1(QThread):\n startcompile1 = pyqtSignal(str)\n endSig = pyqtSignal()\n\n def __init__(self, parent=None):\n super(BackendTread1, self).__init__(parent)\n\n def startCom(self):\n self.process = subprocess.Popen(cmd1)\n\n def run(self):\n \"\"\"os.chdir(self.ProjectName_2.text() + '/Default')\n self.process = subprocess.call(cmd1)\"\"\"\n f = open('conerr.err', 'w+')\n self.process = subprocess.Popen(cmd1, stdout=subprocess.PIPE,\n stderr=f, bufsize=1)\n \"\"\"self.bt=BackendTread()\n self.bt.startcompile.connect(self.PrintConsole)\n self.bt.start()\"\"\"\n self.sleep(3)\n while self.process.poll() is None:\n r = self.process.stdout.readline().decode('gbk')\n if r:\n self.startcompile1.emit(r)\n if 'tool>pause' in r:\n break\n os.system('taskkill /f /t /im make.exe')\n self.endSig.emit()\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n\n def __init__(self):\n super(basePage, self).__init__()\n self.setupUi(self)\n self.startpath = os.getcwd()\n self.actionbuild.triggered.connect(self.checkFLAG)\n self.actionclean.triggered.connect(self.CleanProject)\n self.actionopen_project.triggered.connect(self.ChooseProDir)\n self.actionsave_project.triggered.connect(self.modifyFLAG)\n self.actionexit.triggered.connect(qApp.quit)\n self.tb1 = self.addToolBar('tool')\n actionopen1 = QAction(QIcon('./Compile/file.png'), '打开工程', self)\n self.tb1.addAction(actionopen1)\n actionopen1.triggered.connect(self.ChooseProDir)\n self.tb1.addSeparator()\n actionstop = QAction(QIcon('./Compile/stop.png'), '停止', self)\n self.tb1.addAction(actionstop)\n actionstop.triggered.connect(self.KillProcess)\n self.tb1.addSeparator()\n actionExit = QAction(QIcon('./Compile/exit.png'), '退出', self)\n self.tb1.addAction(actionExit)\n actionExit.triggered.connect(qApp.quit)\n self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.contextMenu = QMenu(self)\n self.actionA = self.contextMenu.addAction('删除')\n self.actionA.triggered.connect(self.remove)\n self.includeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(1))\n self.excludeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(2))\n self.delPath1.clicked.connect(self.includeList.clear)\n self.delPath2.clicked.connect(self.excludeList.clear)\n self.addPath1.clicked.connect(lambda : self.ShowDialog(1))\n self.addPath2.clicked.connect(self.AddExpath)\n self.fileselect = fileselect.Ui_Dialog()\n self.listWidget.currentRowChanged.connect(self.display)\n self.initLibraryWindow()\n self.Llist.setSelectionMode(3)\n self.llist.setSelectionMode(3)\n self.barlabel = QLabel('barlabel')\n\n def initUI(self):\n self.includeList.clear()\n self.excludeList.clear()\n self.Llist.clear()\n self.llist.clear()\n self.ProjectName.setText(self.DebugName)\n self.HithTecDir.setText(self.HighTecDir)\n self.GCCFLAGName.setText(self.CCFLAG)\n self.LINKFLAGName.setText(self.LINKFLAG)\n self.ProjectName_2.setText(self.PROJECTDIR)\n self.ProjectName_2.setEnabled(False)\n self.barlabel.setText('准备中')\n self.statusBar.addPermanentWidget(self.barlabel)\n self.Result.clear()\n if self.includepath:\n self.includeList.addItems(self.includepath)\n if self.excludefiles:\n self.excludeList.addItems(self.excludefiles)\n if self.LibraryPath:\n self.Llist.addItems(self.LibraryPath)\n if self.libraties:\n self.llist.addItems(self.libraties)\n\n def display(self, index):\n self.index = index\n self.stackedWidget.setCurrentIndex(index)\n\n def initLibraryWindow(self):\n self.LWUI = AddLibraryPath.Ui_LSelect()\n self.LWin = QWidget()\n self.LWin.setWindowModality(Qt.ApplicationModal)\n self.LWUI.setupUi(self.LWin)\n self.LWUI.LibraryP.setText('')\n self.add1.clicked.connect(self.LWin.show)\n self.LWUI.L_Cancel.clicked.connect(self.LWin.close)\n self.LWUI.L_Workspace.clicked.connect(lambda : self.ShowDialog(1))\n self.LWUI.L_OK.clicked.connect(self.AddLibraryPath)\n self.del1.clicked.connect(self.DelLibraryPath)\n self.lWUI = Enterlibraries.Ui_LSelect()\n self.lWin = QWidget()\n self.lWin.setWindowModality(Qt.ApplicationModal)\n self.lWUI.setupUi(self.lWin)\n self.LWUI.LibraryP.setText('')\n self.add2.clicked.connect(self.lWin.show)\n self.lWUI.l_OK.clicked.connect(self.AddLibraries)\n self.lWUI.l_Cancel.clicked.connect(self.lWin.close)\n self.del2.clicked.connect(self.DelLibraries)\n\n def KillProcess(self):\n os.system('taskkill /f /t /im make.exe')\n self.Result.append('用户终止执行')\n\n def ChooseProDir(self):\n dir = QFileDialog.getExistingDirectory()\n dir = dir.replace('/', '\\\\')\n self.ProjectName_2.setText(dir)\n if dir != '':\n os.chdir(dir)\n import automake_config as ac\n (DebugName, HighTecDir, CCFLAG, LINKFLAG, includepath,\n excludefiles, g_except_dir_list, g_except_file_list,\n LibraryPath, libraties) = ac.maininit()\n self.includepath = includepath\n self.excludefiles = excludefiles\n self.DebugName = DebugName\n self.CCFLAG = CCFLAG\n self.LINKFLAG = LINKFLAG\n self.HighTecDir = HighTecDir\n self.PROJECTDIR = dir\n self.LibraryPath = LibraryPath\n self.libraties = libraties\n self.AllPath = ac.FindAllPath(dir)\n self.initDialog()\n self.fileselect.buttonBox.accepted.connect(self.GetPath)\n self.fileselect.treeWidget.setSelectionMode(3)\n self.fileselect.buttonBox.rejected.connect(self.Cleartree)\n a.initUI()\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n\n def remove(self):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if self.index == 3:\n if items1:\n for jj in items1:\n self.includeList.removeItemWidget(self.includeList.\n takeItem(jj.row()))\n if self.index == 4:\n if items2:\n for jj in items2:\n self.excludeList.removeItemWidget(self.excludeList.\n takeItem(jj.row()))\n\n def EndResult(self):\n print(os.getcwd())\n f = open('./conerr.err', 'r')\n lines = f.readlines()\n j = 0\n for ii in lines:\n if 'error:' in ii:\n self.Result.append('<font color=\"#FF0000\">%s</font> ' % ii)\n j = 1\n if j != 1:\n self.Result.append('<font color=\"#FF0000\">finished!!!!!!!!</font> '\n )\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working = False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n\n def initBar(self):\n global NUM\n self.progressBar = QProgressBar()\n self.Result.clear()\n self.barlabel.setText('正在编译:')\n self.statusBar.addPermanentWidget(self.progressBar, stretch=2)\n f = open('./Default/Default.objectlist', 'r')\n lines = f.readlines()\n f.close()\n NUM = len(lines)\n self.progressBar.setRange(0, len(lines))\n global VAL\n VAL = 0\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n\n def StartCompile(self, Hdir):\n global cmd1\n cmd1 = '%s\\\\bin\\\\make -j8 all' % Hdir\n os.chdir(self.ProjectName_2.text() + '/Default')\n self.backend1 = BackendTread1()\n self.backend1.startcompile1.connect(self.PrintConsole)\n self.backend1.endSig.connect(self.EndResult)\n self.backend1.start()\n self.backend = BackendTread()\n self.backend.setvalue.connect(self.SetProgressBarVal)\n self.backend.start()\n \"\"\"self.process = subprocess.call(cmd1)\n self.process.wait()\n f= open('console.log','r')\n lines =f.readlines()\n for ii in lines:\n if 'error:'in ii:\n self.Result.insertText(ii+'\n')\"\"\"\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n\n def modifyFLAG(self):\n CCFLAGNOW = self.GCCFLAGName.toPlainText()\n LINKFLAGNOW = self.LINKFLAGName.toPlainText()\n HighTecDirNOW = self.HithTecDir.text()\n DebugNameNOW = self.ProjectName.text()\n inn = self.includeList.count()\n inpathNOW = []\n exn = self.excludeList.count()\n expathNOW = []\n Ln = self.Llist.count()\n LnNOW = []\n ln = self.llist.count()\n lnNOW = []\n try:\n for i in range(inn):\n inpathNOW.append(self.includeList.item(i).text())\n for i in range(exn):\n expathNOW.append(self.excludeList.item(i).text())\n f = open('./py.pyconfig', 'w', encoding='utf-8')\n tLink = re.split(' ', LINKFLAGNOW)\n Linkchange = ''\n for iii in tLink:\n if '-L' not in iii and '-l:' not in iii:\n Linkchange += iii + ' '\n for i in range(Ln):\n p = re.split('{workspace}/', self.Llist.item(i).text())\n if len(p) == 1:\n Linkchange += '-L\"' + os.path.abspath(p[0]) + '\" '\n else:\n Linkchange += '-L\"' + os.path.abspath(p[1]) + '\" '\n LnNOW.append(self.Llist.item(i).text())\n for i in range(ln):\n Linkchange += '-l' + self.llist.item(i).text() + ' '\n lnNOW.append(self.llist.item(i).text())\n f.write('CCFLAG=' + CCFLAGNOW + '\\n')\n f.write('LINKFLAG=' + Linkchange + '\\n')\n f.write('HighTecDir=' + HighTecDirNOW + '\\n')\n f.write('DebugName=' + DebugNameNOW + '\\n')\n aa = 'includepath='\n for a in inpathNOW:\n if a != '':\n aa += a + ','\n f.write(aa + '\\n')\n bb = 'excludefiles='\n for b in expathNOW:\n if b != '':\n bb += b + ','\n f.write(bb + '\\n')\n cc = 'LibraryPath='\n for c in LnNOW:\n if c != '':\n cc += c + ','\n dd = 'libraties='\n for d in lnNOW:\n if d != '':\n dd += d + ','\n f.write(cc + '\\n')\n f.write(dd + '\\n')\n f.close()\n self.LINKFLAGName.setText('')\n self.LINKFLAGName.setText(Linkchange)\n except:\n f.close()\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n\n def testaa(self):\n print('1')\n\n def CloseTools(self):\n print(1)\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n\n def ShowDialog(self, id):\n self.idPath = id\n self.di.exec()\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n\n def AddExpath(self):\n dir1, file1 = QFileDialog.getOpenFileNames(self, '选择过滤文件', os.\n getcwd(), 'C FILES(*.c)')\n for ii in dir1:\n if ii != '':\n dir2 = re.split(os.getcwd().replace('\\\\', '/'), ii)[1]\n self.excludeList.addItem(dir2)\n\n def AddLibraryPath(self):\n txt = self.LWUI.LibraryP.text()\n if txt:\n self.Llist.addItem(txt)\n self.LWin.close()\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n\n def DelLibraryPath(self):\n items1 = self.Llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.Llist.removeItemWidget(self.Llist.takeItem(jj.row()))\n\n def DelLibraries(self):\n items1 = self.llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.llist.removeItemWidget(self.llist.takeItem(jj.row()))\n\n\n<code token>\n", "<import token>\n<class token>\n\n\nclass BackendTread1(QThread):\n <assignment token>\n <assignment token>\n\n def __init__(self, parent=None):\n super(BackendTread1, self).__init__(parent)\n\n def startCom(self):\n self.process = subprocess.Popen(cmd1)\n\n def run(self):\n \"\"\"os.chdir(self.ProjectName_2.text() + '/Default')\n self.process = subprocess.call(cmd1)\"\"\"\n f = open('conerr.err', 'w+')\n self.process = subprocess.Popen(cmd1, stdout=subprocess.PIPE,\n stderr=f, bufsize=1)\n \"\"\"self.bt=BackendTread()\n self.bt.startcompile.connect(self.PrintConsole)\n self.bt.start()\"\"\"\n self.sleep(3)\n while self.process.poll() is None:\n r = self.process.stdout.readline().decode('gbk')\n if r:\n self.startcompile1.emit(r)\n if 'tool>pause' in r:\n break\n os.system('taskkill /f /t /im make.exe')\n self.endSig.emit()\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n\n def __init__(self):\n super(basePage, self).__init__()\n self.setupUi(self)\n self.startpath = os.getcwd()\n self.actionbuild.triggered.connect(self.checkFLAG)\n self.actionclean.triggered.connect(self.CleanProject)\n self.actionopen_project.triggered.connect(self.ChooseProDir)\n self.actionsave_project.triggered.connect(self.modifyFLAG)\n self.actionexit.triggered.connect(qApp.quit)\n self.tb1 = self.addToolBar('tool')\n actionopen1 = QAction(QIcon('./Compile/file.png'), '打开工程', self)\n self.tb1.addAction(actionopen1)\n actionopen1.triggered.connect(self.ChooseProDir)\n self.tb1.addSeparator()\n actionstop = QAction(QIcon('./Compile/stop.png'), '停止', self)\n self.tb1.addAction(actionstop)\n actionstop.triggered.connect(self.KillProcess)\n self.tb1.addSeparator()\n actionExit = QAction(QIcon('./Compile/exit.png'), '退出', self)\n self.tb1.addAction(actionExit)\n actionExit.triggered.connect(qApp.quit)\n self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.contextMenu = QMenu(self)\n self.actionA = self.contextMenu.addAction('删除')\n self.actionA.triggered.connect(self.remove)\n self.includeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(1))\n self.excludeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(2))\n self.delPath1.clicked.connect(self.includeList.clear)\n self.delPath2.clicked.connect(self.excludeList.clear)\n self.addPath1.clicked.connect(lambda : self.ShowDialog(1))\n self.addPath2.clicked.connect(self.AddExpath)\n self.fileselect = fileselect.Ui_Dialog()\n self.listWidget.currentRowChanged.connect(self.display)\n self.initLibraryWindow()\n self.Llist.setSelectionMode(3)\n self.llist.setSelectionMode(3)\n self.barlabel = QLabel('barlabel')\n\n def initUI(self):\n self.includeList.clear()\n self.excludeList.clear()\n self.Llist.clear()\n self.llist.clear()\n self.ProjectName.setText(self.DebugName)\n self.HithTecDir.setText(self.HighTecDir)\n self.GCCFLAGName.setText(self.CCFLAG)\n self.LINKFLAGName.setText(self.LINKFLAG)\n self.ProjectName_2.setText(self.PROJECTDIR)\n self.ProjectName_2.setEnabled(False)\n self.barlabel.setText('准备中')\n self.statusBar.addPermanentWidget(self.barlabel)\n self.Result.clear()\n if self.includepath:\n self.includeList.addItems(self.includepath)\n if self.excludefiles:\n self.excludeList.addItems(self.excludefiles)\n if self.LibraryPath:\n self.Llist.addItems(self.LibraryPath)\n if self.libraties:\n self.llist.addItems(self.libraties)\n\n def display(self, index):\n self.index = index\n self.stackedWidget.setCurrentIndex(index)\n\n def initLibraryWindow(self):\n self.LWUI = AddLibraryPath.Ui_LSelect()\n self.LWin = QWidget()\n self.LWin.setWindowModality(Qt.ApplicationModal)\n self.LWUI.setupUi(self.LWin)\n self.LWUI.LibraryP.setText('')\n self.add1.clicked.connect(self.LWin.show)\n self.LWUI.L_Cancel.clicked.connect(self.LWin.close)\n self.LWUI.L_Workspace.clicked.connect(lambda : self.ShowDialog(1))\n self.LWUI.L_OK.clicked.connect(self.AddLibraryPath)\n self.del1.clicked.connect(self.DelLibraryPath)\n self.lWUI = Enterlibraries.Ui_LSelect()\n self.lWin = QWidget()\n self.lWin.setWindowModality(Qt.ApplicationModal)\n self.lWUI.setupUi(self.lWin)\n self.LWUI.LibraryP.setText('')\n self.add2.clicked.connect(self.lWin.show)\n self.lWUI.l_OK.clicked.connect(self.AddLibraries)\n self.lWUI.l_Cancel.clicked.connect(self.lWin.close)\n self.del2.clicked.connect(self.DelLibraries)\n\n def KillProcess(self):\n os.system('taskkill /f /t /im make.exe')\n self.Result.append('用户终止执行')\n\n def ChooseProDir(self):\n dir = QFileDialog.getExistingDirectory()\n dir = dir.replace('/', '\\\\')\n self.ProjectName_2.setText(dir)\n if dir != '':\n os.chdir(dir)\n import automake_config as ac\n (DebugName, HighTecDir, CCFLAG, LINKFLAG, includepath,\n excludefiles, g_except_dir_list, g_except_file_list,\n LibraryPath, libraties) = ac.maininit()\n self.includepath = includepath\n self.excludefiles = excludefiles\n self.DebugName = DebugName\n self.CCFLAG = CCFLAG\n self.LINKFLAG = LINKFLAG\n self.HighTecDir = HighTecDir\n self.PROJECTDIR = dir\n self.LibraryPath = LibraryPath\n self.libraties = libraties\n self.AllPath = ac.FindAllPath(dir)\n self.initDialog()\n self.fileselect.buttonBox.accepted.connect(self.GetPath)\n self.fileselect.treeWidget.setSelectionMode(3)\n self.fileselect.buttonBox.rejected.connect(self.Cleartree)\n a.initUI()\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n\n def remove(self):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if self.index == 3:\n if items1:\n for jj in items1:\n self.includeList.removeItemWidget(self.includeList.\n takeItem(jj.row()))\n if self.index == 4:\n if items2:\n for jj in items2:\n self.excludeList.removeItemWidget(self.excludeList.\n takeItem(jj.row()))\n\n def EndResult(self):\n print(os.getcwd())\n f = open('./conerr.err', 'r')\n lines = f.readlines()\n j = 0\n for ii in lines:\n if 'error:' in ii:\n self.Result.append('<font color=\"#FF0000\">%s</font> ' % ii)\n j = 1\n if j != 1:\n self.Result.append('<font color=\"#FF0000\">finished!!!!!!!!</font> '\n )\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working = False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n\n def initBar(self):\n global NUM\n self.progressBar = QProgressBar()\n self.Result.clear()\n self.barlabel.setText('正在编译:')\n self.statusBar.addPermanentWidget(self.progressBar, stretch=2)\n f = open('./Default/Default.objectlist', 'r')\n lines = f.readlines()\n f.close()\n NUM = len(lines)\n self.progressBar.setRange(0, len(lines))\n global VAL\n VAL = 0\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n\n def StartCompile(self, Hdir):\n global cmd1\n cmd1 = '%s\\\\bin\\\\make -j8 all' % Hdir\n os.chdir(self.ProjectName_2.text() + '/Default')\n self.backend1 = BackendTread1()\n self.backend1.startcompile1.connect(self.PrintConsole)\n self.backend1.endSig.connect(self.EndResult)\n self.backend1.start()\n self.backend = BackendTread()\n self.backend.setvalue.connect(self.SetProgressBarVal)\n self.backend.start()\n \"\"\"self.process = subprocess.call(cmd1)\n self.process.wait()\n f= open('console.log','r')\n lines =f.readlines()\n for ii in lines:\n if 'error:'in ii:\n self.Result.insertText(ii+'\n')\"\"\"\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n\n def modifyFLAG(self):\n CCFLAGNOW = self.GCCFLAGName.toPlainText()\n LINKFLAGNOW = self.LINKFLAGName.toPlainText()\n HighTecDirNOW = self.HithTecDir.text()\n DebugNameNOW = self.ProjectName.text()\n inn = self.includeList.count()\n inpathNOW = []\n exn = self.excludeList.count()\n expathNOW = []\n Ln = self.Llist.count()\n LnNOW = []\n ln = self.llist.count()\n lnNOW = []\n try:\n for i in range(inn):\n inpathNOW.append(self.includeList.item(i).text())\n for i in range(exn):\n expathNOW.append(self.excludeList.item(i).text())\n f = open('./py.pyconfig', 'w', encoding='utf-8')\n tLink = re.split(' ', LINKFLAGNOW)\n Linkchange = ''\n for iii in tLink:\n if '-L' not in iii and '-l:' not in iii:\n Linkchange += iii + ' '\n for i in range(Ln):\n p = re.split('{workspace}/', self.Llist.item(i).text())\n if len(p) == 1:\n Linkchange += '-L\"' + os.path.abspath(p[0]) + '\" '\n else:\n Linkchange += '-L\"' + os.path.abspath(p[1]) + '\" '\n LnNOW.append(self.Llist.item(i).text())\n for i in range(ln):\n Linkchange += '-l' + self.llist.item(i).text() + ' '\n lnNOW.append(self.llist.item(i).text())\n f.write('CCFLAG=' + CCFLAGNOW + '\\n')\n f.write('LINKFLAG=' + Linkchange + '\\n')\n f.write('HighTecDir=' + HighTecDirNOW + '\\n')\n f.write('DebugName=' + DebugNameNOW + '\\n')\n aa = 'includepath='\n for a in inpathNOW:\n if a != '':\n aa += a + ','\n f.write(aa + '\\n')\n bb = 'excludefiles='\n for b in expathNOW:\n if b != '':\n bb += b + ','\n f.write(bb + '\\n')\n cc = 'LibraryPath='\n for c in LnNOW:\n if c != '':\n cc += c + ','\n dd = 'libraties='\n for d in lnNOW:\n if d != '':\n dd += d + ','\n f.write(cc + '\\n')\n f.write(dd + '\\n')\n f.close()\n self.LINKFLAGName.setText('')\n self.LINKFLAGName.setText(Linkchange)\n except:\n f.close()\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n\n def testaa(self):\n print('1')\n\n def CloseTools(self):\n print(1)\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n\n def ShowDialog(self, id):\n self.idPath = id\n self.di.exec()\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n\n def AddExpath(self):\n dir1, file1 = QFileDialog.getOpenFileNames(self, '选择过滤文件', os.\n getcwd(), 'C FILES(*.c)')\n for ii in dir1:\n if ii != '':\n dir2 = re.split(os.getcwd().replace('\\\\', '/'), ii)[1]\n self.excludeList.addItem(dir2)\n\n def AddLibraryPath(self):\n txt = self.LWUI.LibraryP.text()\n if txt:\n self.Llist.addItem(txt)\n self.LWin.close()\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n\n def DelLibraryPath(self):\n items1 = self.Llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.Llist.removeItemWidget(self.Llist.takeItem(jj.row()))\n\n def DelLibraries(self):\n items1 = self.llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.llist.removeItemWidget(self.llist.takeItem(jj.row()))\n\n\n<code token>\n", "<import token>\n<class token>\n\n\nclass BackendTread1(QThread):\n <assignment token>\n <assignment token>\n\n def __init__(self, parent=None):\n super(BackendTread1, self).__init__(parent)\n\n def startCom(self):\n self.process = subprocess.Popen(cmd1)\n <function token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n\n def __init__(self):\n super(basePage, self).__init__()\n self.setupUi(self)\n self.startpath = os.getcwd()\n self.actionbuild.triggered.connect(self.checkFLAG)\n self.actionclean.triggered.connect(self.CleanProject)\n self.actionopen_project.triggered.connect(self.ChooseProDir)\n self.actionsave_project.triggered.connect(self.modifyFLAG)\n self.actionexit.triggered.connect(qApp.quit)\n self.tb1 = self.addToolBar('tool')\n actionopen1 = QAction(QIcon('./Compile/file.png'), '打开工程', self)\n self.tb1.addAction(actionopen1)\n actionopen1.triggered.connect(self.ChooseProDir)\n self.tb1.addSeparator()\n actionstop = QAction(QIcon('./Compile/stop.png'), '停止', self)\n self.tb1.addAction(actionstop)\n actionstop.triggered.connect(self.KillProcess)\n self.tb1.addSeparator()\n actionExit = QAction(QIcon('./Compile/exit.png'), '退出', self)\n self.tb1.addAction(actionExit)\n actionExit.triggered.connect(qApp.quit)\n self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.contextMenu = QMenu(self)\n self.actionA = self.contextMenu.addAction('删除')\n self.actionA.triggered.connect(self.remove)\n self.includeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(1))\n self.excludeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(2))\n self.delPath1.clicked.connect(self.includeList.clear)\n self.delPath2.clicked.connect(self.excludeList.clear)\n self.addPath1.clicked.connect(lambda : self.ShowDialog(1))\n self.addPath2.clicked.connect(self.AddExpath)\n self.fileselect = fileselect.Ui_Dialog()\n self.listWidget.currentRowChanged.connect(self.display)\n self.initLibraryWindow()\n self.Llist.setSelectionMode(3)\n self.llist.setSelectionMode(3)\n self.barlabel = QLabel('barlabel')\n\n def initUI(self):\n self.includeList.clear()\n self.excludeList.clear()\n self.Llist.clear()\n self.llist.clear()\n self.ProjectName.setText(self.DebugName)\n self.HithTecDir.setText(self.HighTecDir)\n self.GCCFLAGName.setText(self.CCFLAG)\n self.LINKFLAGName.setText(self.LINKFLAG)\n self.ProjectName_2.setText(self.PROJECTDIR)\n self.ProjectName_2.setEnabled(False)\n self.barlabel.setText('准备中')\n self.statusBar.addPermanentWidget(self.barlabel)\n self.Result.clear()\n if self.includepath:\n self.includeList.addItems(self.includepath)\n if self.excludefiles:\n self.excludeList.addItems(self.excludefiles)\n if self.LibraryPath:\n self.Llist.addItems(self.LibraryPath)\n if self.libraties:\n self.llist.addItems(self.libraties)\n\n def display(self, index):\n self.index = index\n self.stackedWidget.setCurrentIndex(index)\n\n def initLibraryWindow(self):\n self.LWUI = AddLibraryPath.Ui_LSelect()\n self.LWin = QWidget()\n self.LWin.setWindowModality(Qt.ApplicationModal)\n self.LWUI.setupUi(self.LWin)\n self.LWUI.LibraryP.setText('')\n self.add1.clicked.connect(self.LWin.show)\n self.LWUI.L_Cancel.clicked.connect(self.LWin.close)\n self.LWUI.L_Workspace.clicked.connect(lambda : self.ShowDialog(1))\n self.LWUI.L_OK.clicked.connect(self.AddLibraryPath)\n self.del1.clicked.connect(self.DelLibraryPath)\n self.lWUI = Enterlibraries.Ui_LSelect()\n self.lWin = QWidget()\n self.lWin.setWindowModality(Qt.ApplicationModal)\n self.lWUI.setupUi(self.lWin)\n self.LWUI.LibraryP.setText('')\n self.add2.clicked.connect(self.lWin.show)\n self.lWUI.l_OK.clicked.connect(self.AddLibraries)\n self.lWUI.l_Cancel.clicked.connect(self.lWin.close)\n self.del2.clicked.connect(self.DelLibraries)\n\n def KillProcess(self):\n os.system('taskkill /f /t /im make.exe')\n self.Result.append('用户终止执行')\n\n def ChooseProDir(self):\n dir = QFileDialog.getExistingDirectory()\n dir = dir.replace('/', '\\\\')\n self.ProjectName_2.setText(dir)\n if dir != '':\n os.chdir(dir)\n import automake_config as ac\n (DebugName, HighTecDir, CCFLAG, LINKFLAG, includepath,\n excludefiles, g_except_dir_list, g_except_file_list,\n LibraryPath, libraties) = ac.maininit()\n self.includepath = includepath\n self.excludefiles = excludefiles\n self.DebugName = DebugName\n self.CCFLAG = CCFLAG\n self.LINKFLAG = LINKFLAG\n self.HighTecDir = HighTecDir\n self.PROJECTDIR = dir\n self.LibraryPath = LibraryPath\n self.libraties = libraties\n self.AllPath = ac.FindAllPath(dir)\n self.initDialog()\n self.fileselect.buttonBox.accepted.connect(self.GetPath)\n self.fileselect.treeWidget.setSelectionMode(3)\n self.fileselect.buttonBox.rejected.connect(self.Cleartree)\n a.initUI()\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n\n def remove(self):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if self.index == 3:\n if items1:\n for jj in items1:\n self.includeList.removeItemWidget(self.includeList.\n takeItem(jj.row()))\n if self.index == 4:\n if items2:\n for jj in items2:\n self.excludeList.removeItemWidget(self.excludeList.\n takeItem(jj.row()))\n\n def EndResult(self):\n print(os.getcwd())\n f = open('./conerr.err', 'r')\n lines = f.readlines()\n j = 0\n for ii in lines:\n if 'error:' in ii:\n self.Result.append('<font color=\"#FF0000\">%s</font> ' % ii)\n j = 1\n if j != 1:\n self.Result.append('<font color=\"#FF0000\">finished!!!!!!!!</font> '\n )\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working = False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n\n def initBar(self):\n global NUM\n self.progressBar = QProgressBar()\n self.Result.clear()\n self.barlabel.setText('正在编译:')\n self.statusBar.addPermanentWidget(self.progressBar, stretch=2)\n f = open('./Default/Default.objectlist', 'r')\n lines = f.readlines()\n f.close()\n NUM = len(lines)\n self.progressBar.setRange(0, len(lines))\n global VAL\n VAL = 0\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n\n def StartCompile(self, Hdir):\n global cmd1\n cmd1 = '%s\\\\bin\\\\make -j8 all' % Hdir\n os.chdir(self.ProjectName_2.text() + '/Default')\n self.backend1 = BackendTread1()\n self.backend1.startcompile1.connect(self.PrintConsole)\n self.backend1.endSig.connect(self.EndResult)\n self.backend1.start()\n self.backend = BackendTread()\n self.backend.setvalue.connect(self.SetProgressBarVal)\n self.backend.start()\n \"\"\"self.process = subprocess.call(cmd1)\n self.process.wait()\n f= open('console.log','r')\n lines =f.readlines()\n for ii in lines:\n if 'error:'in ii:\n self.Result.insertText(ii+'\n')\"\"\"\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n\n def modifyFLAG(self):\n CCFLAGNOW = self.GCCFLAGName.toPlainText()\n LINKFLAGNOW = self.LINKFLAGName.toPlainText()\n HighTecDirNOW = self.HithTecDir.text()\n DebugNameNOW = self.ProjectName.text()\n inn = self.includeList.count()\n inpathNOW = []\n exn = self.excludeList.count()\n expathNOW = []\n Ln = self.Llist.count()\n LnNOW = []\n ln = self.llist.count()\n lnNOW = []\n try:\n for i in range(inn):\n inpathNOW.append(self.includeList.item(i).text())\n for i in range(exn):\n expathNOW.append(self.excludeList.item(i).text())\n f = open('./py.pyconfig', 'w', encoding='utf-8')\n tLink = re.split(' ', LINKFLAGNOW)\n Linkchange = ''\n for iii in tLink:\n if '-L' not in iii and '-l:' not in iii:\n Linkchange += iii + ' '\n for i in range(Ln):\n p = re.split('{workspace}/', self.Llist.item(i).text())\n if len(p) == 1:\n Linkchange += '-L\"' + os.path.abspath(p[0]) + '\" '\n else:\n Linkchange += '-L\"' + os.path.abspath(p[1]) + '\" '\n LnNOW.append(self.Llist.item(i).text())\n for i in range(ln):\n Linkchange += '-l' + self.llist.item(i).text() + ' '\n lnNOW.append(self.llist.item(i).text())\n f.write('CCFLAG=' + CCFLAGNOW + '\\n')\n f.write('LINKFLAG=' + Linkchange + '\\n')\n f.write('HighTecDir=' + HighTecDirNOW + '\\n')\n f.write('DebugName=' + DebugNameNOW + '\\n')\n aa = 'includepath='\n for a in inpathNOW:\n if a != '':\n aa += a + ','\n f.write(aa + '\\n')\n bb = 'excludefiles='\n for b in expathNOW:\n if b != '':\n bb += b + ','\n f.write(bb + '\\n')\n cc = 'LibraryPath='\n for c in LnNOW:\n if c != '':\n cc += c + ','\n dd = 'libraties='\n for d in lnNOW:\n if d != '':\n dd += d + ','\n f.write(cc + '\\n')\n f.write(dd + '\\n')\n f.close()\n self.LINKFLAGName.setText('')\n self.LINKFLAGName.setText(Linkchange)\n except:\n f.close()\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n\n def testaa(self):\n print('1')\n\n def CloseTools(self):\n print(1)\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n\n def ShowDialog(self, id):\n self.idPath = id\n self.di.exec()\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n\n def AddExpath(self):\n dir1, file1 = QFileDialog.getOpenFileNames(self, '选择过滤文件', os.\n getcwd(), 'C FILES(*.c)')\n for ii in dir1:\n if ii != '':\n dir2 = re.split(os.getcwd().replace('\\\\', '/'), ii)[1]\n self.excludeList.addItem(dir2)\n\n def AddLibraryPath(self):\n txt = self.LWUI.LibraryP.text()\n if txt:\n self.Llist.addItem(txt)\n self.LWin.close()\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n\n def DelLibraryPath(self):\n items1 = self.Llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.Llist.removeItemWidget(self.Llist.takeItem(jj.row()))\n\n def DelLibraries(self):\n items1 = self.llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.llist.removeItemWidget(self.llist.takeItem(jj.row()))\n\n\n<code token>\n", "<import token>\n<class token>\n\n\nclass BackendTread1(QThread):\n <assignment token>\n <assignment token>\n <function token>\n\n def startCom(self):\n self.process = subprocess.Popen(cmd1)\n <function token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n\n def __init__(self):\n super(basePage, self).__init__()\n self.setupUi(self)\n self.startpath = os.getcwd()\n self.actionbuild.triggered.connect(self.checkFLAG)\n self.actionclean.triggered.connect(self.CleanProject)\n self.actionopen_project.triggered.connect(self.ChooseProDir)\n self.actionsave_project.triggered.connect(self.modifyFLAG)\n self.actionexit.triggered.connect(qApp.quit)\n self.tb1 = self.addToolBar('tool')\n actionopen1 = QAction(QIcon('./Compile/file.png'), '打开工程', self)\n self.tb1.addAction(actionopen1)\n actionopen1.triggered.connect(self.ChooseProDir)\n self.tb1.addSeparator()\n actionstop = QAction(QIcon('./Compile/stop.png'), '停止', self)\n self.tb1.addAction(actionstop)\n actionstop.triggered.connect(self.KillProcess)\n self.tb1.addSeparator()\n actionExit = QAction(QIcon('./Compile/exit.png'), '退出', self)\n self.tb1.addAction(actionExit)\n actionExit.triggered.connect(qApp.quit)\n self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.contextMenu = QMenu(self)\n self.actionA = self.contextMenu.addAction('删除')\n self.actionA.triggered.connect(self.remove)\n self.includeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(1))\n self.excludeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(2))\n self.delPath1.clicked.connect(self.includeList.clear)\n self.delPath2.clicked.connect(self.excludeList.clear)\n self.addPath1.clicked.connect(lambda : self.ShowDialog(1))\n self.addPath2.clicked.connect(self.AddExpath)\n self.fileselect = fileselect.Ui_Dialog()\n self.listWidget.currentRowChanged.connect(self.display)\n self.initLibraryWindow()\n self.Llist.setSelectionMode(3)\n self.llist.setSelectionMode(3)\n self.barlabel = QLabel('barlabel')\n\n def initUI(self):\n self.includeList.clear()\n self.excludeList.clear()\n self.Llist.clear()\n self.llist.clear()\n self.ProjectName.setText(self.DebugName)\n self.HithTecDir.setText(self.HighTecDir)\n self.GCCFLAGName.setText(self.CCFLAG)\n self.LINKFLAGName.setText(self.LINKFLAG)\n self.ProjectName_2.setText(self.PROJECTDIR)\n self.ProjectName_2.setEnabled(False)\n self.barlabel.setText('准备中')\n self.statusBar.addPermanentWidget(self.barlabel)\n self.Result.clear()\n if self.includepath:\n self.includeList.addItems(self.includepath)\n if self.excludefiles:\n self.excludeList.addItems(self.excludefiles)\n if self.LibraryPath:\n self.Llist.addItems(self.LibraryPath)\n if self.libraties:\n self.llist.addItems(self.libraties)\n\n def display(self, index):\n self.index = index\n self.stackedWidget.setCurrentIndex(index)\n\n def initLibraryWindow(self):\n self.LWUI = AddLibraryPath.Ui_LSelect()\n self.LWin = QWidget()\n self.LWin.setWindowModality(Qt.ApplicationModal)\n self.LWUI.setupUi(self.LWin)\n self.LWUI.LibraryP.setText('')\n self.add1.clicked.connect(self.LWin.show)\n self.LWUI.L_Cancel.clicked.connect(self.LWin.close)\n self.LWUI.L_Workspace.clicked.connect(lambda : self.ShowDialog(1))\n self.LWUI.L_OK.clicked.connect(self.AddLibraryPath)\n self.del1.clicked.connect(self.DelLibraryPath)\n self.lWUI = Enterlibraries.Ui_LSelect()\n self.lWin = QWidget()\n self.lWin.setWindowModality(Qt.ApplicationModal)\n self.lWUI.setupUi(self.lWin)\n self.LWUI.LibraryP.setText('')\n self.add2.clicked.connect(self.lWin.show)\n self.lWUI.l_OK.clicked.connect(self.AddLibraries)\n self.lWUI.l_Cancel.clicked.connect(self.lWin.close)\n self.del2.clicked.connect(self.DelLibraries)\n\n def KillProcess(self):\n os.system('taskkill /f /t /im make.exe')\n self.Result.append('用户终止执行')\n\n def ChooseProDir(self):\n dir = QFileDialog.getExistingDirectory()\n dir = dir.replace('/', '\\\\')\n self.ProjectName_2.setText(dir)\n if dir != '':\n os.chdir(dir)\n import automake_config as ac\n (DebugName, HighTecDir, CCFLAG, LINKFLAG, includepath,\n excludefiles, g_except_dir_list, g_except_file_list,\n LibraryPath, libraties) = ac.maininit()\n self.includepath = includepath\n self.excludefiles = excludefiles\n self.DebugName = DebugName\n self.CCFLAG = CCFLAG\n self.LINKFLAG = LINKFLAG\n self.HighTecDir = HighTecDir\n self.PROJECTDIR = dir\n self.LibraryPath = LibraryPath\n self.libraties = libraties\n self.AllPath = ac.FindAllPath(dir)\n self.initDialog()\n self.fileselect.buttonBox.accepted.connect(self.GetPath)\n self.fileselect.treeWidget.setSelectionMode(3)\n self.fileselect.buttonBox.rejected.connect(self.Cleartree)\n a.initUI()\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n\n def remove(self):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if self.index == 3:\n if items1:\n for jj in items1:\n self.includeList.removeItemWidget(self.includeList.\n takeItem(jj.row()))\n if self.index == 4:\n if items2:\n for jj in items2:\n self.excludeList.removeItemWidget(self.excludeList.\n takeItem(jj.row()))\n\n def EndResult(self):\n print(os.getcwd())\n f = open('./conerr.err', 'r')\n lines = f.readlines()\n j = 0\n for ii in lines:\n if 'error:' in ii:\n self.Result.append('<font color=\"#FF0000\">%s</font> ' % ii)\n j = 1\n if j != 1:\n self.Result.append('<font color=\"#FF0000\">finished!!!!!!!!</font> '\n )\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working = False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n\n def initBar(self):\n global NUM\n self.progressBar = QProgressBar()\n self.Result.clear()\n self.barlabel.setText('正在编译:')\n self.statusBar.addPermanentWidget(self.progressBar, stretch=2)\n f = open('./Default/Default.objectlist', 'r')\n lines = f.readlines()\n f.close()\n NUM = len(lines)\n self.progressBar.setRange(0, len(lines))\n global VAL\n VAL = 0\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n\n def StartCompile(self, Hdir):\n global cmd1\n cmd1 = '%s\\\\bin\\\\make -j8 all' % Hdir\n os.chdir(self.ProjectName_2.text() + '/Default')\n self.backend1 = BackendTread1()\n self.backend1.startcompile1.connect(self.PrintConsole)\n self.backend1.endSig.connect(self.EndResult)\n self.backend1.start()\n self.backend = BackendTread()\n self.backend.setvalue.connect(self.SetProgressBarVal)\n self.backend.start()\n \"\"\"self.process = subprocess.call(cmd1)\n self.process.wait()\n f= open('console.log','r')\n lines =f.readlines()\n for ii in lines:\n if 'error:'in ii:\n self.Result.insertText(ii+'\n')\"\"\"\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n\n def modifyFLAG(self):\n CCFLAGNOW = self.GCCFLAGName.toPlainText()\n LINKFLAGNOW = self.LINKFLAGName.toPlainText()\n HighTecDirNOW = self.HithTecDir.text()\n DebugNameNOW = self.ProjectName.text()\n inn = self.includeList.count()\n inpathNOW = []\n exn = self.excludeList.count()\n expathNOW = []\n Ln = self.Llist.count()\n LnNOW = []\n ln = self.llist.count()\n lnNOW = []\n try:\n for i in range(inn):\n inpathNOW.append(self.includeList.item(i).text())\n for i in range(exn):\n expathNOW.append(self.excludeList.item(i).text())\n f = open('./py.pyconfig', 'w', encoding='utf-8')\n tLink = re.split(' ', LINKFLAGNOW)\n Linkchange = ''\n for iii in tLink:\n if '-L' not in iii and '-l:' not in iii:\n Linkchange += iii + ' '\n for i in range(Ln):\n p = re.split('{workspace}/', self.Llist.item(i).text())\n if len(p) == 1:\n Linkchange += '-L\"' + os.path.abspath(p[0]) + '\" '\n else:\n Linkchange += '-L\"' + os.path.abspath(p[1]) + '\" '\n LnNOW.append(self.Llist.item(i).text())\n for i in range(ln):\n Linkchange += '-l' + self.llist.item(i).text() + ' '\n lnNOW.append(self.llist.item(i).text())\n f.write('CCFLAG=' + CCFLAGNOW + '\\n')\n f.write('LINKFLAG=' + Linkchange + '\\n')\n f.write('HighTecDir=' + HighTecDirNOW + '\\n')\n f.write('DebugName=' + DebugNameNOW + '\\n')\n aa = 'includepath='\n for a in inpathNOW:\n if a != '':\n aa += a + ','\n f.write(aa + '\\n')\n bb = 'excludefiles='\n for b in expathNOW:\n if b != '':\n bb += b + ','\n f.write(bb + '\\n')\n cc = 'LibraryPath='\n for c in LnNOW:\n if c != '':\n cc += c + ','\n dd = 'libraties='\n for d in lnNOW:\n if d != '':\n dd += d + ','\n f.write(cc + '\\n')\n f.write(dd + '\\n')\n f.close()\n self.LINKFLAGName.setText('')\n self.LINKFLAGName.setText(Linkchange)\n except:\n f.close()\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n\n def testaa(self):\n print('1')\n\n def CloseTools(self):\n print(1)\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n\n def ShowDialog(self, id):\n self.idPath = id\n self.di.exec()\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n\n def AddExpath(self):\n dir1, file1 = QFileDialog.getOpenFileNames(self, '选择过滤文件', os.\n getcwd(), 'C FILES(*.c)')\n for ii in dir1:\n if ii != '':\n dir2 = re.split(os.getcwd().replace('\\\\', '/'), ii)[1]\n self.excludeList.addItem(dir2)\n\n def AddLibraryPath(self):\n txt = self.LWUI.LibraryP.text()\n if txt:\n self.Llist.addItem(txt)\n self.LWin.close()\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n\n def DelLibraryPath(self):\n items1 = self.Llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.Llist.removeItemWidget(self.Llist.takeItem(jj.row()))\n\n def DelLibraries(self):\n items1 = self.llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.llist.removeItemWidget(self.llist.takeItem(jj.row()))\n\n\n<code token>\n", "<import token>\n<class token>\n\n\nclass BackendTread1(QThread):\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n\n def __init__(self):\n super(basePage, self).__init__()\n self.setupUi(self)\n self.startpath = os.getcwd()\n self.actionbuild.triggered.connect(self.checkFLAG)\n self.actionclean.triggered.connect(self.CleanProject)\n self.actionopen_project.triggered.connect(self.ChooseProDir)\n self.actionsave_project.triggered.connect(self.modifyFLAG)\n self.actionexit.triggered.connect(qApp.quit)\n self.tb1 = self.addToolBar('tool')\n actionopen1 = QAction(QIcon('./Compile/file.png'), '打开工程', self)\n self.tb1.addAction(actionopen1)\n actionopen1.triggered.connect(self.ChooseProDir)\n self.tb1.addSeparator()\n actionstop = QAction(QIcon('./Compile/stop.png'), '停止', self)\n self.tb1.addAction(actionstop)\n actionstop.triggered.connect(self.KillProcess)\n self.tb1.addSeparator()\n actionExit = QAction(QIcon('./Compile/exit.png'), '退出', self)\n self.tb1.addAction(actionExit)\n actionExit.triggered.connect(qApp.quit)\n self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.contextMenu = QMenu(self)\n self.actionA = self.contextMenu.addAction('删除')\n self.actionA.triggered.connect(self.remove)\n self.includeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(1))\n self.excludeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(2))\n self.delPath1.clicked.connect(self.includeList.clear)\n self.delPath2.clicked.connect(self.excludeList.clear)\n self.addPath1.clicked.connect(lambda : self.ShowDialog(1))\n self.addPath2.clicked.connect(self.AddExpath)\n self.fileselect = fileselect.Ui_Dialog()\n self.listWidget.currentRowChanged.connect(self.display)\n self.initLibraryWindow()\n self.Llist.setSelectionMode(3)\n self.llist.setSelectionMode(3)\n self.barlabel = QLabel('barlabel')\n\n def initUI(self):\n self.includeList.clear()\n self.excludeList.clear()\n self.Llist.clear()\n self.llist.clear()\n self.ProjectName.setText(self.DebugName)\n self.HithTecDir.setText(self.HighTecDir)\n self.GCCFLAGName.setText(self.CCFLAG)\n self.LINKFLAGName.setText(self.LINKFLAG)\n self.ProjectName_2.setText(self.PROJECTDIR)\n self.ProjectName_2.setEnabled(False)\n self.barlabel.setText('准备中')\n self.statusBar.addPermanentWidget(self.barlabel)\n self.Result.clear()\n if self.includepath:\n self.includeList.addItems(self.includepath)\n if self.excludefiles:\n self.excludeList.addItems(self.excludefiles)\n if self.LibraryPath:\n self.Llist.addItems(self.LibraryPath)\n if self.libraties:\n self.llist.addItems(self.libraties)\n\n def display(self, index):\n self.index = index\n self.stackedWidget.setCurrentIndex(index)\n\n def initLibraryWindow(self):\n self.LWUI = AddLibraryPath.Ui_LSelect()\n self.LWin = QWidget()\n self.LWin.setWindowModality(Qt.ApplicationModal)\n self.LWUI.setupUi(self.LWin)\n self.LWUI.LibraryP.setText('')\n self.add1.clicked.connect(self.LWin.show)\n self.LWUI.L_Cancel.clicked.connect(self.LWin.close)\n self.LWUI.L_Workspace.clicked.connect(lambda : self.ShowDialog(1))\n self.LWUI.L_OK.clicked.connect(self.AddLibraryPath)\n self.del1.clicked.connect(self.DelLibraryPath)\n self.lWUI = Enterlibraries.Ui_LSelect()\n self.lWin = QWidget()\n self.lWin.setWindowModality(Qt.ApplicationModal)\n self.lWUI.setupUi(self.lWin)\n self.LWUI.LibraryP.setText('')\n self.add2.clicked.connect(self.lWin.show)\n self.lWUI.l_OK.clicked.connect(self.AddLibraries)\n self.lWUI.l_Cancel.clicked.connect(self.lWin.close)\n self.del2.clicked.connect(self.DelLibraries)\n\n def KillProcess(self):\n os.system('taskkill /f /t /im make.exe')\n self.Result.append('用户终止执行')\n\n def ChooseProDir(self):\n dir = QFileDialog.getExistingDirectory()\n dir = dir.replace('/', '\\\\')\n self.ProjectName_2.setText(dir)\n if dir != '':\n os.chdir(dir)\n import automake_config as ac\n (DebugName, HighTecDir, CCFLAG, LINKFLAG, includepath,\n excludefiles, g_except_dir_list, g_except_file_list,\n LibraryPath, libraties) = ac.maininit()\n self.includepath = includepath\n self.excludefiles = excludefiles\n self.DebugName = DebugName\n self.CCFLAG = CCFLAG\n self.LINKFLAG = LINKFLAG\n self.HighTecDir = HighTecDir\n self.PROJECTDIR = dir\n self.LibraryPath = LibraryPath\n self.libraties = libraties\n self.AllPath = ac.FindAllPath(dir)\n self.initDialog()\n self.fileselect.buttonBox.accepted.connect(self.GetPath)\n self.fileselect.treeWidget.setSelectionMode(3)\n self.fileselect.buttonBox.rejected.connect(self.Cleartree)\n a.initUI()\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n\n def remove(self):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if self.index == 3:\n if items1:\n for jj in items1:\n self.includeList.removeItemWidget(self.includeList.\n takeItem(jj.row()))\n if self.index == 4:\n if items2:\n for jj in items2:\n self.excludeList.removeItemWidget(self.excludeList.\n takeItem(jj.row()))\n\n def EndResult(self):\n print(os.getcwd())\n f = open('./conerr.err', 'r')\n lines = f.readlines()\n j = 0\n for ii in lines:\n if 'error:' in ii:\n self.Result.append('<font color=\"#FF0000\">%s</font> ' % ii)\n j = 1\n if j != 1:\n self.Result.append('<font color=\"#FF0000\">finished!!!!!!!!</font> '\n )\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working = False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n\n def initBar(self):\n global NUM\n self.progressBar = QProgressBar()\n self.Result.clear()\n self.barlabel.setText('正在编译:')\n self.statusBar.addPermanentWidget(self.progressBar, stretch=2)\n f = open('./Default/Default.objectlist', 'r')\n lines = f.readlines()\n f.close()\n NUM = len(lines)\n self.progressBar.setRange(0, len(lines))\n global VAL\n VAL = 0\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n\n def StartCompile(self, Hdir):\n global cmd1\n cmd1 = '%s\\\\bin\\\\make -j8 all' % Hdir\n os.chdir(self.ProjectName_2.text() + '/Default')\n self.backend1 = BackendTread1()\n self.backend1.startcompile1.connect(self.PrintConsole)\n self.backend1.endSig.connect(self.EndResult)\n self.backend1.start()\n self.backend = BackendTread()\n self.backend.setvalue.connect(self.SetProgressBarVal)\n self.backend.start()\n \"\"\"self.process = subprocess.call(cmd1)\n self.process.wait()\n f= open('console.log','r')\n lines =f.readlines()\n for ii in lines:\n if 'error:'in ii:\n self.Result.insertText(ii+'\n')\"\"\"\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n\n def modifyFLAG(self):\n CCFLAGNOW = self.GCCFLAGName.toPlainText()\n LINKFLAGNOW = self.LINKFLAGName.toPlainText()\n HighTecDirNOW = self.HithTecDir.text()\n DebugNameNOW = self.ProjectName.text()\n inn = self.includeList.count()\n inpathNOW = []\n exn = self.excludeList.count()\n expathNOW = []\n Ln = self.Llist.count()\n LnNOW = []\n ln = self.llist.count()\n lnNOW = []\n try:\n for i in range(inn):\n inpathNOW.append(self.includeList.item(i).text())\n for i in range(exn):\n expathNOW.append(self.excludeList.item(i).text())\n f = open('./py.pyconfig', 'w', encoding='utf-8')\n tLink = re.split(' ', LINKFLAGNOW)\n Linkchange = ''\n for iii in tLink:\n if '-L' not in iii and '-l:' not in iii:\n Linkchange += iii + ' '\n for i in range(Ln):\n p = re.split('{workspace}/', self.Llist.item(i).text())\n if len(p) == 1:\n Linkchange += '-L\"' + os.path.abspath(p[0]) + '\" '\n else:\n Linkchange += '-L\"' + os.path.abspath(p[1]) + '\" '\n LnNOW.append(self.Llist.item(i).text())\n for i in range(ln):\n Linkchange += '-l' + self.llist.item(i).text() + ' '\n lnNOW.append(self.llist.item(i).text())\n f.write('CCFLAG=' + CCFLAGNOW + '\\n')\n f.write('LINKFLAG=' + Linkchange + '\\n')\n f.write('HighTecDir=' + HighTecDirNOW + '\\n')\n f.write('DebugName=' + DebugNameNOW + '\\n')\n aa = 'includepath='\n for a in inpathNOW:\n if a != '':\n aa += a + ','\n f.write(aa + '\\n')\n bb = 'excludefiles='\n for b in expathNOW:\n if b != '':\n bb += b + ','\n f.write(bb + '\\n')\n cc = 'LibraryPath='\n for c in LnNOW:\n if c != '':\n cc += c + ','\n dd = 'libraties='\n for d in lnNOW:\n if d != '':\n dd += d + ','\n f.write(cc + '\\n')\n f.write(dd + '\\n')\n f.close()\n self.LINKFLAGName.setText('')\n self.LINKFLAGName.setText(Linkchange)\n except:\n f.close()\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n\n def testaa(self):\n print('1')\n\n def CloseTools(self):\n print(1)\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n\n def ShowDialog(self, id):\n self.idPath = id\n self.di.exec()\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n\n def AddExpath(self):\n dir1, file1 = QFileDialog.getOpenFileNames(self, '选择过滤文件', os.\n getcwd(), 'C FILES(*.c)')\n for ii in dir1:\n if ii != '':\n dir2 = re.split(os.getcwd().replace('\\\\', '/'), ii)[1]\n self.excludeList.addItem(dir2)\n\n def AddLibraryPath(self):\n txt = self.LWUI.LibraryP.text()\n if txt:\n self.Llist.addItem(txt)\n self.LWin.close()\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n\n def DelLibraryPath(self):\n items1 = self.Llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.Llist.removeItemWidget(self.Llist.takeItem(jj.row()))\n\n def DelLibraries(self):\n items1 = self.llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.llist.removeItemWidget(self.llist.takeItem(jj.row()))\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n\n def __init__(self):\n super(basePage, self).__init__()\n self.setupUi(self)\n self.startpath = os.getcwd()\n self.actionbuild.triggered.connect(self.checkFLAG)\n self.actionclean.triggered.connect(self.CleanProject)\n self.actionopen_project.triggered.connect(self.ChooseProDir)\n self.actionsave_project.triggered.connect(self.modifyFLAG)\n self.actionexit.triggered.connect(qApp.quit)\n self.tb1 = self.addToolBar('tool')\n actionopen1 = QAction(QIcon('./Compile/file.png'), '打开工程', self)\n self.tb1.addAction(actionopen1)\n actionopen1.triggered.connect(self.ChooseProDir)\n self.tb1.addSeparator()\n actionstop = QAction(QIcon('./Compile/stop.png'), '停止', self)\n self.tb1.addAction(actionstop)\n actionstop.triggered.connect(self.KillProcess)\n self.tb1.addSeparator()\n actionExit = QAction(QIcon('./Compile/exit.png'), '退出', self)\n self.tb1.addAction(actionExit)\n actionExit.triggered.connect(qApp.quit)\n self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.contextMenu = QMenu(self)\n self.actionA = self.contextMenu.addAction('删除')\n self.actionA.triggered.connect(self.remove)\n self.includeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(1))\n self.excludeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(2))\n self.delPath1.clicked.connect(self.includeList.clear)\n self.delPath2.clicked.connect(self.excludeList.clear)\n self.addPath1.clicked.connect(lambda : self.ShowDialog(1))\n self.addPath2.clicked.connect(self.AddExpath)\n self.fileselect = fileselect.Ui_Dialog()\n self.listWidget.currentRowChanged.connect(self.display)\n self.initLibraryWindow()\n self.Llist.setSelectionMode(3)\n self.llist.setSelectionMode(3)\n self.barlabel = QLabel('barlabel')\n\n def initUI(self):\n self.includeList.clear()\n self.excludeList.clear()\n self.Llist.clear()\n self.llist.clear()\n self.ProjectName.setText(self.DebugName)\n self.HithTecDir.setText(self.HighTecDir)\n self.GCCFLAGName.setText(self.CCFLAG)\n self.LINKFLAGName.setText(self.LINKFLAG)\n self.ProjectName_2.setText(self.PROJECTDIR)\n self.ProjectName_2.setEnabled(False)\n self.barlabel.setText('准备中')\n self.statusBar.addPermanentWidget(self.barlabel)\n self.Result.clear()\n if self.includepath:\n self.includeList.addItems(self.includepath)\n if self.excludefiles:\n self.excludeList.addItems(self.excludefiles)\n if self.LibraryPath:\n self.Llist.addItems(self.LibraryPath)\n if self.libraties:\n self.llist.addItems(self.libraties)\n\n def display(self, index):\n self.index = index\n self.stackedWidget.setCurrentIndex(index)\n\n def initLibraryWindow(self):\n self.LWUI = AddLibraryPath.Ui_LSelect()\n self.LWin = QWidget()\n self.LWin.setWindowModality(Qt.ApplicationModal)\n self.LWUI.setupUi(self.LWin)\n self.LWUI.LibraryP.setText('')\n self.add1.clicked.connect(self.LWin.show)\n self.LWUI.L_Cancel.clicked.connect(self.LWin.close)\n self.LWUI.L_Workspace.clicked.connect(lambda : self.ShowDialog(1))\n self.LWUI.L_OK.clicked.connect(self.AddLibraryPath)\n self.del1.clicked.connect(self.DelLibraryPath)\n self.lWUI = Enterlibraries.Ui_LSelect()\n self.lWin = QWidget()\n self.lWin.setWindowModality(Qt.ApplicationModal)\n self.lWUI.setupUi(self.lWin)\n self.LWUI.LibraryP.setText('')\n self.add2.clicked.connect(self.lWin.show)\n self.lWUI.l_OK.clicked.connect(self.AddLibraries)\n self.lWUI.l_Cancel.clicked.connect(self.lWin.close)\n self.del2.clicked.connect(self.DelLibraries)\n\n def KillProcess(self):\n os.system('taskkill /f /t /im make.exe')\n self.Result.append('用户终止执行')\n\n def ChooseProDir(self):\n dir = QFileDialog.getExistingDirectory()\n dir = dir.replace('/', '\\\\')\n self.ProjectName_2.setText(dir)\n if dir != '':\n os.chdir(dir)\n import automake_config as ac\n (DebugName, HighTecDir, CCFLAG, LINKFLAG, includepath,\n excludefiles, g_except_dir_list, g_except_file_list,\n LibraryPath, libraties) = ac.maininit()\n self.includepath = includepath\n self.excludefiles = excludefiles\n self.DebugName = DebugName\n self.CCFLAG = CCFLAG\n self.LINKFLAG = LINKFLAG\n self.HighTecDir = HighTecDir\n self.PROJECTDIR = dir\n self.LibraryPath = LibraryPath\n self.libraties = libraties\n self.AllPath = ac.FindAllPath(dir)\n self.initDialog()\n self.fileselect.buttonBox.accepted.connect(self.GetPath)\n self.fileselect.treeWidget.setSelectionMode(3)\n self.fileselect.buttonBox.rejected.connect(self.Cleartree)\n a.initUI()\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n\n def remove(self):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if self.index == 3:\n if items1:\n for jj in items1:\n self.includeList.removeItemWidget(self.includeList.\n takeItem(jj.row()))\n if self.index == 4:\n if items2:\n for jj in items2:\n self.excludeList.removeItemWidget(self.excludeList.\n takeItem(jj.row()))\n\n def EndResult(self):\n print(os.getcwd())\n f = open('./conerr.err', 'r')\n lines = f.readlines()\n j = 0\n for ii in lines:\n if 'error:' in ii:\n self.Result.append('<font color=\"#FF0000\">%s</font> ' % ii)\n j = 1\n if j != 1:\n self.Result.append('<font color=\"#FF0000\">finished!!!!!!!!</font> '\n )\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working = False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n\n def initBar(self):\n global NUM\n self.progressBar = QProgressBar()\n self.Result.clear()\n self.barlabel.setText('正在编译:')\n self.statusBar.addPermanentWidget(self.progressBar, stretch=2)\n f = open('./Default/Default.objectlist', 'r')\n lines = f.readlines()\n f.close()\n NUM = len(lines)\n self.progressBar.setRange(0, len(lines))\n global VAL\n VAL = 0\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n\n def StartCompile(self, Hdir):\n global cmd1\n cmd1 = '%s\\\\bin\\\\make -j8 all' % Hdir\n os.chdir(self.ProjectName_2.text() + '/Default')\n self.backend1 = BackendTread1()\n self.backend1.startcompile1.connect(self.PrintConsole)\n self.backend1.endSig.connect(self.EndResult)\n self.backend1.start()\n self.backend = BackendTread()\n self.backend.setvalue.connect(self.SetProgressBarVal)\n self.backend.start()\n \"\"\"self.process = subprocess.call(cmd1)\n self.process.wait()\n f= open('console.log','r')\n lines =f.readlines()\n for ii in lines:\n if 'error:'in ii:\n self.Result.insertText(ii+'\n')\"\"\"\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n\n def modifyFLAG(self):\n CCFLAGNOW = self.GCCFLAGName.toPlainText()\n LINKFLAGNOW = self.LINKFLAGName.toPlainText()\n HighTecDirNOW = self.HithTecDir.text()\n DebugNameNOW = self.ProjectName.text()\n inn = self.includeList.count()\n inpathNOW = []\n exn = self.excludeList.count()\n expathNOW = []\n Ln = self.Llist.count()\n LnNOW = []\n ln = self.llist.count()\n lnNOW = []\n try:\n for i in range(inn):\n inpathNOW.append(self.includeList.item(i).text())\n for i in range(exn):\n expathNOW.append(self.excludeList.item(i).text())\n f = open('./py.pyconfig', 'w', encoding='utf-8')\n tLink = re.split(' ', LINKFLAGNOW)\n Linkchange = ''\n for iii in tLink:\n if '-L' not in iii and '-l:' not in iii:\n Linkchange += iii + ' '\n for i in range(Ln):\n p = re.split('{workspace}/', self.Llist.item(i).text())\n if len(p) == 1:\n Linkchange += '-L\"' + os.path.abspath(p[0]) + '\" '\n else:\n Linkchange += '-L\"' + os.path.abspath(p[1]) + '\" '\n LnNOW.append(self.Llist.item(i).text())\n for i in range(ln):\n Linkchange += '-l' + self.llist.item(i).text() + ' '\n lnNOW.append(self.llist.item(i).text())\n f.write('CCFLAG=' + CCFLAGNOW + '\\n')\n f.write('LINKFLAG=' + Linkchange + '\\n')\n f.write('HighTecDir=' + HighTecDirNOW + '\\n')\n f.write('DebugName=' + DebugNameNOW + '\\n')\n aa = 'includepath='\n for a in inpathNOW:\n if a != '':\n aa += a + ','\n f.write(aa + '\\n')\n bb = 'excludefiles='\n for b in expathNOW:\n if b != '':\n bb += b + ','\n f.write(bb + '\\n')\n cc = 'LibraryPath='\n for c in LnNOW:\n if c != '':\n cc += c + ','\n dd = 'libraties='\n for d in lnNOW:\n if d != '':\n dd += d + ','\n f.write(cc + '\\n')\n f.write(dd + '\\n')\n f.close()\n self.LINKFLAGName.setText('')\n self.LINKFLAGName.setText(Linkchange)\n except:\n f.close()\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n\n def testaa(self):\n print('1')\n\n def CloseTools(self):\n print(1)\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n\n def ShowDialog(self, id):\n self.idPath = id\n self.di.exec()\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n\n def AddExpath(self):\n dir1, file1 = QFileDialog.getOpenFileNames(self, '选择过滤文件', os.\n getcwd(), 'C FILES(*.c)')\n for ii in dir1:\n if ii != '':\n dir2 = re.split(os.getcwd().replace('\\\\', '/'), ii)[1]\n self.excludeList.addItem(dir2)\n\n def AddLibraryPath(self):\n txt = self.LWUI.LibraryP.text()\n if txt:\n self.Llist.addItem(txt)\n self.LWin.close()\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n\n def DelLibraryPath(self):\n items1 = self.Llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.Llist.removeItemWidget(self.Llist.takeItem(jj.row()))\n\n def DelLibraries(self):\n items1 = self.llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.llist.removeItemWidget(self.llist.takeItem(jj.row()))\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n\n def __init__(self):\n super(basePage, self).__init__()\n self.setupUi(self)\n self.startpath = os.getcwd()\n self.actionbuild.triggered.connect(self.checkFLAG)\n self.actionclean.triggered.connect(self.CleanProject)\n self.actionopen_project.triggered.connect(self.ChooseProDir)\n self.actionsave_project.triggered.connect(self.modifyFLAG)\n self.actionexit.triggered.connect(qApp.quit)\n self.tb1 = self.addToolBar('tool')\n actionopen1 = QAction(QIcon('./Compile/file.png'), '打开工程', self)\n self.tb1.addAction(actionopen1)\n actionopen1.triggered.connect(self.ChooseProDir)\n self.tb1.addSeparator()\n actionstop = QAction(QIcon('./Compile/stop.png'), '停止', self)\n self.tb1.addAction(actionstop)\n actionstop.triggered.connect(self.KillProcess)\n self.tb1.addSeparator()\n actionExit = QAction(QIcon('./Compile/exit.png'), '退出', self)\n self.tb1.addAction(actionExit)\n actionExit.triggered.connect(qApp.quit)\n self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.contextMenu = QMenu(self)\n self.actionA = self.contextMenu.addAction('删除')\n self.actionA.triggered.connect(self.remove)\n self.includeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(1))\n self.excludeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(2))\n self.delPath1.clicked.connect(self.includeList.clear)\n self.delPath2.clicked.connect(self.excludeList.clear)\n self.addPath1.clicked.connect(lambda : self.ShowDialog(1))\n self.addPath2.clicked.connect(self.AddExpath)\n self.fileselect = fileselect.Ui_Dialog()\n self.listWidget.currentRowChanged.connect(self.display)\n self.initLibraryWindow()\n self.Llist.setSelectionMode(3)\n self.llist.setSelectionMode(3)\n self.barlabel = QLabel('barlabel')\n\n def initUI(self):\n self.includeList.clear()\n self.excludeList.clear()\n self.Llist.clear()\n self.llist.clear()\n self.ProjectName.setText(self.DebugName)\n self.HithTecDir.setText(self.HighTecDir)\n self.GCCFLAGName.setText(self.CCFLAG)\n self.LINKFLAGName.setText(self.LINKFLAG)\n self.ProjectName_2.setText(self.PROJECTDIR)\n self.ProjectName_2.setEnabled(False)\n self.barlabel.setText('准备中')\n self.statusBar.addPermanentWidget(self.barlabel)\n self.Result.clear()\n if self.includepath:\n self.includeList.addItems(self.includepath)\n if self.excludefiles:\n self.excludeList.addItems(self.excludefiles)\n if self.LibraryPath:\n self.Llist.addItems(self.LibraryPath)\n if self.libraties:\n self.llist.addItems(self.libraties)\n <function token>\n\n def initLibraryWindow(self):\n self.LWUI = AddLibraryPath.Ui_LSelect()\n self.LWin = QWidget()\n self.LWin.setWindowModality(Qt.ApplicationModal)\n self.LWUI.setupUi(self.LWin)\n self.LWUI.LibraryP.setText('')\n self.add1.clicked.connect(self.LWin.show)\n self.LWUI.L_Cancel.clicked.connect(self.LWin.close)\n self.LWUI.L_Workspace.clicked.connect(lambda : self.ShowDialog(1))\n self.LWUI.L_OK.clicked.connect(self.AddLibraryPath)\n self.del1.clicked.connect(self.DelLibraryPath)\n self.lWUI = Enterlibraries.Ui_LSelect()\n self.lWin = QWidget()\n self.lWin.setWindowModality(Qt.ApplicationModal)\n self.lWUI.setupUi(self.lWin)\n self.LWUI.LibraryP.setText('')\n self.add2.clicked.connect(self.lWin.show)\n self.lWUI.l_OK.clicked.connect(self.AddLibraries)\n self.lWUI.l_Cancel.clicked.connect(self.lWin.close)\n self.del2.clicked.connect(self.DelLibraries)\n\n def KillProcess(self):\n os.system('taskkill /f /t /im make.exe')\n self.Result.append('用户终止执行')\n\n def ChooseProDir(self):\n dir = QFileDialog.getExistingDirectory()\n dir = dir.replace('/', '\\\\')\n self.ProjectName_2.setText(dir)\n if dir != '':\n os.chdir(dir)\n import automake_config as ac\n (DebugName, HighTecDir, CCFLAG, LINKFLAG, includepath,\n excludefiles, g_except_dir_list, g_except_file_list,\n LibraryPath, libraties) = ac.maininit()\n self.includepath = includepath\n self.excludefiles = excludefiles\n self.DebugName = DebugName\n self.CCFLAG = CCFLAG\n self.LINKFLAG = LINKFLAG\n self.HighTecDir = HighTecDir\n self.PROJECTDIR = dir\n self.LibraryPath = LibraryPath\n self.libraties = libraties\n self.AllPath = ac.FindAllPath(dir)\n self.initDialog()\n self.fileselect.buttonBox.accepted.connect(self.GetPath)\n self.fileselect.treeWidget.setSelectionMode(3)\n self.fileselect.buttonBox.rejected.connect(self.Cleartree)\n a.initUI()\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n\n def remove(self):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if self.index == 3:\n if items1:\n for jj in items1:\n self.includeList.removeItemWidget(self.includeList.\n takeItem(jj.row()))\n if self.index == 4:\n if items2:\n for jj in items2:\n self.excludeList.removeItemWidget(self.excludeList.\n takeItem(jj.row()))\n\n def EndResult(self):\n print(os.getcwd())\n f = open('./conerr.err', 'r')\n lines = f.readlines()\n j = 0\n for ii in lines:\n if 'error:' in ii:\n self.Result.append('<font color=\"#FF0000\">%s</font> ' % ii)\n j = 1\n if j != 1:\n self.Result.append('<font color=\"#FF0000\">finished!!!!!!!!</font> '\n )\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working = False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n\n def initBar(self):\n global NUM\n self.progressBar = QProgressBar()\n self.Result.clear()\n self.barlabel.setText('正在编译:')\n self.statusBar.addPermanentWidget(self.progressBar, stretch=2)\n f = open('./Default/Default.objectlist', 'r')\n lines = f.readlines()\n f.close()\n NUM = len(lines)\n self.progressBar.setRange(0, len(lines))\n global VAL\n VAL = 0\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n\n def StartCompile(self, Hdir):\n global cmd1\n cmd1 = '%s\\\\bin\\\\make -j8 all' % Hdir\n os.chdir(self.ProjectName_2.text() + '/Default')\n self.backend1 = BackendTread1()\n self.backend1.startcompile1.connect(self.PrintConsole)\n self.backend1.endSig.connect(self.EndResult)\n self.backend1.start()\n self.backend = BackendTread()\n self.backend.setvalue.connect(self.SetProgressBarVal)\n self.backend.start()\n \"\"\"self.process = subprocess.call(cmd1)\n self.process.wait()\n f= open('console.log','r')\n lines =f.readlines()\n for ii in lines:\n if 'error:'in ii:\n self.Result.insertText(ii+'\n')\"\"\"\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n\n def modifyFLAG(self):\n CCFLAGNOW = self.GCCFLAGName.toPlainText()\n LINKFLAGNOW = self.LINKFLAGName.toPlainText()\n HighTecDirNOW = self.HithTecDir.text()\n DebugNameNOW = self.ProjectName.text()\n inn = self.includeList.count()\n inpathNOW = []\n exn = self.excludeList.count()\n expathNOW = []\n Ln = self.Llist.count()\n LnNOW = []\n ln = self.llist.count()\n lnNOW = []\n try:\n for i in range(inn):\n inpathNOW.append(self.includeList.item(i).text())\n for i in range(exn):\n expathNOW.append(self.excludeList.item(i).text())\n f = open('./py.pyconfig', 'w', encoding='utf-8')\n tLink = re.split(' ', LINKFLAGNOW)\n Linkchange = ''\n for iii in tLink:\n if '-L' not in iii and '-l:' not in iii:\n Linkchange += iii + ' '\n for i in range(Ln):\n p = re.split('{workspace}/', self.Llist.item(i).text())\n if len(p) == 1:\n Linkchange += '-L\"' + os.path.abspath(p[0]) + '\" '\n else:\n Linkchange += '-L\"' + os.path.abspath(p[1]) + '\" '\n LnNOW.append(self.Llist.item(i).text())\n for i in range(ln):\n Linkchange += '-l' + self.llist.item(i).text() + ' '\n lnNOW.append(self.llist.item(i).text())\n f.write('CCFLAG=' + CCFLAGNOW + '\\n')\n f.write('LINKFLAG=' + Linkchange + '\\n')\n f.write('HighTecDir=' + HighTecDirNOW + '\\n')\n f.write('DebugName=' + DebugNameNOW + '\\n')\n aa = 'includepath='\n for a in inpathNOW:\n if a != '':\n aa += a + ','\n f.write(aa + '\\n')\n bb = 'excludefiles='\n for b in expathNOW:\n if b != '':\n bb += b + ','\n f.write(bb + '\\n')\n cc = 'LibraryPath='\n for c in LnNOW:\n if c != '':\n cc += c + ','\n dd = 'libraties='\n for d in lnNOW:\n if d != '':\n dd += d + ','\n f.write(cc + '\\n')\n f.write(dd + '\\n')\n f.close()\n self.LINKFLAGName.setText('')\n self.LINKFLAGName.setText(Linkchange)\n except:\n f.close()\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n\n def testaa(self):\n print('1')\n\n def CloseTools(self):\n print(1)\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n\n def ShowDialog(self, id):\n self.idPath = id\n self.di.exec()\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n\n def AddExpath(self):\n dir1, file1 = QFileDialog.getOpenFileNames(self, '选择过滤文件', os.\n getcwd(), 'C FILES(*.c)')\n for ii in dir1:\n if ii != '':\n dir2 = re.split(os.getcwd().replace('\\\\', '/'), ii)[1]\n self.excludeList.addItem(dir2)\n\n def AddLibraryPath(self):\n txt = self.LWUI.LibraryP.text()\n if txt:\n self.Llist.addItem(txt)\n self.LWin.close()\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n\n def DelLibraryPath(self):\n items1 = self.Llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.Llist.removeItemWidget(self.Llist.takeItem(jj.row()))\n\n def DelLibraries(self):\n items1 = self.llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.llist.removeItemWidget(self.llist.takeItem(jj.row()))\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n\n def __init__(self):\n super(basePage, self).__init__()\n self.setupUi(self)\n self.startpath = os.getcwd()\n self.actionbuild.triggered.connect(self.checkFLAG)\n self.actionclean.triggered.connect(self.CleanProject)\n self.actionopen_project.triggered.connect(self.ChooseProDir)\n self.actionsave_project.triggered.connect(self.modifyFLAG)\n self.actionexit.triggered.connect(qApp.quit)\n self.tb1 = self.addToolBar('tool')\n actionopen1 = QAction(QIcon('./Compile/file.png'), '打开工程', self)\n self.tb1.addAction(actionopen1)\n actionopen1.triggered.connect(self.ChooseProDir)\n self.tb1.addSeparator()\n actionstop = QAction(QIcon('./Compile/stop.png'), '停止', self)\n self.tb1.addAction(actionstop)\n actionstop.triggered.connect(self.KillProcess)\n self.tb1.addSeparator()\n actionExit = QAction(QIcon('./Compile/exit.png'), '退出', self)\n self.tb1.addAction(actionExit)\n actionExit.triggered.connect(qApp.quit)\n self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.contextMenu = QMenu(self)\n self.actionA = self.contextMenu.addAction('删除')\n self.actionA.triggered.connect(self.remove)\n self.includeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(1))\n self.excludeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(2))\n self.delPath1.clicked.connect(self.includeList.clear)\n self.delPath2.clicked.connect(self.excludeList.clear)\n self.addPath1.clicked.connect(lambda : self.ShowDialog(1))\n self.addPath2.clicked.connect(self.AddExpath)\n self.fileselect = fileselect.Ui_Dialog()\n self.listWidget.currentRowChanged.connect(self.display)\n self.initLibraryWindow()\n self.Llist.setSelectionMode(3)\n self.llist.setSelectionMode(3)\n self.barlabel = QLabel('barlabel')\n\n def initUI(self):\n self.includeList.clear()\n self.excludeList.clear()\n self.Llist.clear()\n self.llist.clear()\n self.ProjectName.setText(self.DebugName)\n self.HithTecDir.setText(self.HighTecDir)\n self.GCCFLAGName.setText(self.CCFLAG)\n self.LINKFLAGName.setText(self.LINKFLAG)\n self.ProjectName_2.setText(self.PROJECTDIR)\n self.ProjectName_2.setEnabled(False)\n self.barlabel.setText('准备中')\n self.statusBar.addPermanentWidget(self.barlabel)\n self.Result.clear()\n if self.includepath:\n self.includeList.addItems(self.includepath)\n if self.excludefiles:\n self.excludeList.addItems(self.excludefiles)\n if self.LibraryPath:\n self.Llist.addItems(self.LibraryPath)\n if self.libraties:\n self.llist.addItems(self.libraties)\n <function token>\n\n def initLibraryWindow(self):\n self.LWUI = AddLibraryPath.Ui_LSelect()\n self.LWin = QWidget()\n self.LWin.setWindowModality(Qt.ApplicationModal)\n self.LWUI.setupUi(self.LWin)\n self.LWUI.LibraryP.setText('')\n self.add1.clicked.connect(self.LWin.show)\n self.LWUI.L_Cancel.clicked.connect(self.LWin.close)\n self.LWUI.L_Workspace.clicked.connect(lambda : self.ShowDialog(1))\n self.LWUI.L_OK.clicked.connect(self.AddLibraryPath)\n self.del1.clicked.connect(self.DelLibraryPath)\n self.lWUI = Enterlibraries.Ui_LSelect()\n self.lWin = QWidget()\n self.lWin.setWindowModality(Qt.ApplicationModal)\n self.lWUI.setupUi(self.lWin)\n self.LWUI.LibraryP.setText('')\n self.add2.clicked.connect(self.lWin.show)\n self.lWUI.l_OK.clicked.connect(self.AddLibraries)\n self.lWUI.l_Cancel.clicked.connect(self.lWin.close)\n self.del2.clicked.connect(self.DelLibraries)\n\n def KillProcess(self):\n os.system('taskkill /f /t /im make.exe')\n self.Result.append('用户终止执行')\n\n def ChooseProDir(self):\n dir = QFileDialog.getExistingDirectory()\n dir = dir.replace('/', '\\\\')\n self.ProjectName_2.setText(dir)\n if dir != '':\n os.chdir(dir)\n import automake_config as ac\n (DebugName, HighTecDir, CCFLAG, LINKFLAG, includepath,\n excludefiles, g_except_dir_list, g_except_file_list,\n LibraryPath, libraties) = ac.maininit()\n self.includepath = includepath\n self.excludefiles = excludefiles\n self.DebugName = DebugName\n self.CCFLAG = CCFLAG\n self.LINKFLAG = LINKFLAG\n self.HighTecDir = HighTecDir\n self.PROJECTDIR = dir\n self.LibraryPath = LibraryPath\n self.libraties = libraties\n self.AllPath = ac.FindAllPath(dir)\n self.initDialog()\n self.fileselect.buttonBox.accepted.connect(self.GetPath)\n self.fileselect.treeWidget.setSelectionMode(3)\n self.fileselect.buttonBox.rejected.connect(self.Cleartree)\n a.initUI()\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n\n def remove(self):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if self.index == 3:\n if items1:\n for jj in items1:\n self.includeList.removeItemWidget(self.includeList.\n takeItem(jj.row()))\n if self.index == 4:\n if items2:\n for jj in items2:\n self.excludeList.removeItemWidget(self.excludeList.\n takeItem(jj.row()))\n\n def EndResult(self):\n print(os.getcwd())\n f = open('./conerr.err', 'r')\n lines = f.readlines()\n j = 0\n for ii in lines:\n if 'error:' in ii:\n self.Result.append('<font color=\"#FF0000\">%s</font> ' % ii)\n j = 1\n if j != 1:\n self.Result.append('<font color=\"#FF0000\">finished!!!!!!!!</font> '\n )\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working = False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n\n def initBar(self):\n global NUM\n self.progressBar = QProgressBar()\n self.Result.clear()\n self.barlabel.setText('正在编译:')\n self.statusBar.addPermanentWidget(self.progressBar, stretch=2)\n f = open('./Default/Default.objectlist', 'r')\n lines = f.readlines()\n f.close()\n NUM = len(lines)\n self.progressBar.setRange(0, len(lines))\n global VAL\n VAL = 0\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n\n def StartCompile(self, Hdir):\n global cmd1\n cmd1 = '%s\\\\bin\\\\make -j8 all' % Hdir\n os.chdir(self.ProjectName_2.text() + '/Default')\n self.backend1 = BackendTread1()\n self.backend1.startcompile1.connect(self.PrintConsole)\n self.backend1.endSig.connect(self.EndResult)\n self.backend1.start()\n self.backend = BackendTread()\n self.backend.setvalue.connect(self.SetProgressBarVal)\n self.backend.start()\n \"\"\"self.process = subprocess.call(cmd1)\n self.process.wait()\n f= open('console.log','r')\n lines =f.readlines()\n for ii in lines:\n if 'error:'in ii:\n self.Result.insertText(ii+'\n')\"\"\"\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n\n def modifyFLAG(self):\n CCFLAGNOW = self.GCCFLAGName.toPlainText()\n LINKFLAGNOW = self.LINKFLAGName.toPlainText()\n HighTecDirNOW = self.HithTecDir.text()\n DebugNameNOW = self.ProjectName.text()\n inn = self.includeList.count()\n inpathNOW = []\n exn = self.excludeList.count()\n expathNOW = []\n Ln = self.Llist.count()\n LnNOW = []\n ln = self.llist.count()\n lnNOW = []\n try:\n for i in range(inn):\n inpathNOW.append(self.includeList.item(i).text())\n for i in range(exn):\n expathNOW.append(self.excludeList.item(i).text())\n f = open('./py.pyconfig', 'w', encoding='utf-8')\n tLink = re.split(' ', LINKFLAGNOW)\n Linkchange = ''\n for iii in tLink:\n if '-L' not in iii and '-l:' not in iii:\n Linkchange += iii + ' '\n for i in range(Ln):\n p = re.split('{workspace}/', self.Llist.item(i).text())\n if len(p) == 1:\n Linkchange += '-L\"' + os.path.abspath(p[0]) + '\" '\n else:\n Linkchange += '-L\"' + os.path.abspath(p[1]) + '\" '\n LnNOW.append(self.Llist.item(i).text())\n for i in range(ln):\n Linkchange += '-l' + self.llist.item(i).text() + ' '\n lnNOW.append(self.llist.item(i).text())\n f.write('CCFLAG=' + CCFLAGNOW + '\\n')\n f.write('LINKFLAG=' + Linkchange + '\\n')\n f.write('HighTecDir=' + HighTecDirNOW + '\\n')\n f.write('DebugName=' + DebugNameNOW + '\\n')\n aa = 'includepath='\n for a in inpathNOW:\n if a != '':\n aa += a + ','\n f.write(aa + '\\n')\n bb = 'excludefiles='\n for b in expathNOW:\n if b != '':\n bb += b + ','\n f.write(bb + '\\n')\n cc = 'LibraryPath='\n for c in LnNOW:\n if c != '':\n cc += c + ','\n dd = 'libraties='\n for d in lnNOW:\n if d != '':\n dd += d + ','\n f.write(cc + '\\n')\n f.write(dd + '\\n')\n f.close()\n self.LINKFLAGName.setText('')\n self.LINKFLAGName.setText(Linkchange)\n except:\n f.close()\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n\n def testaa(self):\n print('1')\n\n def CloseTools(self):\n print(1)\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n\n def ShowDialog(self, id):\n self.idPath = id\n self.di.exec()\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n <function token>\n\n def AddLibraryPath(self):\n txt = self.LWUI.LibraryP.text()\n if txt:\n self.Llist.addItem(txt)\n self.LWin.close()\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n\n def DelLibraryPath(self):\n items1 = self.Llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.Llist.removeItemWidget(self.Llist.takeItem(jj.row()))\n\n def DelLibraries(self):\n items1 = self.llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.llist.removeItemWidget(self.llist.takeItem(jj.row()))\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n\n def __init__(self):\n super(basePage, self).__init__()\n self.setupUi(self)\n self.startpath = os.getcwd()\n self.actionbuild.triggered.connect(self.checkFLAG)\n self.actionclean.triggered.connect(self.CleanProject)\n self.actionopen_project.triggered.connect(self.ChooseProDir)\n self.actionsave_project.triggered.connect(self.modifyFLAG)\n self.actionexit.triggered.connect(qApp.quit)\n self.tb1 = self.addToolBar('tool')\n actionopen1 = QAction(QIcon('./Compile/file.png'), '打开工程', self)\n self.tb1.addAction(actionopen1)\n actionopen1.triggered.connect(self.ChooseProDir)\n self.tb1.addSeparator()\n actionstop = QAction(QIcon('./Compile/stop.png'), '停止', self)\n self.tb1.addAction(actionstop)\n actionstop.triggered.connect(self.KillProcess)\n self.tb1.addSeparator()\n actionExit = QAction(QIcon('./Compile/exit.png'), '退出', self)\n self.tb1.addAction(actionExit)\n actionExit.triggered.connect(qApp.quit)\n self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.contextMenu = QMenu(self)\n self.actionA = self.contextMenu.addAction('删除')\n self.actionA.triggered.connect(self.remove)\n self.includeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(1))\n self.excludeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(2))\n self.delPath1.clicked.connect(self.includeList.clear)\n self.delPath2.clicked.connect(self.excludeList.clear)\n self.addPath1.clicked.connect(lambda : self.ShowDialog(1))\n self.addPath2.clicked.connect(self.AddExpath)\n self.fileselect = fileselect.Ui_Dialog()\n self.listWidget.currentRowChanged.connect(self.display)\n self.initLibraryWindow()\n self.Llist.setSelectionMode(3)\n self.llist.setSelectionMode(3)\n self.barlabel = QLabel('barlabel')\n <function token>\n <function token>\n\n def initLibraryWindow(self):\n self.LWUI = AddLibraryPath.Ui_LSelect()\n self.LWin = QWidget()\n self.LWin.setWindowModality(Qt.ApplicationModal)\n self.LWUI.setupUi(self.LWin)\n self.LWUI.LibraryP.setText('')\n self.add1.clicked.connect(self.LWin.show)\n self.LWUI.L_Cancel.clicked.connect(self.LWin.close)\n self.LWUI.L_Workspace.clicked.connect(lambda : self.ShowDialog(1))\n self.LWUI.L_OK.clicked.connect(self.AddLibraryPath)\n self.del1.clicked.connect(self.DelLibraryPath)\n self.lWUI = Enterlibraries.Ui_LSelect()\n self.lWin = QWidget()\n self.lWin.setWindowModality(Qt.ApplicationModal)\n self.lWUI.setupUi(self.lWin)\n self.LWUI.LibraryP.setText('')\n self.add2.clicked.connect(self.lWin.show)\n self.lWUI.l_OK.clicked.connect(self.AddLibraries)\n self.lWUI.l_Cancel.clicked.connect(self.lWin.close)\n self.del2.clicked.connect(self.DelLibraries)\n\n def KillProcess(self):\n os.system('taskkill /f /t /im make.exe')\n self.Result.append('用户终止执行')\n\n def ChooseProDir(self):\n dir = QFileDialog.getExistingDirectory()\n dir = dir.replace('/', '\\\\')\n self.ProjectName_2.setText(dir)\n if dir != '':\n os.chdir(dir)\n import automake_config as ac\n (DebugName, HighTecDir, CCFLAG, LINKFLAG, includepath,\n excludefiles, g_except_dir_list, g_except_file_list,\n LibraryPath, libraties) = ac.maininit()\n self.includepath = includepath\n self.excludefiles = excludefiles\n self.DebugName = DebugName\n self.CCFLAG = CCFLAG\n self.LINKFLAG = LINKFLAG\n self.HighTecDir = HighTecDir\n self.PROJECTDIR = dir\n self.LibraryPath = LibraryPath\n self.libraties = libraties\n self.AllPath = ac.FindAllPath(dir)\n self.initDialog()\n self.fileselect.buttonBox.accepted.connect(self.GetPath)\n self.fileselect.treeWidget.setSelectionMode(3)\n self.fileselect.buttonBox.rejected.connect(self.Cleartree)\n a.initUI()\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n\n def remove(self):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if self.index == 3:\n if items1:\n for jj in items1:\n self.includeList.removeItemWidget(self.includeList.\n takeItem(jj.row()))\n if self.index == 4:\n if items2:\n for jj in items2:\n self.excludeList.removeItemWidget(self.excludeList.\n takeItem(jj.row()))\n\n def EndResult(self):\n print(os.getcwd())\n f = open('./conerr.err', 'r')\n lines = f.readlines()\n j = 0\n for ii in lines:\n if 'error:' in ii:\n self.Result.append('<font color=\"#FF0000\">%s</font> ' % ii)\n j = 1\n if j != 1:\n self.Result.append('<font color=\"#FF0000\">finished!!!!!!!!</font> '\n )\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working = False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n\n def initBar(self):\n global NUM\n self.progressBar = QProgressBar()\n self.Result.clear()\n self.barlabel.setText('正在编译:')\n self.statusBar.addPermanentWidget(self.progressBar, stretch=2)\n f = open('./Default/Default.objectlist', 'r')\n lines = f.readlines()\n f.close()\n NUM = len(lines)\n self.progressBar.setRange(0, len(lines))\n global VAL\n VAL = 0\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n\n def StartCompile(self, Hdir):\n global cmd1\n cmd1 = '%s\\\\bin\\\\make -j8 all' % Hdir\n os.chdir(self.ProjectName_2.text() + '/Default')\n self.backend1 = BackendTread1()\n self.backend1.startcompile1.connect(self.PrintConsole)\n self.backend1.endSig.connect(self.EndResult)\n self.backend1.start()\n self.backend = BackendTread()\n self.backend.setvalue.connect(self.SetProgressBarVal)\n self.backend.start()\n \"\"\"self.process = subprocess.call(cmd1)\n self.process.wait()\n f= open('console.log','r')\n lines =f.readlines()\n for ii in lines:\n if 'error:'in ii:\n self.Result.insertText(ii+'\n')\"\"\"\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n\n def modifyFLAG(self):\n CCFLAGNOW = self.GCCFLAGName.toPlainText()\n LINKFLAGNOW = self.LINKFLAGName.toPlainText()\n HighTecDirNOW = self.HithTecDir.text()\n DebugNameNOW = self.ProjectName.text()\n inn = self.includeList.count()\n inpathNOW = []\n exn = self.excludeList.count()\n expathNOW = []\n Ln = self.Llist.count()\n LnNOW = []\n ln = self.llist.count()\n lnNOW = []\n try:\n for i in range(inn):\n inpathNOW.append(self.includeList.item(i).text())\n for i in range(exn):\n expathNOW.append(self.excludeList.item(i).text())\n f = open('./py.pyconfig', 'w', encoding='utf-8')\n tLink = re.split(' ', LINKFLAGNOW)\n Linkchange = ''\n for iii in tLink:\n if '-L' not in iii and '-l:' not in iii:\n Linkchange += iii + ' '\n for i in range(Ln):\n p = re.split('{workspace}/', self.Llist.item(i).text())\n if len(p) == 1:\n Linkchange += '-L\"' + os.path.abspath(p[0]) + '\" '\n else:\n Linkchange += '-L\"' + os.path.abspath(p[1]) + '\" '\n LnNOW.append(self.Llist.item(i).text())\n for i in range(ln):\n Linkchange += '-l' + self.llist.item(i).text() + ' '\n lnNOW.append(self.llist.item(i).text())\n f.write('CCFLAG=' + CCFLAGNOW + '\\n')\n f.write('LINKFLAG=' + Linkchange + '\\n')\n f.write('HighTecDir=' + HighTecDirNOW + '\\n')\n f.write('DebugName=' + DebugNameNOW + '\\n')\n aa = 'includepath='\n for a in inpathNOW:\n if a != '':\n aa += a + ','\n f.write(aa + '\\n')\n bb = 'excludefiles='\n for b in expathNOW:\n if b != '':\n bb += b + ','\n f.write(bb + '\\n')\n cc = 'LibraryPath='\n for c in LnNOW:\n if c != '':\n cc += c + ','\n dd = 'libraties='\n for d in lnNOW:\n if d != '':\n dd += d + ','\n f.write(cc + '\\n')\n f.write(dd + '\\n')\n f.close()\n self.LINKFLAGName.setText('')\n self.LINKFLAGName.setText(Linkchange)\n except:\n f.close()\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n\n def testaa(self):\n print('1')\n\n def CloseTools(self):\n print(1)\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n\n def ShowDialog(self, id):\n self.idPath = id\n self.di.exec()\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n <function token>\n\n def AddLibraryPath(self):\n txt = self.LWUI.LibraryP.text()\n if txt:\n self.Llist.addItem(txt)\n self.LWin.close()\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n\n def DelLibraryPath(self):\n items1 = self.Llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.Llist.removeItemWidget(self.Llist.takeItem(jj.row()))\n\n def DelLibraries(self):\n items1 = self.llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.llist.removeItemWidget(self.llist.takeItem(jj.row()))\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n\n def __init__(self):\n super(basePage, self).__init__()\n self.setupUi(self)\n self.startpath = os.getcwd()\n self.actionbuild.triggered.connect(self.checkFLAG)\n self.actionclean.triggered.connect(self.CleanProject)\n self.actionopen_project.triggered.connect(self.ChooseProDir)\n self.actionsave_project.triggered.connect(self.modifyFLAG)\n self.actionexit.triggered.connect(qApp.quit)\n self.tb1 = self.addToolBar('tool')\n actionopen1 = QAction(QIcon('./Compile/file.png'), '打开工程', self)\n self.tb1.addAction(actionopen1)\n actionopen1.triggered.connect(self.ChooseProDir)\n self.tb1.addSeparator()\n actionstop = QAction(QIcon('./Compile/stop.png'), '停止', self)\n self.tb1.addAction(actionstop)\n actionstop.triggered.connect(self.KillProcess)\n self.tb1.addSeparator()\n actionExit = QAction(QIcon('./Compile/exit.png'), '退出', self)\n self.tb1.addAction(actionExit)\n actionExit.triggered.connect(qApp.quit)\n self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.contextMenu = QMenu(self)\n self.actionA = self.contextMenu.addAction('删除')\n self.actionA.triggered.connect(self.remove)\n self.includeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(1))\n self.excludeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(2))\n self.delPath1.clicked.connect(self.includeList.clear)\n self.delPath2.clicked.connect(self.excludeList.clear)\n self.addPath1.clicked.connect(lambda : self.ShowDialog(1))\n self.addPath2.clicked.connect(self.AddExpath)\n self.fileselect = fileselect.Ui_Dialog()\n self.listWidget.currentRowChanged.connect(self.display)\n self.initLibraryWindow()\n self.Llist.setSelectionMode(3)\n self.llist.setSelectionMode(3)\n self.barlabel = QLabel('barlabel')\n <function token>\n <function token>\n\n def initLibraryWindow(self):\n self.LWUI = AddLibraryPath.Ui_LSelect()\n self.LWin = QWidget()\n self.LWin.setWindowModality(Qt.ApplicationModal)\n self.LWUI.setupUi(self.LWin)\n self.LWUI.LibraryP.setText('')\n self.add1.clicked.connect(self.LWin.show)\n self.LWUI.L_Cancel.clicked.connect(self.LWin.close)\n self.LWUI.L_Workspace.clicked.connect(lambda : self.ShowDialog(1))\n self.LWUI.L_OK.clicked.connect(self.AddLibraryPath)\n self.del1.clicked.connect(self.DelLibraryPath)\n self.lWUI = Enterlibraries.Ui_LSelect()\n self.lWin = QWidget()\n self.lWin.setWindowModality(Qt.ApplicationModal)\n self.lWUI.setupUi(self.lWin)\n self.LWUI.LibraryP.setText('')\n self.add2.clicked.connect(self.lWin.show)\n self.lWUI.l_OK.clicked.connect(self.AddLibraries)\n self.lWUI.l_Cancel.clicked.connect(self.lWin.close)\n self.del2.clicked.connect(self.DelLibraries)\n <function token>\n\n def ChooseProDir(self):\n dir = QFileDialog.getExistingDirectory()\n dir = dir.replace('/', '\\\\')\n self.ProjectName_2.setText(dir)\n if dir != '':\n os.chdir(dir)\n import automake_config as ac\n (DebugName, HighTecDir, CCFLAG, LINKFLAG, includepath,\n excludefiles, g_except_dir_list, g_except_file_list,\n LibraryPath, libraties) = ac.maininit()\n self.includepath = includepath\n self.excludefiles = excludefiles\n self.DebugName = DebugName\n self.CCFLAG = CCFLAG\n self.LINKFLAG = LINKFLAG\n self.HighTecDir = HighTecDir\n self.PROJECTDIR = dir\n self.LibraryPath = LibraryPath\n self.libraties = libraties\n self.AllPath = ac.FindAllPath(dir)\n self.initDialog()\n self.fileselect.buttonBox.accepted.connect(self.GetPath)\n self.fileselect.treeWidget.setSelectionMode(3)\n self.fileselect.buttonBox.rejected.connect(self.Cleartree)\n a.initUI()\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n\n def remove(self):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if self.index == 3:\n if items1:\n for jj in items1:\n self.includeList.removeItemWidget(self.includeList.\n takeItem(jj.row()))\n if self.index == 4:\n if items2:\n for jj in items2:\n self.excludeList.removeItemWidget(self.excludeList.\n takeItem(jj.row()))\n\n def EndResult(self):\n print(os.getcwd())\n f = open('./conerr.err', 'r')\n lines = f.readlines()\n j = 0\n for ii in lines:\n if 'error:' in ii:\n self.Result.append('<font color=\"#FF0000\">%s</font> ' % ii)\n j = 1\n if j != 1:\n self.Result.append('<font color=\"#FF0000\">finished!!!!!!!!</font> '\n )\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working = False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n\n def initBar(self):\n global NUM\n self.progressBar = QProgressBar()\n self.Result.clear()\n self.barlabel.setText('正在编译:')\n self.statusBar.addPermanentWidget(self.progressBar, stretch=2)\n f = open('./Default/Default.objectlist', 'r')\n lines = f.readlines()\n f.close()\n NUM = len(lines)\n self.progressBar.setRange(0, len(lines))\n global VAL\n VAL = 0\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n\n def StartCompile(self, Hdir):\n global cmd1\n cmd1 = '%s\\\\bin\\\\make -j8 all' % Hdir\n os.chdir(self.ProjectName_2.text() + '/Default')\n self.backend1 = BackendTread1()\n self.backend1.startcompile1.connect(self.PrintConsole)\n self.backend1.endSig.connect(self.EndResult)\n self.backend1.start()\n self.backend = BackendTread()\n self.backend.setvalue.connect(self.SetProgressBarVal)\n self.backend.start()\n \"\"\"self.process = subprocess.call(cmd1)\n self.process.wait()\n f= open('console.log','r')\n lines =f.readlines()\n for ii in lines:\n if 'error:'in ii:\n self.Result.insertText(ii+'\n')\"\"\"\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n\n def modifyFLAG(self):\n CCFLAGNOW = self.GCCFLAGName.toPlainText()\n LINKFLAGNOW = self.LINKFLAGName.toPlainText()\n HighTecDirNOW = self.HithTecDir.text()\n DebugNameNOW = self.ProjectName.text()\n inn = self.includeList.count()\n inpathNOW = []\n exn = self.excludeList.count()\n expathNOW = []\n Ln = self.Llist.count()\n LnNOW = []\n ln = self.llist.count()\n lnNOW = []\n try:\n for i in range(inn):\n inpathNOW.append(self.includeList.item(i).text())\n for i in range(exn):\n expathNOW.append(self.excludeList.item(i).text())\n f = open('./py.pyconfig', 'w', encoding='utf-8')\n tLink = re.split(' ', LINKFLAGNOW)\n Linkchange = ''\n for iii in tLink:\n if '-L' not in iii and '-l:' not in iii:\n Linkchange += iii + ' '\n for i in range(Ln):\n p = re.split('{workspace}/', self.Llist.item(i).text())\n if len(p) == 1:\n Linkchange += '-L\"' + os.path.abspath(p[0]) + '\" '\n else:\n Linkchange += '-L\"' + os.path.abspath(p[1]) + '\" '\n LnNOW.append(self.Llist.item(i).text())\n for i in range(ln):\n Linkchange += '-l' + self.llist.item(i).text() + ' '\n lnNOW.append(self.llist.item(i).text())\n f.write('CCFLAG=' + CCFLAGNOW + '\\n')\n f.write('LINKFLAG=' + Linkchange + '\\n')\n f.write('HighTecDir=' + HighTecDirNOW + '\\n')\n f.write('DebugName=' + DebugNameNOW + '\\n')\n aa = 'includepath='\n for a in inpathNOW:\n if a != '':\n aa += a + ','\n f.write(aa + '\\n')\n bb = 'excludefiles='\n for b in expathNOW:\n if b != '':\n bb += b + ','\n f.write(bb + '\\n')\n cc = 'LibraryPath='\n for c in LnNOW:\n if c != '':\n cc += c + ','\n dd = 'libraties='\n for d in lnNOW:\n if d != '':\n dd += d + ','\n f.write(cc + '\\n')\n f.write(dd + '\\n')\n f.close()\n self.LINKFLAGName.setText('')\n self.LINKFLAGName.setText(Linkchange)\n except:\n f.close()\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n\n def testaa(self):\n print('1')\n\n def CloseTools(self):\n print(1)\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n\n def ShowDialog(self, id):\n self.idPath = id\n self.di.exec()\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n <function token>\n\n def AddLibraryPath(self):\n txt = self.LWUI.LibraryP.text()\n if txt:\n self.Llist.addItem(txt)\n self.LWin.close()\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n\n def DelLibraryPath(self):\n items1 = self.Llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.Llist.removeItemWidget(self.Llist.takeItem(jj.row()))\n\n def DelLibraries(self):\n items1 = self.llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.llist.removeItemWidget(self.llist.takeItem(jj.row()))\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n\n def __init__(self):\n super(basePage, self).__init__()\n self.setupUi(self)\n self.startpath = os.getcwd()\n self.actionbuild.triggered.connect(self.checkFLAG)\n self.actionclean.triggered.connect(self.CleanProject)\n self.actionopen_project.triggered.connect(self.ChooseProDir)\n self.actionsave_project.triggered.connect(self.modifyFLAG)\n self.actionexit.triggered.connect(qApp.quit)\n self.tb1 = self.addToolBar('tool')\n actionopen1 = QAction(QIcon('./Compile/file.png'), '打开工程', self)\n self.tb1.addAction(actionopen1)\n actionopen1.triggered.connect(self.ChooseProDir)\n self.tb1.addSeparator()\n actionstop = QAction(QIcon('./Compile/stop.png'), '停止', self)\n self.tb1.addAction(actionstop)\n actionstop.triggered.connect(self.KillProcess)\n self.tb1.addSeparator()\n actionExit = QAction(QIcon('./Compile/exit.png'), '退出', self)\n self.tb1.addAction(actionExit)\n actionExit.triggered.connect(qApp.quit)\n self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.contextMenu = QMenu(self)\n self.actionA = self.contextMenu.addAction('删除')\n self.actionA.triggered.connect(self.remove)\n self.includeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(1))\n self.excludeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(2))\n self.delPath1.clicked.connect(self.includeList.clear)\n self.delPath2.clicked.connect(self.excludeList.clear)\n self.addPath1.clicked.connect(lambda : self.ShowDialog(1))\n self.addPath2.clicked.connect(self.AddExpath)\n self.fileselect = fileselect.Ui_Dialog()\n self.listWidget.currentRowChanged.connect(self.display)\n self.initLibraryWindow()\n self.Llist.setSelectionMode(3)\n self.llist.setSelectionMode(3)\n self.barlabel = QLabel('barlabel')\n <function token>\n <function token>\n\n def initLibraryWindow(self):\n self.LWUI = AddLibraryPath.Ui_LSelect()\n self.LWin = QWidget()\n self.LWin.setWindowModality(Qt.ApplicationModal)\n self.LWUI.setupUi(self.LWin)\n self.LWUI.LibraryP.setText('')\n self.add1.clicked.connect(self.LWin.show)\n self.LWUI.L_Cancel.clicked.connect(self.LWin.close)\n self.LWUI.L_Workspace.clicked.connect(lambda : self.ShowDialog(1))\n self.LWUI.L_OK.clicked.connect(self.AddLibraryPath)\n self.del1.clicked.connect(self.DelLibraryPath)\n self.lWUI = Enterlibraries.Ui_LSelect()\n self.lWin = QWidget()\n self.lWin.setWindowModality(Qt.ApplicationModal)\n self.lWUI.setupUi(self.lWin)\n self.LWUI.LibraryP.setText('')\n self.add2.clicked.connect(self.lWin.show)\n self.lWUI.l_OK.clicked.connect(self.AddLibraries)\n self.lWUI.l_Cancel.clicked.connect(self.lWin.close)\n self.del2.clicked.connect(self.DelLibraries)\n <function token>\n\n def ChooseProDir(self):\n dir = QFileDialog.getExistingDirectory()\n dir = dir.replace('/', '\\\\')\n self.ProjectName_2.setText(dir)\n if dir != '':\n os.chdir(dir)\n import automake_config as ac\n (DebugName, HighTecDir, CCFLAG, LINKFLAG, includepath,\n excludefiles, g_except_dir_list, g_except_file_list,\n LibraryPath, libraties) = ac.maininit()\n self.includepath = includepath\n self.excludefiles = excludefiles\n self.DebugName = DebugName\n self.CCFLAG = CCFLAG\n self.LINKFLAG = LINKFLAG\n self.HighTecDir = HighTecDir\n self.PROJECTDIR = dir\n self.LibraryPath = LibraryPath\n self.libraties = libraties\n self.AllPath = ac.FindAllPath(dir)\n self.initDialog()\n self.fileselect.buttonBox.accepted.connect(self.GetPath)\n self.fileselect.treeWidget.setSelectionMode(3)\n self.fileselect.buttonBox.rejected.connect(self.Cleartree)\n a.initUI()\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n\n def remove(self):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if self.index == 3:\n if items1:\n for jj in items1:\n self.includeList.removeItemWidget(self.includeList.\n takeItem(jj.row()))\n if self.index == 4:\n if items2:\n for jj in items2:\n self.excludeList.removeItemWidget(self.excludeList.\n takeItem(jj.row()))\n\n def EndResult(self):\n print(os.getcwd())\n f = open('./conerr.err', 'r')\n lines = f.readlines()\n j = 0\n for ii in lines:\n if 'error:' in ii:\n self.Result.append('<font color=\"#FF0000\">%s</font> ' % ii)\n j = 1\n if j != 1:\n self.Result.append('<font color=\"#FF0000\">finished!!!!!!!!</font> '\n )\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working = False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n\n def initBar(self):\n global NUM\n self.progressBar = QProgressBar()\n self.Result.clear()\n self.barlabel.setText('正在编译:')\n self.statusBar.addPermanentWidget(self.progressBar, stretch=2)\n f = open('./Default/Default.objectlist', 'r')\n lines = f.readlines()\n f.close()\n NUM = len(lines)\n self.progressBar.setRange(0, len(lines))\n global VAL\n VAL = 0\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n\n def StartCompile(self, Hdir):\n global cmd1\n cmd1 = '%s\\\\bin\\\\make -j8 all' % Hdir\n os.chdir(self.ProjectName_2.text() + '/Default')\n self.backend1 = BackendTread1()\n self.backend1.startcompile1.connect(self.PrintConsole)\n self.backend1.endSig.connect(self.EndResult)\n self.backend1.start()\n self.backend = BackendTread()\n self.backend.setvalue.connect(self.SetProgressBarVal)\n self.backend.start()\n \"\"\"self.process = subprocess.call(cmd1)\n self.process.wait()\n f= open('console.log','r')\n lines =f.readlines()\n for ii in lines:\n if 'error:'in ii:\n self.Result.insertText(ii+'\n')\"\"\"\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n\n def modifyFLAG(self):\n CCFLAGNOW = self.GCCFLAGName.toPlainText()\n LINKFLAGNOW = self.LINKFLAGName.toPlainText()\n HighTecDirNOW = self.HithTecDir.text()\n DebugNameNOW = self.ProjectName.text()\n inn = self.includeList.count()\n inpathNOW = []\n exn = self.excludeList.count()\n expathNOW = []\n Ln = self.Llist.count()\n LnNOW = []\n ln = self.llist.count()\n lnNOW = []\n try:\n for i in range(inn):\n inpathNOW.append(self.includeList.item(i).text())\n for i in range(exn):\n expathNOW.append(self.excludeList.item(i).text())\n f = open('./py.pyconfig', 'w', encoding='utf-8')\n tLink = re.split(' ', LINKFLAGNOW)\n Linkchange = ''\n for iii in tLink:\n if '-L' not in iii and '-l:' not in iii:\n Linkchange += iii + ' '\n for i in range(Ln):\n p = re.split('{workspace}/', self.Llist.item(i).text())\n if len(p) == 1:\n Linkchange += '-L\"' + os.path.abspath(p[0]) + '\" '\n else:\n Linkchange += '-L\"' + os.path.abspath(p[1]) + '\" '\n LnNOW.append(self.Llist.item(i).text())\n for i in range(ln):\n Linkchange += '-l' + self.llist.item(i).text() + ' '\n lnNOW.append(self.llist.item(i).text())\n f.write('CCFLAG=' + CCFLAGNOW + '\\n')\n f.write('LINKFLAG=' + Linkchange + '\\n')\n f.write('HighTecDir=' + HighTecDirNOW + '\\n')\n f.write('DebugName=' + DebugNameNOW + '\\n')\n aa = 'includepath='\n for a in inpathNOW:\n if a != '':\n aa += a + ','\n f.write(aa + '\\n')\n bb = 'excludefiles='\n for b in expathNOW:\n if b != '':\n bb += b + ','\n f.write(bb + '\\n')\n cc = 'LibraryPath='\n for c in LnNOW:\n if c != '':\n cc += c + ','\n dd = 'libraties='\n for d in lnNOW:\n if d != '':\n dd += d + ','\n f.write(cc + '\\n')\n f.write(dd + '\\n')\n f.close()\n self.LINKFLAGName.setText('')\n self.LINKFLAGName.setText(Linkchange)\n except:\n f.close()\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n\n def testaa(self):\n print('1')\n\n def CloseTools(self):\n print(1)\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n <function token>\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n <function token>\n\n def AddLibraryPath(self):\n txt = self.LWUI.LibraryP.text()\n if txt:\n self.Llist.addItem(txt)\n self.LWin.close()\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n\n def DelLibraryPath(self):\n items1 = self.Llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.Llist.removeItemWidget(self.Llist.takeItem(jj.row()))\n\n def DelLibraries(self):\n items1 = self.llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.llist.removeItemWidget(self.llist.takeItem(jj.row()))\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n\n def __init__(self):\n super(basePage, self).__init__()\n self.setupUi(self)\n self.startpath = os.getcwd()\n self.actionbuild.triggered.connect(self.checkFLAG)\n self.actionclean.triggered.connect(self.CleanProject)\n self.actionopen_project.triggered.connect(self.ChooseProDir)\n self.actionsave_project.triggered.connect(self.modifyFLAG)\n self.actionexit.triggered.connect(qApp.quit)\n self.tb1 = self.addToolBar('tool')\n actionopen1 = QAction(QIcon('./Compile/file.png'), '打开工程', self)\n self.tb1.addAction(actionopen1)\n actionopen1.triggered.connect(self.ChooseProDir)\n self.tb1.addSeparator()\n actionstop = QAction(QIcon('./Compile/stop.png'), '停止', self)\n self.tb1.addAction(actionstop)\n actionstop.triggered.connect(self.KillProcess)\n self.tb1.addSeparator()\n actionExit = QAction(QIcon('./Compile/exit.png'), '退出', self)\n self.tb1.addAction(actionExit)\n actionExit.triggered.connect(qApp.quit)\n self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.contextMenu = QMenu(self)\n self.actionA = self.contextMenu.addAction('删除')\n self.actionA.triggered.connect(self.remove)\n self.includeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(1))\n self.excludeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(2))\n self.delPath1.clicked.connect(self.includeList.clear)\n self.delPath2.clicked.connect(self.excludeList.clear)\n self.addPath1.clicked.connect(lambda : self.ShowDialog(1))\n self.addPath2.clicked.connect(self.AddExpath)\n self.fileselect = fileselect.Ui_Dialog()\n self.listWidget.currentRowChanged.connect(self.display)\n self.initLibraryWindow()\n self.Llist.setSelectionMode(3)\n self.llist.setSelectionMode(3)\n self.barlabel = QLabel('barlabel')\n <function token>\n <function token>\n\n def initLibraryWindow(self):\n self.LWUI = AddLibraryPath.Ui_LSelect()\n self.LWin = QWidget()\n self.LWin.setWindowModality(Qt.ApplicationModal)\n self.LWUI.setupUi(self.LWin)\n self.LWUI.LibraryP.setText('')\n self.add1.clicked.connect(self.LWin.show)\n self.LWUI.L_Cancel.clicked.connect(self.LWin.close)\n self.LWUI.L_Workspace.clicked.connect(lambda : self.ShowDialog(1))\n self.LWUI.L_OK.clicked.connect(self.AddLibraryPath)\n self.del1.clicked.connect(self.DelLibraryPath)\n self.lWUI = Enterlibraries.Ui_LSelect()\n self.lWin = QWidget()\n self.lWin.setWindowModality(Qt.ApplicationModal)\n self.lWUI.setupUi(self.lWin)\n self.LWUI.LibraryP.setText('')\n self.add2.clicked.connect(self.lWin.show)\n self.lWUI.l_OK.clicked.connect(self.AddLibraries)\n self.lWUI.l_Cancel.clicked.connect(self.lWin.close)\n self.del2.clicked.connect(self.DelLibraries)\n <function token>\n\n def ChooseProDir(self):\n dir = QFileDialog.getExistingDirectory()\n dir = dir.replace('/', '\\\\')\n self.ProjectName_2.setText(dir)\n if dir != '':\n os.chdir(dir)\n import automake_config as ac\n (DebugName, HighTecDir, CCFLAG, LINKFLAG, includepath,\n excludefiles, g_except_dir_list, g_except_file_list,\n LibraryPath, libraties) = ac.maininit()\n self.includepath = includepath\n self.excludefiles = excludefiles\n self.DebugName = DebugName\n self.CCFLAG = CCFLAG\n self.LINKFLAG = LINKFLAG\n self.HighTecDir = HighTecDir\n self.PROJECTDIR = dir\n self.LibraryPath = LibraryPath\n self.libraties = libraties\n self.AllPath = ac.FindAllPath(dir)\n self.initDialog()\n self.fileselect.buttonBox.accepted.connect(self.GetPath)\n self.fileselect.treeWidget.setSelectionMode(3)\n self.fileselect.buttonBox.rejected.connect(self.Cleartree)\n a.initUI()\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n\n def remove(self):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if self.index == 3:\n if items1:\n for jj in items1:\n self.includeList.removeItemWidget(self.includeList.\n takeItem(jj.row()))\n if self.index == 4:\n if items2:\n for jj in items2:\n self.excludeList.removeItemWidget(self.excludeList.\n takeItem(jj.row()))\n\n def EndResult(self):\n print(os.getcwd())\n f = open('./conerr.err', 'r')\n lines = f.readlines()\n j = 0\n for ii in lines:\n if 'error:' in ii:\n self.Result.append('<font color=\"#FF0000\">%s</font> ' % ii)\n j = 1\n if j != 1:\n self.Result.append('<font color=\"#FF0000\">finished!!!!!!!!</font> '\n )\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working = False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n\n def initBar(self):\n global NUM\n self.progressBar = QProgressBar()\n self.Result.clear()\n self.barlabel.setText('正在编译:')\n self.statusBar.addPermanentWidget(self.progressBar, stretch=2)\n f = open('./Default/Default.objectlist', 'r')\n lines = f.readlines()\n f.close()\n NUM = len(lines)\n self.progressBar.setRange(0, len(lines))\n global VAL\n VAL = 0\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n\n def StartCompile(self, Hdir):\n global cmd1\n cmd1 = '%s\\\\bin\\\\make -j8 all' % Hdir\n os.chdir(self.ProjectName_2.text() + '/Default')\n self.backend1 = BackendTread1()\n self.backend1.startcompile1.connect(self.PrintConsole)\n self.backend1.endSig.connect(self.EndResult)\n self.backend1.start()\n self.backend = BackendTread()\n self.backend.setvalue.connect(self.SetProgressBarVal)\n self.backend.start()\n \"\"\"self.process = subprocess.call(cmd1)\n self.process.wait()\n f= open('console.log','r')\n lines =f.readlines()\n for ii in lines:\n if 'error:'in ii:\n self.Result.insertText(ii+'\n')\"\"\"\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n <function token>\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n\n def testaa(self):\n print('1')\n\n def CloseTools(self):\n print(1)\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n <function token>\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n <function token>\n\n def AddLibraryPath(self):\n txt = self.LWUI.LibraryP.text()\n if txt:\n self.Llist.addItem(txt)\n self.LWin.close()\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n\n def DelLibraryPath(self):\n items1 = self.Llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.Llist.removeItemWidget(self.Llist.takeItem(jj.row()))\n\n def DelLibraries(self):\n items1 = self.llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.llist.removeItemWidget(self.llist.takeItem(jj.row()))\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n\n def __init__(self):\n super(basePage, self).__init__()\n self.setupUi(self)\n self.startpath = os.getcwd()\n self.actionbuild.triggered.connect(self.checkFLAG)\n self.actionclean.triggered.connect(self.CleanProject)\n self.actionopen_project.triggered.connect(self.ChooseProDir)\n self.actionsave_project.triggered.connect(self.modifyFLAG)\n self.actionexit.triggered.connect(qApp.quit)\n self.tb1 = self.addToolBar('tool')\n actionopen1 = QAction(QIcon('./Compile/file.png'), '打开工程', self)\n self.tb1.addAction(actionopen1)\n actionopen1.triggered.connect(self.ChooseProDir)\n self.tb1.addSeparator()\n actionstop = QAction(QIcon('./Compile/stop.png'), '停止', self)\n self.tb1.addAction(actionstop)\n actionstop.triggered.connect(self.KillProcess)\n self.tb1.addSeparator()\n actionExit = QAction(QIcon('./Compile/exit.png'), '退出', self)\n self.tb1.addAction(actionExit)\n actionExit.triggered.connect(qApp.quit)\n self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.contextMenu = QMenu(self)\n self.actionA = self.contextMenu.addAction('删除')\n self.actionA.triggered.connect(self.remove)\n self.includeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(1))\n self.excludeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(2))\n self.delPath1.clicked.connect(self.includeList.clear)\n self.delPath2.clicked.connect(self.excludeList.clear)\n self.addPath1.clicked.connect(lambda : self.ShowDialog(1))\n self.addPath2.clicked.connect(self.AddExpath)\n self.fileselect = fileselect.Ui_Dialog()\n self.listWidget.currentRowChanged.connect(self.display)\n self.initLibraryWindow()\n self.Llist.setSelectionMode(3)\n self.llist.setSelectionMode(3)\n self.barlabel = QLabel('barlabel')\n <function token>\n <function token>\n\n def initLibraryWindow(self):\n self.LWUI = AddLibraryPath.Ui_LSelect()\n self.LWin = QWidget()\n self.LWin.setWindowModality(Qt.ApplicationModal)\n self.LWUI.setupUi(self.LWin)\n self.LWUI.LibraryP.setText('')\n self.add1.clicked.connect(self.LWin.show)\n self.LWUI.L_Cancel.clicked.connect(self.LWin.close)\n self.LWUI.L_Workspace.clicked.connect(lambda : self.ShowDialog(1))\n self.LWUI.L_OK.clicked.connect(self.AddLibraryPath)\n self.del1.clicked.connect(self.DelLibraryPath)\n self.lWUI = Enterlibraries.Ui_LSelect()\n self.lWin = QWidget()\n self.lWin.setWindowModality(Qt.ApplicationModal)\n self.lWUI.setupUi(self.lWin)\n self.LWUI.LibraryP.setText('')\n self.add2.clicked.connect(self.lWin.show)\n self.lWUI.l_OK.clicked.connect(self.AddLibraries)\n self.lWUI.l_Cancel.clicked.connect(self.lWin.close)\n self.del2.clicked.connect(self.DelLibraries)\n <function token>\n\n def ChooseProDir(self):\n dir = QFileDialog.getExistingDirectory()\n dir = dir.replace('/', '\\\\')\n self.ProjectName_2.setText(dir)\n if dir != '':\n os.chdir(dir)\n import automake_config as ac\n (DebugName, HighTecDir, CCFLAG, LINKFLAG, includepath,\n excludefiles, g_except_dir_list, g_except_file_list,\n LibraryPath, libraties) = ac.maininit()\n self.includepath = includepath\n self.excludefiles = excludefiles\n self.DebugName = DebugName\n self.CCFLAG = CCFLAG\n self.LINKFLAG = LINKFLAG\n self.HighTecDir = HighTecDir\n self.PROJECTDIR = dir\n self.LibraryPath = LibraryPath\n self.libraties = libraties\n self.AllPath = ac.FindAllPath(dir)\n self.initDialog()\n self.fileselect.buttonBox.accepted.connect(self.GetPath)\n self.fileselect.treeWidget.setSelectionMode(3)\n self.fileselect.buttonBox.rejected.connect(self.Cleartree)\n a.initUI()\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n\n def remove(self):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if self.index == 3:\n if items1:\n for jj in items1:\n self.includeList.removeItemWidget(self.includeList.\n takeItem(jj.row()))\n if self.index == 4:\n if items2:\n for jj in items2:\n self.excludeList.removeItemWidget(self.excludeList.\n takeItem(jj.row()))\n\n def EndResult(self):\n print(os.getcwd())\n f = open('./conerr.err', 'r')\n lines = f.readlines()\n j = 0\n for ii in lines:\n if 'error:' in ii:\n self.Result.append('<font color=\"#FF0000\">%s</font> ' % ii)\n j = 1\n if j != 1:\n self.Result.append('<font color=\"#FF0000\">finished!!!!!!!!</font> '\n )\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working = False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n\n def initBar(self):\n global NUM\n self.progressBar = QProgressBar()\n self.Result.clear()\n self.barlabel.setText('正在编译:')\n self.statusBar.addPermanentWidget(self.progressBar, stretch=2)\n f = open('./Default/Default.objectlist', 'r')\n lines = f.readlines()\n f.close()\n NUM = len(lines)\n self.progressBar.setRange(0, len(lines))\n global VAL\n VAL = 0\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n\n def StartCompile(self, Hdir):\n global cmd1\n cmd1 = '%s\\\\bin\\\\make -j8 all' % Hdir\n os.chdir(self.ProjectName_2.text() + '/Default')\n self.backend1 = BackendTread1()\n self.backend1.startcompile1.connect(self.PrintConsole)\n self.backend1.endSig.connect(self.EndResult)\n self.backend1.start()\n self.backend = BackendTread()\n self.backend.setvalue.connect(self.SetProgressBarVal)\n self.backend.start()\n \"\"\"self.process = subprocess.call(cmd1)\n self.process.wait()\n f= open('console.log','r')\n lines =f.readlines()\n for ii in lines:\n if 'error:'in ii:\n self.Result.insertText(ii+'\n')\"\"\"\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n <function token>\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n\n def testaa(self):\n print('1')\n\n def CloseTools(self):\n print(1)\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n <function token>\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n <function token>\n\n def AddLibraryPath(self):\n txt = self.LWUI.LibraryP.text()\n if txt:\n self.Llist.addItem(txt)\n self.LWin.close()\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n\n def DelLibraryPath(self):\n items1 = self.Llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.Llist.removeItemWidget(self.Llist.takeItem(jj.row()))\n <function token>\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n\n def __init__(self):\n super(basePage, self).__init__()\n self.setupUi(self)\n self.startpath = os.getcwd()\n self.actionbuild.triggered.connect(self.checkFLAG)\n self.actionclean.triggered.connect(self.CleanProject)\n self.actionopen_project.triggered.connect(self.ChooseProDir)\n self.actionsave_project.triggered.connect(self.modifyFLAG)\n self.actionexit.triggered.connect(qApp.quit)\n self.tb1 = self.addToolBar('tool')\n actionopen1 = QAction(QIcon('./Compile/file.png'), '打开工程', self)\n self.tb1.addAction(actionopen1)\n actionopen1.triggered.connect(self.ChooseProDir)\n self.tb1.addSeparator()\n actionstop = QAction(QIcon('./Compile/stop.png'), '停止', self)\n self.tb1.addAction(actionstop)\n actionstop.triggered.connect(self.KillProcess)\n self.tb1.addSeparator()\n actionExit = QAction(QIcon('./Compile/exit.png'), '退出', self)\n self.tb1.addAction(actionExit)\n actionExit.triggered.connect(qApp.quit)\n self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.contextMenu = QMenu(self)\n self.actionA = self.contextMenu.addAction('删除')\n self.actionA.triggered.connect(self.remove)\n self.includeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(1))\n self.excludeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(2))\n self.delPath1.clicked.connect(self.includeList.clear)\n self.delPath2.clicked.connect(self.excludeList.clear)\n self.addPath1.clicked.connect(lambda : self.ShowDialog(1))\n self.addPath2.clicked.connect(self.AddExpath)\n self.fileselect = fileselect.Ui_Dialog()\n self.listWidget.currentRowChanged.connect(self.display)\n self.initLibraryWindow()\n self.Llist.setSelectionMode(3)\n self.llist.setSelectionMode(3)\n self.barlabel = QLabel('barlabel')\n <function token>\n <function token>\n <function token>\n <function token>\n\n def ChooseProDir(self):\n dir = QFileDialog.getExistingDirectory()\n dir = dir.replace('/', '\\\\')\n self.ProjectName_2.setText(dir)\n if dir != '':\n os.chdir(dir)\n import automake_config as ac\n (DebugName, HighTecDir, CCFLAG, LINKFLAG, includepath,\n excludefiles, g_except_dir_list, g_except_file_list,\n LibraryPath, libraties) = ac.maininit()\n self.includepath = includepath\n self.excludefiles = excludefiles\n self.DebugName = DebugName\n self.CCFLAG = CCFLAG\n self.LINKFLAG = LINKFLAG\n self.HighTecDir = HighTecDir\n self.PROJECTDIR = dir\n self.LibraryPath = LibraryPath\n self.libraties = libraties\n self.AllPath = ac.FindAllPath(dir)\n self.initDialog()\n self.fileselect.buttonBox.accepted.connect(self.GetPath)\n self.fileselect.treeWidget.setSelectionMode(3)\n self.fileselect.buttonBox.rejected.connect(self.Cleartree)\n a.initUI()\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n\n def remove(self):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if self.index == 3:\n if items1:\n for jj in items1:\n self.includeList.removeItemWidget(self.includeList.\n takeItem(jj.row()))\n if self.index == 4:\n if items2:\n for jj in items2:\n self.excludeList.removeItemWidget(self.excludeList.\n takeItem(jj.row()))\n\n def EndResult(self):\n print(os.getcwd())\n f = open('./conerr.err', 'r')\n lines = f.readlines()\n j = 0\n for ii in lines:\n if 'error:' in ii:\n self.Result.append('<font color=\"#FF0000\">%s</font> ' % ii)\n j = 1\n if j != 1:\n self.Result.append('<font color=\"#FF0000\">finished!!!!!!!!</font> '\n )\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working = False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n\n def initBar(self):\n global NUM\n self.progressBar = QProgressBar()\n self.Result.clear()\n self.barlabel.setText('正在编译:')\n self.statusBar.addPermanentWidget(self.progressBar, stretch=2)\n f = open('./Default/Default.objectlist', 'r')\n lines = f.readlines()\n f.close()\n NUM = len(lines)\n self.progressBar.setRange(0, len(lines))\n global VAL\n VAL = 0\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n\n def StartCompile(self, Hdir):\n global cmd1\n cmd1 = '%s\\\\bin\\\\make -j8 all' % Hdir\n os.chdir(self.ProjectName_2.text() + '/Default')\n self.backend1 = BackendTread1()\n self.backend1.startcompile1.connect(self.PrintConsole)\n self.backend1.endSig.connect(self.EndResult)\n self.backend1.start()\n self.backend = BackendTread()\n self.backend.setvalue.connect(self.SetProgressBarVal)\n self.backend.start()\n \"\"\"self.process = subprocess.call(cmd1)\n self.process.wait()\n f= open('console.log','r')\n lines =f.readlines()\n for ii in lines:\n if 'error:'in ii:\n self.Result.insertText(ii+'\n')\"\"\"\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n <function token>\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n\n def testaa(self):\n print('1')\n\n def CloseTools(self):\n print(1)\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n <function token>\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n <function token>\n\n def AddLibraryPath(self):\n txt = self.LWUI.LibraryP.text()\n if txt:\n self.Llist.addItem(txt)\n self.LWin.close()\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n\n def DelLibraryPath(self):\n items1 = self.Llist.selectedIndexes()\n if items1:\n for jj in items1:\n self.Llist.removeItemWidget(self.Llist.takeItem(jj.row()))\n <function token>\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n\n def __init__(self):\n super(basePage, self).__init__()\n self.setupUi(self)\n self.startpath = os.getcwd()\n self.actionbuild.triggered.connect(self.checkFLAG)\n self.actionclean.triggered.connect(self.CleanProject)\n self.actionopen_project.triggered.connect(self.ChooseProDir)\n self.actionsave_project.triggered.connect(self.modifyFLAG)\n self.actionexit.triggered.connect(qApp.quit)\n self.tb1 = self.addToolBar('tool')\n actionopen1 = QAction(QIcon('./Compile/file.png'), '打开工程', self)\n self.tb1.addAction(actionopen1)\n actionopen1.triggered.connect(self.ChooseProDir)\n self.tb1.addSeparator()\n actionstop = QAction(QIcon('./Compile/stop.png'), '停止', self)\n self.tb1.addAction(actionstop)\n actionstop.triggered.connect(self.KillProcess)\n self.tb1.addSeparator()\n actionExit = QAction(QIcon('./Compile/exit.png'), '退出', self)\n self.tb1.addAction(actionExit)\n actionExit.triggered.connect(qApp.quit)\n self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.contextMenu = QMenu(self)\n self.actionA = self.contextMenu.addAction('删除')\n self.actionA.triggered.connect(self.remove)\n self.includeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(1))\n self.excludeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(2))\n self.delPath1.clicked.connect(self.includeList.clear)\n self.delPath2.clicked.connect(self.excludeList.clear)\n self.addPath1.clicked.connect(lambda : self.ShowDialog(1))\n self.addPath2.clicked.connect(self.AddExpath)\n self.fileselect = fileselect.Ui_Dialog()\n self.listWidget.currentRowChanged.connect(self.display)\n self.initLibraryWindow()\n self.Llist.setSelectionMode(3)\n self.llist.setSelectionMode(3)\n self.barlabel = QLabel('barlabel')\n <function token>\n <function token>\n <function token>\n <function token>\n\n def ChooseProDir(self):\n dir = QFileDialog.getExistingDirectory()\n dir = dir.replace('/', '\\\\')\n self.ProjectName_2.setText(dir)\n if dir != '':\n os.chdir(dir)\n import automake_config as ac\n (DebugName, HighTecDir, CCFLAG, LINKFLAG, includepath,\n excludefiles, g_except_dir_list, g_except_file_list,\n LibraryPath, libraties) = ac.maininit()\n self.includepath = includepath\n self.excludefiles = excludefiles\n self.DebugName = DebugName\n self.CCFLAG = CCFLAG\n self.LINKFLAG = LINKFLAG\n self.HighTecDir = HighTecDir\n self.PROJECTDIR = dir\n self.LibraryPath = LibraryPath\n self.libraties = libraties\n self.AllPath = ac.FindAllPath(dir)\n self.initDialog()\n self.fileselect.buttonBox.accepted.connect(self.GetPath)\n self.fileselect.treeWidget.setSelectionMode(3)\n self.fileselect.buttonBox.rejected.connect(self.Cleartree)\n a.initUI()\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n\n def remove(self):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if self.index == 3:\n if items1:\n for jj in items1:\n self.includeList.removeItemWidget(self.includeList.\n takeItem(jj.row()))\n if self.index == 4:\n if items2:\n for jj in items2:\n self.excludeList.removeItemWidget(self.excludeList.\n takeItem(jj.row()))\n\n def EndResult(self):\n print(os.getcwd())\n f = open('./conerr.err', 'r')\n lines = f.readlines()\n j = 0\n for ii in lines:\n if 'error:' in ii:\n self.Result.append('<font color=\"#FF0000\">%s</font> ' % ii)\n j = 1\n if j != 1:\n self.Result.append('<font color=\"#FF0000\">finished!!!!!!!!</font> '\n )\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working = False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n\n def initBar(self):\n global NUM\n self.progressBar = QProgressBar()\n self.Result.clear()\n self.barlabel.setText('正在编译:')\n self.statusBar.addPermanentWidget(self.progressBar, stretch=2)\n f = open('./Default/Default.objectlist', 'r')\n lines = f.readlines()\n f.close()\n NUM = len(lines)\n self.progressBar.setRange(0, len(lines))\n global VAL\n VAL = 0\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n\n def StartCompile(self, Hdir):\n global cmd1\n cmd1 = '%s\\\\bin\\\\make -j8 all' % Hdir\n os.chdir(self.ProjectName_2.text() + '/Default')\n self.backend1 = BackendTread1()\n self.backend1.startcompile1.connect(self.PrintConsole)\n self.backend1.endSig.connect(self.EndResult)\n self.backend1.start()\n self.backend = BackendTread()\n self.backend.setvalue.connect(self.SetProgressBarVal)\n self.backend.start()\n \"\"\"self.process = subprocess.call(cmd1)\n self.process.wait()\n f= open('console.log','r')\n lines =f.readlines()\n for ii in lines:\n if 'error:'in ii:\n self.Result.insertText(ii+'\n')\"\"\"\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n <function token>\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n\n def testaa(self):\n print('1')\n\n def CloseTools(self):\n print(1)\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n <function token>\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n <function token>\n\n def AddLibraryPath(self):\n txt = self.LWUI.LibraryP.text()\n if txt:\n self.Llist.addItem(txt)\n self.LWin.close()\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n <function token>\n <function token>\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n\n def __init__(self):\n super(basePage, self).__init__()\n self.setupUi(self)\n self.startpath = os.getcwd()\n self.actionbuild.triggered.connect(self.checkFLAG)\n self.actionclean.triggered.connect(self.CleanProject)\n self.actionopen_project.triggered.connect(self.ChooseProDir)\n self.actionsave_project.triggered.connect(self.modifyFLAG)\n self.actionexit.triggered.connect(qApp.quit)\n self.tb1 = self.addToolBar('tool')\n actionopen1 = QAction(QIcon('./Compile/file.png'), '打开工程', self)\n self.tb1.addAction(actionopen1)\n actionopen1.triggered.connect(self.ChooseProDir)\n self.tb1.addSeparator()\n actionstop = QAction(QIcon('./Compile/stop.png'), '停止', self)\n self.tb1.addAction(actionstop)\n actionstop.triggered.connect(self.KillProcess)\n self.tb1.addSeparator()\n actionExit = QAction(QIcon('./Compile/exit.png'), '退出', self)\n self.tb1.addAction(actionExit)\n actionExit.triggered.connect(qApp.quit)\n self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.contextMenu = QMenu(self)\n self.actionA = self.contextMenu.addAction('删除')\n self.actionA.triggered.connect(self.remove)\n self.includeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(1))\n self.excludeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(2))\n self.delPath1.clicked.connect(self.includeList.clear)\n self.delPath2.clicked.connect(self.excludeList.clear)\n self.addPath1.clicked.connect(lambda : self.ShowDialog(1))\n self.addPath2.clicked.connect(self.AddExpath)\n self.fileselect = fileselect.Ui_Dialog()\n self.listWidget.currentRowChanged.connect(self.display)\n self.initLibraryWindow()\n self.Llist.setSelectionMode(3)\n self.llist.setSelectionMode(3)\n self.barlabel = QLabel('barlabel')\n <function token>\n <function token>\n <function token>\n <function token>\n\n def ChooseProDir(self):\n dir = QFileDialog.getExistingDirectory()\n dir = dir.replace('/', '\\\\')\n self.ProjectName_2.setText(dir)\n if dir != '':\n os.chdir(dir)\n import automake_config as ac\n (DebugName, HighTecDir, CCFLAG, LINKFLAG, includepath,\n excludefiles, g_except_dir_list, g_except_file_list,\n LibraryPath, libraties) = ac.maininit()\n self.includepath = includepath\n self.excludefiles = excludefiles\n self.DebugName = DebugName\n self.CCFLAG = CCFLAG\n self.LINKFLAG = LINKFLAG\n self.HighTecDir = HighTecDir\n self.PROJECTDIR = dir\n self.LibraryPath = LibraryPath\n self.libraties = libraties\n self.AllPath = ac.FindAllPath(dir)\n self.initDialog()\n self.fileselect.buttonBox.accepted.connect(self.GetPath)\n self.fileselect.treeWidget.setSelectionMode(3)\n self.fileselect.buttonBox.rejected.connect(self.Cleartree)\n a.initUI()\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n\n def remove(self):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if self.index == 3:\n if items1:\n for jj in items1:\n self.includeList.removeItemWidget(self.includeList.\n takeItem(jj.row()))\n if self.index == 4:\n if items2:\n for jj in items2:\n self.excludeList.removeItemWidget(self.excludeList.\n takeItem(jj.row()))\n\n def EndResult(self):\n print(os.getcwd())\n f = open('./conerr.err', 'r')\n lines = f.readlines()\n j = 0\n for ii in lines:\n if 'error:' in ii:\n self.Result.append('<font color=\"#FF0000\">%s</font> ' % ii)\n j = 1\n if j != 1:\n self.Result.append('<font color=\"#FF0000\">finished!!!!!!!!</font> '\n )\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working = False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n <function token>\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n\n def StartCompile(self, Hdir):\n global cmd1\n cmd1 = '%s\\\\bin\\\\make -j8 all' % Hdir\n os.chdir(self.ProjectName_2.text() + '/Default')\n self.backend1 = BackendTread1()\n self.backend1.startcompile1.connect(self.PrintConsole)\n self.backend1.endSig.connect(self.EndResult)\n self.backend1.start()\n self.backend = BackendTread()\n self.backend.setvalue.connect(self.SetProgressBarVal)\n self.backend.start()\n \"\"\"self.process = subprocess.call(cmd1)\n self.process.wait()\n f= open('console.log','r')\n lines =f.readlines()\n for ii in lines:\n if 'error:'in ii:\n self.Result.insertText(ii+'\n')\"\"\"\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n <function token>\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n\n def testaa(self):\n print('1')\n\n def CloseTools(self):\n print(1)\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n <function token>\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n <function token>\n\n def AddLibraryPath(self):\n txt = self.LWUI.LibraryP.text()\n if txt:\n self.Llist.addItem(txt)\n self.LWin.close()\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n <function token>\n <function token>\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n\n def __init__(self):\n super(basePage, self).__init__()\n self.setupUi(self)\n self.startpath = os.getcwd()\n self.actionbuild.triggered.connect(self.checkFLAG)\n self.actionclean.triggered.connect(self.CleanProject)\n self.actionopen_project.triggered.connect(self.ChooseProDir)\n self.actionsave_project.triggered.connect(self.modifyFLAG)\n self.actionexit.triggered.connect(qApp.quit)\n self.tb1 = self.addToolBar('tool')\n actionopen1 = QAction(QIcon('./Compile/file.png'), '打开工程', self)\n self.tb1.addAction(actionopen1)\n actionopen1.triggered.connect(self.ChooseProDir)\n self.tb1.addSeparator()\n actionstop = QAction(QIcon('./Compile/stop.png'), '停止', self)\n self.tb1.addAction(actionstop)\n actionstop.triggered.connect(self.KillProcess)\n self.tb1.addSeparator()\n actionExit = QAction(QIcon('./Compile/exit.png'), '退出', self)\n self.tb1.addAction(actionExit)\n actionExit.triggered.connect(qApp.quit)\n self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.contextMenu = QMenu(self)\n self.actionA = self.contextMenu.addAction('删除')\n self.actionA.triggered.connect(self.remove)\n self.includeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(1))\n self.excludeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(2))\n self.delPath1.clicked.connect(self.includeList.clear)\n self.delPath2.clicked.connect(self.excludeList.clear)\n self.addPath1.clicked.connect(lambda : self.ShowDialog(1))\n self.addPath2.clicked.connect(self.AddExpath)\n self.fileselect = fileselect.Ui_Dialog()\n self.listWidget.currentRowChanged.connect(self.display)\n self.initLibraryWindow()\n self.Llist.setSelectionMode(3)\n self.llist.setSelectionMode(3)\n self.barlabel = QLabel('barlabel')\n <function token>\n <function token>\n <function token>\n <function token>\n\n def ChooseProDir(self):\n dir = QFileDialog.getExistingDirectory()\n dir = dir.replace('/', '\\\\')\n self.ProjectName_2.setText(dir)\n if dir != '':\n os.chdir(dir)\n import automake_config as ac\n (DebugName, HighTecDir, CCFLAG, LINKFLAG, includepath,\n excludefiles, g_except_dir_list, g_except_file_list,\n LibraryPath, libraties) = ac.maininit()\n self.includepath = includepath\n self.excludefiles = excludefiles\n self.DebugName = DebugName\n self.CCFLAG = CCFLAG\n self.LINKFLAG = LINKFLAG\n self.HighTecDir = HighTecDir\n self.PROJECTDIR = dir\n self.LibraryPath = LibraryPath\n self.libraties = libraties\n self.AllPath = ac.FindAllPath(dir)\n self.initDialog()\n self.fileselect.buttonBox.accepted.connect(self.GetPath)\n self.fileselect.treeWidget.setSelectionMode(3)\n self.fileselect.buttonBox.rejected.connect(self.Cleartree)\n a.initUI()\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n <function token>\n\n def EndResult(self):\n print(os.getcwd())\n f = open('./conerr.err', 'r')\n lines = f.readlines()\n j = 0\n for ii in lines:\n if 'error:' in ii:\n self.Result.append('<font color=\"#FF0000\">%s</font> ' % ii)\n j = 1\n if j != 1:\n self.Result.append('<font color=\"#FF0000\">finished!!!!!!!!</font> '\n )\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working = False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n <function token>\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n\n def StartCompile(self, Hdir):\n global cmd1\n cmd1 = '%s\\\\bin\\\\make -j8 all' % Hdir\n os.chdir(self.ProjectName_2.text() + '/Default')\n self.backend1 = BackendTread1()\n self.backend1.startcompile1.connect(self.PrintConsole)\n self.backend1.endSig.connect(self.EndResult)\n self.backend1.start()\n self.backend = BackendTread()\n self.backend.setvalue.connect(self.SetProgressBarVal)\n self.backend.start()\n \"\"\"self.process = subprocess.call(cmd1)\n self.process.wait()\n f= open('console.log','r')\n lines =f.readlines()\n for ii in lines:\n if 'error:'in ii:\n self.Result.insertText(ii+'\n')\"\"\"\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n <function token>\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n\n def testaa(self):\n print('1')\n\n def CloseTools(self):\n print(1)\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n <function token>\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n <function token>\n\n def AddLibraryPath(self):\n txt = self.LWUI.LibraryP.text()\n if txt:\n self.Llist.addItem(txt)\n self.LWin.close()\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n <function token>\n <function token>\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n\n def __init__(self):\n super(basePage, self).__init__()\n self.setupUi(self)\n self.startpath = os.getcwd()\n self.actionbuild.triggered.connect(self.checkFLAG)\n self.actionclean.triggered.connect(self.CleanProject)\n self.actionopen_project.triggered.connect(self.ChooseProDir)\n self.actionsave_project.triggered.connect(self.modifyFLAG)\n self.actionexit.triggered.connect(qApp.quit)\n self.tb1 = self.addToolBar('tool')\n actionopen1 = QAction(QIcon('./Compile/file.png'), '打开工程', self)\n self.tb1.addAction(actionopen1)\n actionopen1.triggered.connect(self.ChooseProDir)\n self.tb1.addSeparator()\n actionstop = QAction(QIcon('./Compile/stop.png'), '停止', self)\n self.tb1.addAction(actionstop)\n actionstop.triggered.connect(self.KillProcess)\n self.tb1.addSeparator()\n actionExit = QAction(QIcon('./Compile/exit.png'), '退出', self)\n self.tb1.addAction(actionExit)\n actionExit.triggered.connect(qApp.quit)\n self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.contextMenu = QMenu(self)\n self.actionA = self.contextMenu.addAction('删除')\n self.actionA.triggered.connect(self.remove)\n self.includeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(1))\n self.excludeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(2))\n self.delPath1.clicked.connect(self.includeList.clear)\n self.delPath2.clicked.connect(self.excludeList.clear)\n self.addPath1.clicked.connect(lambda : self.ShowDialog(1))\n self.addPath2.clicked.connect(self.AddExpath)\n self.fileselect = fileselect.Ui_Dialog()\n self.listWidget.currentRowChanged.connect(self.display)\n self.initLibraryWindow()\n self.Llist.setSelectionMode(3)\n self.llist.setSelectionMode(3)\n self.barlabel = QLabel('barlabel')\n <function token>\n <function token>\n <function token>\n <function token>\n\n def ChooseProDir(self):\n dir = QFileDialog.getExistingDirectory()\n dir = dir.replace('/', '\\\\')\n self.ProjectName_2.setText(dir)\n if dir != '':\n os.chdir(dir)\n import automake_config as ac\n (DebugName, HighTecDir, CCFLAG, LINKFLAG, includepath,\n excludefiles, g_except_dir_list, g_except_file_list,\n LibraryPath, libraties) = ac.maininit()\n self.includepath = includepath\n self.excludefiles = excludefiles\n self.DebugName = DebugName\n self.CCFLAG = CCFLAG\n self.LINKFLAG = LINKFLAG\n self.HighTecDir = HighTecDir\n self.PROJECTDIR = dir\n self.LibraryPath = LibraryPath\n self.libraties = libraties\n self.AllPath = ac.FindAllPath(dir)\n self.initDialog()\n self.fileselect.buttonBox.accepted.connect(self.GetPath)\n self.fileselect.treeWidget.setSelectionMode(3)\n self.fileselect.buttonBox.rejected.connect(self.Cleartree)\n a.initUI()\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n <function token>\n\n def EndResult(self):\n print(os.getcwd())\n f = open('./conerr.err', 'r')\n lines = f.readlines()\n j = 0\n for ii in lines:\n if 'error:' in ii:\n self.Result.append('<font color=\"#FF0000\">%s</font> ' % ii)\n j = 1\n if j != 1:\n self.Result.append('<font color=\"#FF0000\">finished!!!!!!!!</font> '\n )\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working = False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n <function token>\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n\n def StartCompile(self, Hdir):\n global cmd1\n cmd1 = '%s\\\\bin\\\\make -j8 all' % Hdir\n os.chdir(self.ProjectName_2.text() + '/Default')\n self.backend1 = BackendTread1()\n self.backend1.startcompile1.connect(self.PrintConsole)\n self.backend1.endSig.connect(self.EndResult)\n self.backend1.start()\n self.backend = BackendTread()\n self.backend.setvalue.connect(self.SetProgressBarVal)\n self.backend.start()\n \"\"\"self.process = subprocess.call(cmd1)\n self.process.wait()\n f= open('console.log','r')\n lines =f.readlines()\n for ii in lines:\n if 'error:'in ii:\n self.Result.insertText(ii+'\n')\"\"\"\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n <function token>\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n <function token>\n\n def CloseTools(self):\n print(1)\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n <function token>\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n <function token>\n\n def AddLibraryPath(self):\n txt = self.LWUI.LibraryP.text()\n if txt:\n self.Llist.addItem(txt)\n self.LWin.close()\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n <function token>\n <function token>\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n\n def __init__(self):\n super(basePage, self).__init__()\n self.setupUi(self)\n self.startpath = os.getcwd()\n self.actionbuild.triggered.connect(self.checkFLAG)\n self.actionclean.triggered.connect(self.CleanProject)\n self.actionopen_project.triggered.connect(self.ChooseProDir)\n self.actionsave_project.triggered.connect(self.modifyFLAG)\n self.actionexit.triggered.connect(qApp.quit)\n self.tb1 = self.addToolBar('tool')\n actionopen1 = QAction(QIcon('./Compile/file.png'), '打开工程', self)\n self.tb1.addAction(actionopen1)\n actionopen1.triggered.connect(self.ChooseProDir)\n self.tb1.addSeparator()\n actionstop = QAction(QIcon('./Compile/stop.png'), '停止', self)\n self.tb1.addAction(actionstop)\n actionstop.triggered.connect(self.KillProcess)\n self.tb1.addSeparator()\n actionExit = QAction(QIcon('./Compile/exit.png'), '退出', self)\n self.tb1.addAction(actionExit)\n actionExit.triggered.connect(qApp.quit)\n self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.contextMenu = QMenu(self)\n self.actionA = self.contextMenu.addAction('删除')\n self.actionA.triggered.connect(self.remove)\n self.includeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(1))\n self.excludeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(2))\n self.delPath1.clicked.connect(self.includeList.clear)\n self.delPath2.clicked.connect(self.excludeList.clear)\n self.addPath1.clicked.connect(lambda : self.ShowDialog(1))\n self.addPath2.clicked.connect(self.AddExpath)\n self.fileselect = fileselect.Ui_Dialog()\n self.listWidget.currentRowChanged.connect(self.display)\n self.initLibraryWindow()\n self.Llist.setSelectionMode(3)\n self.llist.setSelectionMode(3)\n self.barlabel = QLabel('barlabel')\n <function token>\n <function token>\n <function token>\n <function token>\n\n def ChooseProDir(self):\n dir = QFileDialog.getExistingDirectory()\n dir = dir.replace('/', '\\\\')\n self.ProjectName_2.setText(dir)\n if dir != '':\n os.chdir(dir)\n import automake_config as ac\n (DebugName, HighTecDir, CCFLAG, LINKFLAG, includepath,\n excludefiles, g_except_dir_list, g_except_file_list,\n LibraryPath, libraties) = ac.maininit()\n self.includepath = includepath\n self.excludefiles = excludefiles\n self.DebugName = DebugName\n self.CCFLAG = CCFLAG\n self.LINKFLAG = LINKFLAG\n self.HighTecDir = HighTecDir\n self.PROJECTDIR = dir\n self.LibraryPath = LibraryPath\n self.libraties = libraties\n self.AllPath = ac.FindAllPath(dir)\n self.initDialog()\n self.fileselect.buttonBox.accepted.connect(self.GetPath)\n self.fileselect.treeWidget.setSelectionMode(3)\n self.fileselect.buttonBox.rejected.connect(self.Cleartree)\n a.initUI()\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n <function token>\n\n def EndResult(self):\n print(os.getcwd())\n f = open('./conerr.err', 'r')\n lines = f.readlines()\n j = 0\n for ii in lines:\n if 'error:' in ii:\n self.Result.append('<font color=\"#FF0000\">%s</font> ' % ii)\n j = 1\n if j != 1:\n self.Result.append('<font color=\"#FF0000\">finished!!!!!!!!</font> '\n )\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working = False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n <function token>\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n <function token>\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n <function token>\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n <function token>\n\n def CloseTools(self):\n print(1)\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n <function token>\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n <function token>\n\n def AddLibraryPath(self):\n txt = self.LWUI.LibraryP.text()\n if txt:\n self.Llist.addItem(txt)\n self.LWin.close()\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n <function token>\n <function token>\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n\n def __init__(self):\n super(basePage, self).__init__()\n self.setupUi(self)\n self.startpath = os.getcwd()\n self.actionbuild.triggered.connect(self.checkFLAG)\n self.actionclean.triggered.connect(self.CleanProject)\n self.actionopen_project.triggered.connect(self.ChooseProDir)\n self.actionsave_project.triggered.connect(self.modifyFLAG)\n self.actionexit.triggered.connect(qApp.quit)\n self.tb1 = self.addToolBar('tool')\n actionopen1 = QAction(QIcon('./Compile/file.png'), '打开工程', self)\n self.tb1.addAction(actionopen1)\n actionopen1.triggered.connect(self.ChooseProDir)\n self.tb1.addSeparator()\n actionstop = QAction(QIcon('./Compile/stop.png'), '停止', self)\n self.tb1.addAction(actionstop)\n actionstop.triggered.connect(self.KillProcess)\n self.tb1.addSeparator()\n actionExit = QAction(QIcon('./Compile/exit.png'), '退出', self)\n self.tb1.addAction(actionExit)\n actionExit.triggered.connect(qApp.quit)\n self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.contextMenu = QMenu(self)\n self.actionA = self.contextMenu.addAction('删除')\n self.actionA.triggered.connect(self.remove)\n self.includeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(1))\n self.excludeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(2))\n self.delPath1.clicked.connect(self.includeList.clear)\n self.delPath2.clicked.connect(self.excludeList.clear)\n self.addPath1.clicked.connect(lambda : self.ShowDialog(1))\n self.addPath2.clicked.connect(self.AddExpath)\n self.fileselect = fileselect.Ui_Dialog()\n self.listWidget.currentRowChanged.connect(self.display)\n self.initLibraryWindow()\n self.Llist.setSelectionMode(3)\n self.llist.setSelectionMode(3)\n self.barlabel = QLabel('barlabel')\n <function token>\n <function token>\n <function token>\n <function token>\n\n def ChooseProDir(self):\n dir = QFileDialog.getExistingDirectory()\n dir = dir.replace('/', '\\\\')\n self.ProjectName_2.setText(dir)\n if dir != '':\n os.chdir(dir)\n import automake_config as ac\n (DebugName, HighTecDir, CCFLAG, LINKFLAG, includepath,\n excludefiles, g_except_dir_list, g_except_file_list,\n LibraryPath, libraties) = ac.maininit()\n self.includepath = includepath\n self.excludefiles = excludefiles\n self.DebugName = DebugName\n self.CCFLAG = CCFLAG\n self.LINKFLAG = LINKFLAG\n self.HighTecDir = HighTecDir\n self.PROJECTDIR = dir\n self.LibraryPath = LibraryPath\n self.libraties = libraties\n self.AllPath = ac.FindAllPath(dir)\n self.initDialog()\n self.fileselect.buttonBox.accepted.connect(self.GetPath)\n self.fileselect.treeWidget.setSelectionMode(3)\n self.fileselect.buttonBox.rejected.connect(self.Cleartree)\n a.initUI()\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n <function token>\n\n def EndResult(self):\n print(os.getcwd())\n f = open('./conerr.err', 'r')\n lines = f.readlines()\n j = 0\n for ii in lines:\n if 'error:' in ii:\n self.Result.append('<font color=\"#FF0000\">%s</font> ' % ii)\n j = 1\n if j != 1:\n self.Result.append('<font color=\"#FF0000\">finished!!!!!!!!</font> '\n )\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working = False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n <function token>\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n <function token>\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n <function token>\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n <function token>\n <function token>\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n <function token>\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n <function token>\n\n def AddLibraryPath(self):\n txt = self.LWUI.LibraryP.text()\n if txt:\n self.Llist.addItem(txt)\n self.LWin.close()\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n <function token>\n <function token>\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n\n def __init__(self):\n super(basePage, self).__init__()\n self.setupUi(self)\n self.startpath = os.getcwd()\n self.actionbuild.triggered.connect(self.checkFLAG)\n self.actionclean.triggered.connect(self.CleanProject)\n self.actionopen_project.triggered.connect(self.ChooseProDir)\n self.actionsave_project.triggered.connect(self.modifyFLAG)\n self.actionexit.triggered.connect(qApp.quit)\n self.tb1 = self.addToolBar('tool')\n actionopen1 = QAction(QIcon('./Compile/file.png'), '打开工程', self)\n self.tb1.addAction(actionopen1)\n actionopen1.triggered.connect(self.ChooseProDir)\n self.tb1.addSeparator()\n actionstop = QAction(QIcon('./Compile/stop.png'), '停止', self)\n self.tb1.addAction(actionstop)\n actionstop.triggered.connect(self.KillProcess)\n self.tb1.addSeparator()\n actionExit = QAction(QIcon('./Compile/exit.png'), '退出', self)\n self.tb1.addAction(actionExit)\n actionExit.triggered.connect(qApp.quit)\n self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.contextMenu = QMenu(self)\n self.actionA = self.contextMenu.addAction('删除')\n self.actionA.triggered.connect(self.remove)\n self.includeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(1))\n self.excludeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(2))\n self.delPath1.clicked.connect(self.includeList.clear)\n self.delPath2.clicked.connect(self.excludeList.clear)\n self.addPath1.clicked.connect(lambda : self.ShowDialog(1))\n self.addPath2.clicked.connect(self.AddExpath)\n self.fileselect = fileselect.Ui_Dialog()\n self.listWidget.currentRowChanged.connect(self.display)\n self.initLibraryWindow()\n self.Llist.setSelectionMode(3)\n self.llist.setSelectionMode(3)\n self.barlabel = QLabel('barlabel')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n <function token>\n\n def EndResult(self):\n print(os.getcwd())\n f = open('./conerr.err', 'r')\n lines = f.readlines()\n j = 0\n for ii in lines:\n if 'error:' in ii:\n self.Result.append('<font color=\"#FF0000\">%s</font> ' % ii)\n j = 1\n if j != 1:\n self.Result.append('<font color=\"#FF0000\">finished!!!!!!!!</font> '\n )\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working = False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n <function token>\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n <function token>\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n <function token>\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n <function token>\n <function token>\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n <function token>\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n <function token>\n\n def AddLibraryPath(self):\n txt = self.LWUI.LibraryP.text()\n if txt:\n self.Llist.addItem(txt)\n self.LWin.close()\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n <function token>\n <function token>\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n\n def __init__(self):\n super(basePage, self).__init__()\n self.setupUi(self)\n self.startpath = os.getcwd()\n self.actionbuild.triggered.connect(self.checkFLAG)\n self.actionclean.triggered.connect(self.CleanProject)\n self.actionopen_project.triggered.connect(self.ChooseProDir)\n self.actionsave_project.triggered.connect(self.modifyFLAG)\n self.actionexit.triggered.connect(qApp.quit)\n self.tb1 = self.addToolBar('tool')\n actionopen1 = QAction(QIcon('./Compile/file.png'), '打开工程', self)\n self.tb1.addAction(actionopen1)\n actionopen1.triggered.connect(self.ChooseProDir)\n self.tb1.addSeparator()\n actionstop = QAction(QIcon('./Compile/stop.png'), '停止', self)\n self.tb1.addAction(actionstop)\n actionstop.triggered.connect(self.KillProcess)\n self.tb1.addSeparator()\n actionExit = QAction(QIcon('./Compile/exit.png'), '退出', self)\n self.tb1.addAction(actionExit)\n actionExit.triggered.connect(qApp.quit)\n self.includeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.excludeList.setContextMenuPolicy(Qt.CustomContextMenu)\n self.contextMenu = QMenu(self)\n self.actionA = self.contextMenu.addAction('删除')\n self.actionA.triggered.connect(self.remove)\n self.includeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(1))\n self.excludeList.customContextMenuRequested.connect(lambda : self.\n showContextMenu(2))\n self.delPath1.clicked.connect(self.includeList.clear)\n self.delPath2.clicked.connect(self.excludeList.clear)\n self.addPath1.clicked.connect(lambda : self.ShowDialog(1))\n self.addPath2.clicked.connect(self.AddExpath)\n self.fileselect = fileselect.Ui_Dialog()\n self.listWidget.currentRowChanged.connect(self.display)\n self.initLibraryWindow()\n self.Llist.setSelectionMode(3)\n self.llist.setSelectionMode(3)\n self.barlabel = QLabel('barlabel')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n <function token>\n\n def EndResult(self):\n print(os.getcwd())\n f = open('./conerr.err', 'r')\n lines = f.readlines()\n j = 0\n for ii in lines:\n if 'error:' in ii:\n self.Result.append('<font color=\"#FF0000\">%s</font> ' % ii)\n j = 1\n if j != 1:\n self.Result.append('<font color=\"#FF0000\">finished!!!!!!!!</font> '\n )\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working = False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n <function token>\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n <function token>\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n <function token>\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n <function token>\n <function token>\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n <function token>\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n <function token>\n <function token>\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n <function token>\n <function token>\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n <function token>\n\n def EndResult(self):\n print(os.getcwd())\n f = open('./conerr.err', 'r')\n lines = f.readlines()\n j = 0\n for ii in lines:\n if 'error:' in ii:\n self.Result.append('<font color=\"#FF0000\">%s</font> ' % ii)\n j = 1\n if j != 1:\n self.Result.append('<font color=\"#FF0000\">finished!!!!!!!!</font> '\n )\n self.barlabel.setText('已完成')\n f.close()\n os.remove('./conerr.err')\n self.backend.working = False\n self.statusBar.removeWidget(self.progressBar)\n self.barlabel.setText('准备中')\n os.chdir(self.ProjectName_2.text())\n <function token>\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n <function token>\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n <function token>\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n <function token>\n <function token>\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n <function token>\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n <function token>\n <function token>\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n <function token>\n <function token>\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n <function token>\n <function token>\n <function token>\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n <function token>\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n <function token>\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n <function token>\n <function token>\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n <function token>\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n\n def Cleartree(self):\n pathlist = self.fileselect.treeWidget.selectedItems()\n for pathss in pathlist:\n pathss.setSelected(False)\n self.di.close()\n <function token>\n <function token>\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n <function token>\n <function token>\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n <function token>\n <function token>\n <function token>\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n <function token>\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n\n def checkFLAG(self):\n CCFLAG1 = self.GCCFLAGName.toPlainText()\n LINKFLAG1 = self.LINKFLAGName.toPlainText()\n Hdir = self.HithTecDir.text()\n DebugName1 = self.ProjectName.text()\n inn = self.includeList.count()\n inpath = []\n exn = self.excludeList.count()\n expath = []\n for i in range(inn):\n inpath.append(self.includeList.item(i).text())\n for i in range(exn):\n expath.append(self.excludeList.item(i).text())\n self.modifyFLAG()\n \"\"\"for i in range(0,len(CCFALG)):\n if CCFALG1[i]!=CCFALG[i]:\n print(i)\"\"\"\n cmd = (self.startpath + '\\\\Compile\\\\python ' + self.startpath +\n '\\\\Compile/automake.py ' + self.startpath)\n a = subprocess.call(cmd)\n self.initBar()\n try:\n self.StartCompile(Hdir)\n except BaseException as e:\n print(333333)\n f = open('cons.log', 'w')\n f.write(e.args)\n f.close()\n <function token>\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n <function token>\n <function token>\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n <function token>\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n <function token>\n <function token>\n <function token>\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n <function token>\n <function token>\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n <function token>\n <function token>\n <function token>\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n <function token>\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n <function token>\n <function token>\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n <function token>\n <function token>\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n <function token>\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n <function token>\n <function token>\n <function token>\n\n def AddLibraries(self):\n txt = self.lWUI.libraries.text()\n if txt:\n self.llist.addItem(txt)\n self.lWin.close()\n <function token>\n <function token>\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n <function token>\n <function token>\n <function token>\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n <function token>\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n <function token>\n <function token>\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n <function token>\n <function token>\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n <function token>\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n\n def GetPath(self):\n if self.index == 3:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempinclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempinclude and tp != '':\n tempinclude.append(tp)\n pathss.setSelected(False)\n self.includeList.addItems(sorted(tempinclude))\n elif self.idPath == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append(tp)\n self.excludeList.addItems(sorted(tempexclude))\n elif self.index == 2:\n pathlist = self.fileselect.treeWidget.selectedItems()\n tempexclude = []\n for pathss in pathlist:\n tpathss = pathss\n tp = ''\n while 1:\n if tpathss.text(0) != self.DebugName:\n tp = tpathss.text(0) + tp\n if tpathss.parent():\n tpathss = tpathss.parent()\n tp = '/' + tp\n else:\n break\n if tp not in tempexclude and tp != '':\n tempexclude.append('{workspace}' + tp)\n pathss.setSelected(False)\n self.Llist.addItems(tempexclude)\n self.LWin.close()\n self.di.close()\n \"\"\"for selectedPath in pathlist:\n \n print(selectedPath.text(0))\n print(pathlist)\"\"\"\n \"\"\"while pathlist.value():\n if pathlist.value().checkState(0)==Qt.Checked:\n print(pathlist.value.text(0))\n break\"\"\"\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n <function token>\n <function token>\n <function token>\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n <function token>\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n <function token>\n <function token>\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n <function token>\n <function token>\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n <function token>\n\n def adds(self, paths, root):\n if os.path.isdir(paths):\n list = os.listdir(paths)\n for i in list:\n if ('Default' not in i and '.' not in i and '_pycache_' not in\n os.path.join(paths, i) and os.path.join(paths, i) in\n self.AllPath):\n if os.path.isdir(os.path.join(paths, i)):\n childs = QTreeWidgetItem(root)\n childs.setText(0, i)\n childs.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.path.join(paths, i), childs)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n <function token>\n <function token>\n <function token>\n\n def SetProgressBarVal(self, val):\n n = VAL + val\n self.progressBar.setValue(n)\n <function token>\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n <function token>\n <function token>\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n <function token>\n <function token>\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def PrintConsole(self, r):\n self.Result.append('<font color=\"#000000\">%s</font> ' % r)\n <function token>\n <function token>\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n <function token>\n <function token>\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n <function token>\n <function token>\n\n def delPath(self, id):\n if id == 1:\n self.includeList.clear()\n if id == 2:\n self.excludeList.clear()\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def initDialog(self):\n self.di = QDialog()\n fileselect1 = self.fileselect\n fileselect1.setupUi(self.di)\n child0 = QTreeWidgetItem(fileselect1.treeWidget)\n child0.setText(0, self.DebugName)\n child0.setIcon(0, QIcon('./Compile/01.png'))\n self.adds(os.getcwd(), child0)\n child1 = QTreeWidgetItem(child0)\n child1.setText(0, 'TOOLS')\n child1.setIcon(0, QIcon('./Compile/01.png'))\n fileselect1.treeWidget.expandAll()\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def CleanProject(self):\n print('Cleanning project...... ')\n if os.path.exists('./Default'):\n shutil.rmtree('./Default')\n if os.path.exists('./delivery'):\n shutil.rmtree('./delivery')\n QMessageBox.about(self, '消息', 'Clean has finished!')\n print('Clean has finished!')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def showContextMenu(self, id):\n items1 = self.includeList.selectedIndexes()\n items2 = self.excludeList.selectedIndexes()\n if items1 or items2:\n self.contextMenu.show()\n self.contextMenu.exec_(QCursor.pos())\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass basePage(QMainWindow, Ui_MainWindow):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<code token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n<code token>\n" ]
false
98,707
04f13e8b33acb098928e8d1ee19836185730a48c
from typing import List from lib.utils import hex_to_bin from lib.utils import hash_sha256 from lib.transaction import Transaction, genesis_transaction from dataclasses import dataclass @dataclass class Block: index: int bhash: str prev_bhash: str timestamp: int data: List[Transaction] difficulty: int nonce: int def valid(self, prev: 'Block') -> bool: """ Checks block's validity """ return self.prev_bhash == prev.bhash and validate_hash_difficulty( self.bhash, self.difficulty) and hash_block_content( self.index, self.prev_bhash, self.timestamp, self.data, self.difficulty, self.nonce) == self.bhash def hash_block_content(index: int, prev_bhash: str, timestamp: int, data: List[Transaction], difficulty: int, nonce: int): """ Hashes content of block. """ return hash_sha256([index, prev_bhash, timestamp, data, difficulty, nonce]) def validate_hash_difficulty(bhash: str, difficulty: int) -> bool: """ Checks if hash has expected difficulty. """ b = hex_to_bin(bhash) print(b[:4], type(b)) return hex_to_bin(bhash).startswith('0' * difficulty) def build_block(index: int, prev_bhash: str, timestamp: int, data: List[Transaction], difficulty: int): """ Mines single block. """ nonce: int = 0 print("hi") while True: bhash = hash_block_content(index, prev_bhash, timestamp, data, difficulty, nonce) if validate_hash_difficulty(bhash, difficulty): return Block(index, bhash, prev_bhash, timestamp, data, difficulty, nonce) nonce += 1 def verify_block_hash(block: Block): """ Verifies Block\'s Hash. """ return hash_block_content(block.index, block.prev_bhash, block.timestamp, block.data, block.difficulty, block.nonce) == block.bhash genesis_block = Block( 0, '7300c100475b78a3840eccd0b5cb6b187a38fde950a8555915a84697029b26a8', '', 1627141460, [genesis_transaction], 0, 0)
[ "from typing import List\nfrom lib.utils import hex_to_bin\nfrom lib.utils import hash_sha256\nfrom lib.transaction import Transaction, genesis_transaction\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Block:\n index: int\n bhash: str\n prev_bhash: str\n timestamp: int\n data: List[Transaction]\n difficulty: int\n nonce: int\n\n def valid(self, prev: 'Block') -> bool:\n \"\"\" Checks block's validity \"\"\"\n return self.prev_bhash == prev.bhash and validate_hash_difficulty(\n self.bhash, self.difficulty) and hash_block_content(\n self.index, self.prev_bhash, self.timestamp, self.data,\n self.difficulty, self.nonce) == self.bhash\n\n\ndef hash_block_content(index: int, prev_bhash: str, timestamp: int,\n data: List[Transaction], difficulty: int, nonce: int):\n \"\"\" Hashes content of block. \"\"\"\n return hash_sha256([index, prev_bhash, timestamp, data, difficulty, nonce])\n\n\ndef validate_hash_difficulty(bhash: str, difficulty: int) -> bool:\n \"\"\" Checks if hash has expected difficulty. \"\"\"\n b = hex_to_bin(bhash)\n print(b[:4], type(b))\n return hex_to_bin(bhash).startswith('0' * difficulty)\n\n\ndef build_block(index: int, prev_bhash: str, timestamp: int,\n data: List[Transaction], difficulty: int):\n \"\"\" Mines single block. \"\"\"\n nonce: int = 0\n print(\"hi\")\n while True:\n bhash = hash_block_content(index, prev_bhash, timestamp, data,\n difficulty, nonce)\n if validate_hash_difficulty(bhash, difficulty):\n return Block(index, bhash, prev_bhash, timestamp, data, difficulty,\n nonce)\n nonce += 1\n\n\ndef verify_block_hash(block: Block):\n \"\"\" Verifies Block\\'s Hash. \"\"\"\n return hash_block_content(block.index, block.prev_bhash, block.timestamp,\n block.data, block.difficulty,\n block.nonce) == block.bhash\n\n\ngenesis_block = Block(\n 0, '7300c100475b78a3840eccd0b5cb6b187a38fde950a8555915a84697029b26a8', '',\n 1627141460, [genesis_transaction], 0, 0)\n", "from typing import List\nfrom lib.utils import hex_to_bin\nfrom lib.utils import hash_sha256\nfrom lib.transaction import Transaction, genesis_transaction\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Block:\n index: int\n bhash: str\n prev_bhash: str\n timestamp: int\n data: List[Transaction]\n difficulty: int\n nonce: int\n\n def valid(self, prev: 'Block') ->bool:\n \"\"\" Checks block's validity \"\"\"\n return self.prev_bhash == prev.bhash and validate_hash_difficulty(self\n .bhash, self.difficulty) and hash_block_content(self.index,\n self.prev_bhash, self.timestamp, self.data, self.difficulty,\n self.nonce) == self.bhash\n\n\ndef hash_block_content(index: int, prev_bhash: str, timestamp: int, data:\n List[Transaction], difficulty: int, nonce: int):\n \"\"\" Hashes content of block. \"\"\"\n return hash_sha256([index, prev_bhash, timestamp, data, difficulty, nonce])\n\n\ndef validate_hash_difficulty(bhash: str, difficulty: int) ->bool:\n \"\"\" Checks if hash has expected difficulty. \"\"\"\n b = hex_to_bin(bhash)\n print(b[:4], type(b))\n return hex_to_bin(bhash).startswith('0' * difficulty)\n\n\ndef build_block(index: int, prev_bhash: str, timestamp: int, data: List[\n Transaction], difficulty: int):\n \"\"\" Mines single block. \"\"\"\n nonce: int = 0\n print('hi')\n while True:\n bhash = hash_block_content(index, prev_bhash, timestamp, data,\n difficulty, nonce)\n if validate_hash_difficulty(bhash, difficulty):\n return Block(index, bhash, prev_bhash, timestamp, data,\n difficulty, nonce)\n nonce += 1\n\n\ndef verify_block_hash(block: Block):\n \"\"\" Verifies Block's Hash. \"\"\"\n return hash_block_content(block.index, block.prev_bhash, block.\n timestamp, block.data, block.difficulty, block.nonce) == block.bhash\n\n\ngenesis_block = Block(0,\n '7300c100475b78a3840eccd0b5cb6b187a38fde950a8555915a84697029b26a8', '',\n 1627141460, [genesis_transaction], 0, 0)\n", "<import token>\n\n\n@dataclass\nclass Block:\n index: int\n bhash: str\n prev_bhash: str\n timestamp: int\n data: List[Transaction]\n difficulty: int\n nonce: int\n\n def valid(self, prev: 'Block') ->bool:\n \"\"\" Checks block's validity \"\"\"\n return self.prev_bhash == prev.bhash and validate_hash_difficulty(self\n .bhash, self.difficulty) and hash_block_content(self.index,\n self.prev_bhash, self.timestamp, self.data, self.difficulty,\n self.nonce) == self.bhash\n\n\ndef hash_block_content(index: int, prev_bhash: str, timestamp: int, data:\n List[Transaction], difficulty: int, nonce: int):\n \"\"\" Hashes content of block. \"\"\"\n return hash_sha256([index, prev_bhash, timestamp, data, difficulty, nonce])\n\n\ndef validate_hash_difficulty(bhash: str, difficulty: int) ->bool:\n \"\"\" Checks if hash has expected difficulty. \"\"\"\n b = hex_to_bin(bhash)\n print(b[:4], type(b))\n return hex_to_bin(bhash).startswith('0' * difficulty)\n\n\ndef build_block(index: int, prev_bhash: str, timestamp: int, data: List[\n Transaction], difficulty: int):\n \"\"\" Mines single block. \"\"\"\n nonce: int = 0\n print('hi')\n while True:\n bhash = hash_block_content(index, prev_bhash, timestamp, data,\n difficulty, nonce)\n if validate_hash_difficulty(bhash, difficulty):\n return Block(index, bhash, prev_bhash, timestamp, data,\n difficulty, nonce)\n nonce += 1\n\n\ndef verify_block_hash(block: Block):\n \"\"\" Verifies Block's Hash. \"\"\"\n return hash_block_content(block.index, block.prev_bhash, block.\n timestamp, block.data, block.difficulty, block.nonce) == block.bhash\n\n\ngenesis_block = Block(0,\n '7300c100475b78a3840eccd0b5cb6b187a38fde950a8555915a84697029b26a8', '',\n 1627141460, [genesis_transaction], 0, 0)\n", "<import token>\n\n\n@dataclass\nclass Block:\n index: int\n bhash: str\n prev_bhash: str\n timestamp: int\n data: List[Transaction]\n difficulty: int\n nonce: int\n\n def valid(self, prev: 'Block') ->bool:\n \"\"\" Checks block's validity \"\"\"\n return self.prev_bhash == prev.bhash and validate_hash_difficulty(self\n .bhash, self.difficulty) and hash_block_content(self.index,\n self.prev_bhash, self.timestamp, self.data, self.difficulty,\n self.nonce) == self.bhash\n\n\ndef hash_block_content(index: int, prev_bhash: str, timestamp: int, data:\n List[Transaction], difficulty: int, nonce: int):\n \"\"\" Hashes content of block. \"\"\"\n return hash_sha256([index, prev_bhash, timestamp, data, difficulty, nonce])\n\n\ndef validate_hash_difficulty(bhash: str, difficulty: int) ->bool:\n \"\"\" Checks if hash has expected difficulty. \"\"\"\n b = hex_to_bin(bhash)\n print(b[:4], type(b))\n return hex_to_bin(bhash).startswith('0' * difficulty)\n\n\ndef build_block(index: int, prev_bhash: str, timestamp: int, data: List[\n Transaction], difficulty: int):\n \"\"\" Mines single block. \"\"\"\n nonce: int = 0\n print('hi')\n while True:\n bhash = hash_block_content(index, prev_bhash, timestamp, data,\n difficulty, nonce)\n if validate_hash_difficulty(bhash, difficulty):\n return Block(index, bhash, prev_bhash, timestamp, data,\n difficulty, nonce)\n nonce += 1\n\n\ndef verify_block_hash(block: Block):\n \"\"\" Verifies Block's Hash. \"\"\"\n return hash_block_content(block.index, block.prev_bhash, block.\n timestamp, block.data, block.difficulty, block.nonce) == block.bhash\n\n\n<assignment token>\n", "<import token>\n\n\n@dataclass\nclass Block:\n index: int\n bhash: str\n prev_bhash: str\n timestamp: int\n data: List[Transaction]\n difficulty: int\n nonce: int\n\n def valid(self, prev: 'Block') ->bool:\n \"\"\" Checks block's validity \"\"\"\n return self.prev_bhash == prev.bhash and validate_hash_difficulty(self\n .bhash, self.difficulty) and hash_block_content(self.index,\n self.prev_bhash, self.timestamp, self.data, self.difficulty,\n self.nonce) == self.bhash\n\n\n<function token>\n\n\ndef validate_hash_difficulty(bhash: str, difficulty: int) ->bool:\n \"\"\" Checks if hash has expected difficulty. \"\"\"\n b = hex_to_bin(bhash)\n print(b[:4], type(b))\n return hex_to_bin(bhash).startswith('0' * difficulty)\n\n\ndef build_block(index: int, prev_bhash: str, timestamp: int, data: List[\n Transaction], difficulty: int):\n \"\"\" Mines single block. \"\"\"\n nonce: int = 0\n print('hi')\n while True:\n bhash = hash_block_content(index, prev_bhash, timestamp, data,\n difficulty, nonce)\n if validate_hash_difficulty(bhash, difficulty):\n return Block(index, bhash, prev_bhash, timestamp, data,\n difficulty, nonce)\n nonce += 1\n\n\ndef verify_block_hash(block: Block):\n \"\"\" Verifies Block's Hash. \"\"\"\n return hash_block_content(block.index, block.prev_bhash, block.\n timestamp, block.data, block.difficulty, block.nonce) == block.bhash\n\n\n<assignment token>\n", "<import token>\n\n\n@dataclass\nclass Block:\n index: int\n bhash: str\n prev_bhash: str\n timestamp: int\n data: List[Transaction]\n difficulty: int\n nonce: int\n\n def valid(self, prev: 'Block') ->bool:\n \"\"\" Checks block's validity \"\"\"\n return self.prev_bhash == prev.bhash and validate_hash_difficulty(self\n .bhash, self.difficulty) and hash_block_content(self.index,\n self.prev_bhash, self.timestamp, self.data, self.difficulty,\n self.nonce) == self.bhash\n\n\n<function token>\n\n\ndef validate_hash_difficulty(bhash: str, difficulty: int) ->bool:\n \"\"\" Checks if hash has expected difficulty. \"\"\"\n b = hex_to_bin(bhash)\n print(b[:4], type(b))\n return hex_to_bin(bhash).startswith('0' * difficulty)\n\n\ndef build_block(index: int, prev_bhash: str, timestamp: int, data: List[\n Transaction], difficulty: int):\n \"\"\" Mines single block. \"\"\"\n nonce: int = 0\n print('hi')\n while True:\n bhash = hash_block_content(index, prev_bhash, timestamp, data,\n difficulty, nonce)\n if validate_hash_difficulty(bhash, difficulty):\n return Block(index, bhash, prev_bhash, timestamp, data,\n difficulty, nonce)\n nonce += 1\n\n\n<function token>\n<assignment token>\n", "<import token>\n\n\n@dataclass\nclass Block:\n index: int\n bhash: str\n prev_bhash: str\n timestamp: int\n data: List[Transaction]\n difficulty: int\n nonce: int\n\n def valid(self, prev: 'Block') ->bool:\n \"\"\" Checks block's validity \"\"\"\n return self.prev_bhash == prev.bhash and validate_hash_difficulty(self\n .bhash, self.difficulty) and hash_block_content(self.index,\n self.prev_bhash, self.timestamp, self.data, self.difficulty,\n self.nonce) == self.bhash\n\n\n<function token>\n\n\ndef validate_hash_difficulty(bhash: str, difficulty: int) ->bool:\n \"\"\" Checks if hash has expected difficulty. \"\"\"\n b = hex_to_bin(bhash)\n print(b[:4], type(b))\n return hex_to_bin(bhash).startswith('0' * difficulty)\n\n\n<function token>\n<function token>\n<assignment token>\n", "<import token>\n\n\n@dataclass\nclass Block:\n index: int\n bhash: str\n prev_bhash: str\n timestamp: int\n data: List[Transaction]\n difficulty: int\n nonce: int\n\n def valid(self, prev: 'Block') ->bool:\n \"\"\" Checks block's validity \"\"\"\n return self.prev_bhash == prev.bhash and validate_hash_difficulty(self\n .bhash, self.difficulty) and hash_block_content(self.index,\n self.prev_bhash, self.timestamp, self.data, self.difficulty,\n self.nonce) == self.bhash\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<assignment token>\n", "<import token>\n\n\n@dataclass\nclass Block:\n index: int\n bhash: str\n prev_bhash: str\n timestamp: int\n data: List[Transaction]\n difficulty: int\n nonce: int\n <function token>\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<assignment token>\n", "<import token>\n<class token>\n<function token>\n<function token>\n<function token>\n<function token>\n<assignment token>\n" ]
false
98,708
6c7d423709b64154473f24f9cb65a987877d64cc
from bottle import * @route("/formy") @post("/formy") @view("fm", data = "") def formy(): if request.POST.get("submit"): val = request.POST.get("val") return dict(data = val) return dict() @route("/names-ages") @view("external", ttl = "Names & Ages") def names_ages(): na = [('Lisa', 30), ("John", 21), ("Wanda", None)] return dict(na_list = na) ## return template("external", name = name) @route("/<uid:re:\d{2}>/<name>") def info(uid, name): return template("hello {{uid}}, {{name}}", uid = uid, name = name) @route("/") def hello(): return "<h1>hello</h1> there!" debug(True) ## by default, host = localhost, port = 8080 ## like to input it anyways because it blocks ## auto-incrementing. run(reloader=True, host="localhost", port=8080)
[ "from bottle import *\n\n@route(\"/formy\")\n@post(\"/formy\")\n@view(\"fm\", data = \"\")\ndef formy():\n if request.POST.get(\"submit\"):\n val = request.POST.get(\"val\")\n return dict(data = val)\n return dict()\n\n@route(\"/names-ages\")\n@view(\"external\", ttl = \"Names & Ages\")\ndef names_ages():\n na = [('Lisa', 30), (\"John\", 21), (\"Wanda\", None)]\n return dict(na_list = na)\n\n## return template(\"external\", name = name)\n\n@route(\"/<uid:re:\\d{2}>/<name>\")\ndef info(uid, name):\n return template(\"hello {{uid}}, {{name}}\", uid = uid, name = name)\n\n@route(\"/\")\ndef hello():\n return \"<h1>hello</h1> there!\"\n\ndebug(True)\n## by default, host = localhost, port = 8080\n## like to input it anyways because it blocks\n## auto-incrementing.\nrun(reloader=True, host=\"localhost\", port=8080)\n", "from bottle import *\n\n\n@route('/formy')\n@post('/formy')\n@view('fm', data='')\ndef formy():\n if request.POST.get('submit'):\n val = request.POST.get('val')\n return dict(data=val)\n return dict()\n\n\n@route('/names-ages')\n@view('external', ttl='Names & Ages')\ndef names_ages():\n na = [('Lisa', 30), ('John', 21), ('Wanda', None)]\n return dict(na_list=na)\n\n\n@route('/<uid:re:\\\\d{2}>/<name>')\ndef info(uid, name):\n return template('hello {{uid}}, {{name}}', uid=uid, name=name)\n\n\n@route('/')\ndef hello():\n return '<h1>hello</h1> there!'\n\n\ndebug(True)\nrun(reloader=True, host='localhost', port=8080)\n", "<import token>\n\n\n@route('/formy')\n@post('/formy')\n@view('fm', data='')\ndef formy():\n if request.POST.get('submit'):\n val = request.POST.get('val')\n return dict(data=val)\n return dict()\n\n\n@route('/names-ages')\n@view('external', ttl='Names & Ages')\ndef names_ages():\n na = [('Lisa', 30), ('John', 21), ('Wanda', None)]\n return dict(na_list=na)\n\n\n@route('/<uid:re:\\\\d{2}>/<name>')\ndef info(uid, name):\n return template('hello {{uid}}, {{name}}', uid=uid, name=name)\n\n\n@route('/')\ndef hello():\n return '<h1>hello</h1> there!'\n\n\ndebug(True)\nrun(reloader=True, host='localhost', port=8080)\n", "<import token>\n\n\n@route('/formy')\n@post('/formy')\n@view('fm', data='')\ndef formy():\n if request.POST.get('submit'):\n val = request.POST.get('val')\n return dict(data=val)\n return dict()\n\n\n@route('/names-ages')\n@view('external', ttl='Names & Ages')\ndef names_ages():\n na = [('Lisa', 30), ('John', 21), ('Wanda', None)]\n return dict(na_list=na)\n\n\n@route('/<uid:re:\\\\d{2}>/<name>')\ndef info(uid, name):\n return template('hello {{uid}}, {{name}}', uid=uid, name=name)\n\n\n@route('/')\ndef hello():\n return '<h1>hello</h1> there!'\n\n\n<code token>\n", "<import token>\n\n\n@route('/formy')\n@post('/formy')\n@view('fm', data='')\ndef formy():\n if request.POST.get('submit'):\n val = request.POST.get('val')\n return dict(data=val)\n return dict()\n\n\n@route('/names-ages')\n@view('external', ttl='Names & Ages')\ndef names_ages():\n na = [('Lisa', 30), ('John', 21), ('Wanda', None)]\n return dict(na_list=na)\n\n\n<function token>\n\n\n@route('/')\ndef hello():\n return '<h1>hello</h1> there!'\n\n\n<code token>\n", "<import token>\n\n\n@route('/formy')\n@post('/formy')\n@view('fm', data='')\ndef formy():\n if request.POST.get('submit'):\n val = request.POST.get('val')\n return dict(data=val)\n return dict()\n\n\n<function token>\n<function token>\n\n\n@route('/')\ndef hello():\n return '<h1>hello</h1> there!'\n\n\n<code token>\n", "<import token>\n\n\n@route('/formy')\n@post('/formy')\n@view('fm', data='')\ndef formy():\n if request.POST.get('submit'):\n val = request.POST.get('val')\n return dict(data=val)\n return dict()\n\n\n<function token>\n<function token>\n<function token>\n<code token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n" ]
false
98,709
492f2f07da59d820f790c745eb222619654400a9
from urllib.request import urlopen import urllib.parse, urllib.error import xml.etree.ElementTree as ET import ssl # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE url = input('Enter Location ') uh = urlopen(url, context=ctx) data=uh.read() print('Retrieved', len(data), 'characters') data.decode() tree=ET.fromstring(data) ###REPLACE CODE BELOW WITH DESIRED CODEBLOCK### comments=tree.findall('comments/comment') print('count:', len(comments)) sum=0 for comment in comments: sum=sum+int(comment.find('count').text) print(sum)
[ "from urllib.request import urlopen\nimport urllib.parse, urllib.error\nimport xml.etree.ElementTree as ET\nimport ssl\n\n# Ignore SSL certificate errors\nctx = ssl.create_default_context()\nctx.check_hostname = False\nctx.verify_mode = ssl.CERT_NONE\n\nurl = input('Enter Location ')\nuh = urlopen(url, context=ctx)\ndata=uh.read()\n\nprint('Retrieved', len(data), 'characters')\n\ndata.decode()\ntree=ET.fromstring(data)\n\n###REPLACE CODE BELOW WITH DESIRED CODEBLOCK###\n\ncomments=tree.findall('comments/comment')\nprint('count:', len(comments))\n\nsum=0\n\nfor comment in comments:\n sum=sum+int(comment.find('count').text)\n\nprint(sum)", "from urllib.request import urlopen\nimport urllib.parse, urllib.error\nimport xml.etree.ElementTree as ET\nimport ssl\nctx = ssl.create_default_context()\nctx.check_hostname = False\nctx.verify_mode = ssl.CERT_NONE\nurl = input('Enter Location ')\nuh = urlopen(url, context=ctx)\ndata = uh.read()\nprint('Retrieved', len(data), 'characters')\ndata.decode()\ntree = ET.fromstring(data)\ncomments = tree.findall('comments/comment')\nprint('count:', len(comments))\nsum = 0\nfor comment in comments:\n sum = sum + int(comment.find('count').text)\nprint(sum)\n", "<import token>\nctx = ssl.create_default_context()\nctx.check_hostname = False\nctx.verify_mode = ssl.CERT_NONE\nurl = input('Enter Location ')\nuh = urlopen(url, context=ctx)\ndata = uh.read()\nprint('Retrieved', len(data), 'characters')\ndata.decode()\ntree = ET.fromstring(data)\ncomments = tree.findall('comments/comment')\nprint('count:', len(comments))\nsum = 0\nfor comment in comments:\n sum = sum + int(comment.find('count').text)\nprint(sum)\n", "<import token>\n<assignment token>\nprint('Retrieved', len(data), 'characters')\ndata.decode()\n<assignment token>\nprint('count:', len(comments))\n<assignment token>\nfor comment in comments:\n sum = sum + int(comment.find('count').text)\nprint(sum)\n", "<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
98,710
c8962372ade639d6c3ffd1e83c14bcae05c60aef
from datetime import datetime as d from datetime import timedelta import re records = re.sub(r"^\s|\s$", "", open("day4.txt").read()).split("\n") shiftTimes = { d.strptime(re.sub(r"(^\s)|\[|(\].+)|(\s$)", "", rec), "%Y-%m-%d %H:%M"): int(re.sub(r"\[.+\]|\D", "", rec)) for rec in records if "Guard" in rec } actionTimes = { d.strptime(re.sub(r"(^\s)|\[|(\].+)|(\s$)", "", rec), "%Y-%m-%d %H:%M"): re.sub(r"(\[[^a-z]+)|(\]\s+)", "", rec) for rec in records if "Guard" not in rec } guardSleep = {} guardMinutes = {} guardInd = 0 topGuard = 0 sortedShifts = shiftTimes.keys() sortedShifts.sort() sortedActions = actionTimes.keys() sortedActions.sort() for timeInd in range(0, len(sortedActions), 2): while guardInd < len(sortedShifts) - 1\ and sortedActions[timeInd] >= sortedShifts[guardInd + 1]: guardInd += 1 guard = shiftTimes[sortedShifts[guardInd]] if guard not in guardMinutes: guardMinutes[guard] = {} if guard not in guardSleep: guardSleep[guard] = 0 for minute in range(sortedActions[timeInd].minute, sortedActions[timeInd + 1].minute + 1): if minute not in guardMinutes[guard]: guardMinutes[guard][minute] = 0 guardMinutes[guard][minute] += 1 guardSleep[guard] += 1 if topGuard in guardSleep and guardSleep[guard] < guardSleep[topGuard]: continue topGuard = guard topMinute = 0 for minute in range(0, 59): if minute in guardMinutes[topGuard] and guardMinutes[topGuard][ minute] > guardMinutes[topGuard][topMinute]: topMinute = minute print "Guard " + str(topGuard) + " slept " + str( guardSleep[topGuard]) + " minutes and was asleep during minute " + str( topMinute) + " the most (" + str( guardMinutes[topGuard][topMinute]) + " days)"
[ "from datetime import datetime as d\nfrom datetime import timedelta\nimport re\n\nrecords = re.sub(r\"^\\s|\\s$\", \"\", open(\"day4.txt\").read()).split(\"\\n\")\nshiftTimes = {\n d.strptime(re.sub(r\"(^\\s)|\\[|(\\].+)|(\\s$)\", \"\", rec), \"%Y-%m-%d %H:%M\"):\n int(re.sub(r\"\\[.+\\]|\\D\", \"\", rec))\n for rec in records if \"Guard\" in rec\n}\nactionTimes = {\n d.strptime(re.sub(r\"(^\\s)|\\[|(\\].+)|(\\s$)\", \"\", rec), \"%Y-%m-%d %H:%M\"):\n re.sub(r\"(\\[[^a-z]+)|(\\]\\s+)\", \"\", rec)\n for rec in records if \"Guard\" not in rec\n}\n\nguardSleep = {}\nguardMinutes = {}\nguardInd = 0\ntopGuard = 0\nsortedShifts = shiftTimes.keys()\nsortedShifts.sort()\nsortedActions = actionTimes.keys()\nsortedActions.sort()\n\nfor timeInd in range(0, len(sortedActions), 2):\n while guardInd < len(sortedShifts) - 1\\\n and sortedActions[timeInd] >= sortedShifts[guardInd + 1]:\n guardInd += 1\n\n guard = shiftTimes[sortedShifts[guardInd]]\n\n if guard not in guardMinutes:\n guardMinutes[guard] = {}\n\n if guard not in guardSleep:\n guardSleep[guard] = 0\n\n for minute in range(sortedActions[timeInd].minute,\n sortedActions[timeInd + 1].minute + 1):\n if minute not in guardMinutes[guard]:\n guardMinutes[guard][minute] = 0\n\n guardMinutes[guard][minute] += 1\n guardSleep[guard] += 1\n\n if topGuard in guardSleep and guardSleep[guard] < guardSleep[topGuard]:\n continue\n\n topGuard = guard\n\ntopMinute = 0\nfor minute in range(0, 59):\n if minute in guardMinutes[topGuard] and guardMinutes[topGuard][\n minute] > guardMinutes[topGuard][topMinute]:\n topMinute = minute\n\nprint \"Guard \" + str(topGuard) + \" slept \" + str(\n guardSleep[topGuard]) + \" minutes and was asleep during minute \" + str(\n topMinute) + \" the most (\" + str(\n guardMinutes[topGuard][topMinute]) + \" days)\"\n" ]
true
98,711
cd2b4402b53c37b934c19abe46ee69a7ac4bc9d3
grade = {"A": 5, "B": 5, "C": 4, "D": 3, "E": 3, "FX": 2, "F": 1} def formatted_grades(students): count = 0 new_list = [] for i, j in students.items(): for x, z in grade.items(): if j == x: count += 1 spisok = '{:>4}|{:<10}|{:^5}|{:^5}'.format (count, i, x, z) new_list.append(spisok) return new_list students = {"Nick": "A", "Olga": "B", "Mike": "FX", "Anna": "C"} print(formatted_grades(students))
[ "grade = {\"A\": 5, \"B\": 5, \"C\": 4, \"D\": 3, \"E\": 3, \"FX\": 2, \"F\": 1}\r\n\r\ndef formatted_grades(students):\r\n count = 0\r\n new_list = []\r\n for i, j in students.items():\r\n for x, z in grade.items():\r\n if j == x:\r\n count += 1\r\n spisok = '{:>4}|{:<10}|{:^5}|{:^5}'.format (count, i, x, z)\r\n new_list.append(spisok)\r\n return new_list\r\n \r\nstudents = {\"Nick\": \"A\", \"Olga\": \"B\", \"Mike\": \"FX\", \"Anna\": \"C\"}\r\n\r\nprint(formatted_grades(students))\r\n", "grade = {'A': 5, 'B': 5, 'C': 4, 'D': 3, 'E': 3, 'FX': 2, 'F': 1}\n\n\ndef formatted_grades(students):\n count = 0\n new_list = []\n for i, j in students.items():\n for x, z in grade.items():\n if j == x:\n count += 1\n spisok = '{:>4}|{:<10}|{:^5}|{:^5}'.format(count, i, x, z)\n new_list.append(spisok)\n return new_list\n\n\nstudents = {'Nick': 'A', 'Olga': 'B', 'Mike': 'FX', 'Anna': 'C'}\nprint(formatted_grades(students))\n", "<assignment token>\n\n\ndef formatted_grades(students):\n count = 0\n new_list = []\n for i, j in students.items():\n for x, z in grade.items():\n if j == x:\n count += 1\n spisok = '{:>4}|{:<10}|{:^5}|{:^5}'.format(count, i, x, z)\n new_list.append(spisok)\n return new_list\n\n\n<assignment token>\nprint(formatted_grades(students))\n", "<assignment token>\n\n\ndef formatted_grades(students):\n count = 0\n new_list = []\n for i, j in students.items():\n for x, z in grade.items():\n if j == x:\n count += 1\n spisok = '{:>4}|{:<10}|{:^5}|{:^5}'.format(count, i, x, z)\n new_list.append(spisok)\n return new_list\n\n\n<assignment token>\n<code token>\n", "<assignment token>\n<function token>\n<assignment token>\n<code token>\n" ]
false
98,712
9e630a87c27a0300a0fbfbc9c53e69fdd8eca9f9
#encoding:utf-8 import sys sys.path.insert(0, "/home/liuhongyu/intelligent") sys.path.insert(1, "/home/liuhongyu/anaconda2/lib/python2.7/site-packages") from intelligent.platform.predict.predict_server import PredictServer #PredictServer().predict( # projectname = '美赞臣基础预测服务', # brands = '夕阳#移动', # input = 'test.dat.xlsx', # output = 'out.xlsx' #) PredictServer().predict( projectname = '通信行业识别(仅有策略)', input = 'yidong8-14.xlsx', output = 'out1.xlsx' ) print PredictServer().getServers()
[ "#encoding:utf-8\nimport sys\nsys.path.insert(0, \"/home/liuhongyu/intelligent\")\nsys.path.insert(1, \"/home/liuhongyu/anaconda2/lib/python2.7/site-packages\")\nfrom intelligent.platform.predict.predict_server import PredictServer\n\n#PredictServer().predict(\n# projectname = '美赞臣基础预测服务', \n# brands = '夕阳#移动',\n# input = 'test.dat.xlsx', \n# output = 'out.xlsx'\n#)\n\nPredictServer().predict(\n projectname = '通信行业识别(仅有策略)', \n input = 'yidong8-14.xlsx',\n output = 'out1.xlsx'\n)\n\nprint PredictServer().getServers()\n" ]
true
98,713
555c13b358722a1a3563a72f07eb2e93348754ed
#!/usr/bin/python # This is server.py file import socket # Import socket module import threading # Import threads import Queue # Queue to pass data safely between threads class RobotNetworkService(threading.Thread): _recvQueue = 0 _sendQueue = 0 def __init__(self, recv_queue, send_queue): super(RobotNetworkService, self).__init__() self._recvQueue = recv_queue self._sendQueue = send_queue self.alive = threading.Event() self.alive.set() # Routine for handling messages from the client. def receive_thread(self, conn): print 'Receive thread started' rec_msg = "" # Client disconnect is handled here, not sure how I feel about it. while (self.alive.isSet() and rec_msg.lower() != "disconnect" and rec_msg.lower() != "quit"): # TODO: Add a timeout! rec_msg = conn.recv(1024) # recv returns an empty string when the client disconnects if rec_msg: print 'Server received: ' + rec_msg self._recvQueue.put(rec_msg) else: # Client is gone print 'Client disconnected, exiting receive_thread' self._recvQueue.put("Client disconnected: broken pipe") return # Client responsibly told us it was disconnecting if (rec_msg.lower() == "quit"): print 'Client issued quit, exiting receive_thread' elif (rec_msg.lower() == "disconnect"): print 'Client issued disconnect, exiting receive_thread' else: print 'Exiting receive_thread on join request' # Routine for accepting a connection and starting the server. def send_thread(self): print 'Send thread started' s = socket.socket() # Create a socket object s.settimeout(1) # Default timeout of 1 second # Commenting out the next line to remove restrictions on who can connect. #host = socket.gethostname() # Get local machine name port = 12345 # Reserve a port for your service. try: #s.bind((host, port)) # Bind to the port s.bind(('', port)) # Bind to the port s.listen(1) # Now wait for client connection. except socket.error as msg: s.close() print 'Server socket error, exiting' return while (self.alive.isSet()): # Holds message received from the remote msg = "" print 'Server is waiting for connection!' # Try making a connection. If we timeout waiting check the # while loop exit condition and keep trying. # A timeout here prevents the server thread from blocking # even when the program is trying to exit. try: c, addr = s.accept() # Establish connection with client. except socket.timeout as msg: print 'Server timeout on listen' continue print 'Server received connection from', addr c.send('Robot server ready! Starting receive thread') # Kick off the thread that will receive messages from the client. receiveThread = threading.Thread(target = self.receive_thread, args = [c]) receiveThread.start() # This loop will check for messages to transmit and send them. # If the connection is lost, we are told to stop, or the receive # thread quits, then break out of the loop. # TODO: 'c' check may not be useful here while (c and self.alive.isSet() and receiveThread.isAlive()): # See if there are messages on the queue, block for a while # and bail out if nothing is received. This allows us to check # the stop condition on occasion. try: msg = self._sendQueue.get(True, 1) except Queue.Empty: # Not a bad thing, just need to check the exit conditions. pass else: c.send(msg) if (receiveThread.isAlive() == False): print 'Server disconnected on receive thread death' elif (self.alive.isSet() == False): print 'Server exiting on join request' elif (not c): print 'Server disconnected on broken pipe' # Left the loop c.close() # Close the connection receiveThread.join() # Received a quit print 'Server closed (Asked to quit)' def run(self): self.send_thread() def join(self, timeout = None): self.alive.clear() threading.Thread.join(self, timeout)
[ "#!/usr/bin/python # This is server.py file\n\nimport socket # Import socket module\nimport threading # Import threads\nimport Queue # Queue to pass data safely between threads\n\nclass RobotNetworkService(threading.Thread):\n _recvQueue = 0\n _sendQueue = 0\n\n def __init__(self, recv_queue, send_queue):\n super(RobotNetworkService, self).__init__()\n self._recvQueue = recv_queue\n self._sendQueue = send_queue\n self.alive = threading.Event()\n self.alive.set()\n \n # Routine for handling messages from the client.\n def receive_thread(self, conn):\n print 'Receive thread started'\n rec_msg = \"\"\n\n # Client disconnect is handled here, not sure how I feel about it.\n while (self.alive.isSet() and rec_msg.lower() != \"disconnect\" and rec_msg.lower() != \"quit\"):\n # TODO: Add a timeout! \n rec_msg = conn.recv(1024)\n\n # recv returns an empty string when the client disconnects\n if rec_msg:\n print 'Server received: ' + rec_msg\n self._recvQueue.put(rec_msg)\n else:\n # Client is gone\n print 'Client disconnected, exiting receive_thread'\n self._recvQueue.put(\"Client disconnected: broken pipe\")\n return\n\n # Client responsibly told us it was disconnecting\n if (rec_msg.lower() == \"quit\"):\n print 'Client issued quit, exiting receive_thread'\n elif (rec_msg.lower() == \"disconnect\"):\n print 'Client issued disconnect, exiting receive_thread'\n else:\n print 'Exiting receive_thread on join request'\n\n # Routine for accepting a connection and starting the server.\n def send_thread(self):\n print 'Send thread started'\n\n s = socket.socket() # Create a socket object\n s.settimeout(1) # Default timeout of 1 second\n # Commenting out the next line to remove restrictions on who can connect.\n #host = socket.gethostname() # Get local machine name\n port = 12345 # Reserve a port for your service.\n try:\n #s.bind((host, port)) # Bind to the port\n s.bind(('', port)) # Bind to the port\n s.listen(1) # Now wait for client connection.\n except socket.error as msg:\n s.close()\n print 'Server socket error, exiting'\n return\n\n while (self.alive.isSet()):\n \n # Holds message received from the remote\n msg = \"\"\n\n print 'Server is waiting for connection!'\n\n # Try making a connection. If we timeout waiting check the\n # while loop exit condition and keep trying.\n # A timeout here prevents the server thread from blocking\n # even when the program is trying to exit.\n try:\n c, addr = s.accept() # Establish connection with client.\n except socket.timeout as msg:\n print 'Server timeout on listen'\n continue\n\n print 'Server received connection from', addr\n c.send('Robot server ready! Starting receive thread')\n\n # Kick off the thread that will receive messages from the client.\n receiveThread = threading.Thread(target = self.receive_thread, args = [c])\n receiveThread.start()\n\n # This loop will check for messages to transmit and send them.\n # If the connection is lost, we are told to stop, or the receive\n # thread quits, then break out of the loop.\n # TODO: 'c' check may not be useful here\n while (c and self.alive.isSet() and receiveThread.isAlive()):\n # See if there are messages on the queue, block for a while\n # and bail out if nothing is received. This allows us to check\n # the stop condition on occasion.\n try:\n msg = self._sendQueue.get(True, 1)\n except Queue.Empty:\n # Not a bad thing, just need to check the exit conditions.\n pass\n else:\n c.send(msg)\n\n if (receiveThread.isAlive() == False):\n print 'Server disconnected on receive thread death'\n elif (self.alive.isSet() == False):\n print 'Server exiting on join request'\n elif (not c):\n print 'Server disconnected on broken pipe'\n\n # Left the loop\n c.close() # Close the connection\n receiveThread.join()\n\n # Received a quit\n print 'Server closed (Asked to quit)'\n\n def run(self):\n self.send_thread()\n\n def join(self, timeout = None):\n self.alive.clear()\n threading.Thread.join(self, timeout)\n\n" ]
true
98,714
fac9cf792a85085270d3251b4c0dca8e1d8c706b
import matlab.engine def matlab_start(): eng=matlab.engine.start_matlab("-desktop") l=['r',67] eng.workspace['y'] = l print(eng.workspace['y']) print(type(eng.workspace['y']))
[ "import matlab.engine\ndef matlab_start():\n eng=matlab.engine.start_matlab(\"-desktop\")\nl=['r',67]\neng.workspace['y'] = l\nprint(eng.workspace['y'])\nprint(type(eng.workspace['y']))\n", "import matlab.engine\n\n\ndef matlab_start():\n eng = matlab.engine.start_matlab('-desktop')\n\n\nl = ['r', 67]\neng.workspace['y'] = l\nprint(eng.workspace['y'])\nprint(type(eng.workspace['y']))\n", "<import token>\n\n\ndef matlab_start():\n eng = matlab.engine.start_matlab('-desktop')\n\n\nl = ['r', 67]\neng.workspace['y'] = l\nprint(eng.workspace['y'])\nprint(type(eng.workspace['y']))\n", "<import token>\n\n\ndef matlab_start():\n eng = matlab.engine.start_matlab('-desktop')\n\n\n<assignment token>\nprint(eng.workspace['y'])\nprint(type(eng.workspace['y']))\n", "<import token>\n\n\ndef matlab_start():\n eng = matlab.engine.start_matlab('-desktop')\n\n\n<assignment token>\n<code token>\n", "<import token>\n<function token>\n<assignment token>\n<code token>\n" ]
false
98,715
f08daa5ac964d6c83ccc9603294c4d6275f4a874
#!/usr/bin/env pipenv run python import re import itertools import collections from dataclasses import dataclass from get_input import get_input, line_parser class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): if not isinstance(other, type(self)): return NotImplemented return Point(self.x + other.x, self.y + other.y) def __repr__(self): return f"Point(x={self.x}, y={self.y})" def __hash__(self): return hash((self.x, self.y)) def __eq__(self, other): if not isinstance(other, type(self)): return NotImplemented return self.x == other.x and self.y == other.y class BoardItem: def __init__(self, board=None, pos=None): self.board = board self.pos = pos def __str__(self): return self.__class__.char class Wall(BoardItem): char = '#' class Space(BoardItem): char = '.' class Unit(BoardItem): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._hp = type(self).cls_hp self.ap = type(self).cls_ap @property def hp(self): return self._hp @hp.setter def hp(self, other): self._hp = other if self._hp <= 0: self.board[self.pos] = Space() if self.on_death: raise self.on_death(repr(self)) def is_enemy(self, other): return isinstance(other, Unit) and not isinstance(other, type(self)) and other.hp > 0 def find_defender(self): defender = None for diff in [self.board[self.pos + diff] for diff in self.board.READ_ORDER]: if self.is_enemy(diff): if not defender or diff.hp < defender.hp: defender = diff return defender @classmethod def make_unit_class(cls, char, attack=3, hp=200, on_death=None): unit_type = "Elf" if char == "E" else "Goblin" class Cls(cls): def __repr__(self): return f"{unit_type}({repr(self.pos)}, attack={self.ap}, hp={self.hp})" Cls.char = char Cls.cls_ap = attack Cls.cls_hp = hp Cls.on_death = on_death return Cls def get_targets(self): targets = set() enemies = [u for u in self.board.units if self.is_enemy(u)] if enemies == []: raise Board.NoEnemies for unit in enemies: for diff in self.board.READ_ORDER: if isinstance(self.board[unit.pos + diff], Space) or \ self.pos == unit.pos + diff: targets.add(unit.pos + diff) return targets def attack(self, defender): if defender is not None: defender.hp -= self.ap class Board: READ_ORDER = (Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1)) def __init__(self, power=3): self._rows = [] self.round = 0 self.power = power class NoEnemies(Exception): pass @classmethod def make_board(cls, lines, mapping, power=3): board = cls(power) for y, line in enumerate(lines.splitlines()): for x, char in enumerate(list(line)): board[Point(x, y)] = mapping[char]() board.unit_order = board.units board.attacker = board.unit_order.pop(0) return board def __getitem__(self, pos): if isinstance(pos, Point): return self._rows[pos.y][pos.x] return NotImplemented def __setitem__(self, point, value): if not isinstance(point, Point): return NotImplemented elif not isinstance(value, BoardItem): return NotImplemented while point.y >= len(self._rows): self._rows.append([]) while point.x >= len(self._rows[point.y]): self._rows[point.y].append(None) self._rows[point.y][point.x] = value value.board = self value.pos = point def __iter__(self): return iter(self._rows) @property def units(self): return [u for row in self for u in row if isinstance(u, Unit)] def find_move(self, attacker, targets): if attacker.pos in targets: return None queue = [(0, attacker.pos, None)] step_map = {} while queue: steps, pos, prev = queue.pop(0) if pos in step_map or not (isinstance(self[pos], Space) or prev is None): continue step_map[pos] = (steps, prev) for diff in self.READ_ORDER: queue.append((steps + 1, pos + diff, pos)) smallest, first = None, None for square in [u for row in self for u in row]: steps, pos = step_map.get(square.pos, (smallest, first)) if square.pos in targets and (smallest is None or smallest > steps): smallest, first = steps, square.pos if smallest is None: return attacker.pos prev = first while smallest is not None and smallest > 1: first = prev smallest, prev = step_map[first] return first or attacker.pos def __repr__(self): representation = [f"Round {self.round}/{self.power}"] representation.extend(''.join(str(u) for u in row) for row in self) representation.extend(repr(u) for u in self.units) return '\n'.join(representation) def play_round(self): for attacker in self.units: if attacker.hp <= 0: continue targets = attacker.get_targets() move = self.find_move(attacker, targets) self[attacker.pos], self[move] = self[move], self[attacker.pos] defender = attacker.find_defender() attacker.attack(defender) self.round += 1 def part1(lines): """Solution to part 1""" board = Board.make_board(lines, { 'E': Unit.make_unit_class('E'), 'G': Unit.make_unit_class('G'), '#': Wall, '.': Space}) while True: try: board.play_round() except Board.NoEnemies: break return sum(u.hp for u in board.units) * board.round def part2(lines): """Solution to part 2""" goblin_class = Unit.make_unit_class('G') class DeadElf(Exception): pass for elf_ap in itertools.count(4): elf_class = Unit.make_unit_class('E', elf_ap, 200, DeadElf) board = Board.make_board(lines, {'E': elf_class, 'G': goblin_class, '#': Wall, '.': Space}, power=elf_ap) try: while True: board.play_round() except DeadElf: continue except Board.NoEnemies: return sum(u.hp for u in board.units) * board.round sample_boards = [("""####### #.G...# #...EG# #.#.#G# #..G#E# #.....# #######""", 27730, 4988), ("""####### #G..#E# #E#E.E# #G.##.# #...#E# #...E.# #######""", 36334, None), ("""####### #E..EG# #.#G.E# #E.##E# #G..#.# #..E#.# #######""", 39514, 31284), ("""####### #E.G#.# #.#G..# #G.#.G# #G..#.# #...E.# #######""", 27755, 3478), ("""####### #.E...# #.#..G# #.###.# #E#G#G# #...#G# #######""", 28944, 6474), ("""######### #G......# #.E.#...# #..##..G# #...##..# #...#...# #.G...G.# #.....G.# #########""", 18740, 1140), ] if __name__ == '__main__': for board, part1_score, part2_score in sample_boards: assert part1_score == part1(board) assert part2_score is None or part2_score == part2(board) board = get_input(day=15, year=2018) # Issues occure during round 90, (x: 10, y: 15) # Moves right when it should move down (Why?) print("Part 1: {}".format(part1(board))) print("Part 2: {}".format(part2(board))) # Not 47678 46140 # Is 46784
[ "#!/usr/bin/env pipenv run python\nimport re\nimport itertools\nimport collections\nfrom dataclasses import dataclass\n\nfrom get_input import get_input, line_parser\n\n\nclass Point:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __add__(self, other):\n if not isinstance(other, type(self)):\n return NotImplemented\n return Point(self.x + other.x, self.y + other.y)\n\n def __repr__(self):\n return f\"Point(x={self.x}, y={self.y})\"\n\n def __hash__(self):\n return hash((self.x, self.y))\n\n def __eq__(self, other):\n if not isinstance(other, type(self)):\n return NotImplemented\n return self.x == other.x and self.y == other.y\n\nclass BoardItem:\n def __init__(self, board=None, pos=None):\n self.board = board \n self.pos = pos\n\n def __str__(self):\n return self.__class__.char\n \nclass Wall(BoardItem):\n char = '#'\n\nclass Space(BoardItem):\n char = '.'\n\nclass Unit(BoardItem):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._hp = type(self).cls_hp\n self.ap = type(self).cls_ap\n\n @property\n def hp(self):\n return self._hp\n\n @hp.setter\n def hp(self, other):\n self._hp = other\n if self._hp <= 0:\n self.board[self.pos] = Space()\n if self.on_death:\n raise self.on_death(repr(self))\n\n def is_enemy(self, other):\n return isinstance(other, Unit) and not isinstance(other, type(self)) and other.hp > 0\n\n def find_defender(self):\n defender = None\n for diff in [self.board[self.pos + diff] for diff in self.board.READ_ORDER]:\n if self.is_enemy(diff):\n if not defender or diff.hp < defender.hp:\n defender = diff\n return defender\n\n @classmethod\n def make_unit_class(cls, char, attack=3, hp=200, on_death=None):\n unit_type = \"Elf\" if char == \"E\" else \"Goblin\"\n class Cls(cls):\n def __repr__(self):\n return f\"{unit_type}({repr(self.pos)}, attack={self.ap}, hp={self.hp})\"\n Cls.char = char\n Cls.cls_ap = attack\n Cls.cls_hp = hp\n Cls.on_death = on_death\n return Cls \n\n def get_targets(self):\n targets = set()\n enemies = [u for u in self.board.units if self.is_enemy(u)]\n if enemies == []:\n raise Board.NoEnemies\n for unit in enemies:\n for diff in self.board.READ_ORDER:\n if isinstance(self.board[unit.pos + diff], Space) or \\\n self.pos == unit.pos + diff:\n targets.add(unit.pos + diff)\n return targets\n\n def attack(self, defender):\n if defender is not None:\n defender.hp -= self.ap\n\n\nclass Board:\n READ_ORDER = (Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1))\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is None): \n continue \n step_map[pos] = (steps, prev)\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps):\n smallest, first = steps, square.pos \n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f\"Round {self.round}/{self.power}\"]\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\ndef part1(lines):\n \"\"\"Solution to part 1\"\"\"\n board = Board.make_board(lines, {\n 'E': Unit.make_unit_class('E'),\n 'G': Unit.make_unit_class('G'),\n '#': Wall,\n '.': Space})\n while True:\n try:\n board.play_round()\n except Board.NoEnemies:\n break\n return sum(u.hp for u in board.units) * board.round\n\ndef part2(lines):\n \"\"\"Solution to part 2\"\"\"\n goblin_class = Unit.make_unit_class('G')\n class DeadElf(Exception):\n pass\n for elf_ap in itertools.count(4):\n elf_class = Unit.make_unit_class('E', elf_ap, 200, DeadElf)\n board = Board.make_board(lines, {'E': elf_class, 'G': goblin_class, '#': Wall, '.': Space}, power=elf_ap)\n try:\n while True:\n board.play_round()\n except DeadElf:\n continue\n except Board.NoEnemies:\n return sum(u.hp for u in board.units) * board.round\n\nsample_boards = [(\"\"\"#######\n#.G...#\n#...EG#\n#.#.#G#\n#..G#E#\n#.....#\n#######\"\"\", 27730, 4988),\n(\"\"\"#######\n#G..#E#\n#E#E.E#\n#G.##.#\n#...#E#\n#...E.#\n#######\"\"\", 36334, None),\n(\"\"\"#######\n#E..EG#\n#.#G.E#\n#E.##E#\n#G..#.#\n#..E#.#\n#######\"\"\", 39514, 31284),\n(\"\"\"#######\n#E.G#.#\n#.#G..#\n#G.#.G#\n#G..#.#\n#...E.#\n#######\"\"\", 27755, 3478),\n(\"\"\"#######\n#.E...#\n#.#..G#\n#.###.#\n#E#G#G#\n#...#G#\n#######\"\"\", 28944, 6474),\n(\"\"\"#########\n#G......#\n#.E.#...#\n#..##..G#\n#...##..#\n#...#...#\n#.G...G.#\n#.....G.#\n#########\"\"\", 18740, 1140),\n]\n\nif __name__ == '__main__':\n for board, part1_score, part2_score in sample_boards:\n assert part1_score == part1(board)\n assert part2_score is None or part2_score == part2(board)\n board = get_input(day=15, year=2018)\n # Issues occure during round 90, (x: 10, y: 15)\n # Moves right when it should move down (Why?)\n print(\"Part 1: {}\".format(part1(board)))\n print(\"Part 2: {}\".format(part2(board)))\n # Not 47678 46140\n # Is 46784\n", "import re\nimport itertools\nimport collections\nfrom dataclasses import dataclass\nfrom get_input import get_input, line_parser\n\n\nclass Point:\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __add__(self, other):\n if not isinstance(other, type(self)):\n return NotImplemented\n return Point(self.x + other.x, self.y + other.y)\n\n def __repr__(self):\n return f'Point(x={self.x}, y={self.y})'\n\n def __hash__(self):\n return hash((self.x, self.y))\n\n def __eq__(self, other):\n if not isinstance(other, type(self)):\n return NotImplemented\n return self.x == other.x and self.y == other.y\n\n\nclass BoardItem:\n\n def __init__(self, board=None, pos=None):\n self.board = board\n self.pos = pos\n\n def __str__(self):\n return self.__class__.char\n\n\nclass Wall(BoardItem):\n char = '#'\n\n\nclass Space(BoardItem):\n char = '.'\n\n\nclass Unit(BoardItem):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._hp = type(self).cls_hp\n self.ap = type(self).cls_ap\n\n @property\n def hp(self):\n return self._hp\n\n @hp.setter\n def hp(self, other):\n self._hp = other\n if self._hp <= 0:\n self.board[self.pos] = Space()\n if self.on_death:\n raise self.on_death(repr(self))\n\n def is_enemy(self, other):\n return isinstance(other, Unit) and not isinstance(other, type(self)\n ) and other.hp > 0\n\n def find_defender(self):\n defender = None\n for diff in [self.board[self.pos + diff] for diff in self.board.\n READ_ORDER]:\n if self.is_enemy(diff):\n if not defender or diff.hp < defender.hp:\n defender = diff\n return defender\n\n @classmethod\n def make_unit_class(cls, char, attack=3, hp=200, on_death=None):\n unit_type = 'Elf' if char == 'E' else 'Goblin'\n\n\n class Cls(cls):\n\n def __repr__(self):\n return (\n f'{unit_type}({repr(self.pos)}, attack={self.ap}, hp={self.hp})'\n )\n Cls.char = char\n Cls.cls_ap = attack\n Cls.cls_hp = hp\n Cls.on_death = on_death\n return Cls\n\n def get_targets(self):\n targets = set()\n enemies = [u for u in self.board.units if self.is_enemy(u)]\n if enemies == []:\n raise Board.NoEnemies\n for unit in enemies:\n for diff in self.board.READ_ORDER:\n if isinstance(self.board[unit.pos + diff], Space\n ) or self.pos == unit.pos + diff:\n targets.add(unit.pos + diff)\n return targets\n\n def attack(self, defender):\n if defender is not None:\n defender.hp -= self.ap\n\n\nclass Board:\n READ_ORDER = Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1)\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is\n None):\n continue\n step_map[pos] = steps, prev\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps\n ):\n smallest, first = steps, square.pos\n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\ndef part1(lines):\n \"\"\"Solution to part 1\"\"\"\n board = Board.make_board(lines, {'E': Unit.make_unit_class('E'), 'G':\n Unit.make_unit_class('G'), '#': Wall, '.': Space})\n while True:\n try:\n board.play_round()\n except Board.NoEnemies:\n break\n return sum(u.hp for u in board.units) * board.round\n\n\ndef part2(lines):\n \"\"\"Solution to part 2\"\"\"\n goblin_class = Unit.make_unit_class('G')\n\n\n class DeadElf(Exception):\n pass\n for elf_ap in itertools.count(4):\n elf_class = Unit.make_unit_class('E', elf_ap, 200, DeadElf)\n board = Board.make_board(lines, {'E': elf_class, 'G': goblin_class,\n '#': Wall, '.': Space}, power=elf_ap)\n try:\n while True:\n board.play_round()\n except DeadElf:\n continue\n except Board.NoEnemies:\n return sum(u.hp for u in board.units) * board.round\n\n\nsample_boards = [(\n \"\"\"#######\n#.G...#\n#...EG#\n#.#.#G#\n#..G#E#\n#.....#\n#######\"\"\", 27730, \n 4988), (\"\"\"#######\n#G..#E#\n#E#E.E#\n#G.##.#\n#...#E#\n#...E.#\n#######\"\"\", \n 36334, None), (\n \"\"\"#######\n#E..EG#\n#.#G.E#\n#E.##E#\n#G..#.#\n#..E#.#\n#######\"\"\", 39514, \n 31284), (\"\"\"#######\n#E.G#.#\n#.#G..#\n#G.#.G#\n#G..#.#\n#...E.#\n#######\"\"\",\n 27755, 3478), (\n \"\"\"#######\n#.E...#\n#.#..G#\n#.###.#\n#E#G#G#\n#...#G#\n#######\"\"\", 28944, \n 6474), (\n \"\"\"#########\n#G......#\n#.E.#...#\n#..##..G#\n#...##..#\n#...#...#\n#.G...G.#\n#.....G.#\n#########\"\"\"\n , 18740, 1140)]\nif __name__ == '__main__':\n for board, part1_score, part2_score in sample_boards:\n assert part1_score == part1(board)\n assert part2_score is None or part2_score == part2(board)\n board = get_input(day=15, year=2018)\n print('Part 1: {}'.format(part1(board)))\n print('Part 2: {}'.format(part2(board)))\n", "<import token>\n\n\nclass Point:\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __add__(self, other):\n if not isinstance(other, type(self)):\n return NotImplemented\n return Point(self.x + other.x, self.y + other.y)\n\n def __repr__(self):\n return f'Point(x={self.x}, y={self.y})'\n\n def __hash__(self):\n return hash((self.x, self.y))\n\n def __eq__(self, other):\n if not isinstance(other, type(self)):\n return NotImplemented\n return self.x == other.x and self.y == other.y\n\n\nclass BoardItem:\n\n def __init__(self, board=None, pos=None):\n self.board = board\n self.pos = pos\n\n def __str__(self):\n return self.__class__.char\n\n\nclass Wall(BoardItem):\n char = '#'\n\n\nclass Space(BoardItem):\n char = '.'\n\n\nclass Unit(BoardItem):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._hp = type(self).cls_hp\n self.ap = type(self).cls_ap\n\n @property\n def hp(self):\n return self._hp\n\n @hp.setter\n def hp(self, other):\n self._hp = other\n if self._hp <= 0:\n self.board[self.pos] = Space()\n if self.on_death:\n raise self.on_death(repr(self))\n\n def is_enemy(self, other):\n return isinstance(other, Unit) and not isinstance(other, type(self)\n ) and other.hp > 0\n\n def find_defender(self):\n defender = None\n for diff in [self.board[self.pos + diff] for diff in self.board.\n READ_ORDER]:\n if self.is_enemy(diff):\n if not defender or diff.hp < defender.hp:\n defender = diff\n return defender\n\n @classmethod\n def make_unit_class(cls, char, attack=3, hp=200, on_death=None):\n unit_type = 'Elf' if char == 'E' else 'Goblin'\n\n\n class Cls(cls):\n\n def __repr__(self):\n return (\n f'{unit_type}({repr(self.pos)}, attack={self.ap}, hp={self.hp})'\n )\n Cls.char = char\n Cls.cls_ap = attack\n Cls.cls_hp = hp\n Cls.on_death = on_death\n return Cls\n\n def get_targets(self):\n targets = set()\n enemies = [u for u in self.board.units if self.is_enemy(u)]\n if enemies == []:\n raise Board.NoEnemies\n for unit in enemies:\n for diff in self.board.READ_ORDER:\n if isinstance(self.board[unit.pos + diff], Space\n ) or self.pos == unit.pos + diff:\n targets.add(unit.pos + diff)\n return targets\n\n def attack(self, defender):\n if defender is not None:\n defender.hp -= self.ap\n\n\nclass Board:\n READ_ORDER = Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1)\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is\n None):\n continue\n step_map[pos] = steps, prev\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps\n ):\n smallest, first = steps, square.pos\n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\ndef part1(lines):\n \"\"\"Solution to part 1\"\"\"\n board = Board.make_board(lines, {'E': Unit.make_unit_class('E'), 'G':\n Unit.make_unit_class('G'), '#': Wall, '.': Space})\n while True:\n try:\n board.play_round()\n except Board.NoEnemies:\n break\n return sum(u.hp for u in board.units) * board.round\n\n\ndef part2(lines):\n \"\"\"Solution to part 2\"\"\"\n goblin_class = Unit.make_unit_class('G')\n\n\n class DeadElf(Exception):\n pass\n for elf_ap in itertools.count(4):\n elf_class = Unit.make_unit_class('E', elf_ap, 200, DeadElf)\n board = Board.make_board(lines, {'E': elf_class, 'G': goblin_class,\n '#': Wall, '.': Space}, power=elf_ap)\n try:\n while True:\n board.play_round()\n except DeadElf:\n continue\n except Board.NoEnemies:\n return sum(u.hp for u in board.units) * board.round\n\n\nsample_boards = [(\n \"\"\"#######\n#.G...#\n#...EG#\n#.#.#G#\n#..G#E#\n#.....#\n#######\"\"\", 27730, \n 4988), (\"\"\"#######\n#G..#E#\n#E#E.E#\n#G.##.#\n#...#E#\n#...E.#\n#######\"\"\", \n 36334, None), (\n \"\"\"#######\n#E..EG#\n#.#G.E#\n#E.##E#\n#G..#.#\n#..E#.#\n#######\"\"\", 39514, \n 31284), (\"\"\"#######\n#E.G#.#\n#.#G..#\n#G.#.G#\n#G..#.#\n#...E.#\n#######\"\"\",\n 27755, 3478), (\n \"\"\"#######\n#.E...#\n#.#..G#\n#.###.#\n#E#G#G#\n#...#G#\n#######\"\"\", 28944, \n 6474), (\n \"\"\"#########\n#G......#\n#.E.#...#\n#..##..G#\n#...##..#\n#...#...#\n#.G...G.#\n#.....G.#\n#########\"\"\"\n , 18740, 1140)]\nif __name__ == '__main__':\n for board, part1_score, part2_score in sample_boards:\n assert part1_score == part1(board)\n assert part2_score is None or part2_score == part2(board)\n board = get_input(day=15, year=2018)\n print('Part 1: {}'.format(part1(board)))\n print('Part 2: {}'.format(part2(board)))\n", "<import token>\n\n\nclass Point:\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __add__(self, other):\n if not isinstance(other, type(self)):\n return NotImplemented\n return Point(self.x + other.x, self.y + other.y)\n\n def __repr__(self):\n return f'Point(x={self.x}, y={self.y})'\n\n def __hash__(self):\n return hash((self.x, self.y))\n\n def __eq__(self, other):\n if not isinstance(other, type(self)):\n return NotImplemented\n return self.x == other.x and self.y == other.y\n\n\nclass BoardItem:\n\n def __init__(self, board=None, pos=None):\n self.board = board\n self.pos = pos\n\n def __str__(self):\n return self.__class__.char\n\n\nclass Wall(BoardItem):\n char = '#'\n\n\nclass Space(BoardItem):\n char = '.'\n\n\nclass Unit(BoardItem):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._hp = type(self).cls_hp\n self.ap = type(self).cls_ap\n\n @property\n def hp(self):\n return self._hp\n\n @hp.setter\n def hp(self, other):\n self._hp = other\n if self._hp <= 0:\n self.board[self.pos] = Space()\n if self.on_death:\n raise self.on_death(repr(self))\n\n def is_enemy(self, other):\n return isinstance(other, Unit) and not isinstance(other, type(self)\n ) and other.hp > 0\n\n def find_defender(self):\n defender = None\n for diff in [self.board[self.pos + diff] for diff in self.board.\n READ_ORDER]:\n if self.is_enemy(diff):\n if not defender or diff.hp < defender.hp:\n defender = diff\n return defender\n\n @classmethod\n def make_unit_class(cls, char, attack=3, hp=200, on_death=None):\n unit_type = 'Elf' if char == 'E' else 'Goblin'\n\n\n class Cls(cls):\n\n def __repr__(self):\n return (\n f'{unit_type}({repr(self.pos)}, attack={self.ap}, hp={self.hp})'\n )\n Cls.char = char\n Cls.cls_ap = attack\n Cls.cls_hp = hp\n Cls.on_death = on_death\n return Cls\n\n def get_targets(self):\n targets = set()\n enemies = [u for u in self.board.units if self.is_enemy(u)]\n if enemies == []:\n raise Board.NoEnemies\n for unit in enemies:\n for diff in self.board.READ_ORDER:\n if isinstance(self.board[unit.pos + diff], Space\n ) or self.pos == unit.pos + diff:\n targets.add(unit.pos + diff)\n return targets\n\n def attack(self, defender):\n if defender is not None:\n defender.hp -= self.ap\n\n\nclass Board:\n READ_ORDER = Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1)\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is\n None):\n continue\n step_map[pos] = steps, prev\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps\n ):\n smallest, first = steps, square.pos\n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\ndef part1(lines):\n \"\"\"Solution to part 1\"\"\"\n board = Board.make_board(lines, {'E': Unit.make_unit_class('E'), 'G':\n Unit.make_unit_class('G'), '#': Wall, '.': Space})\n while True:\n try:\n board.play_round()\n except Board.NoEnemies:\n break\n return sum(u.hp for u in board.units) * board.round\n\n\ndef part2(lines):\n \"\"\"Solution to part 2\"\"\"\n goblin_class = Unit.make_unit_class('G')\n\n\n class DeadElf(Exception):\n pass\n for elf_ap in itertools.count(4):\n elf_class = Unit.make_unit_class('E', elf_ap, 200, DeadElf)\n board = Board.make_board(lines, {'E': elf_class, 'G': goblin_class,\n '#': Wall, '.': Space}, power=elf_ap)\n try:\n while True:\n board.play_round()\n except DeadElf:\n continue\n except Board.NoEnemies:\n return sum(u.hp for u in board.units) * board.round\n\n\n<assignment token>\nif __name__ == '__main__':\n for board, part1_score, part2_score in sample_boards:\n assert part1_score == part1(board)\n assert part2_score is None or part2_score == part2(board)\n board = get_input(day=15, year=2018)\n print('Part 1: {}'.format(part1(board)))\n print('Part 2: {}'.format(part2(board)))\n", "<import token>\n\n\nclass Point:\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __add__(self, other):\n if not isinstance(other, type(self)):\n return NotImplemented\n return Point(self.x + other.x, self.y + other.y)\n\n def __repr__(self):\n return f'Point(x={self.x}, y={self.y})'\n\n def __hash__(self):\n return hash((self.x, self.y))\n\n def __eq__(self, other):\n if not isinstance(other, type(self)):\n return NotImplemented\n return self.x == other.x and self.y == other.y\n\n\nclass BoardItem:\n\n def __init__(self, board=None, pos=None):\n self.board = board\n self.pos = pos\n\n def __str__(self):\n return self.__class__.char\n\n\nclass Wall(BoardItem):\n char = '#'\n\n\nclass Space(BoardItem):\n char = '.'\n\n\nclass Unit(BoardItem):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._hp = type(self).cls_hp\n self.ap = type(self).cls_ap\n\n @property\n def hp(self):\n return self._hp\n\n @hp.setter\n def hp(self, other):\n self._hp = other\n if self._hp <= 0:\n self.board[self.pos] = Space()\n if self.on_death:\n raise self.on_death(repr(self))\n\n def is_enemy(self, other):\n return isinstance(other, Unit) and not isinstance(other, type(self)\n ) and other.hp > 0\n\n def find_defender(self):\n defender = None\n for diff in [self.board[self.pos + diff] for diff in self.board.\n READ_ORDER]:\n if self.is_enemy(diff):\n if not defender or diff.hp < defender.hp:\n defender = diff\n return defender\n\n @classmethod\n def make_unit_class(cls, char, attack=3, hp=200, on_death=None):\n unit_type = 'Elf' if char == 'E' else 'Goblin'\n\n\n class Cls(cls):\n\n def __repr__(self):\n return (\n f'{unit_type}({repr(self.pos)}, attack={self.ap}, hp={self.hp})'\n )\n Cls.char = char\n Cls.cls_ap = attack\n Cls.cls_hp = hp\n Cls.on_death = on_death\n return Cls\n\n def get_targets(self):\n targets = set()\n enemies = [u for u in self.board.units if self.is_enemy(u)]\n if enemies == []:\n raise Board.NoEnemies\n for unit in enemies:\n for diff in self.board.READ_ORDER:\n if isinstance(self.board[unit.pos + diff], Space\n ) or self.pos == unit.pos + diff:\n targets.add(unit.pos + diff)\n return targets\n\n def attack(self, defender):\n if defender is not None:\n defender.hp -= self.ap\n\n\nclass Board:\n READ_ORDER = Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1)\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is\n None):\n continue\n step_map[pos] = steps, prev\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps\n ):\n smallest, first = steps, square.pos\n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\ndef part1(lines):\n \"\"\"Solution to part 1\"\"\"\n board = Board.make_board(lines, {'E': Unit.make_unit_class('E'), 'G':\n Unit.make_unit_class('G'), '#': Wall, '.': Space})\n while True:\n try:\n board.play_round()\n except Board.NoEnemies:\n break\n return sum(u.hp for u in board.units) * board.round\n\n\ndef part2(lines):\n \"\"\"Solution to part 2\"\"\"\n goblin_class = Unit.make_unit_class('G')\n\n\n class DeadElf(Exception):\n pass\n for elf_ap in itertools.count(4):\n elf_class = Unit.make_unit_class('E', elf_ap, 200, DeadElf)\n board = Board.make_board(lines, {'E': elf_class, 'G': goblin_class,\n '#': Wall, '.': Space}, power=elf_ap)\n try:\n while True:\n board.play_round()\n except DeadElf:\n continue\n except Board.NoEnemies:\n return sum(u.hp for u in board.units) * board.round\n\n\n<assignment token>\n<code token>\n", "<import token>\n\n\nclass Point:\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __add__(self, other):\n if not isinstance(other, type(self)):\n return NotImplemented\n return Point(self.x + other.x, self.y + other.y)\n\n def __repr__(self):\n return f'Point(x={self.x}, y={self.y})'\n\n def __hash__(self):\n return hash((self.x, self.y))\n\n def __eq__(self, other):\n if not isinstance(other, type(self)):\n return NotImplemented\n return self.x == other.x and self.y == other.y\n\n\nclass BoardItem:\n\n def __init__(self, board=None, pos=None):\n self.board = board\n self.pos = pos\n\n def __str__(self):\n return self.__class__.char\n\n\nclass Wall(BoardItem):\n char = '#'\n\n\nclass Space(BoardItem):\n char = '.'\n\n\nclass Unit(BoardItem):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._hp = type(self).cls_hp\n self.ap = type(self).cls_ap\n\n @property\n def hp(self):\n return self._hp\n\n @hp.setter\n def hp(self, other):\n self._hp = other\n if self._hp <= 0:\n self.board[self.pos] = Space()\n if self.on_death:\n raise self.on_death(repr(self))\n\n def is_enemy(self, other):\n return isinstance(other, Unit) and not isinstance(other, type(self)\n ) and other.hp > 0\n\n def find_defender(self):\n defender = None\n for diff in [self.board[self.pos + diff] for diff in self.board.\n READ_ORDER]:\n if self.is_enemy(diff):\n if not defender or diff.hp < defender.hp:\n defender = diff\n return defender\n\n @classmethod\n def make_unit_class(cls, char, attack=3, hp=200, on_death=None):\n unit_type = 'Elf' if char == 'E' else 'Goblin'\n\n\n class Cls(cls):\n\n def __repr__(self):\n return (\n f'{unit_type}({repr(self.pos)}, attack={self.ap}, hp={self.hp})'\n )\n Cls.char = char\n Cls.cls_ap = attack\n Cls.cls_hp = hp\n Cls.on_death = on_death\n return Cls\n\n def get_targets(self):\n targets = set()\n enemies = [u for u in self.board.units if self.is_enemy(u)]\n if enemies == []:\n raise Board.NoEnemies\n for unit in enemies:\n for diff in self.board.READ_ORDER:\n if isinstance(self.board[unit.pos + diff], Space\n ) or self.pos == unit.pos + diff:\n targets.add(unit.pos + diff)\n return targets\n\n def attack(self, defender):\n if defender is not None:\n defender.hp -= self.ap\n\n\nclass Board:\n READ_ORDER = Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1)\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is\n None):\n continue\n step_map[pos] = steps, prev\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps\n ):\n smallest, first = steps, square.pos\n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\n<function token>\n\n\ndef part2(lines):\n \"\"\"Solution to part 2\"\"\"\n goblin_class = Unit.make_unit_class('G')\n\n\n class DeadElf(Exception):\n pass\n for elf_ap in itertools.count(4):\n elf_class = Unit.make_unit_class('E', elf_ap, 200, DeadElf)\n board = Board.make_board(lines, {'E': elf_class, 'G': goblin_class,\n '#': Wall, '.': Space}, power=elf_ap)\n try:\n while True:\n board.play_round()\n except DeadElf:\n continue\n except Board.NoEnemies:\n return sum(u.hp for u in board.units) * board.round\n\n\n<assignment token>\n<code token>\n", "<import token>\n\n\nclass Point:\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __add__(self, other):\n if not isinstance(other, type(self)):\n return NotImplemented\n return Point(self.x + other.x, self.y + other.y)\n\n def __repr__(self):\n return f'Point(x={self.x}, y={self.y})'\n\n def __hash__(self):\n return hash((self.x, self.y))\n\n def __eq__(self, other):\n if not isinstance(other, type(self)):\n return NotImplemented\n return self.x == other.x and self.y == other.y\n\n\nclass BoardItem:\n\n def __init__(self, board=None, pos=None):\n self.board = board\n self.pos = pos\n\n def __str__(self):\n return self.__class__.char\n\n\nclass Wall(BoardItem):\n char = '#'\n\n\nclass Space(BoardItem):\n char = '.'\n\n\nclass Unit(BoardItem):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._hp = type(self).cls_hp\n self.ap = type(self).cls_ap\n\n @property\n def hp(self):\n return self._hp\n\n @hp.setter\n def hp(self, other):\n self._hp = other\n if self._hp <= 0:\n self.board[self.pos] = Space()\n if self.on_death:\n raise self.on_death(repr(self))\n\n def is_enemy(self, other):\n return isinstance(other, Unit) and not isinstance(other, type(self)\n ) and other.hp > 0\n\n def find_defender(self):\n defender = None\n for diff in [self.board[self.pos + diff] for diff in self.board.\n READ_ORDER]:\n if self.is_enemy(diff):\n if not defender or diff.hp < defender.hp:\n defender = diff\n return defender\n\n @classmethod\n def make_unit_class(cls, char, attack=3, hp=200, on_death=None):\n unit_type = 'Elf' if char == 'E' else 'Goblin'\n\n\n class Cls(cls):\n\n def __repr__(self):\n return (\n f'{unit_type}({repr(self.pos)}, attack={self.ap}, hp={self.hp})'\n )\n Cls.char = char\n Cls.cls_ap = attack\n Cls.cls_hp = hp\n Cls.on_death = on_death\n return Cls\n\n def get_targets(self):\n targets = set()\n enemies = [u for u in self.board.units if self.is_enemy(u)]\n if enemies == []:\n raise Board.NoEnemies\n for unit in enemies:\n for diff in self.board.READ_ORDER:\n if isinstance(self.board[unit.pos + diff], Space\n ) or self.pos == unit.pos + diff:\n targets.add(unit.pos + diff)\n return targets\n\n def attack(self, defender):\n if defender is not None:\n defender.hp -= self.ap\n\n\nclass Board:\n READ_ORDER = Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1)\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is\n None):\n continue\n step_map[pos] = steps, prev\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps\n ):\n smallest, first = steps, square.pos\n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n\n\nclass Point:\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n <function token>\n\n def __repr__(self):\n return f'Point(x={self.x}, y={self.y})'\n\n def __hash__(self):\n return hash((self.x, self.y))\n\n def __eq__(self, other):\n if not isinstance(other, type(self)):\n return NotImplemented\n return self.x == other.x and self.y == other.y\n\n\nclass BoardItem:\n\n def __init__(self, board=None, pos=None):\n self.board = board\n self.pos = pos\n\n def __str__(self):\n return self.__class__.char\n\n\nclass Wall(BoardItem):\n char = '#'\n\n\nclass Space(BoardItem):\n char = '.'\n\n\nclass Unit(BoardItem):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._hp = type(self).cls_hp\n self.ap = type(self).cls_ap\n\n @property\n def hp(self):\n return self._hp\n\n @hp.setter\n def hp(self, other):\n self._hp = other\n if self._hp <= 0:\n self.board[self.pos] = Space()\n if self.on_death:\n raise self.on_death(repr(self))\n\n def is_enemy(self, other):\n return isinstance(other, Unit) and not isinstance(other, type(self)\n ) and other.hp > 0\n\n def find_defender(self):\n defender = None\n for diff in [self.board[self.pos + diff] for diff in self.board.\n READ_ORDER]:\n if self.is_enemy(diff):\n if not defender or diff.hp < defender.hp:\n defender = diff\n return defender\n\n @classmethod\n def make_unit_class(cls, char, attack=3, hp=200, on_death=None):\n unit_type = 'Elf' if char == 'E' else 'Goblin'\n\n\n class Cls(cls):\n\n def __repr__(self):\n return (\n f'{unit_type}({repr(self.pos)}, attack={self.ap}, hp={self.hp})'\n )\n Cls.char = char\n Cls.cls_ap = attack\n Cls.cls_hp = hp\n Cls.on_death = on_death\n return Cls\n\n def get_targets(self):\n targets = set()\n enemies = [u for u in self.board.units if self.is_enemy(u)]\n if enemies == []:\n raise Board.NoEnemies\n for unit in enemies:\n for diff in self.board.READ_ORDER:\n if isinstance(self.board[unit.pos + diff], Space\n ) or self.pos == unit.pos + diff:\n targets.add(unit.pos + diff)\n return targets\n\n def attack(self, defender):\n if defender is not None:\n defender.hp -= self.ap\n\n\nclass Board:\n READ_ORDER = Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1)\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is\n None):\n continue\n step_map[pos] = steps, prev\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps\n ):\n smallest, first = steps, square.pos\n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n\n\nclass Point:\n <function token>\n <function token>\n\n def __repr__(self):\n return f'Point(x={self.x}, y={self.y})'\n\n def __hash__(self):\n return hash((self.x, self.y))\n\n def __eq__(self, other):\n if not isinstance(other, type(self)):\n return NotImplemented\n return self.x == other.x and self.y == other.y\n\n\nclass BoardItem:\n\n def __init__(self, board=None, pos=None):\n self.board = board\n self.pos = pos\n\n def __str__(self):\n return self.__class__.char\n\n\nclass Wall(BoardItem):\n char = '#'\n\n\nclass Space(BoardItem):\n char = '.'\n\n\nclass Unit(BoardItem):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._hp = type(self).cls_hp\n self.ap = type(self).cls_ap\n\n @property\n def hp(self):\n return self._hp\n\n @hp.setter\n def hp(self, other):\n self._hp = other\n if self._hp <= 0:\n self.board[self.pos] = Space()\n if self.on_death:\n raise self.on_death(repr(self))\n\n def is_enemy(self, other):\n return isinstance(other, Unit) and not isinstance(other, type(self)\n ) and other.hp > 0\n\n def find_defender(self):\n defender = None\n for diff in [self.board[self.pos + diff] for diff in self.board.\n READ_ORDER]:\n if self.is_enemy(diff):\n if not defender or diff.hp < defender.hp:\n defender = diff\n return defender\n\n @classmethod\n def make_unit_class(cls, char, attack=3, hp=200, on_death=None):\n unit_type = 'Elf' if char == 'E' else 'Goblin'\n\n\n class Cls(cls):\n\n def __repr__(self):\n return (\n f'{unit_type}({repr(self.pos)}, attack={self.ap}, hp={self.hp})'\n )\n Cls.char = char\n Cls.cls_ap = attack\n Cls.cls_hp = hp\n Cls.on_death = on_death\n return Cls\n\n def get_targets(self):\n targets = set()\n enemies = [u for u in self.board.units if self.is_enemy(u)]\n if enemies == []:\n raise Board.NoEnemies\n for unit in enemies:\n for diff in self.board.READ_ORDER:\n if isinstance(self.board[unit.pos + diff], Space\n ) or self.pos == unit.pos + diff:\n targets.add(unit.pos + diff)\n return targets\n\n def attack(self, defender):\n if defender is not None:\n defender.hp -= self.ap\n\n\nclass Board:\n READ_ORDER = Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1)\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is\n None):\n continue\n step_map[pos] = steps, prev\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps\n ):\n smallest, first = steps, square.pos\n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n\n\nclass Point:\n <function token>\n <function token>\n <function token>\n\n def __hash__(self):\n return hash((self.x, self.y))\n\n def __eq__(self, other):\n if not isinstance(other, type(self)):\n return NotImplemented\n return self.x == other.x and self.y == other.y\n\n\nclass BoardItem:\n\n def __init__(self, board=None, pos=None):\n self.board = board\n self.pos = pos\n\n def __str__(self):\n return self.__class__.char\n\n\nclass Wall(BoardItem):\n char = '#'\n\n\nclass Space(BoardItem):\n char = '.'\n\n\nclass Unit(BoardItem):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._hp = type(self).cls_hp\n self.ap = type(self).cls_ap\n\n @property\n def hp(self):\n return self._hp\n\n @hp.setter\n def hp(self, other):\n self._hp = other\n if self._hp <= 0:\n self.board[self.pos] = Space()\n if self.on_death:\n raise self.on_death(repr(self))\n\n def is_enemy(self, other):\n return isinstance(other, Unit) and not isinstance(other, type(self)\n ) and other.hp > 0\n\n def find_defender(self):\n defender = None\n for diff in [self.board[self.pos + diff] for diff in self.board.\n READ_ORDER]:\n if self.is_enemy(diff):\n if not defender or diff.hp < defender.hp:\n defender = diff\n return defender\n\n @classmethod\n def make_unit_class(cls, char, attack=3, hp=200, on_death=None):\n unit_type = 'Elf' if char == 'E' else 'Goblin'\n\n\n class Cls(cls):\n\n def __repr__(self):\n return (\n f'{unit_type}({repr(self.pos)}, attack={self.ap}, hp={self.hp})'\n )\n Cls.char = char\n Cls.cls_ap = attack\n Cls.cls_hp = hp\n Cls.on_death = on_death\n return Cls\n\n def get_targets(self):\n targets = set()\n enemies = [u for u in self.board.units if self.is_enemy(u)]\n if enemies == []:\n raise Board.NoEnemies\n for unit in enemies:\n for diff in self.board.READ_ORDER:\n if isinstance(self.board[unit.pos + diff], Space\n ) or self.pos == unit.pos + diff:\n targets.add(unit.pos + diff)\n return targets\n\n def attack(self, defender):\n if defender is not None:\n defender.hp -= self.ap\n\n\nclass Board:\n READ_ORDER = Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1)\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is\n None):\n continue\n step_map[pos] = steps, prev\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps\n ):\n smallest, first = steps, square.pos\n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n\n\nclass Point:\n <function token>\n <function token>\n <function token>\n\n def __hash__(self):\n return hash((self.x, self.y))\n <function token>\n\n\nclass BoardItem:\n\n def __init__(self, board=None, pos=None):\n self.board = board\n self.pos = pos\n\n def __str__(self):\n return self.__class__.char\n\n\nclass Wall(BoardItem):\n char = '#'\n\n\nclass Space(BoardItem):\n char = '.'\n\n\nclass Unit(BoardItem):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._hp = type(self).cls_hp\n self.ap = type(self).cls_ap\n\n @property\n def hp(self):\n return self._hp\n\n @hp.setter\n def hp(self, other):\n self._hp = other\n if self._hp <= 0:\n self.board[self.pos] = Space()\n if self.on_death:\n raise self.on_death(repr(self))\n\n def is_enemy(self, other):\n return isinstance(other, Unit) and not isinstance(other, type(self)\n ) and other.hp > 0\n\n def find_defender(self):\n defender = None\n for diff in [self.board[self.pos + diff] for diff in self.board.\n READ_ORDER]:\n if self.is_enemy(diff):\n if not defender or diff.hp < defender.hp:\n defender = diff\n return defender\n\n @classmethod\n def make_unit_class(cls, char, attack=3, hp=200, on_death=None):\n unit_type = 'Elf' if char == 'E' else 'Goblin'\n\n\n class Cls(cls):\n\n def __repr__(self):\n return (\n f'{unit_type}({repr(self.pos)}, attack={self.ap}, hp={self.hp})'\n )\n Cls.char = char\n Cls.cls_ap = attack\n Cls.cls_hp = hp\n Cls.on_death = on_death\n return Cls\n\n def get_targets(self):\n targets = set()\n enemies = [u for u in self.board.units if self.is_enemy(u)]\n if enemies == []:\n raise Board.NoEnemies\n for unit in enemies:\n for diff in self.board.READ_ORDER:\n if isinstance(self.board[unit.pos + diff], Space\n ) or self.pos == unit.pos + diff:\n targets.add(unit.pos + diff)\n return targets\n\n def attack(self, defender):\n if defender is not None:\n defender.hp -= self.ap\n\n\nclass Board:\n READ_ORDER = Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1)\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is\n None):\n continue\n step_map[pos] = steps, prev\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps\n ):\n smallest, first = steps, square.pos\n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n\n\nclass Point:\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass BoardItem:\n\n def __init__(self, board=None, pos=None):\n self.board = board\n self.pos = pos\n\n def __str__(self):\n return self.__class__.char\n\n\nclass Wall(BoardItem):\n char = '#'\n\n\nclass Space(BoardItem):\n char = '.'\n\n\nclass Unit(BoardItem):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._hp = type(self).cls_hp\n self.ap = type(self).cls_ap\n\n @property\n def hp(self):\n return self._hp\n\n @hp.setter\n def hp(self, other):\n self._hp = other\n if self._hp <= 0:\n self.board[self.pos] = Space()\n if self.on_death:\n raise self.on_death(repr(self))\n\n def is_enemy(self, other):\n return isinstance(other, Unit) and not isinstance(other, type(self)\n ) and other.hp > 0\n\n def find_defender(self):\n defender = None\n for diff in [self.board[self.pos + diff] for diff in self.board.\n READ_ORDER]:\n if self.is_enemy(diff):\n if not defender or diff.hp < defender.hp:\n defender = diff\n return defender\n\n @classmethod\n def make_unit_class(cls, char, attack=3, hp=200, on_death=None):\n unit_type = 'Elf' if char == 'E' else 'Goblin'\n\n\n class Cls(cls):\n\n def __repr__(self):\n return (\n f'{unit_type}({repr(self.pos)}, attack={self.ap}, hp={self.hp})'\n )\n Cls.char = char\n Cls.cls_ap = attack\n Cls.cls_hp = hp\n Cls.on_death = on_death\n return Cls\n\n def get_targets(self):\n targets = set()\n enemies = [u for u in self.board.units if self.is_enemy(u)]\n if enemies == []:\n raise Board.NoEnemies\n for unit in enemies:\n for diff in self.board.READ_ORDER:\n if isinstance(self.board[unit.pos + diff], Space\n ) or self.pos == unit.pos + diff:\n targets.add(unit.pos + diff)\n return targets\n\n def attack(self, defender):\n if defender is not None:\n defender.hp -= self.ap\n\n\nclass Board:\n READ_ORDER = Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1)\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is\n None):\n continue\n step_map[pos] = steps, prev\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps\n ):\n smallest, first = steps, square.pos\n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<class token>\n\n\nclass BoardItem:\n\n def __init__(self, board=None, pos=None):\n self.board = board\n self.pos = pos\n\n def __str__(self):\n return self.__class__.char\n\n\nclass Wall(BoardItem):\n char = '#'\n\n\nclass Space(BoardItem):\n char = '.'\n\n\nclass Unit(BoardItem):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._hp = type(self).cls_hp\n self.ap = type(self).cls_ap\n\n @property\n def hp(self):\n return self._hp\n\n @hp.setter\n def hp(self, other):\n self._hp = other\n if self._hp <= 0:\n self.board[self.pos] = Space()\n if self.on_death:\n raise self.on_death(repr(self))\n\n def is_enemy(self, other):\n return isinstance(other, Unit) and not isinstance(other, type(self)\n ) and other.hp > 0\n\n def find_defender(self):\n defender = None\n for diff in [self.board[self.pos + diff] for diff in self.board.\n READ_ORDER]:\n if self.is_enemy(diff):\n if not defender or diff.hp < defender.hp:\n defender = diff\n return defender\n\n @classmethod\n def make_unit_class(cls, char, attack=3, hp=200, on_death=None):\n unit_type = 'Elf' if char == 'E' else 'Goblin'\n\n\n class Cls(cls):\n\n def __repr__(self):\n return (\n f'{unit_type}({repr(self.pos)}, attack={self.ap}, hp={self.hp})'\n )\n Cls.char = char\n Cls.cls_ap = attack\n Cls.cls_hp = hp\n Cls.on_death = on_death\n return Cls\n\n def get_targets(self):\n targets = set()\n enemies = [u for u in self.board.units if self.is_enemy(u)]\n if enemies == []:\n raise Board.NoEnemies\n for unit in enemies:\n for diff in self.board.READ_ORDER:\n if isinstance(self.board[unit.pos + diff], Space\n ) or self.pos == unit.pos + diff:\n targets.add(unit.pos + diff)\n return targets\n\n def attack(self, defender):\n if defender is not None:\n defender.hp -= self.ap\n\n\nclass Board:\n READ_ORDER = Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1)\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is\n None):\n continue\n step_map[pos] = steps, prev\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps\n ):\n smallest, first = steps, square.pos\n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<class token>\n\n\nclass BoardItem:\n\n def __init__(self, board=None, pos=None):\n self.board = board\n self.pos = pos\n <function token>\n\n\nclass Wall(BoardItem):\n char = '#'\n\n\nclass Space(BoardItem):\n char = '.'\n\n\nclass Unit(BoardItem):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._hp = type(self).cls_hp\n self.ap = type(self).cls_ap\n\n @property\n def hp(self):\n return self._hp\n\n @hp.setter\n def hp(self, other):\n self._hp = other\n if self._hp <= 0:\n self.board[self.pos] = Space()\n if self.on_death:\n raise self.on_death(repr(self))\n\n def is_enemy(self, other):\n return isinstance(other, Unit) and not isinstance(other, type(self)\n ) and other.hp > 0\n\n def find_defender(self):\n defender = None\n for diff in [self.board[self.pos + diff] for diff in self.board.\n READ_ORDER]:\n if self.is_enemy(diff):\n if not defender or diff.hp < defender.hp:\n defender = diff\n return defender\n\n @classmethod\n def make_unit_class(cls, char, attack=3, hp=200, on_death=None):\n unit_type = 'Elf' if char == 'E' else 'Goblin'\n\n\n class Cls(cls):\n\n def __repr__(self):\n return (\n f'{unit_type}({repr(self.pos)}, attack={self.ap}, hp={self.hp})'\n )\n Cls.char = char\n Cls.cls_ap = attack\n Cls.cls_hp = hp\n Cls.on_death = on_death\n return Cls\n\n def get_targets(self):\n targets = set()\n enemies = [u for u in self.board.units if self.is_enemy(u)]\n if enemies == []:\n raise Board.NoEnemies\n for unit in enemies:\n for diff in self.board.READ_ORDER:\n if isinstance(self.board[unit.pos + diff], Space\n ) or self.pos == unit.pos + diff:\n targets.add(unit.pos + diff)\n return targets\n\n def attack(self, defender):\n if defender is not None:\n defender.hp -= self.ap\n\n\nclass Board:\n READ_ORDER = Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1)\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is\n None):\n continue\n step_map[pos] = steps, prev\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps\n ):\n smallest, first = steps, square.pos\n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<class token>\n\n\nclass BoardItem:\n <function token>\n <function token>\n\n\nclass Wall(BoardItem):\n char = '#'\n\n\nclass Space(BoardItem):\n char = '.'\n\n\nclass Unit(BoardItem):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._hp = type(self).cls_hp\n self.ap = type(self).cls_ap\n\n @property\n def hp(self):\n return self._hp\n\n @hp.setter\n def hp(self, other):\n self._hp = other\n if self._hp <= 0:\n self.board[self.pos] = Space()\n if self.on_death:\n raise self.on_death(repr(self))\n\n def is_enemy(self, other):\n return isinstance(other, Unit) and not isinstance(other, type(self)\n ) and other.hp > 0\n\n def find_defender(self):\n defender = None\n for diff in [self.board[self.pos + diff] for diff in self.board.\n READ_ORDER]:\n if self.is_enemy(diff):\n if not defender or diff.hp < defender.hp:\n defender = diff\n return defender\n\n @classmethod\n def make_unit_class(cls, char, attack=3, hp=200, on_death=None):\n unit_type = 'Elf' if char == 'E' else 'Goblin'\n\n\n class Cls(cls):\n\n def __repr__(self):\n return (\n f'{unit_type}({repr(self.pos)}, attack={self.ap}, hp={self.hp})'\n )\n Cls.char = char\n Cls.cls_ap = attack\n Cls.cls_hp = hp\n Cls.on_death = on_death\n return Cls\n\n def get_targets(self):\n targets = set()\n enemies = [u for u in self.board.units if self.is_enemy(u)]\n if enemies == []:\n raise Board.NoEnemies\n for unit in enemies:\n for diff in self.board.READ_ORDER:\n if isinstance(self.board[unit.pos + diff], Space\n ) or self.pos == unit.pos + diff:\n targets.add(unit.pos + diff)\n return targets\n\n def attack(self, defender):\n if defender is not None:\n defender.hp -= self.ap\n\n\nclass Board:\n READ_ORDER = Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1)\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is\n None):\n continue\n step_map[pos] = steps, prev\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps\n ):\n smallest, first = steps, square.pos\n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass Wall(BoardItem):\n char = '#'\n\n\nclass Space(BoardItem):\n char = '.'\n\n\nclass Unit(BoardItem):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._hp = type(self).cls_hp\n self.ap = type(self).cls_ap\n\n @property\n def hp(self):\n return self._hp\n\n @hp.setter\n def hp(self, other):\n self._hp = other\n if self._hp <= 0:\n self.board[self.pos] = Space()\n if self.on_death:\n raise self.on_death(repr(self))\n\n def is_enemy(self, other):\n return isinstance(other, Unit) and not isinstance(other, type(self)\n ) and other.hp > 0\n\n def find_defender(self):\n defender = None\n for diff in [self.board[self.pos + diff] for diff in self.board.\n READ_ORDER]:\n if self.is_enemy(diff):\n if not defender or diff.hp < defender.hp:\n defender = diff\n return defender\n\n @classmethod\n def make_unit_class(cls, char, attack=3, hp=200, on_death=None):\n unit_type = 'Elf' if char == 'E' else 'Goblin'\n\n\n class Cls(cls):\n\n def __repr__(self):\n return (\n f'{unit_type}({repr(self.pos)}, attack={self.ap}, hp={self.hp})'\n )\n Cls.char = char\n Cls.cls_ap = attack\n Cls.cls_hp = hp\n Cls.on_death = on_death\n return Cls\n\n def get_targets(self):\n targets = set()\n enemies = [u for u in self.board.units if self.is_enemy(u)]\n if enemies == []:\n raise Board.NoEnemies\n for unit in enemies:\n for diff in self.board.READ_ORDER:\n if isinstance(self.board[unit.pos + diff], Space\n ) or self.pos == unit.pos + diff:\n targets.add(unit.pos + diff)\n return targets\n\n def attack(self, defender):\n if defender is not None:\n defender.hp -= self.ap\n\n\nclass Board:\n READ_ORDER = Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1)\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is\n None):\n continue\n step_map[pos] = steps, prev\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps\n ):\n smallest, first = steps, square.pos\n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass Wall(BoardItem):\n <assignment token>\n\n\nclass Space(BoardItem):\n char = '.'\n\n\nclass Unit(BoardItem):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._hp = type(self).cls_hp\n self.ap = type(self).cls_ap\n\n @property\n def hp(self):\n return self._hp\n\n @hp.setter\n def hp(self, other):\n self._hp = other\n if self._hp <= 0:\n self.board[self.pos] = Space()\n if self.on_death:\n raise self.on_death(repr(self))\n\n def is_enemy(self, other):\n return isinstance(other, Unit) and not isinstance(other, type(self)\n ) and other.hp > 0\n\n def find_defender(self):\n defender = None\n for diff in [self.board[self.pos + diff] for diff in self.board.\n READ_ORDER]:\n if self.is_enemy(diff):\n if not defender or diff.hp < defender.hp:\n defender = diff\n return defender\n\n @classmethod\n def make_unit_class(cls, char, attack=3, hp=200, on_death=None):\n unit_type = 'Elf' if char == 'E' else 'Goblin'\n\n\n class Cls(cls):\n\n def __repr__(self):\n return (\n f'{unit_type}({repr(self.pos)}, attack={self.ap}, hp={self.hp})'\n )\n Cls.char = char\n Cls.cls_ap = attack\n Cls.cls_hp = hp\n Cls.on_death = on_death\n return Cls\n\n def get_targets(self):\n targets = set()\n enemies = [u for u in self.board.units if self.is_enemy(u)]\n if enemies == []:\n raise Board.NoEnemies\n for unit in enemies:\n for diff in self.board.READ_ORDER:\n if isinstance(self.board[unit.pos + diff], Space\n ) or self.pos == unit.pos + diff:\n targets.add(unit.pos + diff)\n return targets\n\n def attack(self, defender):\n if defender is not None:\n defender.hp -= self.ap\n\n\nclass Board:\n READ_ORDER = Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1)\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is\n None):\n continue\n step_map[pos] = steps, prev\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps\n ):\n smallest, first = steps, square.pos\n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass Space(BoardItem):\n char = '.'\n\n\nclass Unit(BoardItem):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._hp = type(self).cls_hp\n self.ap = type(self).cls_ap\n\n @property\n def hp(self):\n return self._hp\n\n @hp.setter\n def hp(self, other):\n self._hp = other\n if self._hp <= 0:\n self.board[self.pos] = Space()\n if self.on_death:\n raise self.on_death(repr(self))\n\n def is_enemy(self, other):\n return isinstance(other, Unit) and not isinstance(other, type(self)\n ) and other.hp > 0\n\n def find_defender(self):\n defender = None\n for diff in [self.board[self.pos + diff] for diff in self.board.\n READ_ORDER]:\n if self.is_enemy(diff):\n if not defender or diff.hp < defender.hp:\n defender = diff\n return defender\n\n @classmethod\n def make_unit_class(cls, char, attack=3, hp=200, on_death=None):\n unit_type = 'Elf' if char == 'E' else 'Goblin'\n\n\n class Cls(cls):\n\n def __repr__(self):\n return (\n f'{unit_type}({repr(self.pos)}, attack={self.ap}, hp={self.hp})'\n )\n Cls.char = char\n Cls.cls_ap = attack\n Cls.cls_hp = hp\n Cls.on_death = on_death\n return Cls\n\n def get_targets(self):\n targets = set()\n enemies = [u for u in self.board.units if self.is_enemy(u)]\n if enemies == []:\n raise Board.NoEnemies\n for unit in enemies:\n for diff in self.board.READ_ORDER:\n if isinstance(self.board[unit.pos + diff], Space\n ) or self.pos == unit.pos + diff:\n targets.add(unit.pos + diff)\n return targets\n\n def attack(self, defender):\n if defender is not None:\n defender.hp -= self.ap\n\n\nclass Board:\n READ_ORDER = Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1)\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is\n None):\n continue\n step_map[pos] = steps, prev\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps\n ):\n smallest, first = steps, square.pos\n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass Space(BoardItem):\n <assignment token>\n\n\nclass Unit(BoardItem):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._hp = type(self).cls_hp\n self.ap = type(self).cls_ap\n\n @property\n def hp(self):\n return self._hp\n\n @hp.setter\n def hp(self, other):\n self._hp = other\n if self._hp <= 0:\n self.board[self.pos] = Space()\n if self.on_death:\n raise self.on_death(repr(self))\n\n def is_enemy(self, other):\n return isinstance(other, Unit) and not isinstance(other, type(self)\n ) and other.hp > 0\n\n def find_defender(self):\n defender = None\n for diff in [self.board[self.pos + diff] for diff in self.board.\n READ_ORDER]:\n if self.is_enemy(diff):\n if not defender or diff.hp < defender.hp:\n defender = diff\n return defender\n\n @classmethod\n def make_unit_class(cls, char, attack=3, hp=200, on_death=None):\n unit_type = 'Elf' if char == 'E' else 'Goblin'\n\n\n class Cls(cls):\n\n def __repr__(self):\n return (\n f'{unit_type}({repr(self.pos)}, attack={self.ap}, hp={self.hp})'\n )\n Cls.char = char\n Cls.cls_ap = attack\n Cls.cls_hp = hp\n Cls.on_death = on_death\n return Cls\n\n def get_targets(self):\n targets = set()\n enemies = [u for u in self.board.units if self.is_enemy(u)]\n if enemies == []:\n raise Board.NoEnemies\n for unit in enemies:\n for diff in self.board.READ_ORDER:\n if isinstance(self.board[unit.pos + diff], Space\n ) or self.pos == unit.pos + diff:\n targets.add(unit.pos + diff)\n return targets\n\n def attack(self, defender):\n if defender is not None:\n defender.hp -= self.ap\n\n\nclass Board:\n READ_ORDER = Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1)\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is\n None):\n continue\n step_map[pos] = steps, prev\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps\n ):\n smallest, first = steps, square.pos\n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Unit(BoardItem):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._hp = type(self).cls_hp\n self.ap = type(self).cls_ap\n\n @property\n def hp(self):\n return self._hp\n\n @hp.setter\n def hp(self, other):\n self._hp = other\n if self._hp <= 0:\n self.board[self.pos] = Space()\n if self.on_death:\n raise self.on_death(repr(self))\n\n def is_enemy(self, other):\n return isinstance(other, Unit) and not isinstance(other, type(self)\n ) and other.hp > 0\n\n def find_defender(self):\n defender = None\n for diff in [self.board[self.pos + diff] for diff in self.board.\n READ_ORDER]:\n if self.is_enemy(diff):\n if not defender or diff.hp < defender.hp:\n defender = diff\n return defender\n\n @classmethod\n def make_unit_class(cls, char, attack=3, hp=200, on_death=None):\n unit_type = 'Elf' if char == 'E' else 'Goblin'\n\n\n class Cls(cls):\n\n def __repr__(self):\n return (\n f'{unit_type}({repr(self.pos)}, attack={self.ap}, hp={self.hp})'\n )\n Cls.char = char\n Cls.cls_ap = attack\n Cls.cls_hp = hp\n Cls.on_death = on_death\n return Cls\n\n def get_targets(self):\n targets = set()\n enemies = [u for u in self.board.units if self.is_enemy(u)]\n if enemies == []:\n raise Board.NoEnemies\n for unit in enemies:\n for diff in self.board.READ_ORDER:\n if isinstance(self.board[unit.pos + diff], Space\n ) or self.pos == unit.pos + diff:\n targets.add(unit.pos + diff)\n return targets\n\n def attack(self, defender):\n if defender is not None:\n defender.hp -= self.ap\n\n\nclass Board:\n READ_ORDER = Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1)\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is\n None):\n continue\n step_map[pos] = steps, prev\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps\n ):\n smallest, first = steps, square.pos\n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Unit(BoardItem):\n <function token>\n\n @property\n def hp(self):\n return self._hp\n\n @hp.setter\n def hp(self, other):\n self._hp = other\n if self._hp <= 0:\n self.board[self.pos] = Space()\n if self.on_death:\n raise self.on_death(repr(self))\n\n def is_enemy(self, other):\n return isinstance(other, Unit) and not isinstance(other, type(self)\n ) and other.hp > 0\n\n def find_defender(self):\n defender = None\n for diff in [self.board[self.pos + diff] for diff in self.board.\n READ_ORDER]:\n if self.is_enemy(diff):\n if not defender or diff.hp < defender.hp:\n defender = diff\n return defender\n\n @classmethod\n def make_unit_class(cls, char, attack=3, hp=200, on_death=None):\n unit_type = 'Elf' if char == 'E' else 'Goblin'\n\n\n class Cls(cls):\n\n def __repr__(self):\n return (\n f'{unit_type}({repr(self.pos)}, attack={self.ap}, hp={self.hp})'\n )\n Cls.char = char\n Cls.cls_ap = attack\n Cls.cls_hp = hp\n Cls.on_death = on_death\n return Cls\n\n def get_targets(self):\n targets = set()\n enemies = [u for u in self.board.units if self.is_enemy(u)]\n if enemies == []:\n raise Board.NoEnemies\n for unit in enemies:\n for diff in self.board.READ_ORDER:\n if isinstance(self.board[unit.pos + diff], Space\n ) or self.pos == unit.pos + diff:\n targets.add(unit.pos + diff)\n return targets\n\n def attack(self, defender):\n if defender is not None:\n defender.hp -= self.ap\n\n\nclass Board:\n READ_ORDER = Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1)\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is\n None):\n continue\n step_map[pos] = steps, prev\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps\n ):\n smallest, first = steps, square.pos\n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Unit(BoardItem):\n <function token>\n\n @property\n def hp(self):\n return self._hp\n\n @hp.setter\n def hp(self, other):\n self._hp = other\n if self._hp <= 0:\n self.board[self.pos] = Space()\n if self.on_death:\n raise self.on_death(repr(self))\n\n def is_enemy(self, other):\n return isinstance(other, Unit) and not isinstance(other, type(self)\n ) and other.hp > 0\n\n def find_defender(self):\n defender = None\n for diff in [self.board[self.pos + diff] for diff in self.board.\n READ_ORDER]:\n if self.is_enemy(diff):\n if not defender or diff.hp < defender.hp:\n defender = diff\n return defender\n\n @classmethod\n def make_unit_class(cls, char, attack=3, hp=200, on_death=None):\n unit_type = 'Elf' if char == 'E' else 'Goblin'\n\n\n class Cls(cls):\n\n def __repr__(self):\n return (\n f'{unit_type}({repr(self.pos)}, attack={self.ap}, hp={self.hp})'\n )\n Cls.char = char\n Cls.cls_ap = attack\n Cls.cls_hp = hp\n Cls.on_death = on_death\n return Cls\n\n def get_targets(self):\n targets = set()\n enemies = [u for u in self.board.units if self.is_enemy(u)]\n if enemies == []:\n raise Board.NoEnemies\n for unit in enemies:\n for diff in self.board.READ_ORDER:\n if isinstance(self.board[unit.pos + diff], Space\n ) or self.pos == unit.pos + diff:\n targets.add(unit.pos + diff)\n return targets\n <function token>\n\n\nclass Board:\n READ_ORDER = Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1)\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is\n None):\n continue\n step_map[pos] = steps, prev\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps\n ):\n smallest, first = steps, square.pos\n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Unit(BoardItem):\n <function token>\n\n @property\n def hp(self):\n return self._hp\n <function token>\n\n def is_enemy(self, other):\n return isinstance(other, Unit) and not isinstance(other, type(self)\n ) and other.hp > 0\n\n def find_defender(self):\n defender = None\n for diff in [self.board[self.pos + diff] for diff in self.board.\n READ_ORDER]:\n if self.is_enemy(diff):\n if not defender or diff.hp < defender.hp:\n defender = diff\n return defender\n\n @classmethod\n def make_unit_class(cls, char, attack=3, hp=200, on_death=None):\n unit_type = 'Elf' if char == 'E' else 'Goblin'\n\n\n class Cls(cls):\n\n def __repr__(self):\n return (\n f'{unit_type}({repr(self.pos)}, attack={self.ap}, hp={self.hp})'\n )\n Cls.char = char\n Cls.cls_ap = attack\n Cls.cls_hp = hp\n Cls.on_death = on_death\n return Cls\n\n def get_targets(self):\n targets = set()\n enemies = [u for u in self.board.units if self.is_enemy(u)]\n if enemies == []:\n raise Board.NoEnemies\n for unit in enemies:\n for diff in self.board.READ_ORDER:\n if isinstance(self.board[unit.pos + diff], Space\n ) or self.pos == unit.pos + diff:\n targets.add(unit.pos + diff)\n return targets\n <function token>\n\n\nclass Board:\n READ_ORDER = Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1)\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is\n None):\n continue\n step_map[pos] = steps, prev\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps\n ):\n smallest, first = steps, square.pos\n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Unit(BoardItem):\n <function token>\n <function token>\n <function token>\n\n def is_enemy(self, other):\n return isinstance(other, Unit) and not isinstance(other, type(self)\n ) and other.hp > 0\n\n def find_defender(self):\n defender = None\n for diff in [self.board[self.pos + diff] for diff in self.board.\n READ_ORDER]:\n if self.is_enemy(diff):\n if not defender or diff.hp < defender.hp:\n defender = diff\n return defender\n\n @classmethod\n def make_unit_class(cls, char, attack=3, hp=200, on_death=None):\n unit_type = 'Elf' if char == 'E' else 'Goblin'\n\n\n class Cls(cls):\n\n def __repr__(self):\n return (\n f'{unit_type}({repr(self.pos)}, attack={self.ap}, hp={self.hp})'\n )\n Cls.char = char\n Cls.cls_ap = attack\n Cls.cls_hp = hp\n Cls.on_death = on_death\n return Cls\n\n def get_targets(self):\n targets = set()\n enemies = [u for u in self.board.units if self.is_enemy(u)]\n if enemies == []:\n raise Board.NoEnemies\n for unit in enemies:\n for diff in self.board.READ_ORDER:\n if isinstance(self.board[unit.pos + diff], Space\n ) or self.pos == unit.pos + diff:\n targets.add(unit.pos + diff)\n return targets\n <function token>\n\n\nclass Board:\n READ_ORDER = Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1)\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is\n None):\n continue\n step_map[pos] = steps, prev\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps\n ):\n smallest, first = steps, square.pos\n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Unit(BoardItem):\n <function token>\n <function token>\n <function token>\n\n def is_enemy(self, other):\n return isinstance(other, Unit) and not isinstance(other, type(self)\n ) and other.hp > 0\n\n def find_defender(self):\n defender = None\n for diff in [self.board[self.pos + diff] for diff in self.board.\n READ_ORDER]:\n if self.is_enemy(diff):\n if not defender or diff.hp < defender.hp:\n defender = diff\n return defender\n\n @classmethod\n def make_unit_class(cls, char, attack=3, hp=200, on_death=None):\n unit_type = 'Elf' if char == 'E' else 'Goblin'\n\n\n class Cls(cls):\n\n def __repr__(self):\n return (\n f'{unit_type}({repr(self.pos)}, attack={self.ap}, hp={self.hp})'\n )\n Cls.char = char\n Cls.cls_ap = attack\n Cls.cls_hp = hp\n Cls.on_death = on_death\n return Cls\n <function token>\n <function token>\n\n\nclass Board:\n READ_ORDER = Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1)\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is\n None):\n continue\n step_map[pos] = steps, prev\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps\n ):\n smallest, first = steps, square.pos\n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Unit(BoardItem):\n <function token>\n <function token>\n <function token>\n <function token>\n\n def find_defender(self):\n defender = None\n for diff in [self.board[self.pos + diff] for diff in self.board.\n READ_ORDER]:\n if self.is_enemy(diff):\n if not defender or diff.hp < defender.hp:\n defender = diff\n return defender\n\n @classmethod\n def make_unit_class(cls, char, attack=3, hp=200, on_death=None):\n unit_type = 'Elf' if char == 'E' else 'Goblin'\n\n\n class Cls(cls):\n\n def __repr__(self):\n return (\n f'{unit_type}({repr(self.pos)}, attack={self.ap}, hp={self.hp})'\n )\n Cls.char = char\n Cls.cls_ap = attack\n Cls.cls_hp = hp\n Cls.on_death = on_death\n return Cls\n <function token>\n <function token>\n\n\nclass Board:\n READ_ORDER = Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1)\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is\n None):\n continue\n step_map[pos] = steps, prev\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps\n ):\n smallest, first = steps, square.pos\n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Unit(BoardItem):\n <function token>\n <function token>\n <function token>\n <function token>\n\n def find_defender(self):\n defender = None\n for diff in [self.board[self.pos + diff] for diff in self.board.\n READ_ORDER]:\n if self.is_enemy(diff):\n if not defender or diff.hp < defender.hp:\n defender = diff\n return defender\n <function token>\n <function token>\n <function token>\n\n\nclass Board:\n READ_ORDER = Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1)\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is\n None):\n continue\n step_map[pos] = steps, prev\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps\n ):\n smallest, first = steps, square.pos\n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Unit(BoardItem):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass Board:\n READ_ORDER = Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1)\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is\n None):\n continue\n step_map[pos] = steps, prev\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps\n ):\n smallest, first = steps, square.pos\n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Board:\n READ_ORDER = Point(0, -1), Point(-1, 0), Point(1, 0), Point(0, 1)\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is\n None):\n continue\n step_map[pos] = steps, prev\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps\n ):\n smallest, first = steps, square.pos\n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Board:\n <assignment token>\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n\n def __setitem__(self, point, value):\n if not isinstance(point, Point):\n return NotImplemented\n elif not isinstance(value, BoardItem):\n return NotImplemented\n while point.y >= len(self._rows):\n self._rows.append([])\n while point.x >= len(self._rows[point.y]):\n self._rows[point.y].append(None)\n self._rows[point.y][point.x] = value\n value.board = self\n value.pos = point\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is\n None):\n continue\n step_map[pos] = steps, prev\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps\n ):\n smallest, first = steps, square.pos\n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Board:\n <assignment token>\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n <function token>\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n\n def find_move(self, attacker, targets):\n if attacker.pos in targets:\n return None\n queue = [(0, attacker.pos, None)]\n step_map = {}\n while queue:\n steps, pos, prev = queue.pop(0)\n if pos in step_map or not (isinstance(self[pos], Space) or prev is\n None):\n continue\n step_map[pos] = steps, prev\n for diff in self.READ_ORDER:\n queue.append((steps + 1, pos + diff, pos))\n smallest, first = None, None\n for square in [u for row in self for u in row]:\n steps, pos = step_map.get(square.pos, (smallest, first))\n if square.pos in targets and (smallest is None or smallest > steps\n ):\n smallest, first = steps, square.pos\n if smallest is None:\n return attacker.pos\n prev = first\n while smallest is not None and smallest > 1:\n first = prev\n smallest, prev = step_map[first]\n return first or attacker.pos\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Board:\n <assignment token>\n\n def __init__(self, power=3):\n self._rows = []\n self.round = 0\n self.power = power\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n <function token>\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n <function token>\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Board:\n <assignment token>\n <function token>\n\n\n class NoEnemies(Exception):\n pass\n\n @classmethod\n def make_board(cls, lines, mapping, power=3):\n board = cls(power)\n for y, line in enumerate(lines.splitlines()):\n for x, char in enumerate(list(line)):\n board[Point(x, y)] = mapping[char]()\n board.unit_order = board.units\n board.attacker = board.unit_order.pop(0)\n return board\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n <function token>\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n <function token>\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Board:\n <assignment token>\n <function token>\n\n\n class NoEnemies(Exception):\n pass\n <function token>\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n <function token>\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n <function token>\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n\n def play_round(self):\n for attacker in self.units:\n if attacker.hp <= 0:\n continue\n targets = attacker.get_targets()\n move = self.find_move(attacker, targets)\n self[attacker.pos], self[move] = self[move], self[attacker.pos]\n defender = attacker.find_defender()\n attacker.attack(defender)\n self.round += 1\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Board:\n <assignment token>\n <function token>\n\n\n class NoEnemies(Exception):\n pass\n <function token>\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n <function token>\n\n def __iter__(self):\n return iter(self._rows)\n\n @property\n def units(self):\n return [u for row in self for u in row if isinstance(u, Unit)]\n <function token>\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n <function token>\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Board:\n <assignment token>\n <function token>\n\n\n class NoEnemies(Exception):\n pass\n <function token>\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n <function token>\n\n def __iter__(self):\n return iter(self._rows)\n <function token>\n <function token>\n\n def __repr__(self):\n representation = [f'Round {self.round}/{self.power}']\n representation.extend(''.join(str(u) for u in row) for row in self)\n representation.extend(repr(u) for u in self.units)\n return '\\n'.join(representation)\n <function token>\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Board:\n <assignment token>\n <function token>\n\n\n class NoEnemies(Exception):\n pass\n <function token>\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n <function token>\n\n def __iter__(self):\n return iter(self._rows)\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Board:\n <assignment token>\n <function token>\n\n\n class NoEnemies(Exception):\n pass\n <function token>\n\n def __getitem__(self, pos):\n if isinstance(pos, Point):\n return self._rows[pos.y][pos.x]\n return NotImplemented\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Board:\n <assignment token>\n <function token>\n\n\n class NoEnemies(Exception):\n pass\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<function token>\n<function token>\n<assignment token>\n<code token>\n" ]
false
98,716
14bc43d423ee5003079eedd030a83db13a44850a
# encoding: utf-8 """ @author: lileilei @file: htmltestreport.py @time: 2017/6/5 17:04 """ import os titles = '接口测试' def title(titles): title = '''<!DOCTYPE html> <html> <head> <title>%s</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- 引入 Bootstrap --> <link href="https://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"> <!-- HTML5 Shim 和 Respond.js 用于让 IE8 支持 HTML5元素和媒体查询 --> <!-- 注意: 如果通过 file:// 引入 Respond.js 文件,则该文件无法起效果 --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script> <![endif]--> <style type="text/css"> .hidden-detail,.hidden-tr{ display:none; } </style> </head> <body> ''' % (titles) return title connent = ''' <div class='col-md-5 col-md-offset-5' style="margin-left: 2%;margin-top: -16px;"> <h1>FXTest测试平台接口测试的结果</h1>''' def time(starttime, endtime, passge, fail, excepts, yuqi, weizhi, maxs, mins, pingluns): beijing = ''' <table class="table table-hover table-condensed"> <tbody> <tr> <td><strong>开始时间:</strong> %s</td> </tr> <td><strong>结束时间:</strong> %s</td></tr> <td><strong>耗时:</strong> %s</td></tr> <td> <strong>结果:</strong> <span >通过: <strong >%s</strong> 失败: <strong >%s</strong> Exception: <strong >%s</strong> 预期不存在: <strong >%s</strong> 未知错误: <strong >%s</strong> </td> </tr> <tr> <td> <strong>单接口耗时最大值:</strong>%s s, <strong>最小值:</strong> %s s, <strong>平均耗时:</strong> %s s </td> </tr> </tbody></table> </div> ''' % ( starttime, endtime, (endtime - starttime), passge, fail, excepts, yuqi, weizhi, maxs, mins, pingluns) return beijing shanghai = '''<div class="row " style="margin:35px"> <div style=' margin-top: 18%;' > <div class="btn-group" role="group" aria-label="..."> <button type="button" id="check-all" class="btn btn-primary">所有用例</button> <button type="button" id="check-success" class="btn btn-success">成功用例</button> <button type="button" id="check-danger" class="btn btn-danger">失败用例</button> <button type="button" id="check-warning" class="btn btn-warning">错误用例</button> <button type="button" id="check-except" class="btn btn-defult">异常用例</button> </div> <div class="btn-group" role="group" aria-label="..."> </div> <table class="table table-hover table-condensed table-bordered" style="word-wrap:break-word; word-break:break-all; margin-top: 7px;"> <tr > <td ><strong>用例ID&nbsp;</strong></td> <td><strong>项目</strong></td> <td><strong>url</strong></td> <td><strong>请求方式</strong></td> <td><strong>参数</strong></td> <td><strong>headers</strong></td> <td><strong>预期</strong></td> <td><strong>实际返回</strong></td> <td><strong>结果</strong></td> </tr> ''' def passfail(tend): if tend == 'pass': htl = ' <td bgcolor="green">pass</td>' elif tend == 'fail': htl = ' <td bgcolor="fail">fail</td>' elif tend == 'Exception': htl = '<td bgcolor="#8b0000">Exception</td>' elif tend == '预期不存在': htl = '<td bgcolor="#8b0000">预期不存在</td>' elif tend == '未知错误': htl = '<td bgcolor="#8b0000">未知错误</td>' elif tend == '测试环境不存在': htl = '<td bgcolor="#8b0000">测试环境不存在</td>' else: htl = '<td bgcolor="#8b0000">查看日志</td>' return htl def ceshixiangqing(res_id, id, name, coneent, url, meth, yuqi, json, relust, headers): xiangqing = ''' <tr class="case-tr %s"> <td>%s</td> <td>%s</td> <td>%s</td> <td>%s</td> <td>%s</td> <td>%s</td> <td>%s</td> <td>%s</td> %s </tr> ''' % (res_id, id, name, coneent, url, meth, headers, yuqi, json, (passfail(relust))) return xiangqing weibu = '''</div></div></table><script src="https://code.jquery.com/jquery.js"></script> <script src="https://cdn.bootcss.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <script type="text/javascript"> $("#check-danger").click(function(e){ $(".case-tr").removeClass("hidden-tr"); $(".success").addClass("hidden-tr"); $(".warning").addClass("hidden-tr"); $(".error").addClass("hidden-tr"); }); $("#check-warning").click(function(e){ $(".case-tr").removeClass("hidden-tr"); $(".success").addClass("hidden-tr"); $(".danger").addClass("hidden-tr"); $(".error").addClass("hidden-tr"); }); $("#check-success").click(function(e){ $(".case-tr").removeClass("hidden-tr"); $(".warning").addClass("hidden-tr"); $(".danger").addClass("hidden-tr"); $(".error").addClass("hidden-tr"); }); $("#check-except").click(function(e){ $(".case-tr").removeClass("hidden-tr"); $(".warning").addClass("hidden-tr"); $(".danger").addClass("hidden-tr"); $(".success").addClass("hidden-tr"); }); $("#check-all").click(function(e){ $(".case-tr").removeClass("hidden-tr"); }); </script> </body> </html>''' def relust(titles, starttime, endtime, passge, fail, id: list, name: list, headers: list, coneent: list, url: list, meth: list, yuqi: list, json: list, relust: list, excepts, yuqis, weizhi, maxs, mins, pingluns): if type(name) is list: relus = ' ' for i in range(len(name)): if relust[i] == "pass": clazz = "success" elif relust[i] == "fail": clazz = "warning" elif relust[i] == "未知错误": clazz = "danger" else: clazz = 'error' relus += ( ceshixiangqing(clazz, id[i], name[i], coneent=coneent[i], url=url[i], headers=headers[i], meth=meth[i], yuqi=yuqi[i], json=json[i], relust=relust[i])) text = title(titles) + connent + time(starttime, endtime, passge, fail, excepts, yuqis, weizhi, maxs, mins, pingluns) + shanghai + relus + weibu else: text = title(titles) + connent + time(starttime, endtime, passge, fail, excepts, yuqis, weizhi, maxs, mins, pingluns) + shanghai + ceshixiangqing(id=id, name=name, headers=headers, coneent=coneent, url=url, meth=meth, yuqi=int(yuqi), json=json, relust=relust) + weibu return text def createHtml(filepath, titles, starttime, endtime, passge, fail, id, name, headers, coneent, url, meth, yuqi, json, relusts, excepts, yuqis, weizhi, maxs, mins, pingluns): texts = relust(titles=titles, starttime=starttime, endtime=endtime, passge=passge, fail=fail, id=id, name=name, headers=headers, coneent=coneent, url=url, meth=meth, yuqi=yuqi, json=json, relust=relusts, excepts=excepts, yuqis=yuqis, weizhi=weizhi, maxs=maxs, mins=mins, pingluns=pingluns) with open(filepath, 'wb') as f: f.write(texts.encode())
[ "# encoding: utf-8\n\"\"\"\n@author: lileilei\n@file: htmltestreport.py\n@time: 2017/6/5 17:04\n\"\"\"\nimport os\n\ntitles = '接口测试'\n\n\ndef title(titles):\n title = '''<!DOCTYPE html>\n<html>\n<head>\n\t<title>%s</title>\n\t<meta charset=\"UTF-8\">\n\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <!-- 引入 Bootstrap -->\n <link href=\"https://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.min.css\" rel=\"stylesheet\">\n <!-- HTML5 Shim 和 Respond.js 用于让 IE8 支持 HTML5元素和媒体查询 -->\n <!-- 注意: 如果通过 file:// 引入 Respond.js 文件,则该文件无法起效果 -->\n <!--[if lt IE 9]>\n <script src=\"https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js\"></script>\n <script src=\"https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js\"></script>\n <![endif]-->\n <style type=\"text/css\">\n .hidden-detail,.hidden-tr{\n display:none;\n }\n </style>\n</head>\n<body>\n\t''' % (titles)\n return title\n\n\nconnent = '''\n<div class='col-md-5 col-md-offset-5' style=\"margin-left: 2%;margin-top: -16px;\">\n<h1>FXTest测试平台接口测试的结果</h1>'''\n\n\ndef time(starttime, endtime, passge, fail, excepts, yuqi, weizhi, maxs, mins, pingluns):\n beijing = '''\n <table class=\"table table-hover table-condensed\">\n <tbody>\n <tr>\n\t\t<td><strong>开始时间:</strong> %s</td>\n\t\t</tr>\n\t\t<td><strong>结束时间:</strong> %s</td></tr>\n\t\t<td><strong>耗时:</strong> %s</td></tr>\n\t\t<td>\n\t\t\t<strong>结果:</strong>\n\t\t\t<span >通过: \n\t\t\t<strong >%s</strong>\n\t\t\t失败: \n\t\t\t<strong >%s</strong>\n\t\t\tException: \n\t\t\t<strong >%s</strong>\n\t\t\t预期不存在: \n\t\t\t<strong >%s</strong>\n\t\t\t未知错误: \n\t\t\t<strong >%s</strong>\n\t\t\t</td> \n\t\t\t </tr>\n\t\t\t <tr>\n\t\t\t <td>\n\t\t\t <strong>单接口耗时最大值:</strong>%s s,\n\t\t\t <strong>最小值:</strong> %s s,\n\t\t\t <strong>平均耗时:</strong> %s s\n\t\t\t </td>\n\t\t\t </tr> \n\t\t\t </tbody></table>\n\t\t\t </div> ''' % (\n starttime, endtime, (endtime - starttime), passge, fail, excepts, yuqi, weizhi, maxs, mins, pingluns)\n return beijing\n\n\nshanghai = '''<div class=\"row \" style=\"margin:35px\">\n <div style=' margin-top: 18%;' >\n <div class=\"btn-group\" role=\"group\" aria-label=\"...\">\n <button type=\"button\" id=\"check-all\" class=\"btn btn-primary\">所有用例</button>\n <button type=\"button\" id=\"check-success\" class=\"btn btn-success\">成功用例</button>\n <button type=\"button\" id=\"check-danger\" class=\"btn btn-danger\">失败用例</button>\n <button type=\"button\" id=\"check-warning\" class=\"btn btn-warning\">错误用例</button>\n <button type=\"button\" id=\"check-except\" class=\"btn btn-defult\">异常用例</button>\n </div>\n <div class=\"btn-group\" role=\"group\" aria-label=\"...\">\n </div>\n <table class=\"table table-hover table-condensed table-bordered\" style=\"word-wrap:break-word; word-break:break-all; margin-top: 7px;\">\n\t\t<tr >\n <td ><strong>用例ID&nbsp;</strong></td>\n <td><strong>项目</strong></td>\n <td><strong>url</strong></td>\n <td><strong>请求方式</strong></td>\n <td><strong>参数</strong></td>\n <td><strong>headers</strong></td>\n <td><strong>预期</strong></td>\n <td><strong>实际返回</strong></td> \n <td><strong>结果</strong></td>\n </tr>\n '''\n\n\ndef passfail(tend):\n if tend == 'pass':\n htl = ' <td bgcolor=\"green\">pass</td>'\n elif tend == 'fail':\n htl = ' <td bgcolor=\"fail\">fail</td>'\n elif tend == 'Exception':\n htl = '<td bgcolor=\"#8b0000\">Exception</td>'\n elif tend == '预期不存在':\n htl = '<td bgcolor=\"#8b0000\">预期不存在</td>'\n elif tend == '未知错误':\n htl = '<td bgcolor=\"#8b0000\">未知错误</td>'\n elif tend == '测试环境不存在':\n htl = '<td bgcolor=\"#8b0000\">测试环境不存在</td>'\n else:\n htl = '<td bgcolor=\"#8b0000\">查看日志</td>'\n return htl\n\n\ndef ceshixiangqing(res_id, id, name, coneent, url, meth, yuqi, json, relust, headers):\n xiangqing = '''\n <tr class=\"case-tr %s\">\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n %s\n </tr>\n ''' % (res_id, id, name, coneent, url, meth, headers, yuqi, json, (passfail(relust)))\n return xiangqing\n\n\nweibu = '''</div></div></table><script src=\"https://code.jquery.com/jquery.js\"></script>\n<script src=\"https://cdn.bootcss.com/bootstrap/3.3.6/js/bootstrap.min.js\"></script>\n<script type=\"text/javascript\">\n\t$(\"#check-danger\").click(function(e){\n\t $(\".case-tr\").removeClass(\"hidden-tr\");\n $(\".success\").addClass(\"hidden-tr\");\n $(\".warning\").addClass(\"hidden-tr\");\n $(\".error\").addClass(\"hidden-tr\");\n\t});\n\t$(\"#check-warning\").click(function(e){\n\t\t $(\".case-tr\").removeClass(\"hidden-tr\");\n $(\".success\").addClass(\"hidden-tr\");\n $(\".danger\").addClass(\"hidden-tr\");\n $(\".error\").addClass(\"hidden-tr\");\n\t});\n\t$(\"#check-success\").click(function(e){\n\t\t $(\".case-tr\").removeClass(\"hidden-tr\");\n $(\".warning\").addClass(\"hidden-tr\");\n $(\".danger\").addClass(\"hidden-tr\");\n $(\".error\").addClass(\"hidden-tr\");\n\t});\n\t$(\"#check-except\").click(function(e){\n\t\t $(\".case-tr\").removeClass(\"hidden-tr\");\n $(\".warning\").addClass(\"hidden-tr\");\n $(\".danger\").addClass(\"hidden-tr\");\n $(\".success\").addClass(\"hidden-tr\");\n\t});\n\t$(\"#check-all\").click(function(e){\n\t $(\".case-tr\").removeClass(\"hidden-tr\");\n\t});\n</script>\n</body>\n</html>'''\n\n\ndef relust(titles, starttime, endtime, passge, fail, id: list, name: list, headers: list, coneent: list, url: list,\n meth: list, yuqi: list, json: list, relust: list, excepts, yuqis, weizhi, maxs, mins, pingluns):\n if type(name) is list:\n relus = ' '\n for i in range(len(name)):\n if relust[i] == \"pass\":\n clazz = \"success\"\n elif relust[i] == \"fail\":\n clazz = \"warning\"\n elif relust[i] == \"未知错误\":\n clazz = \"danger\"\n else:\n clazz = 'error'\n relus += (\n ceshixiangqing(clazz, id[i], name[i], coneent=coneent[i], url=url[i], headers=headers[i], meth=meth[i],\n yuqi=yuqi[i], json=json[i], relust=relust[i]))\n text = title(titles) + connent + time(starttime, endtime, passge, fail, excepts, yuqis, weizhi, maxs, mins,\n pingluns) + shanghai + relus + weibu\n else:\n text = title(titles) + connent + time(starttime, endtime, passge, fail, excepts, yuqis, weizhi, maxs, mins,\n pingluns) + shanghai + ceshixiangqing(id=id, name=name, headers=headers,\n coneent=coneent, url=url, meth=meth,\n yuqi=int(yuqi), json=json,\n relust=relust) + weibu\n return text\n\n\ndef createHtml(filepath, titles, starttime, endtime, passge, fail, id, name, headers, coneent, url, meth, yuqi, json,\n relusts, excepts, yuqis, weizhi, maxs, mins, pingluns):\n texts = relust(titles=titles, starttime=starttime, endtime=endtime, passge=passge, fail=fail, id=id, name=name,\n headers=headers, coneent=coneent,\n url=url, meth=meth, yuqi=yuqi, json=json, relust=relusts, excepts=excepts, yuqis=yuqis,\n weizhi=weizhi, maxs=maxs, mins=mins, pingluns=pingluns)\n with open(filepath, 'wb') as f:\n f.write(texts.encode())\n", "<docstring token>\nimport os\ntitles = '接口测试'\n\n\ndef title(titles):\n title = (\n \"\"\"<!DOCTYPE html>\n<html>\n<head>\n\t<title>%s</title>\n\t<meta charset=\"UTF-8\">\n\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <!-- 引入 Bootstrap -->\n <link href=\"https://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.min.css\" rel=\"stylesheet\">\n <!-- HTML5 Shim 和 Respond.js 用于让 IE8 支持 HTML5元素和媒体查询 -->\n <!-- 注意: 如果通过 file:// 引入 Respond.js 文件,则该文件无法起效果 -->\n <!--[if lt IE 9]>\n <script src=\"https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js\"></script>\n <script src=\"https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js\"></script>\n <![endif]-->\n <style type=\"text/css\">\n .hidden-detail,.hidden-tr{\n display:none;\n }\n </style>\n</head>\n<body>\n\t\"\"\"\n % titles)\n return title\n\n\nconnent = \"\"\"\n<div class='col-md-5 col-md-offset-5' style=\"margin-left: 2%;margin-top: -16px;\">\n<h1>FXTest测试平台接口测试的结果</h1>\"\"\"\n\n\ndef time(starttime, endtime, passge, fail, excepts, yuqi, weizhi, maxs,\n mins, pingluns):\n beijing = (\n \"\"\"\n <table class=\"table table-hover table-condensed\">\n <tbody>\n <tr>\n\t\t<td><strong>开始时间:</strong> %s</td>\n\t\t</tr>\n\t\t<td><strong>结束时间:</strong> %s</td></tr>\n\t\t<td><strong>耗时:</strong> %s</td></tr>\n\t\t<td>\n\t\t\t<strong>结果:</strong>\n\t\t\t<span >通过: \n\t\t\t<strong >%s</strong>\n\t\t\t失败: \n\t\t\t<strong >%s</strong>\n\t\t\tException: \n\t\t\t<strong >%s</strong>\n\t\t\t预期不存在: \n\t\t\t<strong >%s</strong>\n\t\t\t未知错误: \n\t\t\t<strong >%s</strong>\n\t\t\t</td> \n\t\t\t </tr>\n\t\t\t <tr>\n\t\t\t <td>\n\t\t\t <strong>单接口耗时最大值:</strong>%s s,\n\t\t\t <strong>最小值:</strong> %s s,\n\t\t\t <strong>平均耗时:</strong> %s s\n\t\t\t </td>\n\t\t\t </tr> \n\t\t\t </tbody></table>\n\t\t\t </div> \"\"\"\n % (starttime, endtime, endtime - starttime, passge, fail, excepts,\n yuqi, weizhi, maxs, mins, pingluns))\n return beijing\n\n\nshanghai = \"\"\"<div class=\"row \" style=\"margin:35px\">\n <div style=' margin-top: 18%;' >\n <div class=\"btn-group\" role=\"group\" aria-label=\"...\">\n <button type=\"button\" id=\"check-all\" class=\"btn btn-primary\">所有用例</button>\n <button type=\"button\" id=\"check-success\" class=\"btn btn-success\">成功用例</button>\n <button type=\"button\" id=\"check-danger\" class=\"btn btn-danger\">失败用例</button>\n <button type=\"button\" id=\"check-warning\" class=\"btn btn-warning\">错误用例</button>\n <button type=\"button\" id=\"check-except\" class=\"btn btn-defult\">异常用例</button>\n </div>\n <div class=\"btn-group\" role=\"group\" aria-label=\"...\">\n </div>\n <table class=\"table table-hover table-condensed table-bordered\" style=\"word-wrap:break-word; word-break:break-all; margin-top: 7px;\">\n\t\t<tr >\n <td ><strong>用例ID&nbsp;</strong></td>\n <td><strong>项目</strong></td>\n <td><strong>url</strong></td>\n <td><strong>请求方式</strong></td>\n <td><strong>参数</strong></td>\n <td><strong>headers</strong></td>\n <td><strong>预期</strong></td>\n <td><strong>实际返回</strong></td> \n <td><strong>结果</strong></td>\n </tr>\n \"\"\"\n\n\ndef passfail(tend):\n if tend == 'pass':\n htl = ' <td bgcolor=\"green\">pass</td>'\n elif tend == 'fail':\n htl = ' <td bgcolor=\"fail\">fail</td>'\n elif tend == 'Exception':\n htl = '<td bgcolor=\"#8b0000\">Exception</td>'\n elif tend == '预期不存在':\n htl = '<td bgcolor=\"#8b0000\">预期不存在</td>'\n elif tend == '未知错误':\n htl = '<td bgcolor=\"#8b0000\">未知错误</td>'\n elif tend == '测试环境不存在':\n htl = '<td bgcolor=\"#8b0000\">测试环境不存在</td>'\n else:\n htl = '<td bgcolor=\"#8b0000\">查看日志</td>'\n return htl\n\n\ndef ceshixiangqing(res_id, id, name, coneent, url, meth, yuqi, json, relust,\n headers):\n xiangqing = (\n \"\"\"\n <tr class=\"case-tr %s\">\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n %s\n </tr>\n \"\"\"\n % (res_id, id, name, coneent, url, meth, headers, yuqi, json,\n passfail(relust)))\n return xiangqing\n\n\nweibu = \"\"\"</div></div></table><script src=\"https://code.jquery.com/jquery.js\"></script>\n<script src=\"https://cdn.bootcss.com/bootstrap/3.3.6/js/bootstrap.min.js\"></script>\n<script type=\"text/javascript\">\n\t$(\"#check-danger\").click(function(e){\n\t $(\".case-tr\").removeClass(\"hidden-tr\");\n $(\".success\").addClass(\"hidden-tr\");\n $(\".warning\").addClass(\"hidden-tr\");\n $(\".error\").addClass(\"hidden-tr\");\n\t});\n\t$(\"#check-warning\").click(function(e){\n\t\t $(\".case-tr\").removeClass(\"hidden-tr\");\n $(\".success\").addClass(\"hidden-tr\");\n $(\".danger\").addClass(\"hidden-tr\");\n $(\".error\").addClass(\"hidden-tr\");\n\t});\n\t$(\"#check-success\").click(function(e){\n\t\t $(\".case-tr\").removeClass(\"hidden-tr\");\n $(\".warning\").addClass(\"hidden-tr\");\n $(\".danger\").addClass(\"hidden-tr\");\n $(\".error\").addClass(\"hidden-tr\");\n\t});\n\t$(\"#check-except\").click(function(e){\n\t\t $(\".case-tr\").removeClass(\"hidden-tr\");\n $(\".warning\").addClass(\"hidden-tr\");\n $(\".danger\").addClass(\"hidden-tr\");\n $(\".success\").addClass(\"hidden-tr\");\n\t});\n\t$(\"#check-all\").click(function(e){\n\t $(\".case-tr\").removeClass(\"hidden-tr\");\n\t});\n</script>\n</body>\n</html>\"\"\"\n\n\ndef relust(titles, starttime, endtime, passge, fail, id: list, name: list,\n headers: list, coneent: list, url: list, meth: list, yuqi: list, json:\n list, relust: list, excepts, yuqis, weizhi, maxs, mins, pingluns):\n if type(name) is list:\n relus = ' '\n for i in range(len(name)):\n if relust[i] == 'pass':\n clazz = 'success'\n elif relust[i] == 'fail':\n clazz = 'warning'\n elif relust[i] == '未知错误':\n clazz = 'danger'\n else:\n clazz = 'error'\n relus += ceshixiangqing(clazz, id[i], name[i], coneent=coneent[\n i], url=url[i], headers=headers[i], meth=meth[i], yuqi=yuqi\n [i], json=json[i], relust=relust[i])\n text = title(titles) + connent + time(starttime, endtime, passge,\n fail, excepts, yuqis, weizhi, maxs, mins, pingluns\n ) + shanghai + relus + weibu\n else:\n text = title(titles) + connent + time(starttime, endtime, passge,\n fail, excepts, yuqis, weizhi, maxs, mins, pingluns\n ) + shanghai + ceshixiangqing(id=id, name=name, headers=headers,\n coneent=coneent, url=url, meth=meth, yuqi=int(yuqi), json=json,\n relust=relust) + weibu\n return text\n\n\ndef createHtml(filepath, titles, starttime, endtime, passge, fail, id, name,\n headers, coneent, url, meth, yuqi, json, relusts, excepts, yuqis,\n weizhi, maxs, mins, pingluns):\n texts = relust(titles=titles, starttime=starttime, endtime=endtime,\n passge=passge, fail=fail, id=id, name=name, headers=headers,\n coneent=coneent, url=url, meth=meth, yuqi=yuqi, json=json, relust=\n relusts, excepts=excepts, yuqis=yuqis, weizhi=weizhi, maxs=maxs,\n mins=mins, pingluns=pingluns)\n with open(filepath, 'wb') as f:\n f.write(texts.encode())\n", "<docstring token>\n<import token>\ntitles = '接口测试'\n\n\ndef title(titles):\n title = (\n \"\"\"<!DOCTYPE html>\n<html>\n<head>\n\t<title>%s</title>\n\t<meta charset=\"UTF-8\">\n\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <!-- 引入 Bootstrap -->\n <link href=\"https://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.min.css\" rel=\"stylesheet\">\n <!-- HTML5 Shim 和 Respond.js 用于让 IE8 支持 HTML5元素和媒体查询 -->\n <!-- 注意: 如果通过 file:// 引入 Respond.js 文件,则该文件无法起效果 -->\n <!--[if lt IE 9]>\n <script src=\"https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js\"></script>\n <script src=\"https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js\"></script>\n <![endif]-->\n <style type=\"text/css\">\n .hidden-detail,.hidden-tr{\n display:none;\n }\n </style>\n</head>\n<body>\n\t\"\"\"\n % titles)\n return title\n\n\nconnent = \"\"\"\n<div class='col-md-5 col-md-offset-5' style=\"margin-left: 2%;margin-top: -16px;\">\n<h1>FXTest测试平台接口测试的结果</h1>\"\"\"\n\n\ndef time(starttime, endtime, passge, fail, excepts, yuqi, weizhi, maxs,\n mins, pingluns):\n beijing = (\n \"\"\"\n <table class=\"table table-hover table-condensed\">\n <tbody>\n <tr>\n\t\t<td><strong>开始时间:</strong> %s</td>\n\t\t</tr>\n\t\t<td><strong>结束时间:</strong> %s</td></tr>\n\t\t<td><strong>耗时:</strong> %s</td></tr>\n\t\t<td>\n\t\t\t<strong>结果:</strong>\n\t\t\t<span >通过: \n\t\t\t<strong >%s</strong>\n\t\t\t失败: \n\t\t\t<strong >%s</strong>\n\t\t\tException: \n\t\t\t<strong >%s</strong>\n\t\t\t预期不存在: \n\t\t\t<strong >%s</strong>\n\t\t\t未知错误: \n\t\t\t<strong >%s</strong>\n\t\t\t</td> \n\t\t\t </tr>\n\t\t\t <tr>\n\t\t\t <td>\n\t\t\t <strong>单接口耗时最大值:</strong>%s s,\n\t\t\t <strong>最小值:</strong> %s s,\n\t\t\t <strong>平均耗时:</strong> %s s\n\t\t\t </td>\n\t\t\t </tr> \n\t\t\t </tbody></table>\n\t\t\t </div> \"\"\"\n % (starttime, endtime, endtime - starttime, passge, fail, excepts,\n yuqi, weizhi, maxs, mins, pingluns))\n return beijing\n\n\nshanghai = \"\"\"<div class=\"row \" style=\"margin:35px\">\n <div style=' margin-top: 18%;' >\n <div class=\"btn-group\" role=\"group\" aria-label=\"...\">\n <button type=\"button\" id=\"check-all\" class=\"btn btn-primary\">所有用例</button>\n <button type=\"button\" id=\"check-success\" class=\"btn btn-success\">成功用例</button>\n <button type=\"button\" id=\"check-danger\" class=\"btn btn-danger\">失败用例</button>\n <button type=\"button\" id=\"check-warning\" class=\"btn btn-warning\">错误用例</button>\n <button type=\"button\" id=\"check-except\" class=\"btn btn-defult\">异常用例</button>\n </div>\n <div class=\"btn-group\" role=\"group\" aria-label=\"...\">\n </div>\n <table class=\"table table-hover table-condensed table-bordered\" style=\"word-wrap:break-word; word-break:break-all; margin-top: 7px;\">\n\t\t<tr >\n <td ><strong>用例ID&nbsp;</strong></td>\n <td><strong>项目</strong></td>\n <td><strong>url</strong></td>\n <td><strong>请求方式</strong></td>\n <td><strong>参数</strong></td>\n <td><strong>headers</strong></td>\n <td><strong>预期</strong></td>\n <td><strong>实际返回</strong></td> \n <td><strong>结果</strong></td>\n </tr>\n \"\"\"\n\n\ndef passfail(tend):\n if tend == 'pass':\n htl = ' <td bgcolor=\"green\">pass</td>'\n elif tend == 'fail':\n htl = ' <td bgcolor=\"fail\">fail</td>'\n elif tend == 'Exception':\n htl = '<td bgcolor=\"#8b0000\">Exception</td>'\n elif tend == '预期不存在':\n htl = '<td bgcolor=\"#8b0000\">预期不存在</td>'\n elif tend == '未知错误':\n htl = '<td bgcolor=\"#8b0000\">未知错误</td>'\n elif tend == '测试环境不存在':\n htl = '<td bgcolor=\"#8b0000\">测试环境不存在</td>'\n else:\n htl = '<td bgcolor=\"#8b0000\">查看日志</td>'\n return htl\n\n\ndef ceshixiangqing(res_id, id, name, coneent, url, meth, yuqi, json, relust,\n headers):\n xiangqing = (\n \"\"\"\n <tr class=\"case-tr %s\">\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n %s\n </tr>\n \"\"\"\n % (res_id, id, name, coneent, url, meth, headers, yuqi, json,\n passfail(relust)))\n return xiangqing\n\n\nweibu = \"\"\"</div></div></table><script src=\"https://code.jquery.com/jquery.js\"></script>\n<script src=\"https://cdn.bootcss.com/bootstrap/3.3.6/js/bootstrap.min.js\"></script>\n<script type=\"text/javascript\">\n\t$(\"#check-danger\").click(function(e){\n\t $(\".case-tr\").removeClass(\"hidden-tr\");\n $(\".success\").addClass(\"hidden-tr\");\n $(\".warning\").addClass(\"hidden-tr\");\n $(\".error\").addClass(\"hidden-tr\");\n\t});\n\t$(\"#check-warning\").click(function(e){\n\t\t $(\".case-tr\").removeClass(\"hidden-tr\");\n $(\".success\").addClass(\"hidden-tr\");\n $(\".danger\").addClass(\"hidden-tr\");\n $(\".error\").addClass(\"hidden-tr\");\n\t});\n\t$(\"#check-success\").click(function(e){\n\t\t $(\".case-tr\").removeClass(\"hidden-tr\");\n $(\".warning\").addClass(\"hidden-tr\");\n $(\".danger\").addClass(\"hidden-tr\");\n $(\".error\").addClass(\"hidden-tr\");\n\t});\n\t$(\"#check-except\").click(function(e){\n\t\t $(\".case-tr\").removeClass(\"hidden-tr\");\n $(\".warning\").addClass(\"hidden-tr\");\n $(\".danger\").addClass(\"hidden-tr\");\n $(\".success\").addClass(\"hidden-tr\");\n\t});\n\t$(\"#check-all\").click(function(e){\n\t $(\".case-tr\").removeClass(\"hidden-tr\");\n\t});\n</script>\n</body>\n</html>\"\"\"\n\n\ndef relust(titles, starttime, endtime, passge, fail, id: list, name: list,\n headers: list, coneent: list, url: list, meth: list, yuqi: list, json:\n list, relust: list, excepts, yuqis, weizhi, maxs, mins, pingluns):\n if type(name) is list:\n relus = ' '\n for i in range(len(name)):\n if relust[i] == 'pass':\n clazz = 'success'\n elif relust[i] == 'fail':\n clazz = 'warning'\n elif relust[i] == '未知错误':\n clazz = 'danger'\n else:\n clazz = 'error'\n relus += ceshixiangqing(clazz, id[i], name[i], coneent=coneent[\n i], url=url[i], headers=headers[i], meth=meth[i], yuqi=yuqi\n [i], json=json[i], relust=relust[i])\n text = title(titles) + connent + time(starttime, endtime, passge,\n fail, excepts, yuqis, weizhi, maxs, mins, pingluns\n ) + shanghai + relus + weibu\n else:\n text = title(titles) + connent + time(starttime, endtime, passge,\n fail, excepts, yuqis, weizhi, maxs, mins, pingluns\n ) + shanghai + ceshixiangqing(id=id, name=name, headers=headers,\n coneent=coneent, url=url, meth=meth, yuqi=int(yuqi), json=json,\n relust=relust) + weibu\n return text\n\n\ndef createHtml(filepath, titles, starttime, endtime, passge, fail, id, name,\n headers, coneent, url, meth, yuqi, json, relusts, excepts, yuqis,\n weizhi, maxs, mins, pingluns):\n texts = relust(titles=titles, starttime=starttime, endtime=endtime,\n passge=passge, fail=fail, id=id, name=name, headers=headers,\n coneent=coneent, url=url, meth=meth, yuqi=yuqi, json=json, relust=\n relusts, excepts=excepts, yuqis=yuqis, weizhi=weizhi, maxs=maxs,\n mins=mins, pingluns=pingluns)\n with open(filepath, 'wb') as f:\n f.write(texts.encode())\n", "<docstring token>\n<import token>\n<assignment token>\n\n\ndef title(titles):\n title = (\n \"\"\"<!DOCTYPE html>\n<html>\n<head>\n\t<title>%s</title>\n\t<meta charset=\"UTF-8\">\n\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <!-- 引入 Bootstrap -->\n <link href=\"https://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.min.css\" rel=\"stylesheet\">\n <!-- HTML5 Shim 和 Respond.js 用于让 IE8 支持 HTML5元素和媒体查询 -->\n <!-- 注意: 如果通过 file:// 引入 Respond.js 文件,则该文件无法起效果 -->\n <!--[if lt IE 9]>\n <script src=\"https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js\"></script>\n <script src=\"https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js\"></script>\n <![endif]-->\n <style type=\"text/css\">\n .hidden-detail,.hidden-tr{\n display:none;\n }\n </style>\n</head>\n<body>\n\t\"\"\"\n % titles)\n return title\n\n\n<assignment token>\n\n\ndef time(starttime, endtime, passge, fail, excepts, yuqi, weizhi, maxs,\n mins, pingluns):\n beijing = (\n \"\"\"\n <table class=\"table table-hover table-condensed\">\n <tbody>\n <tr>\n\t\t<td><strong>开始时间:</strong> %s</td>\n\t\t</tr>\n\t\t<td><strong>结束时间:</strong> %s</td></tr>\n\t\t<td><strong>耗时:</strong> %s</td></tr>\n\t\t<td>\n\t\t\t<strong>结果:</strong>\n\t\t\t<span >通过: \n\t\t\t<strong >%s</strong>\n\t\t\t失败: \n\t\t\t<strong >%s</strong>\n\t\t\tException: \n\t\t\t<strong >%s</strong>\n\t\t\t预期不存在: \n\t\t\t<strong >%s</strong>\n\t\t\t未知错误: \n\t\t\t<strong >%s</strong>\n\t\t\t</td> \n\t\t\t </tr>\n\t\t\t <tr>\n\t\t\t <td>\n\t\t\t <strong>单接口耗时最大值:</strong>%s s,\n\t\t\t <strong>最小值:</strong> %s s,\n\t\t\t <strong>平均耗时:</strong> %s s\n\t\t\t </td>\n\t\t\t </tr> \n\t\t\t </tbody></table>\n\t\t\t </div> \"\"\"\n % (starttime, endtime, endtime - starttime, passge, fail, excepts,\n yuqi, weizhi, maxs, mins, pingluns))\n return beijing\n\n\n<assignment token>\n\n\ndef passfail(tend):\n if tend == 'pass':\n htl = ' <td bgcolor=\"green\">pass</td>'\n elif tend == 'fail':\n htl = ' <td bgcolor=\"fail\">fail</td>'\n elif tend == 'Exception':\n htl = '<td bgcolor=\"#8b0000\">Exception</td>'\n elif tend == '预期不存在':\n htl = '<td bgcolor=\"#8b0000\">预期不存在</td>'\n elif tend == '未知错误':\n htl = '<td bgcolor=\"#8b0000\">未知错误</td>'\n elif tend == '测试环境不存在':\n htl = '<td bgcolor=\"#8b0000\">测试环境不存在</td>'\n else:\n htl = '<td bgcolor=\"#8b0000\">查看日志</td>'\n return htl\n\n\ndef ceshixiangqing(res_id, id, name, coneent, url, meth, yuqi, json, relust,\n headers):\n xiangqing = (\n \"\"\"\n <tr class=\"case-tr %s\">\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n %s\n </tr>\n \"\"\"\n % (res_id, id, name, coneent, url, meth, headers, yuqi, json,\n passfail(relust)))\n return xiangqing\n\n\n<assignment token>\n\n\ndef relust(titles, starttime, endtime, passge, fail, id: list, name: list,\n headers: list, coneent: list, url: list, meth: list, yuqi: list, json:\n list, relust: list, excepts, yuqis, weizhi, maxs, mins, pingluns):\n if type(name) is list:\n relus = ' '\n for i in range(len(name)):\n if relust[i] == 'pass':\n clazz = 'success'\n elif relust[i] == 'fail':\n clazz = 'warning'\n elif relust[i] == '未知错误':\n clazz = 'danger'\n else:\n clazz = 'error'\n relus += ceshixiangqing(clazz, id[i], name[i], coneent=coneent[\n i], url=url[i], headers=headers[i], meth=meth[i], yuqi=yuqi\n [i], json=json[i], relust=relust[i])\n text = title(titles) + connent + time(starttime, endtime, passge,\n fail, excepts, yuqis, weizhi, maxs, mins, pingluns\n ) + shanghai + relus + weibu\n else:\n text = title(titles) + connent + time(starttime, endtime, passge,\n fail, excepts, yuqis, weizhi, maxs, mins, pingluns\n ) + shanghai + ceshixiangqing(id=id, name=name, headers=headers,\n coneent=coneent, url=url, meth=meth, yuqi=int(yuqi), json=json,\n relust=relust) + weibu\n return text\n\n\ndef createHtml(filepath, titles, starttime, endtime, passge, fail, id, name,\n headers, coneent, url, meth, yuqi, json, relusts, excepts, yuqis,\n weizhi, maxs, mins, pingluns):\n texts = relust(titles=titles, starttime=starttime, endtime=endtime,\n passge=passge, fail=fail, id=id, name=name, headers=headers,\n coneent=coneent, url=url, meth=meth, yuqi=yuqi, json=json, relust=\n relusts, excepts=excepts, yuqis=yuqis, weizhi=weizhi, maxs=maxs,\n mins=mins, pingluns=pingluns)\n with open(filepath, 'wb') as f:\n f.write(texts.encode())\n", "<docstring token>\n<import token>\n<assignment token>\n\n\ndef title(titles):\n title = (\n \"\"\"<!DOCTYPE html>\n<html>\n<head>\n\t<title>%s</title>\n\t<meta charset=\"UTF-8\">\n\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <!-- 引入 Bootstrap -->\n <link href=\"https://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.min.css\" rel=\"stylesheet\">\n <!-- HTML5 Shim 和 Respond.js 用于让 IE8 支持 HTML5元素和媒体查询 -->\n <!-- 注意: 如果通过 file:// 引入 Respond.js 文件,则该文件无法起效果 -->\n <!--[if lt IE 9]>\n <script src=\"https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js\"></script>\n <script src=\"https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js\"></script>\n <![endif]-->\n <style type=\"text/css\">\n .hidden-detail,.hidden-tr{\n display:none;\n }\n </style>\n</head>\n<body>\n\t\"\"\"\n % titles)\n return title\n\n\n<assignment token>\n<function token>\n<assignment token>\n\n\ndef passfail(tend):\n if tend == 'pass':\n htl = ' <td bgcolor=\"green\">pass</td>'\n elif tend == 'fail':\n htl = ' <td bgcolor=\"fail\">fail</td>'\n elif tend == 'Exception':\n htl = '<td bgcolor=\"#8b0000\">Exception</td>'\n elif tend == '预期不存在':\n htl = '<td bgcolor=\"#8b0000\">预期不存在</td>'\n elif tend == '未知错误':\n htl = '<td bgcolor=\"#8b0000\">未知错误</td>'\n elif tend == '测试环境不存在':\n htl = '<td bgcolor=\"#8b0000\">测试环境不存在</td>'\n else:\n htl = '<td bgcolor=\"#8b0000\">查看日志</td>'\n return htl\n\n\ndef ceshixiangqing(res_id, id, name, coneent, url, meth, yuqi, json, relust,\n headers):\n xiangqing = (\n \"\"\"\n <tr class=\"case-tr %s\">\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n %s\n </tr>\n \"\"\"\n % (res_id, id, name, coneent, url, meth, headers, yuqi, json,\n passfail(relust)))\n return xiangqing\n\n\n<assignment token>\n\n\ndef relust(titles, starttime, endtime, passge, fail, id: list, name: list,\n headers: list, coneent: list, url: list, meth: list, yuqi: list, json:\n list, relust: list, excepts, yuqis, weizhi, maxs, mins, pingluns):\n if type(name) is list:\n relus = ' '\n for i in range(len(name)):\n if relust[i] == 'pass':\n clazz = 'success'\n elif relust[i] == 'fail':\n clazz = 'warning'\n elif relust[i] == '未知错误':\n clazz = 'danger'\n else:\n clazz = 'error'\n relus += ceshixiangqing(clazz, id[i], name[i], coneent=coneent[\n i], url=url[i], headers=headers[i], meth=meth[i], yuqi=yuqi\n [i], json=json[i], relust=relust[i])\n text = title(titles) + connent + time(starttime, endtime, passge,\n fail, excepts, yuqis, weizhi, maxs, mins, pingluns\n ) + shanghai + relus + weibu\n else:\n text = title(titles) + connent + time(starttime, endtime, passge,\n fail, excepts, yuqis, weizhi, maxs, mins, pingluns\n ) + shanghai + ceshixiangqing(id=id, name=name, headers=headers,\n coneent=coneent, url=url, meth=meth, yuqi=int(yuqi), json=json,\n relust=relust) + weibu\n return text\n\n\ndef createHtml(filepath, titles, starttime, endtime, passge, fail, id, name,\n headers, coneent, url, meth, yuqi, json, relusts, excepts, yuqis,\n weizhi, maxs, mins, pingluns):\n texts = relust(titles=titles, starttime=starttime, endtime=endtime,\n passge=passge, fail=fail, id=id, name=name, headers=headers,\n coneent=coneent, url=url, meth=meth, yuqi=yuqi, json=json, relust=\n relusts, excepts=excepts, yuqis=yuqis, weizhi=weizhi, maxs=maxs,\n mins=mins, pingluns=pingluns)\n with open(filepath, 'wb') as f:\n f.write(texts.encode())\n", "<docstring token>\n<import token>\n<assignment token>\n\n\ndef title(titles):\n title = (\n \"\"\"<!DOCTYPE html>\n<html>\n<head>\n\t<title>%s</title>\n\t<meta charset=\"UTF-8\">\n\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <!-- 引入 Bootstrap -->\n <link href=\"https://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.min.css\" rel=\"stylesheet\">\n <!-- HTML5 Shim 和 Respond.js 用于让 IE8 支持 HTML5元素和媒体查询 -->\n <!-- 注意: 如果通过 file:// 引入 Respond.js 文件,则该文件无法起效果 -->\n <!--[if lt IE 9]>\n <script src=\"https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js\"></script>\n <script src=\"https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js\"></script>\n <![endif]-->\n <style type=\"text/css\">\n .hidden-detail,.hidden-tr{\n display:none;\n }\n </style>\n</head>\n<body>\n\t\"\"\"\n % titles)\n return title\n\n\n<assignment token>\n<function token>\n<assignment token>\n\n\ndef passfail(tend):\n if tend == 'pass':\n htl = ' <td bgcolor=\"green\">pass</td>'\n elif tend == 'fail':\n htl = ' <td bgcolor=\"fail\">fail</td>'\n elif tend == 'Exception':\n htl = '<td bgcolor=\"#8b0000\">Exception</td>'\n elif tend == '预期不存在':\n htl = '<td bgcolor=\"#8b0000\">预期不存在</td>'\n elif tend == '未知错误':\n htl = '<td bgcolor=\"#8b0000\">未知错误</td>'\n elif tend == '测试环境不存在':\n htl = '<td bgcolor=\"#8b0000\">测试环境不存在</td>'\n else:\n htl = '<td bgcolor=\"#8b0000\">查看日志</td>'\n return htl\n\n\ndef ceshixiangqing(res_id, id, name, coneent, url, meth, yuqi, json, relust,\n headers):\n xiangqing = (\n \"\"\"\n <tr class=\"case-tr %s\">\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n %s\n </tr>\n \"\"\"\n % (res_id, id, name, coneent, url, meth, headers, yuqi, json,\n passfail(relust)))\n return xiangqing\n\n\n<assignment token>\n<function token>\n\n\ndef createHtml(filepath, titles, starttime, endtime, passge, fail, id, name,\n headers, coneent, url, meth, yuqi, json, relusts, excepts, yuqis,\n weizhi, maxs, mins, pingluns):\n texts = relust(titles=titles, starttime=starttime, endtime=endtime,\n passge=passge, fail=fail, id=id, name=name, headers=headers,\n coneent=coneent, url=url, meth=meth, yuqi=yuqi, json=json, relust=\n relusts, excepts=excepts, yuqis=yuqis, weizhi=weizhi, maxs=maxs,\n mins=mins, pingluns=pingluns)\n with open(filepath, 'wb') as f:\n f.write(texts.encode())\n", "<docstring token>\n<import token>\n<assignment token>\n<function token>\n<assignment token>\n<function token>\n<assignment token>\n\n\ndef passfail(tend):\n if tend == 'pass':\n htl = ' <td bgcolor=\"green\">pass</td>'\n elif tend == 'fail':\n htl = ' <td bgcolor=\"fail\">fail</td>'\n elif tend == 'Exception':\n htl = '<td bgcolor=\"#8b0000\">Exception</td>'\n elif tend == '预期不存在':\n htl = '<td bgcolor=\"#8b0000\">预期不存在</td>'\n elif tend == '未知错误':\n htl = '<td bgcolor=\"#8b0000\">未知错误</td>'\n elif tend == '测试环境不存在':\n htl = '<td bgcolor=\"#8b0000\">测试环境不存在</td>'\n else:\n htl = '<td bgcolor=\"#8b0000\">查看日志</td>'\n return htl\n\n\ndef ceshixiangqing(res_id, id, name, coneent, url, meth, yuqi, json, relust,\n headers):\n xiangqing = (\n \"\"\"\n <tr class=\"case-tr %s\">\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n %s\n </tr>\n \"\"\"\n % (res_id, id, name, coneent, url, meth, headers, yuqi, json,\n passfail(relust)))\n return xiangqing\n\n\n<assignment token>\n<function token>\n\n\ndef createHtml(filepath, titles, starttime, endtime, passge, fail, id, name,\n headers, coneent, url, meth, yuqi, json, relusts, excepts, yuqis,\n weizhi, maxs, mins, pingluns):\n texts = relust(titles=titles, starttime=starttime, endtime=endtime,\n passge=passge, fail=fail, id=id, name=name, headers=headers,\n coneent=coneent, url=url, meth=meth, yuqi=yuqi, json=json, relust=\n relusts, excepts=excepts, yuqis=yuqis, weizhi=weizhi, maxs=maxs,\n mins=mins, pingluns=pingluns)\n with open(filepath, 'wb') as f:\n f.write(texts.encode())\n", "<docstring token>\n<import token>\n<assignment token>\n<function token>\n<assignment token>\n<function token>\n<assignment token>\n\n\ndef passfail(tend):\n if tend == 'pass':\n htl = ' <td bgcolor=\"green\">pass</td>'\n elif tend == 'fail':\n htl = ' <td bgcolor=\"fail\">fail</td>'\n elif tend == 'Exception':\n htl = '<td bgcolor=\"#8b0000\">Exception</td>'\n elif tend == '预期不存在':\n htl = '<td bgcolor=\"#8b0000\">预期不存在</td>'\n elif tend == '未知错误':\n htl = '<td bgcolor=\"#8b0000\">未知错误</td>'\n elif tend == '测试环境不存在':\n htl = '<td bgcolor=\"#8b0000\">测试环境不存在</td>'\n else:\n htl = '<td bgcolor=\"#8b0000\">查看日志</td>'\n return htl\n\n\ndef ceshixiangqing(res_id, id, name, coneent, url, meth, yuqi, json, relust,\n headers):\n xiangqing = (\n \"\"\"\n <tr class=\"case-tr %s\">\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n %s\n </tr>\n \"\"\"\n % (res_id, id, name, coneent, url, meth, headers, yuqi, json,\n passfail(relust)))\n return xiangqing\n\n\n<assignment token>\n<function token>\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<function token>\n<assignment token>\n<function token>\n<assignment token>\n<function token>\n\n\ndef ceshixiangqing(res_id, id, name, coneent, url, meth, yuqi, json, relust,\n headers):\n xiangqing = (\n \"\"\"\n <tr class=\"case-tr %s\">\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n %s\n </tr>\n \"\"\"\n % (res_id, id, name, coneent, url, meth, headers, yuqi, json,\n passfail(relust)))\n return xiangqing\n\n\n<assignment token>\n<function token>\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<function token>\n<assignment token>\n<function token>\n<assignment token>\n<function token>\n<function token>\n<assignment token>\n<function token>\n<function token>\n" ]
false
98,717
0fc4bfe3f8058b159e753ce9cd7deed3261ef9ae
import attr from pi_pid.hardware.mock import Sensor, Switch from pi_pid.controller import controller @attr.s class SimpleStrategy(): sensor = attr.ib() def evaluate(self): if self.sensor.read() > 0: return 'on' else: return 'off' def test_on_when_high(): sense = Sensor() strat = SimpleStrategy(sensor=sense) switch = Switch() controller(switch, strategy=strat) assert switch.state == 'ON' def test_off_when_low(): sense = Sensor() sense.reading = 0 strat = SimpleStrategy(sensor=sense) switch = Switch() controller(switch, strategy=strat) assert switch.state == 'OFF'
[ "import attr\nfrom pi_pid.hardware.mock import Sensor, Switch\nfrom pi_pid.controller import controller\n\n\[email protected]\nclass SimpleStrategy():\n\n sensor = attr.ib()\n\n def evaluate(self):\n if self.sensor.read() > 0:\n return 'on'\n else:\n return 'off'\n\n\ndef test_on_when_high():\n sense = Sensor()\n strat = SimpleStrategy(sensor=sense)\n switch = Switch()\n controller(switch, strategy=strat)\n assert switch.state == 'ON'\n\n\ndef test_off_when_low():\n sense = Sensor()\n sense.reading = 0\n strat = SimpleStrategy(sensor=sense)\n switch = Switch()\n controller(switch, strategy=strat)\n assert switch.state == 'OFF'\n", "import attr\nfrom pi_pid.hardware.mock import Sensor, Switch\nfrom pi_pid.controller import controller\n\n\[email protected]\nclass SimpleStrategy:\n sensor = attr.ib()\n\n def evaluate(self):\n if self.sensor.read() > 0:\n return 'on'\n else:\n return 'off'\n\n\ndef test_on_when_high():\n sense = Sensor()\n strat = SimpleStrategy(sensor=sense)\n switch = Switch()\n controller(switch, strategy=strat)\n assert switch.state == 'ON'\n\n\ndef test_off_when_low():\n sense = Sensor()\n sense.reading = 0\n strat = SimpleStrategy(sensor=sense)\n switch = Switch()\n controller(switch, strategy=strat)\n assert switch.state == 'OFF'\n", "<import token>\n\n\[email protected]\nclass SimpleStrategy:\n sensor = attr.ib()\n\n def evaluate(self):\n if self.sensor.read() > 0:\n return 'on'\n else:\n return 'off'\n\n\ndef test_on_when_high():\n sense = Sensor()\n strat = SimpleStrategy(sensor=sense)\n switch = Switch()\n controller(switch, strategy=strat)\n assert switch.state == 'ON'\n\n\ndef test_off_when_low():\n sense = Sensor()\n sense.reading = 0\n strat = SimpleStrategy(sensor=sense)\n switch = Switch()\n controller(switch, strategy=strat)\n assert switch.state == 'OFF'\n", "<import token>\n\n\[email protected]\nclass SimpleStrategy:\n sensor = attr.ib()\n\n def evaluate(self):\n if self.sensor.read() > 0:\n return 'on'\n else:\n return 'off'\n\n\ndef test_on_when_high():\n sense = Sensor()\n strat = SimpleStrategy(sensor=sense)\n switch = Switch()\n controller(switch, strategy=strat)\n assert switch.state == 'ON'\n\n\n<function token>\n", "<import token>\n\n\[email protected]\nclass SimpleStrategy:\n sensor = attr.ib()\n\n def evaluate(self):\n if self.sensor.read() > 0:\n return 'on'\n else:\n return 'off'\n\n\n<function token>\n<function token>\n", "<import token>\n\n\[email protected]\nclass SimpleStrategy:\n <assignment token>\n\n def evaluate(self):\n if self.sensor.read() > 0:\n return 'on'\n else:\n return 'off'\n\n\n<function token>\n<function token>\n", "<import token>\n\n\[email protected]\nclass SimpleStrategy:\n <assignment token>\n <function token>\n\n\n<function token>\n<function token>\n", "<import token>\n<class token>\n<function token>\n<function token>\n" ]
false
98,718
ef54c241982ad83eeeae2095c92b1eccd82b856a
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Создать класс Goods (товар). В классе должны быть представлены поля: наименование # товара, дата оформления, цена товара, количество единиц товара, номер накладной, по # которой товар поступил на склад. Реализовать методы изменения цены товара, изменения # количества товара (увеличения и уменьшения), вычисления стоимости товара import math class Goods: def __init__(self): self.__coast = 0 self.__date = 0 self.__name = 0 self.__quan = 0 self.__number = 0 def read(self, name, quan, date, coast, number): self.name(name) self.quan(quan) self.date(date) self.coast(coast) self.number(number) def name(self, prompt=None): self.__name = input() if prompt is None else input(prompt) def date(self, prompt=None): self.__date = input() if prompt is None else input(prompt) def coast(self, prompt=None): self.__coast = int(input()) if prompt is None else input(prompt) def quan(self, prompt=None): self.__quan = int(input()) if prompt is None else input(prompt) def number(self, prompt=None): self.__number = input() if prompt is None else input(prompt) def set_coast(self, a): self.__coast = a def set_quan(self, a): self.__quan = a def get_info(self): return self.__coast, self.__date, self.__name, self.__quan, self.__number def __stiom(self): return int(self.__coast) * int(self.__quan) def dispaly(self): print("Наименование товара: {}; " "Дата оформления - {}; " "Цена товара - {};" "Количество единиц товара - {}; " "Номер накладной - {}." "Стоимость всего товара - {}".format(self.__name, self.__date, self.__coast, self.__quan, self.__number, self.__stiom() ) ) if __name__ == '__main__': T1 = Goods() T1.read("Введите названия ", "Введите количество товара ", "Введите дату оформления ", "цену товара ", " и номер накладной " ) T1.dispaly() T1.set_quan(50) T1.set_coast(250) T1.dispaly()
[ "#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\r\n# Создать класс Goods (товар). В классе должны быть представлены поля: наименование\r\n# товара, дата оформления, цена товара, количество единиц товара, номер накладной, по\r\n# которой товар поступил на склад. Реализовать методы изменения цены товара, изменения\r\n# количества товара (увеличения и уменьшения), вычисления стоимости товара\r\n\r\nimport math\r\n\r\n\r\nclass Goods:\r\n\r\n def __init__(self):\r\n self.__coast = 0\r\n self.__date = 0\r\n self.__name = 0\r\n self.__quan = 0\r\n self.__number = 0\r\n\r\n def read(self, name, quan, date, coast, number):\r\n self.name(name)\r\n self.quan(quan)\r\n self.date(date)\r\n self.coast(coast)\r\n self.number(number)\r\n\r\n def name(self, prompt=None):\r\n self.__name = input() if prompt is None else input(prompt)\r\n\r\n def date(self, prompt=None):\r\n self.__date = input() if prompt is None else input(prompt)\r\n\r\n def coast(self, prompt=None):\r\n self.__coast = int(input()) if prompt is None else input(prompt)\r\n\r\n def quan(self, prompt=None):\r\n self.__quan = int(input()) if prompt is None else input(prompt)\r\n\r\n def number(self, prompt=None):\r\n self.__number = input() if prompt is None else input(prompt)\r\n\r\n def set_coast(self, a):\r\n self.__coast = a\r\n\r\n def set_quan(self, a):\r\n self.__quan = a\r\n\r\n def get_info(self):\r\n return self.__coast, self.__date, self.__name, self.__quan, self.__number\r\n\r\n def __stiom(self):\r\n return int(self.__coast) * int(self.__quan)\r\n\r\n def dispaly(self):\r\n print(\"Наименование товара: {}; \"\r\n \"Дата оформления - {}; \"\r\n \"Цена товара - {};\"\r\n \"Количество единиц товара - {}; \"\r\n \"Номер накладной - {}.\"\r\n \"Стоимость всего товара - {}\".format(self.__name, self.__date, self.__coast, self.__quan, self.__number,\r\n self.__stiom()\r\n )\r\n )\r\n\r\n\r\nif __name__ == '__main__':\r\n T1 = Goods()\r\n T1.read(\"Введите названия \",\r\n \"Введите количество товара \",\r\n \"Введите дату оформления \",\r\n \"цену товара \",\r\n \" и номер накладной \"\r\n )\r\n T1.dispaly()\r\n T1.set_quan(50)\r\n T1.set_coast(250)\r\n T1.dispaly()\r\n", "import math\n\n\nclass Goods:\n\n def __init__(self):\n self.__coast = 0\n self.__date = 0\n self.__name = 0\n self.__quan = 0\n self.__number = 0\n\n def read(self, name, quan, date, coast, number):\n self.name(name)\n self.quan(quan)\n self.date(date)\n self.coast(coast)\n self.number(number)\n\n def name(self, prompt=None):\n self.__name = input() if prompt is None else input(prompt)\n\n def date(self, prompt=None):\n self.__date = input() if prompt is None else input(prompt)\n\n def coast(self, prompt=None):\n self.__coast = int(input()) if prompt is None else input(prompt)\n\n def quan(self, prompt=None):\n self.__quan = int(input()) if prompt is None else input(prompt)\n\n def number(self, prompt=None):\n self.__number = input() if prompt is None else input(prompt)\n\n def set_coast(self, a):\n self.__coast = a\n\n def set_quan(self, a):\n self.__quan = a\n\n def get_info(self):\n return (self.__coast, self.__date, self.__name, self.__quan, self.\n __number)\n\n def __stiom(self):\n return int(self.__coast) * int(self.__quan)\n\n def dispaly(self):\n print(\n 'Наименование товара: {}; Дата оформления - {}; Цена товара - {};Количество единиц товара - {}; Номер накладной - {}.Стоимость всего товара - {}'\n .format(self.__name, self.__date, self.__coast, self.__quan,\n self.__number, self.__stiom()))\n\n\nif __name__ == '__main__':\n T1 = Goods()\n T1.read('Введите названия ', 'Введите количество товара ',\n 'Введите дату оформления ', 'цену товара ', ' и номер накладной ')\n T1.dispaly()\n T1.set_quan(50)\n T1.set_coast(250)\n T1.dispaly()\n", "<import token>\n\n\nclass Goods:\n\n def __init__(self):\n self.__coast = 0\n self.__date = 0\n self.__name = 0\n self.__quan = 0\n self.__number = 0\n\n def read(self, name, quan, date, coast, number):\n self.name(name)\n self.quan(quan)\n self.date(date)\n self.coast(coast)\n self.number(number)\n\n def name(self, prompt=None):\n self.__name = input() if prompt is None else input(prompt)\n\n def date(self, prompt=None):\n self.__date = input() if prompt is None else input(prompt)\n\n def coast(self, prompt=None):\n self.__coast = int(input()) if prompt is None else input(prompt)\n\n def quan(self, prompt=None):\n self.__quan = int(input()) if prompt is None else input(prompt)\n\n def number(self, prompt=None):\n self.__number = input() if prompt is None else input(prompt)\n\n def set_coast(self, a):\n self.__coast = a\n\n def set_quan(self, a):\n self.__quan = a\n\n def get_info(self):\n return (self.__coast, self.__date, self.__name, self.__quan, self.\n __number)\n\n def __stiom(self):\n return int(self.__coast) * int(self.__quan)\n\n def dispaly(self):\n print(\n 'Наименование товара: {}; Дата оформления - {}; Цена товара - {};Количество единиц товара - {}; Номер накладной - {}.Стоимость всего товара - {}'\n .format(self.__name, self.__date, self.__coast, self.__quan,\n self.__number, self.__stiom()))\n\n\nif __name__ == '__main__':\n T1 = Goods()\n T1.read('Введите названия ', 'Введите количество товара ',\n 'Введите дату оформления ', 'цену товара ', ' и номер накладной ')\n T1.dispaly()\n T1.set_quan(50)\n T1.set_coast(250)\n T1.dispaly()\n", "<import token>\n\n\nclass Goods:\n\n def __init__(self):\n self.__coast = 0\n self.__date = 0\n self.__name = 0\n self.__quan = 0\n self.__number = 0\n\n def read(self, name, quan, date, coast, number):\n self.name(name)\n self.quan(quan)\n self.date(date)\n self.coast(coast)\n self.number(number)\n\n def name(self, prompt=None):\n self.__name = input() if prompt is None else input(prompt)\n\n def date(self, prompt=None):\n self.__date = input() if prompt is None else input(prompt)\n\n def coast(self, prompt=None):\n self.__coast = int(input()) if prompt is None else input(prompt)\n\n def quan(self, prompt=None):\n self.__quan = int(input()) if prompt is None else input(prompt)\n\n def number(self, prompt=None):\n self.__number = input() if prompt is None else input(prompt)\n\n def set_coast(self, a):\n self.__coast = a\n\n def set_quan(self, a):\n self.__quan = a\n\n def get_info(self):\n return (self.__coast, self.__date, self.__name, self.__quan, self.\n __number)\n\n def __stiom(self):\n return int(self.__coast) * int(self.__quan)\n\n def dispaly(self):\n print(\n 'Наименование товара: {}; Дата оформления - {}; Цена товара - {};Количество единиц товара - {}; Номер накладной - {}.Стоимость всего товара - {}'\n .format(self.__name, self.__date, self.__coast, self.__quan,\n self.__number, self.__stiom()))\n\n\n<code token>\n", "<import token>\n\n\nclass Goods:\n\n def __init__(self):\n self.__coast = 0\n self.__date = 0\n self.__name = 0\n self.__quan = 0\n self.__number = 0\n\n def read(self, name, quan, date, coast, number):\n self.name(name)\n self.quan(quan)\n self.date(date)\n self.coast(coast)\n self.number(number)\n\n def name(self, prompt=None):\n self.__name = input() if prompt is None else input(prompt)\n\n def date(self, prompt=None):\n self.__date = input() if prompt is None else input(prompt)\n\n def coast(self, prompt=None):\n self.__coast = int(input()) if prompt is None else input(prompt)\n\n def quan(self, prompt=None):\n self.__quan = int(input()) if prompt is None else input(prompt)\n\n def number(self, prompt=None):\n self.__number = input() if prompt is None else input(prompt)\n\n def set_coast(self, a):\n self.__coast = a\n\n def set_quan(self, a):\n self.__quan = a\n <function token>\n\n def __stiom(self):\n return int(self.__coast) * int(self.__quan)\n\n def dispaly(self):\n print(\n 'Наименование товара: {}; Дата оформления - {}; Цена товара - {};Количество единиц товара - {}; Номер накладной - {}.Стоимость всего товара - {}'\n .format(self.__name, self.__date, self.__coast, self.__quan,\n self.__number, self.__stiom()))\n\n\n<code token>\n", "<import token>\n\n\nclass Goods:\n\n def __init__(self):\n self.__coast = 0\n self.__date = 0\n self.__name = 0\n self.__quan = 0\n self.__number = 0\n\n def read(self, name, quan, date, coast, number):\n self.name(name)\n self.quan(quan)\n self.date(date)\n self.coast(coast)\n self.number(number)\n\n def name(self, prompt=None):\n self.__name = input() if prompt is None else input(prompt)\n\n def date(self, prompt=None):\n self.__date = input() if prompt is None else input(prompt)\n\n def coast(self, prompt=None):\n self.__coast = int(input()) if prompt is None else input(prompt)\n\n def quan(self, prompt=None):\n self.__quan = int(input()) if prompt is None else input(prompt)\n\n def number(self, prompt=None):\n self.__number = input() if prompt is None else input(prompt)\n\n def set_coast(self, a):\n self.__coast = a\n <function token>\n <function token>\n\n def __stiom(self):\n return int(self.__coast) * int(self.__quan)\n\n def dispaly(self):\n print(\n 'Наименование товара: {}; Дата оформления - {}; Цена товара - {};Количество единиц товара - {}; Номер накладной - {}.Стоимость всего товара - {}'\n .format(self.__name, self.__date, self.__coast, self.__quan,\n self.__number, self.__stiom()))\n\n\n<code token>\n", "<import token>\n\n\nclass Goods:\n\n def __init__(self):\n self.__coast = 0\n self.__date = 0\n self.__name = 0\n self.__quan = 0\n self.__number = 0\n\n def read(self, name, quan, date, coast, number):\n self.name(name)\n self.quan(quan)\n self.date(date)\n self.coast(coast)\n self.number(number)\n\n def name(self, prompt=None):\n self.__name = input() if prompt is None else input(prompt)\n\n def date(self, prompt=None):\n self.__date = input() if prompt is None else input(prompt)\n\n def coast(self, prompt=None):\n self.__coast = int(input()) if prompt is None else input(prompt)\n\n def quan(self, prompt=None):\n self.__quan = int(input()) if prompt is None else input(prompt)\n\n def number(self, prompt=None):\n self.__number = input() if prompt is None else input(prompt)\n\n def set_coast(self, a):\n self.__coast = a\n <function token>\n <function token>\n <function token>\n\n def dispaly(self):\n print(\n 'Наименование товара: {}; Дата оформления - {}; Цена товара - {};Количество единиц товара - {}; Номер накладной - {}.Стоимость всего товара - {}'\n .format(self.__name, self.__date, self.__coast, self.__quan,\n self.__number, self.__stiom()))\n\n\n<code token>\n", "<import token>\n\n\nclass Goods:\n\n def __init__(self):\n self.__coast = 0\n self.__date = 0\n self.__name = 0\n self.__quan = 0\n self.__number = 0\n\n def read(self, name, quan, date, coast, number):\n self.name(name)\n self.quan(quan)\n self.date(date)\n self.coast(coast)\n self.number(number)\n\n def name(self, prompt=None):\n self.__name = input() if prompt is None else input(prompt)\n\n def date(self, prompt=None):\n self.__date = input() if prompt is None else input(prompt)\n <function token>\n\n def quan(self, prompt=None):\n self.__quan = int(input()) if prompt is None else input(prompt)\n\n def number(self, prompt=None):\n self.__number = input() if prompt is None else input(prompt)\n\n def set_coast(self, a):\n self.__coast = a\n <function token>\n <function token>\n <function token>\n\n def dispaly(self):\n print(\n 'Наименование товара: {}; Дата оформления - {}; Цена товара - {};Количество единиц товара - {}; Номер накладной - {}.Стоимость всего товара - {}'\n .format(self.__name, self.__date, self.__coast, self.__quan,\n self.__number, self.__stiom()))\n\n\n<code token>\n", "<import token>\n\n\nclass Goods:\n\n def __init__(self):\n self.__coast = 0\n self.__date = 0\n self.__name = 0\n self.__quan = 0\n self.__number = 0\n\n def read(self, name, quan, date, coast, number):\n self.name(name)\n self.quan(quan)\n self.date(date)\n self.coast(coast)\n self.number(number)\n <function token>\n\n def date(self, prompt=None):\n self.__date = input() if prompt is None else input(prompt)\n <function token>\n\n def quan(self, prompt=None):\n self.__quan = int(input()) if prompt is None else input(prompt)\n\n def number(self, prompt=None):\n self.__number = input() if prompt is None else input(prompt)\n\n def set_coast(self, a):\n self.__coast = a\n <function token>\n <function token>\n <function token>\n\n def dispaly(self):\n print(\n 'Наименование товара: {}; Дата оформления - {}; Цена товара - {};Количество единиц товара - {}; Номер накладной - {}.Стоимость всего товара - {}'\n .format(self.__name, self.__date, self.__coast, self.__quan,\n self.__number, self.__stiom()))\n\n\n<code token>\n", "<import token>\n\n\nclass Goods:\n\n def __init__(self):\n self.__coast = 0\n self.__date = 0\n self.__name = 0\n self.__quan = 0\n self.__number = 0\n\n def read(self, name, quan, date, coast, number):\n self.name(name)\n self.quan(quan)\n self.date(date)\n self.coast(coast)\n self.number(number)\n <function token>\n\n def date(self, prompt=None):\n self.__date = input() if prompt is None else input(prompt)\n <function token>\n\n def quan(self, prompt=None):\n self.__quan = int(input()) if prompt is None else input(prompt)\n\n def number(self, prompt=None):\n self.__number = input() if prompt is None else input(prompt)\n <function token>\n <function token>\n <function token>\n <function token>\n\n def dispaly(self):\n print(\n 'Наименование товара: {}; Дата оформления - {}; Цена товара - {};Количество единиц товара - {}; Номер накладной - {}.Стоимость всего товара - {}'\n .format(self.__name, self.__date, self.__coast, self.__quan,\n self.__number, self.__stiom()))\n\n\n<code token>\n", "<import token>\n\n\nclass Goods:\n <function token>\n\n def read(self, name, quan, date, coast, number):\n self.name(name)\n self.quan(quan)\n self.date(date)\n self.coast(coast)\n self.number(number)\n <function token>\n\n def date(self, prompt=None):\n self.__date = input() if prompt is None else input(prompt)\n <function token>\n\n def quan(self, prompt=None):\n self.__quan = int(input()) if prompt is None else input(prompt)\n\n def number(self, prompt=None):\n self.__number = input() if prompt is None else input(prompt)\n <function token>\n <function token>\n <function token>\n <function token>\n\n def dispaly(self):\n print(\n 'Наименование товара: {}; Дата оформления - {}; Цена товара - {};Количество единиц товара - {}; Номер накладной - {}.Стоимость всего товара - {}'\n .format(self.__name, self.__date, self.__coast, self.__quan,\n self.__number, self.__stiom()))\n\n\n<code token>\n", "<import token>\n\n\nclass Goods:\n <function token>\n\n def read(self, name, quan, date, coast, number):\n self.name(name)\n self.quan(quan)\n self.date(date)\n self.coast(coast)\n self.number(number)\n <function token>\n\n def date(self, prompt=None):\n self.__date = input() if prompt is None else input(prompt)\n <function token>\n <function token>\n\n def number(self, prompt=None):\n self.__number = input() if prompt is None else input(prompt)\n <function token>\n <function token>\n <function token>\n <function token>\n\n def dispaly(self):\n print(\n 'Наименование товара: {}; Дата оформления - {}; Цена товара - {};Количество единиц товара - {}; Номер накладной - {}.Стоимость всего товара - {}'\n .format(self.__name, self.__date, self.__coast, self.__quan,\n self.__number, self.__stiom()))\n\n\n<code token>\n", "<import token>\n\n\nclass Goods:\n <function token>\n\n def read(self, name, quan, date, coast, number):\n self.name(name)\n self.quan(quan)\n self.date(date)\n self.coast(coast)\n self.number(number)\n <function token>\n <function token>\n <function token>\n <function token>\n\n def number(self, prompt=None):\n self.__number = input() if prompt is None else input(prompt)\n <function token>\n <function token>\n <function token>\n <function token>\n\n def dispaly(self):\n print(\n 'Наименование товара: {}; Дата оформления - {}; Цена товара - {};Количество единиц товара - {}; Номер накладной - {}.Стоимость всего товара - {}'\n .format(self.__name, self.__date, self.__coast, self.__quan,\n self.__number, self.__stiom()))\n\n\n<code token>\n", "<import token>\n\n\nclass Goods:\n <function token>\n\n def read(self, name, quan, date, coast, number):\n self.name(name)\n self.quan(quan)\n self.date(date)\n self.coast(coast)\n self.number(number)\n <function token>\n <function token>\n <function token>\n <function token>\n\n def number(self, prompt=None):\n self.__number = input() if prompt is None else input(prompt)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<code token>\n", "<import token>\n\n\nclass Goods:\n <function token>\n\n def read(self, name, quan, date, coast, number):\n self.name(name)\n self.quan(quan)\n self.date(date)\n self.coast(coast)\n self.number(number)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<code token>\n", "<import token>\n\n\nclass Goods:\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<code token>\n", "<import token>\n<class token>\n<code token>\n" ]
false
98,719
45b2b132e4985b20d06b4a982a4ccc0c31b25640
from collections import defaultdict class Solution: def countPoints(self, rings: str) -> int: l = len(rings) d = defaultdict(list) for i in range(1, l, 2): d[rings[i]].append(rings[i - 1]) res = 0 for k, v in d.items(): v = "".join(v) if set(v) == set("RGB"): res += 1 return res if __name__ == '__main__': rings = "B0B6G0R6R0R6G9" sol = Solution().countPoints print(sol(rings))
[ "from collections import defaultdict\r\n\r\n\r\nclass Solution:\r\n def countPoints(self, rings: str) -> int:\r\n l = len(rings)\r\n d = defaultdict(list)\r\n for i in range(1, l, 2):\r\n d[rings[i]].append(rings[i - 1])\r\n res = 0\r\n for k, v in d.items():\r\n v = \"\".join(v)\r\n if set(v) == set(\"RGB\"):\r\n res += 1\r\n return res\r\n\r\n\r\nif __name__ == '__main__':\r\n rings = \"B0B6G0R6R0R6G9\"\r\n sol = Solution().countPoints\r\n print(sol(rings))\r\n", "from collections import defaultdict\n\n\nclass Solution:\n\n def countPoints(self, rings: str) ->int:\n l = len(rings)\n d = defaultdict(list)\n for i in range(1, l, 2):\n d[rings[i]].append(rings[i - 1])\n res = 0\n for k, v in d.items():\n v = ''.join(v)\n if set(v) == set('RGB'):\n res += 1\n return res\n\n\nif __name__ == '__main__':\n rings = 'B0B6G0R6R0R6G9'\n sol = Solution().countPoints\n print(sol(rings))\n", "<import token>\n\n\nclass Solution:\n\n def countPoints(self, rings: str) ->int:\n l = len(rings)\n d = defaultdict(list)\n for i in range(1, l, 2):\n d[rings[i]].append(rings[i - 1])\n res = 0\n for k, v in d.items():\n v = ''.join(v)\n if set(v) == set('RGB'):\n res += 1\n return res\n\n\nif __name__ == '__main__':\n rings = 'B0B6G0R6R0R6G9'\n sol = Solution().countPoints\n print(sol(rings))\n", "<import token>\n\n\nclass Solution:\n\n def countPoints(self, rings: str) ->int:\n l = len(rings)\n d = defaultdict(list)\n for i in range(1, l, 2):\n d[rings[i]].append(rings[i - 1])\n res = 0\n for k, v in d.items():\n v = ''.join(v)\n if set(v) == set('RGB'):\n res += 1\n return res\n\n\n<code token>\n", "<import token>\n\n\nclass Solution:\n <function token>\n\n\n<code token>\n", "<import token>\n<class token>\n<code token>\n" ]
false
98,720
a683bc3d4f119427bcf42cf480cb632dd4f457a8
#!/usr/bin/env python import radio_status import subprocess import time import sys # utility function to test connection to server def ping(address): args = ['ping', '-I', 'ppp0', '-c1', address] f = open('/dev/null', 'w') return (0 == subprocess.call(args, stdout=f)) if __name__ == '__main__': radio = radio_status.gsp1720(dtr_pin=None) (avail, rssi) = radio.is_service_available() while not avail: sys.stdout.write(' ' + str(rssi)) sys.stdout.flush() time.sleep(5) (avail, rssi) = radio.is_service_available() print('\nservice available!') # Wait a small amount of time before making a call, possibly the # radio is getting messed up (status, msg) = radio.call('777') if status: print('call success!') time.sleep(0.5) args = [ '/usr/sbin/pppd', '/dev/ttyO2', '19200', 'noauth', 'defaultroute', 'persist', 'maxfail', '0', 'crtscts', 'local' ] subprocess.call(args) time.sleep(10) server_state = ping('www.google.com') print('server state = {}'.format(server_state)) else: print('call failed: ' + msg)
[ "#!/usr/bin/env python\n\nimport radio_status\nimport subprocess\nimport time\nimport sys\n\n# utility function to test connection to server\ndef ping(address):\n args = ['ping', '-I', 'ppp0', '-c1', address]\n f = open('/dev/null', 'w')\n return (0 == subprocess.call(args, stdout=f))\n\nif __name__ == '__main__':\n radio = radio_status.gsp1720(dtr_pin=None)\n (avail, rssi) = radio.is_service_available()\n while not avail:\n sys.stdout.write(' ' + str(rssi))\n sys.stdout.flush()\n time.sleep(5)\n (avail, rssi) = radio.is_service_available()\n print('\\nservice available!')\n\n # Wait a small amount of time before making a call, possibly the\n # radio is getting messed up\n (status, msg) = radio.call('777')\n if status:\n print('call success!')\n time.sleep(0.5)\n\n args = [ '/usr/sbin/pppd', '/dev/ttyO2', '19200', 'noauth', 'defaultroute', 'persist', 'maxfail', '0', 'crtscts', 'local' ]\n subprocess.call(args)\n\n time.sleep(10)\n server_state = ping('www.google.com')\n print('server state = {}'.format(server_state))\n else:\n print('call failed: ' + msg)\n\n", "import radio_status\nimport subprocess\nimport time\nimport sys\n\n\ndef ping(address):\n args = ['ping', '-I', 'ppp0', '-c1', address]\n f = open('/dev/null', 'w')\n return 0 == subprocess.call(args, stdout=f)\n\n\nif __name__ == '__main__':\n radio = radio_status.gsp1720(dtr_pin=None)\n avail, rssi = radio.is_service_available()\n while not avail:\n sys.stdout.write(' ' + str(rssi))\n sys.stdout.flush()\n time.sleep(5)\n avail, rssi = radio.is_service_available()\n print('\\nservice available!')\n status, msg = radio.call('777')\n if status:\n print('call success!')\n time.sleep(0.5)\n args = ['/usr/sbin/pppd', '/dev/ttyO2', '19200', 'noauth',\n 'defaultroute', 'persist', 'maxfail', '0', 'crtscts', 'local']\n subprocess.call(args)\n time.sleep(10)\n server_state = ping('www.google.com')\n print('server state = {}'.format(server_state))\n else:\n print('call failed: ' + msg)\n", "<import token>\n\n\ndef ping(address):\n args = ['ping', '-I', 'ppp0', '-c1', address]\n f = open('/dev/null', 'w')\n return 0 == subprocess.call(args, stdout=f)\n\n\nif __name__ == '__main__':\n radio = radio_status.gsp1720(dtr_pin=None)\n avail, rssi = radio.is_service_available()\n while not avail:\n sys.stdout.write(' ' + str(rssi))\n sys.stdout.flush()\n time.sleep(5)\n avail, rssi = radio.is_service_available()\n print('\\nservice available!')\n status, msg = radio.call('777')\n if status:\n print('call success!')\n time.sleep(0.5)\n args = ['/usr/sbin/pppd', '/dev/ttyO2', '19200', 'noauth',\n 'defaultroute', 'persist', 'maxfail', '0', 'crtscts', 'local']\n subprocess.call(args)\n time.sleep(10)\n server_state = ping('www.google.com')\n print('server state = {}'.format(server_state))\n else:\n print('call failed: ' + msg)\n", "<import token>\n\n\ndef ping(address):\n args = ['ping', '-I', 'ppp0', '-c1', address]\n f = open('/dev/null', 'w')\n return 0 == subprocess.call(args, stdout=f)\n\n\n<code token>\n", "<import token>\n<function token>\n<code token>\n" ]
false
98,721
930dbf7e1c94e3703dbb768118de71da30eda0cd
''' Author: Alejandro Meza Tudela Simulate the action of taking from input values to a vector that is declared ''' def clean_screen(): print() vector = list() len_vector = (int)(input("Enter the number of elements of the vector: ")) clean_screen() print("Now, enter the elements for the vector: ") for i in range(len_vector): elem = (int)(input(f"elem {i+1}: ")) vector.append(elem) clean_screen() print(f"The vector is {vector}")
[ "'''\r\nAuthor: Alejandro Meza Tudela\r\n Simulate the action of taking from input\r\n values to a vector that is declared\r\n'''\r\n\r\ndef clean_screen():\r\n print()\r\n\r\nvector = list()\r\nlen_vector = (int)(input(\"Enter the number of elements of the vector: \"))\r\nclean_screen()\r\nprint(\"Now, enter the elements for the vector: \")\r\nfor i in range(len_vector):\r\n elem = (int)(input(f\"elem {i+1}: \"))\r\n vector.append(elem)\r\nclean_screen()\r\nprint(f\"The vector is {vector}\")\r\n", "<docstring token>\n\n\ndef clean_screen():\n print()\n\n\nvector = list()\nlen_vector = int(input('Enter the number of elements of the vector: '))\nclean_screen()\nprint('Now, enter the elements for the vector: ')\nfor i in range(len_vector):\n elem = int(input(f'elem {i + 1}: '))\n vector.append(elem)\nclean_screen()\nprint(f'The vector is {vector}')\n", "<docstring token>\n\n\ndef clean_screen():\n print()\n\n\n<assignment token>\nclean_screen()\nprint('Now, enter the elements for the vector: ')\nfor i in range(len_vector):\n elem = int(input(f'elem {i + 1}: '))\n vector.append(elem)\nclean_screen()\nprint(f'The vector is {vector}')\n", "<docstring token>\n\n\ndef clean_screen():\n print()\n\n\n<assignment token>\n<code token>\n", "<docstring token>\n<function token>\n<assignment token>\n<code token>\n" ]
false
98,722
fcd6e3eaf410786c0f9cb442b740ebb9aa04e4af
# -*- coding: utf-8 -*- import math class FuncionPertenencia: def __init__(self,valor,tipo,coordenadas): self.valor = float(valor) self.tipo = tipo self.coordenadas = coordenadas def determinarFuncion(self): if self.tipo == "Trapezoidal": return Trapezoidal(self.valor,self.coordenadas) if self.tipo == "Triangular": return Triangular(self.valor,self.coordenadas) if self.tipo == "Singleton": return Singleton(self.valor,self.coordenadas) if self.tipo == "Gausiana": return Gausiana(self.valor,self.coordenadas) if self.tipo == "Campana": return Campana(self.valor,self.coordenadas) if self.tipo == "Sigmoide": return Sigmoide(self.valor,self.coordenadas) class Trapezoidal: def __init__(self,valor,coordenadas): self.valor = valor self.a,self.b,self.c,self.d = coordenadas self.vp = 0 def calcular(self): if self.valor < self.a: self.vp = 0 return self.vp if self.a <= self.valor <= self.b: self.vp = (self.valor - self.a) / (self.b - self.a) return self.vp if self.b <= self.valor <= self.c: self.vp = 1 return self.vp if self.c <= self.valor <= self.d: self.vp = (self.d - self.valor) / (self.d - self.c) return self.vp if self.valor > self.d: self.vp = 0 return self.vp class Trapezoidal_Derecho: def __init__(self,valor,coordenadas): self.valor = valor self.a,self.b = coordenadas self.vp = 0 def calcular(self): if self.valor < self.a: self.vp = 0 return self.vp if self.a <= self.valor <= self.b: self.vp = (self.valor - self.a) / (self.b - self.a) return self.vp if self.valor > self.b: self.vp = 1 return self.vp class Trapezoidal_Izquierdo: def __init__(self,valor,coordenadas): self.valor = valor self.a,self.b = coordenadas self.vp = 0 def calcular(self): if self.valor < self.a: self.vp = 1 return self.vp if self.a <= self.valor <= self.b: self.vp = (self.b-self.valor) / (self.b - self.a) return self.vp if self.valor > self.b: self.vp = 0 return self.vp class Triangular: def __init__(self,valor,coordenadas): self.valor = valor self.a,self.b,self.c = coordenadas self.vp = 0 def calcular(self): if self.valor < self.a: self.vp = 0 return self.vp if self.a <= self.valor <= self.b: self.vp = (self.valor - self.a) / (self.b - self.a) return self.vp if self.b <= self.valor <= self.c: self.vp = (self.c - self.valor) / (self.c - self.b) return self.vp if self.valor > self.c: self.vp = 0 return self.vp class Singleton: def __init__(self,valor,coordenadas): self.valor = valor self.a = coordenadas self.vp = 0 def calcular(self): if self.valor == self.a: self.vp = 1 return self.vp else: self.valor = 0 return self.vp class Gausiana: def __init__(self,valor,coordenadas): self.valor = valor self.a, self.b = coordenadas self.vp = 0 def calcular(self): self.vp = math.exp((-1/2)*(((self.valor-self.a)/self.b)**2)) return self.vp class Campana: def __init__(self,valor,coordenadas): self.valor = valor self.a,self.b,self.c = coordenadas self.vp = 0 def calcular(self): self.vp = 1 / (1 + (abs((self.valor - self.c) / self.a)**(2 * self.b))) return self.vp class Sigmoide: def __init__(self,valor,coordenadas): self.valor = valor self.a,self.b = coordenadas self.vp = 0 def calcular(self): self.vp = 1 / (1 + math.exp(-self.a * (self.valor - self.b))) return self.vp
[ "# -*- coding: utf-8 -*-\nimport math\n\n\nclass FuncionPertenencia:\n\n def __init__(self,valor,tipo,coordenadas):\n self.valor = float(valor)\n self.tipo = tipo\n self.coordenadas = coordenadas\n\n def determinarFuncion(self):\n if self.tipo == \"Trapezoidal\":\n return Trapezoidal(self.valor,self.coordenadas)\n\n if self.tipo == \"Triangular\":\n return Triangular(self.valor,self.coordenadas)\n\n if self.tipo == \"Singleton\":\n return Singleton(self.valor,self.coordenadas)\n\n if self.tipo == \"Gausiana\":\n return Gausiana(self.valor,self.coordenadas)\n\n if self.tipo == \"Campana\":\n return Campana(self.valor,self.coordenadas)\n\n if self.tipo == \"Sigmoide\":\n return Sigmoide(self.valor,self.coordenadas)\n\n\nclass Trapezoidal:\n\n def __init__(self,valor,coordenadas):\n self.valor = valor\n self.a,self.b,self.c,self.d = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n\n if self.b <= self.valor <= self.c:\n self.vp = 1\n return self.vp\n\n if self.c <= self.valor <= self.d:\n self.vp = (self.d - self.valor) / (self.d - self.c)\n return self.vp\n\n if self.valor > self.d:\n self.vp = 0\n return self.vp\n\n\nclass Trapezoidal_Derecho:\n\n def __init__(self,valor,coordenadas):\n self.valor = valor\n self.a,self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n\n if self.valor > self.b:\n self.vp = 1\n return self.vp\n\n\nclass Trapezoidal_Izquierdo:\n\n def __init__(self,valor,coordenadas):\n self.valor = valor\n self.a,self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 1\n return self.vp\n\n if self.a <= self.valor <= self.b:\n self.vp = (self.b-self.valor) / (self.b - self.a)\n return self.vp\n\n if self.valor > self.b:\n self.vp = 0\n return self.vp\n\n\nclass Triangular:\n\n def __init__(self,valor,coordenadas):\n self.valor = valor\n self.a,self.b,self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n\n if self.b <= self.valor <= self.c:\n self.vp = (self.c - self.valor) / (self.c - self.b)\n return self.vp\n\n if self.valor > self.c:\n self.vp = 0\n return self.vp\n\n\nclass Singleton:\n\n def __init__(self,valor,coordenadas):\n self.valor = valor\n self.a = coordenadas\n self.vp = 0\n\n def calcular(self):\n\n if self.valor == self.a:\n self.vp = 1\n return self.vp\n\n else:\n self.valor = 0\n return self.vp\n\n\nclass Gausiana:\n\n def __init__(self,valor,coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = math.exp((-1/2)*(((self.valor-self.a)/self.b)**2))\n return self.vp\n\n\nclass Campana:\n\n def __init__(self,valor,coordenadas):\n self.valor = valor\n self.a,self.b,self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + (abs((self.valor - self.c) / self.a)**(2 * self.b)))\n return self.vp\n\n\nclass Sigmoide:\n\n def __init__(self,valor,coordenadas):\n self.valor = valor\n self.a,self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + math.exp(-self.a * (self.valor - self.b)))\n return self.vp\n\n", "import math\n\n\nclass FuncionPertenencia:\n\n def __init__(self, valor, tipo, coordenadas):\n self.valor = float(valor)\n self.tipo = tipo\n self.coordenadas = coordenadas\n\n def determinarFuncion(self):\n if self.tipo == 'Trapezoidal':\n return Trapezoidal(self.valor, self.coordenadas)\n if self.tipo == 'Triangular':\n return Triangular(self.valor, self.coordenadas)\n if self.tipo == 'Singleton':\n return Singleton(self.valor, self.coordenadas)\n if self.tipo == 'Gausiana':\n return Gausiana(self.valor, self.coordenadas)\n if self.tipo == 'Campana':\n return Campana(self.valor, self.coordenadas)\n if self.tipo == 'Sigmoide':\n return Sigmoide(self.valor, self.coordenadas)\n\n\nclass Trapezoidal:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c, self.d = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n if self.b <= self.valor <= self.c:\n self.vp = 1\n return self.vp\n if self.c <= self.valor <= self.d:\n self.vp = (self.d - self.valor) / (self.d - self.c)\n return self.vp\n if self.valor > self.d:\n self.vp = 0\n return self.vp\n\n\nclass Trapezoidal_Derecho:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n if self.valor > self.b:\n self.vp = 1\n return self.vp\n\n\nclass Trapezoidal_Izquierdo:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 1\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.b - self.valor) / (self.b - self.a)\n return self.vp\n if self.valor > self.b:\n self.vp = 0\n return self.vp\n\n\nclass Triangular:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n if self.b <= self.valor <= self.c:\n self.vp = (self.c - self.valor) / (self.c - self.b)\n return self.vp\n if self.valor > self.c:\n self.vp = 0\n return self.vp\n\n\nclass Singleton:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor == self.a:\n self.vp = 1\n return self.vp\n else:\n self.valor = 0\n return self.vp\n\n\nclass Gausiana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = math.exp(-1 / 2 * ((self.valor - self.a) / self.b) ** 2)\n return self.vp\n\n\nclass Campana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + abs((self.valor - self.c) / self.a) ** (2 * self.b))\n return self.vp\n\n\nclass Sigmoide:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + math.exp(-self.a * (self.valor - self.b)))\n return self.vp\n", "<import token>\n\n\nclass FuncionPertenencia:\n\n def __init__(self, valor, tipo, coordenadas):\n self.valor = float(valor)\n self.tipo = tipo\n self.coordenadas = coordenadas\n\n def determinarFuncion(self):\n if self.tipo == 'Trapezoidal':\n return Trapezoidal(self.valor, self.coordenadas)\n if self.tipo == 'Triangular':\n return Triangular(self.valor, self.coordenadas)\n if self.tipo == 'Singleton':\n return Singleton(self.valor, self.coordenadas)\n if self.tipo == 'Gausiana':\n return Gausiana(self.valor, self.coordenadas)\n if self.tipo == 'Campana':\n return Campana(self.valor, self.coordenadas)\n if self.tipo == 'Sigmoide':\n return Sigmoide(self.valor, self.coordenadas)\n\n\nclass Trapezoidal:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c, self.d = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n if self.b <= self.valor <= self.c:\n self.vp = 1\n return self.vp\n if self.c <= self.valor <= self.d:\n self.vp = (self.d - self.valor) / (self.d - self.c)\n return self.vp\n if self.valor > self.d:\n self.vp = 0\n return self.vp\n\n\nclass Trapezoidal_Derecho:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n if self.valor > self.b:\n self.vp = 1\n return self.vp\n\n\nclass Trapezoidal_Izquierdo:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 1\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.b - self.valor) / (self.b - self.a)\n return self.vp\n if self.valor > self.b:\n self.vp = 0\n return self.vp\n\n\nclass Triangular:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n if self.b <= self.valor <= self.c:\n self.vp = (self.c - self.valor) / (self.c - self.b)\n return self.vp\n if self.valor > self.c:\n self.vp = 0\n return self.vp\n\n\nclass Singleton:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor == self.a:\n self.vp = 1\n return self.vp\n else:\n self.valor = 0\n return self.vp\n\n\nclass Gausiana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = math.exp(-1 / 2 * ((self.valor - self.a) / self.b) ** 2)\n return self.vp\n\n\nclass Campana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + abs((self.valor - self.c) / self.a) ** (2 * self.b))\n return self.vp\n\n\nclass Sigmoide:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + math.exp(-self.a * (self.valor - self.b)))\n return self.vp\n", "<import token>\n\n\nclass FuncionPertenencia:\n <function token>\n\n def determinarFuncion(self):\n if self.tipo == 'Trapezoidal':\n return Trapezoidal(self.valor, self.coordenadas)\n if self.tipo == 'Triangular':\n return Triangular(self.valor, self.coordenadas)\n if self.tipo == 'Singleton':\n return Singleton(self.valor, self.coordenadas)\n if self.tipo == 'Gausiana':\n return Gausiana(self.valor, self.coordenadas)\n if self.tipo == 'Campana':\n return Campana(self.valor, self.coordenadas)\n if self.tipo == 'Sigmoide':\n return Sigmoide(self.valor, self.coordenadas)\n\n\nclass Trapezoidal:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c, self.d = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n if self.b <= self.valor <= self.c:\n self.vp = 1\n return self.vp\n if self.c <= self.valor <= self.d:\n self.vp = (self.d - self.valor) / (self.d - self.c)\n return self.vp\n if self.valor > self.d:\n self.vp = 0\n return self.vp\n\n\nclass Trapezoidal_Derecho:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n if self.valor > self.b:\n self.vp = 1\n return self.vp\n\n\nclass Trapezoidal_Izquierdo:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 1\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.b - self.valor) / (self.b - self.a)\n return self.vp\n if self.valor > self.b:\n self.vp = 0\n return self.vp\n\n\nclass Triangular:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n if self.b <= self.valor <= self.c:\n self.vp = (self.c - self.valor) / (self.c - self.b)\n return self.vp\n if self.valor > self.c:\n self.vp = 0\n return self.vp\n\n\nclass Singleton:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor == self.a:\n self.vp = 1\n return self.vp\n else:\n self.valor = 0\n return self.vp\n\n\nclass Gausiana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = math.exp(-1 / 2 * ((self.valor - self.a) / self.b) ** 2)\n return self.vp\n\n\nclass Campana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + abs((self.valor - self.c) / self.a) ** (2 * self.b))\n return self.vp\n\n\nclass Sigmoide:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + math.exp(-self.a * (self.valor - self.b)))\n return self.vp\n", "<import token>\n\n\nclass FuncionPertenencia:\n <function token>\n <function token>\n\n\nclass Trapezoidal:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c, self.d = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n if self.b <= self.valor <= self.c:\n self.vp = 1\n return self.vp\n if self.c <= self.valor <= self.d:\n self.vp = (self.d - self.valor) / (self.d - self.c)\n return self.vp\n if self.valor > self.d:\n self.vp = 0\n return self.vp\n\n\nclass Trapezoidal_Derecho:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n if self.valor > self.b:\n self.vp = 1\n return self.vp\n\n\nclass Trapezoidal_Izquierdo:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 1\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.b - self.valor) / (self.b - self.a)\n return self.vp\n if self.valor > self.b:\n self.vp = 0\n return self.vp\n\n\nclass Triangular:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n if self.b <= self.valor <= self.c:\n self.vp = (self.c - self.valor) / (self.c - self.b)\n return self.vp\n if self.valor > self.c:\n self.vp = 0\n return self.vp\n\n\nclass Singleton:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor == self.a:\n self.vp = 1\n return self.vp\n else:\n self.valor = 0\n return self.vp\n\n\nclass Gausiana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = math.exp(-1 / 2 * ((self.valor - self.a) / self.b) ** 2)\n return self.vp\n\n\nclass Campana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + abs((self.valor - self.c) / self.a) ** (2 * self.b))\n return self.vp\n\n\nclass Sigmoide:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + math.exp(-self.a * (self.valor - self.b)))\n return self.vp\n", "<import token>\n<class token>\n\n\nclass Trapezoidal:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c, self.d = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n if self.b <= self.valor <= self.c:\n self.vp = 1\n return self.vp\n if self.c <= self.valor <= self.d:\n self.vp = (self.d - self.valor) / (self.d - self.c)\n return self.vp\n if self.valor > self.d:\n self.vp = 0\n return self.vp\n\n\nclass Trapezoidal_Derecho:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n if self.valor > self.b:\n self.vp = 1\n return self.vp\n\n\nclass Trapezoidal_Izquierdo:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 1\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.b - self.valor) / (self.b - self.a)\n return self.vp\n if self.valor > self.b:\n self.vp = 0\n return self.vp\n\n\nclass Triangular:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n if self.b <= self.valor <= self.c:\n self.vp = (self.c - self.valor) / (self.c - self.b)\n return self.vp\n if self.valor > self.c:\n self.vp = 0\n return self.vp\n\n\nclass Singleton:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor == self.a:\n self.vp = 1\n return self.vp\n else:\n self.valor = 0\n return self.vp\n\n\nclass Gausiana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = math.exp(-1 / 2 * ((self.valor - self.a) / self.b) ** 2)\n return self.vp\n\n\nclass Campana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + abs((self.valor - self.c) / self.a) ** (2 * self.b))\n return self.vp\n\n\nclass Sigmoide:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + math.exp(-self.a * (self.valor - self.b)))\n return self.vp\n", "<import token>\n<class token>\n\n\nclass Trapezoidal:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c, self.d = coordenadas\n self.vp = 0\n <function token>\n\n\nclass Trapezoidal_Derecho:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n if self.valor > self.b:\n self.vp = 1\n return self.vp\n\n\nclass Trapezoidal_Izquierdo:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 1\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.b - self.valor) / (self.b - self.a)\n return self.vp\n if self.valor > self.b:\n self.vp = 0\n return self.vp\n\n\nclass Triangular:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n if self.b <= self.valor <= self.c:\n self.vp = (self.c - self.valor) / (self.c - self.b)\n return self.vp\n if self.valor > self.c:\n self.vp = 0\n return self.vp\n\n\nclass Singleton:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor == self.a:\n self.vp = 1\n return self.vp\n else:\n self.valor = 0\n return self.vp\n\n\nclass Gausiana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = math.exp(-1 / 2 * ((self.valor - self.a) / self.b) ** 2)\n return self.vp\n\n\nclass Campana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + abs((self.valor - self.c) / self.a) ** (2 * self.b))\n return self.vp\n\n\nclass Sigmoide:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + math.exp(-self.a * (self.valor - self.b)))\n return self.vp\n", "<import token>\n<class token>\n\n\nclass Trapezoidal:\n <function token>\n <function token>\n\n\nclass Trapezoidal_Derecho:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n if self.valor > self.b:\n self.vp = 1\n return self.vp\n\n\nclass Trapezoidal_Izquierdo:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 1\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.b - self.valor) / (self.b - self.a)\n return self.vp\n if self.valor > self.b:\n self.vp = 0\n return self.vp\n\n\nclass Triangular:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n if self.b <= self.valor <= self.c:\n self.vp = (self.c - self.valor) / (self.c - self.b)\n return self.vp\n if self.valor > self.c:\n self.vp = 0\n return self.vp\n\n\nclass Singleton:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor == self.a:\n self.vp = 1\n return self.vp\n else:\n self.valor = 0\n return self.vp\n\n\nclass Gausiana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = math.exp(-1 / 2 * ((self.valor - self.a) / self.b) ** 2)\n return self.vp\n\n\nclass Campana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + abs((self.valor - self.c) / self.a) ** (2 * self.b))\n return self.vp\n\n\nclass Sigmoide:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + math.exp(-self.a * (self.valor - self.b)))\n return self.vp\n", "<import token>\n<class token>\n<class token>\n\n\nclass Trapezoidal_Derecho:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n if self.valor > self.b:\n self.vp = 1\n return self.vp\n\n\nclass Trapezoidal_Izquierdo:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 1\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.b - self.valor) / (self.b - self.a)\n return self.vp\n if self.valor > self.b:\n self.vp = 0\n return self.vp\n\n\nclass Triangular:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n if self.b <= self.valor <= self.c:\n self.vp = (self.c - self.valor) / (self.c - self.b)\n return self.vp\n if self.valor > self.c:\n self.vp = 0\n return self.vp\n\n\nclass Singleton:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor == self.a:\n self.vp = 1\n return self.vp\n else:\n self.valor = 0\n return self.vp\n\n\nclass Gausiana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = math.exp(-1 / 2 * ((self.valor - self.a) / self.b) ** 2)\n return self.vp\n\n\nclass Campana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + abs((self.valor - self.c) / self.a) ** (2 * self.b))\n return self.vp\n\n\nclass Sigmoide:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + math.exp(-self.a * (self.valor - self.b)))\n return self.vp\n", "<import token>\n<class token>\n<class token>\n\n\nclass Trapezoidal_Derecho:\n <function token>\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n if self.valor > self.b:\n self.vp = 1\n return self.vp\n\n\nclass Trapezoidal_Izquierdo:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 1\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.b - self.valor) / (self.b - self.a)\n return self.vp\n if self.valor > self.b:\n self.vp = 0\n return self.vp\n\n\nclass Triangular:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n if self.b <= self.valor <= self.c:\n self.vp = (self.c - self.valor) / (self.c - self.b)\n return self.vp\n if self.valor > self.c:\n self.vp = 0\n return self.vp\n\n\nclass Singleton:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor == self.a:\n self.vp = 1\n return self.vp\n else:\n self.valor = 0\n return self.vp\n\n\nclass Gausiana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = math.exp(-1 / 2 * ((self.valor - self.a) / self.b) ** 2)\n return self.vp\n\n\nclass Campana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + abs((self.valor - self.c) / self.a) ** (2 * self.b))\n return self.vp\n\n\nclass Sigmoide:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + math.exp(-self.a * (self.valor - self.b)))\n return self.vp\n", "<import token>\n<class token>\n<class token>\n\n\nclass Trapezoidal_Derecho:\n <function token>\n <function token>\n\n\nclass Trapezoidal_Izquierdo:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 1\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.b - self.valor) / (self.b - self.a)\n return self.vp\n if self.valor > self.b:\n self.vp = 0\n return self.vp\n\n\nclass Triangular:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n if self.b <= self.valor <= self.c:\n self.vp = (self.c - self.valor) / (self.c - self.b)\n return self.vp\n if self.valor > self.c:\n self.vp = 0\n return self.vp\n\n\nclass Singleton:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor == self.a:\n self.vp = 1\n return self.vp\n else:\n self.valor = 0\n return self.vp\n\n\nclass Gausiana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = math.exp(-1 / 2 * ((self.valor - self.a) / self.b) ** 2)\n return self.vp\n\n\nclass Campana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + abs((self.valor - self.c) / self.a) ** (2 * self.b))\n return self.vp\n\n\nclass Sigmoide:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + math.exp(-self.a * (self.valor - self.b)))\n return self.vp\n", "<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass Trapezoidal_Izquierdo:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 1\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.b - self.valor) / (self.b - self.a)\n return self.vp\n if self.valor > self.b:\n self.vp = 0\n return self.vp\n\n\nclass Triangular:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n if self.b <= self.valor <= self.c:\n self.vp = (self.c - self.valor) / (self.c - self.b)\n return self.vp\n if self.valor > self.c:\n self.vp = 0\n return self.vp\n\n\nclass Singleton:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor == self.a:\n self.vp = 1\n return self.vp\n else:\n self.valor = 0\n return self.vp\n\n\nclass Gausiana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = math.exp(-1 / 2 * ((self.valor - self.a) / self.b) ** 2)\n return self.vp\n\n\nclass Campana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + abs((self.valor - self.c) / self.a) ** (2 * self.b))\n return self.vp\n\n\nclass Sigmoide:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + math.exp(-self.a * (self.valor - self.b)))\n return self.vp\n", "<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass Trapezoidal_Izquierdo:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n <function token>\n\n\nclass Triangular:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n if self.b <= self.valor <= self.c:\n self.vp = (self.c - self.valor) / (self.c - self.b)\n return self.vp\n if self.valor > self.c:\n self.vp = 0\n return self.vp\n\n\nclass Singleton:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor == self.a:\n self.vp = 1\n return self.vp\n else:\n self.valor = 0\n return self.vp\n\n\nclass Gausiana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = math.exp(-1 / 2 * ((self.valor - self.a) / self.b) ** 2)\n return self.vp\n\n\nclass Campana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + abs((self.valor - self.c) / self.a) ** (2 * self.b))\n return self.vp\n\n\nclass Sigmoide:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + math.exp(-self.a * (self.valor - self.b)))\n return self.vp\n", "<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass Trapezoidal_Izquierdo:\n <function token>\n <function token>\n\n\nclass Triangular:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n if self.b <= self.valor <= self.c:\n self.vp = (self.c - self.valor) / (self.c - self.b)\n return self.vp\n if self.valor > self.c:\n self.vp = 0\n return self.vp\n\n\nclass Singleton:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor == self.a:\n self.vp = 1\n return self.vp\n else:\n self.valor = 0\n return self.vp\n\n\nclass Gausiana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = math.exp(-1 / 2 * ((self.valor - self.a) / self.b) ** 2)\n return self.vp\n\n\nclass Campana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + abs((self.valor - self.c) / self.a) ** (2 * self.b))\n return self.vp\n\n\nclass Sigmoide:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + math.exp(-self.a * (self.valor - self.b)))\n return self.vp\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Triangular:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n if self.b <= self.valor <= self.c:\n self.vp = (self.c - self.valor) / (self.c - self.b)\n return self.vp\n if self.valor > self.c:\n self.vp = 0\n return self.vp\n\n\nclass Singleton:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor == self.a:\n self.vp = 1\n return self.vp\n else:\n self.valor = 0\n return self.vp\n\n\nclass Gausiana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = math.exp(-1 / 2 * ((self.valor - self.a) / self.b) ** 2)\n return self.vp\n\n\nclass Campana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + abs((self.valor - self.c) / self.a) ** (2 * self.b))\n return self.vp\n\n\nclass Sigmoide:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + math.exp(-self.a * (self.valor - self.b)))\n return self.vp\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Triangular:\n <function token>\n\n def calcular(self):\n if self.valor < self.a:\n self.vp = 0\n return self.vp\n if self.a <= self.valor <= self.b:\n self.vp = (self.valor - self.a) / (self.b - self.a)\n return self.vp\n if self.b <= self.valor <= self.c:\n self.vp = (self.c - self.valor) / (self.c - self.b)\n return self.vp\n if self.valor > self.c:\n self.vp = 0\n return self.vp\n\n\nclass Singleton:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor == self.a:\n self.vp = 1\n return self.vp\n else:\n self.valor = 0\n return self.vp\n\n\nclass Gausiana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = math.exp(-1 / 2 * ((self.valor - self.a) / self.b) ** 2)\n return self.vp\n\n\nclass Campana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + abs((self.valor - self.c) / self.a) ** (2 * self.b))\n return self.vp\n\n\nclass Sigmoide:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + math.exp(-self.a * (self.valor - self.b)))\n return self.vp\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Triangular:\n <function token>\n <function token>\n\n\nclass Singleton:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor == self.a:\n self.vp = 1\n return self.vp\n else:\n self.valor = 0\n return self.vp\n\n\nclass Gausiana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = math.exp(-1 / 2 * ((self.valor - self.a) / self.b) ** 2)\n return self.vp\n\n\nclass Campana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + abs((self.valor - self.c) / self.a) ** (2 * self.b))\n return self.vp\n\n\nclass Sigmoide:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + math.exp(-self.a * (self.valor - self.b)))\n return self.vp\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Singleton:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a = coordenadas\n self.vp = 0\n\n def calcular(self):\n if self.valor == self.a:\n self.vp = 1\n return self.vp\n else:\n self.valor = 0\n return self.vp\n\n\nclass Gausiana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = math.exp(-1 / 2 * ((self.valor - self.a) / self.b) ** 2)\n return self.vp\n\n\nclass Campana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + abs((self.valor - self.c) / self.a) ** (2 * self.b))\n return self.vp\n\n\nclass Sigmoide:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + math.exp(-self.a * (self.valor - self.b)))\n return self.vp\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Singleton:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a = coordenadas\n self.vp = 0\n <function token>\n\n\nclass Gausiana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = math.exp(-1 / 2 * ((self.valor - self.a) / self.b) ** 2)\n return self.vp\n\n\nclass Campana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + abs((self.valor - self.c) / self.a) ** (2 * self.b))\n return self.vp\n\n\nclass Sigmoide:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + math.exp(-self.a * (self.valor - self.b)))\n return self.vp\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Singleton:\n <function token>\n <function token>\n\n\nclass Gausiana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = math.exp(-1 / 2 * ((self.valor - self.a) / self.b) ** 2)\n return self.vp\n\n\nclass Campana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + abs((self.valor - self.c) / self.a) ** (2 * self.b))\n return self.vp\n\n\nclass Sigmoide:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + math.exp(-self.a * (self.valor - self.b)))\n return self.vp\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Gausiana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = math.exp(-1 / 2 * ((self.valor - self.a) / self.b) ** 2)\n return self.vp\n\n\nclass Campana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + abs((self.valor - self.c) / self.a) ** (2 * self.b))\n return self.vp\n\n\nclass Sigmoide:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + math.exp(-self.a * (self.valor - self.b)))\n return self.vp\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Gausiana:\n <function token>\n\n def calcular(self):\n self.vp = math.exp(-1 / 2 * ((self.valor - self.a) / self.b) ** 2)\n return self.vp\n\n\nclass Campana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + abs((self.valor - self.c) / self.a) ** (2 * self.b))\n return self.vp\n\n\nclass Sigmoide:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + math.exp(-self.a * (self.valor - self.b)))\n return self.vp\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Gausiana:\n <function token>\n <function token>\n\n\nclass Campana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + abs((self.valor - self.c) / self.a) ** (2 * self.b))\n return self.vp\n\n\nclass Sigmoide:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + math.exp(-self.a * (self.valor - self.b)))\n return self.vp\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Campana:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b, self.c = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + abs((self.valor - self.c) / self.a) ** (2 * self.b))\n return self.vp\n\n\nclass Sigmoide:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + math.exp(-self.a * (self.valor - self.b)))\n return self.vp\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Campana:\n <function token>\n\n def calcular(self):\n self.vp = 1 / (1 + abs((self.valor - self.c) / self.a) ** (2 * self.b))\n return self.vp\n\n\nclass Sigmoide:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + math.exp(-self.a * (self.valor - self.b)))\n return self.vp\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Campana:\n <function token>\n <function token>\n\n\nclass Sigmoide:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + math.exp(-self.a * (self.valor - self.b)))\n return self.vp\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Sigmoide:\n\n def __init__(self, valor, coordenadas):\n self.valor = valor\n self.a, self.b = coordenadas\n self.vp = 0\n\n def calcular(self):\n self.vp = 1 / (1 + math.exp(-self.a * (self.valor - self.b)))\n return self.vp\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Sigmoide:\n <function token>\n\n def calcular(self):\n self.vp = 1 / (1 + math.exp(-self.a * (self.valor - self.b)))\n return self.vp\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Sigmoide:\n <function token>\n <function token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n" ]
false
98,723
03c9437a7b6b474d4c486970aade85e4739d1961
# Generated by Django 2.1.7 on 2019-02-19 14:37 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Film', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('film_title', models.CharField(max_length=200)), ('year', models.PositiveSmallIntegerField(blank=True, null=True)), ('genre', models.CharField(max_length=100)), ], options={ 'ordering': ['film_title'], }, ), migrations.CreateModel( name='Review', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('summary', models.TextField(null=True)), ('review', models.TextField()), ('review_film', models.ForeignKey(default=1, on_delete=django.db.models.deletion.SET_DEFAULT, to='film_info.Film')), ], ), ]
[ "# Generated by Django 2.1.7 on 2019-02-19 14:37\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Film',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('film_title', models.CharField(max_length=200)),\n ('year', models.PositiveSmallIntegerField(blank=True, null=True)),\n ('genre', models.CharField(max_length=100)),\n ],\n options={\n 'ordering': ['film_title'],\n },\n ),\n migrations.CreateModel(\n name='Review',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('summary', models.TextField(null=True)),\n ('review', models.TextField()),\n ('review_film', models.ForeignKey(default=1, on_delete=django.db.models.deletion.SET_DEFAULT, to='film_info.Film')),\n ],\n ),\n ]\n", "from django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n initial = True\n dependencies = []\n operations = [migrations.CreateModel(name='Film', fields=[('id', models\n .AutoField(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')), ('film_title', models.CharField(max_length=200\n )), ('year', models.PositiveSmallIntegerField(blank=True, null=True\n )), ('genre', models.CharField(max_length=100))], options={\n 'ordering': ['film_title']}), migrations.CreateModel(name='Review',\n fields=[('id', models.AutoField(auto_created=True, primary_key=True,\n serialize=False, verbose_name='ID')), ('summary', models.TextField(\n null=True)), ('review', models.TextField()), ('review_film', models\n .ForeignKey(default=1, on_delete=django.db.models.deletion.\n SET_DEFAULT, to='film_info.Film'))])]\n", "<import token>\n\n\nclass Migration(migrations.Migration):\n initial = True\n dependencies = []\n operations = [migrations.CreateModel(name='Film', fields=[('id', models\n .AutoField(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')), ('film_title', models.CharField(max_length=200\n )), ('year', models.PositiveSmallIntegerField(blank=True, null=True\n )), ('genre', models.CharField(max_length=100))], options={\n 'ordering': ['film_title']}), migrations.CreateModel(name='Review',\n fields=[('id', models.AutoField(auto_created=True, primary_key=True,\n serialize=False, verbose_name='ID')), ('summary', models.TextField(\n null=True)), ('review', models.TextField()), ('review_film', models\n .ForeignKey(default=1, on_delete=django.db.models.deletion.\n SET_DEFAULT, to='film_info.Film'))])]\n", "<import token>\n\n\nclass Migration(migrations.Migration):\n <assignment token>\n <assignment token>\n <assignment token>\n", "<import token>\n<class token>\n" ]
false
98,724
d4ff49f491a986503a0afd50aeb1ac2144e35f4e
#!/usr/bin/env python import rospy from std_msgs.msg import Int16 from sensor_msgs.msg import Joy # Base on the joystick code by Author: Andrew Dai but converted for my purpose # This ROS Node converts Joystick inputs from the joy node # into commands for the motors # Receives joystick messages (subscribed to Joy topic) then converts that to # Int16 messages to the topics for: left_motor_effort and right_motor_effort. # Then will take the value passed in by the joystick left thumbstick up and down (index 1) and # and the value passed in by the joystick right thumbstick left and right (index 2) and # shift the values right by 7. Doing this because the numbers coming in are 16 bit signed and # the desired output is an 9 bit signed number. The output to the motor is actually an 8 bit # unsigned number but I am using the nineth bit for the desired direction and converting # it on the Mega. Shifting the number to the left effectively spreading the value over the integer # range -255 to +255. This value will be added to the obosite side and subtracted from the same # side so the vehicle will turn even if no value is applied to the left thumbstick. An example # of the operation being a desired right turn, the thumbstick applied and the value is subtracted # from the right motor rotating it backward and the value will be added to the left motor rotating # it forward allowing for a right turn. If the vehicle is already in motion and the value is # applied then the same thing will happen only now they will no longer be adding or subtracting # from zero but rather the left thumbstick value. This shows that each right value with just # subtract or add to the left value. def callback(data): # the left thumb value is the up or down value read from the controller left_thumb_value = 100*data.axes[1] # the right thumb value is the left right value. right_thumb_value = 100*data.axes[2] # right motor command value right_motor_command = 0 # left motor command value left_motor_command = 0 # minimum value to turn on mc = 20 # checking to see if the left thumbstick is up or down if left_thumb_value < -mc: right_motor_command = int(left_thumb_value - right_thumb_value) left_motor_command = int(left_thumb_value + right_thumb_value) elif left_thumb_value > mc: right_motor_command = int(left_thumb_value + right_thumb_value) left_motor_command = int(left_thumb_value - right_thumb_value) else: right_motor_command = 0 left_motor_command = 0 left_motor.publish(left_motor_command) right_motor.publish(right_motor_command) # Intializes everything def start(): # publishing to the left motor and the right motor global left_motor global right_motor left_motor = rospy.Publisher('left_motor_effort', Int16, queue_size=10) right_motor = rospy.Publisher('right_motor_effort', Int16, queue_size=10) # subscribing to the joystick inputs on topic "joy" to get inputs from the controller rospy.Subscriber("joy", Joy, callback) # starting the node rospy.init_node('Joy2Turtle') rospy.spin() if __name__ == '__main__': start()
[ "#!/usr/bin/env python\nimport rospy\nfrom std_msgs.msg import Int16\nfrom sensor_msgs.msg import Joy\n\n# Base on the joystick code by Author: Andrew Dai but converted for my purpose\n# This ROS Node converts Joystick inputs from the joy node\n# into commands for the motors\n\n# Receives joystick messages (subscribed to Joy topic) then converts that to \n# Int16 messages to the topics for: left_motor_effort and right_motor_effort.\n# Then will take the value passed in by the joystick left thumbstick up and down (index 1) and \n# and the value passed in by the joystick right thumbstick left and right (index 2) and \n# shift the values right by 7. Doing this because the numbers coming in are 16 bit signed and \n# the desired output is an 9 bit signed number. The output to the motor is actually an 8 bit \n# unsigned number but I am using the nineth bit for the desired direction and converting \n# it on the Mega. Shifting the number to the left effectively spreading the value over the integer \n# range -255 to +255. This value will be added to the obosite side and subtracted from the same \n# side so the vehicle will turn even if no value is applied to the left thumbstick. An example \n# of the operation being a desired right turn, the thumbstick applied and the value is subtracted # from the right motor rotating it backward and the value will be added to the left motor rotating # it forward allowing for a right turn. If the vehicle is already in motion and the value is \n# applied then the same thing will happen only now they will no longer be adding or subtracting \n# from zero but rather the left thumbstick value. This shows that each right value with just \n# subtract or add to the left value.\n\ndef callback(data):\n # the left thumb value is the up or down value read from the controller\n left_thumb_value = 100*data.axes[1]\n # the right thumb value is the left right value.\n right_thumb_value = 100*data.axes[2]\n # right motor command value\n right_motor_command = 0\n # left motor command value\n left_motor_command = 0\n # minimum value to turn on\n mc = 20\n\n # checking to see if the left thumbstick is up or down\n if left_thumb_value < -mc:\n right_motor_command = int(left_thumb_value - right_thumb_value)\n left_motor_command = int(left_thumb_value + right_thumb_value)\n\n elif left_thumb_value > mc:\n right_motor_command = int(left_thumb_value + right_thumb_value)\n left_motor_command = int(left_thumb_value - right_thumb_value)\n\n else:\n right_motor_command = 0\n left_motor_command = 0\n \n \n left_motor.publish(left_motor_command)\n right_motor.publish(right_motor_command)\n\n# Intializes everything\ndef start():\n # publishing to the left motor and the right motor\n global left_motor\n global right_motor\n \n left_motor = rospy.Publisher('left_motor_effort', Int16, queue_size=10)\n right_motor = rospy.Publisher('right_motor_effort', Int16, queue_size=10)\n \n # subscribing to the joystick inputs on topic \"joy\" to get inputs from the controller\n rospy.Subscriber(\"joy\", Joy, callback)\n # starting the node \n rospy.init_node('Joy2Turtle')\n rospy.spin()\n\nif __name__ == '__main__':\n start()\n\n", "import rospy\nfrom std_msgs.msg import Int16\nfrom sensor_msgs.msg import Joy\n\n\ndef callback(data):\n left_thumb_value = 100 * data.axes[1]\n right_thumb_value = 100 * data.axes[2]\n right_motor_command = 0\n left_motor_command = 0\n mc = 20\n if left_thumb_value < -mc:\n right_motor_command = int(left_thumb_value - right_thumb_value)\n left_motor_command = int(left_thumb_value + right_thumb_value)\n elif left_thumb_value > mc:\n right_motor_command = int(left_thumb_value + right_thumb_value)\n left_motor_command = int(left_thumb_value - right_thumb_value)\n else:\n right_motor_command = 0\n left_motor_command = 0\n left_motor.publish(left_motor_command)\n right_motor.publish(right_motor_command)\n\n\ndef start():\n global left_motor\n global right_motor\n left_motor = rospy.Publisher('left_motor_effort', Int16, queue_size=10)\n right_motor = rospy.Publisher('right_motor_effort', Int16, queue_size=10)\n rospy.Subscriber('joy', Joy, callback)\n rospy.init_node('Joy2Turtle')\n rospy.spin()\n\n\nif __name__ == '__main__':\n start()\n", "<import token>\n\n\ndef callback(data):\n left_thumb_value = 100 * data.axes[1]\n right_thumb_value = 100 * data.axes[2]\n right_motor_command = 0\n left_motor_command = 0\n mc = 20\n if left_thumb_value < -mc:\n right_motor_command = int(left_thumb_value - right_thumb_value)\n left_motor_command = int(left_thumb_value + right_thumb_value)\n elif left_thumb_value > mc:\n right_motor_command = int(left_thumb_value + right_thumb_value)\n left_motor_command = int(left_thumb_value - right_thumb_value)\n else:\n right_motor_command = 0\n left_motor_command = 0\n left_motor.publish(left_motor_command)\n right_motor.publish(right_motor_command)\n\n\ndef start():\n global left_motor\n global right_motor\n left_motor = rospy.Publisher('left_motor_effort', Int16, queue_size=10)\n right_motor = rospy.Publisher('right_motor_effort', Int16, queue_size=10)\n rospy.Subscriber('joy', Joy, callback)\n rospy.init_node('Joy2Turtle')\n rospy.spin()\n\n\nif __name__ == '__main__':\n start()\n", "<import token>\n\n\ndef callback(data):\n left_thumb_value = 100 * data.axes[1]\n right_thumb_value = 100 * data.axes[2]\n right_motor_command = 0\n left_motor_command = 0\n mc = 20\n if left_thumb_value < -mc:\n right_motor_command = int(left_thumb_value - right_thumb_value)\n left_motor_command = int(left_thumb_value + right_thumb_value)\n elif left_thumb_value > mc:\n right_motor_command = int(left_thumb_value + right_thumb_value)\n left_motor_command = int(left_thumb_value - right_thumb_value)\n else:\n right_motor_command = 0\n left_motor_command = 0\n left_motor.publish(left_motor_command)\n right_motor.publish(right_motor_command)\n\n\ndef start():\n global left_motor\n global right_motor\n left_motor = rospy.Publisher('left_motor_effort', Int16, queue_size=10)\n right_motor = rospy.Publisher('right_motor_effort', Int16, queue_size=10)\n rospy.Subscriber('joy', Joy, callback)\n rospy.init_node('Joy2Turtle')\n rospy.spin()\n\n\n<code token>\n", "<import token>\n\n\ndef callback(data):\n left_thumb_value = 100 * data.axes[1]\n right_thumb_value = 100 * data.axes[2]\n right_motor_command = 0\n left_motor_command = 0\n mc = 20\n if left_thumb_value < -mc:\n right_motor_command = int(left_thumb_value - right_thumb_value)\n left_motor_command = int(left_thumb_value + right_thumb_value)\n elif left_thumb_value > mc:\n right_motor_command = int(left_thumb_value + right_thumb_value)\n left_motor_command = int(left_thumb_value - right_thumb_value)\n else:\n right_motor_command = 0\n left_motor_command = 0\n left_motor.publish(left_motor_command)\n right_motor.publish(right_motor_command)\n\n\n<function token>\n<code token>\n", "<import token>\n<function token>\n<function token>\n<code token>\n" ]
false
98,725
8afc3e942b93d7d9b8565041685dfea6179ca16e
from text_parser import * from lmfit import Model import os dir_path = './2020_03_18' CDBS_files = glob.glob(os.path.join(dir_path, "*CDBS*.asc")) file_name = [] DBS_matrix = {} CDBS_matrix = {} label_list = ['sample A', 'sample B', 'sample 1', 'sample 2', 'sample 3'] width = 30 gmodel = Model(gaussian) linestyle = ['s', 'o', '^', '.', '-.', ':', '--'] for n, file in enumerate(CDBS_files): basename = os.path.basename(file) file_name.append(basename) f = open(file, 'r') lines = f.readlines() CDBS_data = [] for i in range(1024): count = lines[i+23].split(",") count = list(map(int, count)) del count[0] CDBS_data.append(count) DBS_matrix[basename] = np.array(CDBS_data, dtype=float) rot_matrix = ndimage.rotate(np.array(CDBS_data, dtype=float), -45) CDBS_matrix[basename] = ndimage.zoom(rot_matrix, 1 / np.sqrt(2)) x, y, max_point = find_sudo_peak(DBS_matrix[basename], width=width) x_CDBS, y_CDBS, max_point_CBDS = find_sudo_peak(CDBS_matrix[basename], width=width) # plt.plot(x, np.divide(y, AUC), '.', label=basename) params = gmodel.make_params(cen=max_point[1], amp=np.max(y) * (np.sqrt(2 * np.pi) * width / 2), wid=width / 2) result = gmodel.fit(y, params, x=x) AUC = integrate.simps(result.best_fit, x) x_adj = np.add(0.134*np.subtract(x, max_point[1]), 511) print(result.best_values['wid']) plt.plot(x_adj, np.divide(y, AUC), linestyle[n], label=label_list[n]) ###################################################################### params_CDBS = gmodel.make_params(cen=max_point_CBDS[1], amp=np.max(y_CDBS) * (np.sqrt(2 * np.pi) * width / 2), wid=width / 2) result_CDBS = gmodel.fit(y_CDBS, params_CDBS, x=x_CDBS) AUC_CDBS = integrate.simps(result_CDBS.best_fit, x_CDBS) x_adj_CDBS = np.add(0.134 * np.subtract(x_CDBS, max_point_CBDS[1]), 511) print(result_CDBS.best_values['wid']) plt.plot(x_adj_CDBS, np.divide(y_CDBS, AUC_CDBS), linestyle[n], label=label_list[n]+'CDBS') # x_hr = np.linspace(x[0], x[-1], 10*len(x)) # y_hr = gaussian(x_hr, cen=result.best_values['cen'], amp=result.best_values['amp'], wid=result.best_values['wid']) # plt.plot(x_hr, y_hr, '-') margin = 0.06 plt.xlim(x_adj_CDBS[0]-margin, 515) plt.yscale('log') plt.xlabel("Energy (keV)") plt.ylabel("Counts (A.U.)") plt.legend(loc='best') plt.show()
[ "from text_parser import *\nfrom lmfit import Model\nimport os\n\ndir_path = './2020_03_18'\nCDBS_files = glob.glob(os.path.join(dir_path, \"*CDBS*.asc\"))\nfile_name = []\nDBS_matrix = {}\nCDBS_matrix = {}\nlabel_list = ['sample A', 'sample B', 'sample 1', 'sample 2', 'sample 3']\n\nwidth = 30\ngmodel = Model(gaussian)\n\n\nlinestyle = ['s', 'o', '^', '.', '-.', ':', '--']\n\nfor n, file in enumerate(CDBS_files):\n basename = os.path.basename(file)\n file_name.append(basename)\n f = open(file, 'r')\n lines = f.readlines()\n CDBS_data = []\n for i in range(1024):\n count = lines[i+23].split(\",\")\n count = list(map(int, count))\n del count[0]\n CDBS_data.append(count)\n DBS_matrix[basename] = np.array(CDBS_data, dtype=float)\n rot_matrix = ndimage.rotate(np.array(CDBS_data, dtype=float), -45)\n CDBS_matrix[basename] = ndimage.zoom(rot_matrix, 1 / np.sqrt(2))\n\n x, y, max_point = find_sudo_peak(DBS_matrix[basename], width=width)\n x_CDBS, y_CDBS, max_point_CBDS = find_sudo_peak(CDBS_matrix[basename], width=width)\n\n # plt.plot(x, np.divide(y, AUC), '.', label=basename)\n\n params = gmodel.make_params(cen=max_point[1], amp=np.max(y) * (np.sqrt(2 * np.pi) * width / 2), wid=width / 2)\n result = gmodel.fit(y, params, x=x)\n AUC = integrate.simps(result.best_fit, x)\n\n x_adj = np.add(0.134*np.subtract(x, max_point[1]), 511)\n print(result.best_values['wid'])\n plt.plot(x_adj, np.divide(y, AUC), linestyle[n], label=label_list[n])\n######################################################################\n params_CDBS = gmodel.make_params(cen=max_point_CBDS[1], amp=np.max(y_CDBS) * (np.sqrt(2 * np.pi) * width / 2),\n wid=width / 2)\n result_CDBS = gmodel.fit(y_CDBS, params_CDBS, x=x_CDBS)\n AUC_CDBS = integrate.simps(result_CDBS.best_fit, x_CDBS)\n\n x_adj_CDBS = np.add(0.134 * np.subtract(x_CDBS, max_point_CBDS[1]), 511)\n print(result_CDBS.best_values['wid'])\n plt.plot(x_adj_CDBS, np.divide(y_CDBS, AUC_CDBS), linestyle[n], label=label_list[n]+'CDBS')\n # x_hr = np.linspace(x[0], x[-1], 10*len(x))\n # y_hr = gaussian(x_hr, cen=result.best_values['cen'], amp=result.best_values['amp'], wid=result.best_values['wid'])\n # plt.plot(x_hr, y_hr, '-')\n\nmargin = 0.06\nplt.xlim(x_adj_CDBS[0]-margin, 515)\nplt.yscale('log')\nplt.xlabel(\"Energy (keV)\")\nplt.ylabel(\"Counts (A.U.)\")\nplt.legend(loc='best')\nplt.show()\n\n", "from text_parser import *\nfrom lmfit import Model\nimport os\ndir_path = './2020_03_18'\nCDBS_files = glob.glob(os.path.join(dir_path, '*CDBS*.asc'))\nfile_name = []\nDBS_matrix = {}\nCDBS_matrix = {}\nlabel_list = ['sample A', 'sample B', 'sample 1', 'sample 2', 'sample 3']\nwidth = 30\ngmodel = Model(gaussian)\nlinestyle = ['s', 'o', '^', '.', '-.', ':', '--']\nfor n, file in enumerate(CDBS_files):\n basename = os.path.basename(file)\n file_name.append(basename)\n f = open(file, 'r')\n lines = f.readlines()\n CDBS_data = []\n for i in range(1024):\n count = lines[i + 23].split(',')\n count = list(map(int, count))\n del count[0]\n CDBS_data.append(count)\n DBS_matrix[basename] = np.array(CDBS_data, dtype=float)\n rot_matrix = ndimage.rotate(np.array(CDBS_data, dtype=float), -45)\n CDBS_matrix[basename] = ndimage.zoom(rot_matrix, 1 / np.sqrt(2))\n x, y, max_point = find_sudo_peak(DBS_matrix[basename], width=width)\n x_CDBS, y_CDBS, max_point_CBDS = find_sudo_peak(CDBS_matrix[basename],\n width=width)\n params = gmodel.make_params(cen=max_point[1], amp=np.max(y) * (np.sqrt(\n 2 * np.pi) * width / 2), wid=width / 2)\n result = gmodel.fit(y, params, x=x)\n AUC = integrate.simps(result.best_fit, x)\n x_adj = np.add(0.134 * np.subtract(x, max_point[1]), 511)\n print(result.best_values['wid'])\n plt.plot(x_adj, np.divide(y, AUC), linestyle[n], label=label_list[n])\n params_CDBS = gmodel.make_params(cen=max_point_CBDS[1], amp=np.max(\n y_CDBS) * (np.sqrt(2 * np.pi) * width / 2), wid=width / 2)\n result_CDBS = gmodel.fit(y_CDBS, params_CDBS, x=x_CDBS)\n AUC_CDBS = integrate.simps(result_CDBS.best_fit, x_CDBS)\n x_adj_CDBS = np.add(0.134 * np.subtract(x_CDBS, max_point_CBDS[1]), 511)\n print(result_CDBS.best_values['wid'])\n plt.plot(x_adj_CDBS, np.divide(y_CDBS, AUC_CDBS), linestyle[n], label=\n label_list[n] + 'CDBS')\nmargin = 0.06\nplt.xlim(x_adj_CDBS[0] - margin, 515)\nplt.yscale('log')\nplt.xlabel('Energy (keV)')\nplt.ylabel('Counts (A.U.)')\nplt.legend(loc='best')\nplt.show()\n", "<import token>\ndir_path = './2020_03_18'\nCDBS_files = glob.glob(os.path.join(dir_path, '*CDBS*.asc'))\nfile_name = []\nDBS_matrix = {}\nCDBS_matrix = {}\nlabel_list = ['sample A', 'sample B', 'sample 1', 'sample 2', 'sample 3']\nwidth = 30\ngmodel = Model(gaussian)\nlinestyle = ['s', 'o', '^', '.', '-.', ':', '--']\nfor n, file in enumerate(CDBS_files):\n basename = os.path.basename(file)\n file_name.append(basename)\n f = open(file, 'r')\n lines = f.readlines()\n CDBS_data = []\n for i in range(1024):\n count = lines[i + 23].split(',')\n count = list(map(int, count))\n del count[0]\n CDBS_data.append(count)\n DBS_matrix[basename] = np.array(CDBS_data, dtype=float)\n rot_matrix = ndimage.rotate(np.array(CDBS_data, dtype=float), -45)\n CDBS_matrix[basename] = ndimage.zoom(rot_matrix, 1 / np.sqrt(2))\n x, y, max_point = find_sudo_peak(DBS_matrix[basename], width=width)\n x_CDBS, y_CDBS, max_point_CBDS = find_sudo_peak(CDBS_matrix[basename],\n width=width)\n params = gmodel.make_params(cen=max_point[1], amp=np.max(y) * (np.sqrt(\n 2 * np.pi) * width / 2), wid=width / 2)\n result = gmodel.fit(y, params, x=x)\n AUC = integrate.simps(result.best_fit, x)\n x_adj = np.add(0.134 * np.subtract(x, max_point[1]), 511)\n print(result.best_values['wid'])\n plt.plot(x_adj, np.divide(y, AUC), linestyle[n], label=label_list[n])\n params_CDBS = gmodel.make_params(cen=max_point_CBDS[1], amp=np.max(\n y_CDBS) * (np.sqrt(2 * np.pi) * width / 2), wid=width / 2)\n result_CDBS = gmodel.fit(y_CDBS, params_CDBS, x=x_CDBS)\n AUC_CDBS = integrate.simps(result_CDBS.best_fit, x_CDBS)\n x_adj_CDBS = np.add(0.134 * np.subtract(x_CDBS, max_point_CBDS[1]), 511)\n print(result_CDBS.best_values['wid'])\n plt.plot(x_adj_CDBS, np.divide(y_CDBS, AUC_CDBS), linestyle[n], label=\n label_list[n] + 'CDBS')\nmargin = 0.06\nplt.xlim(x_adj_CDBS[0] - margin, 515)\nplt.yscale('log')\nplt.xlabel('Energy (keV)')\nplt.ylabel('Counts (A.U.)')\nplt.legend(loc='best')\nplt.show()\n", "<import token>\n<assignment token>\nfor n, file in enumerate(CDBS_files):\n basename = os.path.basename(file)\n file_name.append(basename)\n f = open(file, 'r')\n lines = f.readlines()\n CDBS_data = []\n for i in range(1024):\n count = lines[i + 23].split(',')\n count = list(map(int, count))\n del count[0]\n CDBS_data.append(count)\n DBS_matrix[basename] = np.array(CDBS_data, dtype=float)\n rot_matrix = ndimage.rotate(np.array(CDBS_data, dtype=float), -45)\n CDBS_matrix[basename] = ndimage.zoom(rot_matrix, 1 / np.sqrt(2))\n x, y, max_point = find_sudo_peak(DBS_matrix[basename], width=width)\n x_CDBS, y_CDBS, max_point_CBDS = find_sudo_peak(CDBS_matrix[basename],\n width=width)\n params = gmodel.make_params(cen=max_point[1], amp=np.max(y) * (np.sqrt(\n 2 * np.pi) * width / 2), wid=width / 2)\n result = gmodel.fit(y, params, x=x)\n AUC = integrate.simps(result.best_fit, x)\n x_adj = np.add(0.134 * np.subtract(x, max_point[1]), 511)\n print(result.best_values['wid'])\n plt.plot(x_adj, np.divide(y, AUC), linestyle[n], label=label_list[n])\n params_CDBS = gmodel.make_params(cen=max_point_CBDS[1], amp=np.max(\n y_CDBS) * (np.sqrt(2 * np.pi) * width / 2), wid=width / 2)\n result_CDBS = gmodel.fit(y_CDBS, params_CDBS, x=x_CDBS)\n AUC_CDBS = integrate.simps(result_CDBS.best_fit, x_CDBS)\n x_adj_CDBS = np.add(0.134 * np.subtract(x_CDBS, max_point_CBDS[1]), 511)\n print(result_CDBS.best_values['wid'])\n plt.plot(x_adj_CDBS, np.divide(y_CDBS, AUC_CDBS), linestyle[n], label=\n label_list[n] + 'CDBS')\n<assignment token>\nplt.xlim(x_adj_CDBS[0] - margin, 515)\nplt.yscale('log')\nplt.xlabel('Energy (keV)')\nplt.ylabel('Counts (A.U.)')\nplt.legend(loc='best')\nplt.show()\n", "<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
98,726
f9f1ce8f646990cbe0a34883db41b080c3896081
"""TTAccount.py is for communicating with account servers""" from pandac.PandaModules import * from pandac.PandaModules import * from direct.directnotify import DirectNotifyGlobal from direct.showbase import PythonUtil from otp.otpbase import OTPLocalizer import HTTPUtil import RemoteValueSet import copy accountServer = '' accountServer = launcher.getAccountServer() print "TTAccount: accountServer from launcher: ", (accountServer) configAccountServer = base.config.GetString('account-server', '') if configAccountServer: accountServer = configAccountServer print "TTAccount: overriding accountServer from config: ", (accountServer) if not accountServer: accountServer = "https://toontown.go.com" print "TTAccount: default accountServer: ", (accountServer) accountServer = URLSpec(accountServer, 1) def getAccountServer(): return accountServer # TTAccount only raises HTTPUtil exceptions; rename the base # exception for easy/handsome client exception catching TTAccountException = HTTPUtil.HTTPUtilException class TTAccount: notify = DirectNotifyGlobal.directNotify.newCategory("TTAccount") def __init__(self, cr): self.cr = cr self.response = None """ UNLESS OTHERWISE SPECIFIED, these functions return None on success, return an error string on 'normal' failure, and raise a TTAccountException on connection problem, bad response, etc. """ def createAccount(self, loginName, password, data): """ Ask the account server to create a new account. see talk() for list of required fields in 'data' dict see above for return values """ return self.talk('create', data=self.__makeLoginDict(loginName, password, data)) def authorize(self, loginName, password): """ Ask the account server to give us a play token. see above for return values """ return self.talk('play', data=self.__makeLoginDict(loginName, password)) def createBilling(self, loginName, password, data): """ Start paying using a credit card. see talk() for list of required fields in 'data' dict see above for return values """ return self.talk('purchase', data=self.__makeLoginDict(loginName, password, data)) def setParentPassword(self, loginName, password, parentPassword): """ set the parent password see above for return values """ return self.talk( 'setParentPassword', data=self.__makeLoginDict(loginName, password, {'parentPassword': parentPassword})) def supportsParentPassword(self): """Returns true if authenticateParentPassword is implemented and meaningful for this type of account system.""" return 1 def authenticateParentPassword(self, loginName, password, parentPassword): """ try to authenticate the parent password NOTE: this does not actually set any state on the account, it just tests a parent password returns (int success, string error) you will get: (1, None) --> success, password cleared (0, None) --> failure, password did not clear (0, '<some message>') --> failure, but not due to bad password, error msg explains what the problem is this function will never intentionally raise an exception """ try: errorMsg = self.talk( 'authenticateParentPassword', data=self.__makeLoginDict(loginName, parentPassword)) if not errorMsg: return (1, None) # we got an error message; check to see if it's the # 'wrong password' error if self.response.getInt('errorCode') in (5, 72): return (0, None) # some other error, pass it back return (0, errorMsg) except TTAccountException, e: # connection error, bad response, etc. # pass it back return (0, str(e)) def supportsAuthenticateDelete(self): """ Returns true if authenticateDelete is implemented for this type of account system """ return 1 def authenticateDelete(self, loginName, password): """ authenticate the deletion of a toon password can be either the login or parent password NOTE: this does not actually set any state on the account, it just authenticates the password returns (int success, string error) you will get: (1, None) --> success, password cleared (0, None) --> failure, password did not clear (0, '<some message>') --> failure, but not due to bad password, error msg explains what the problem is this function will never intentionally raise an exception """ try: errorMsg = self.talk( 'authenticateDelete', data=self.__makeLoginDict(loginName, password)) if not errorMsg: return (1, None) # we got an error message; check to see if it's the # 'wrong password' error if self.response.getInt('errorCode') in (5, 72): return (0, None) # some other error, pass it back return (0, errorMsg) except TTAccountException, e: # connection error, bad response, etc. # pass it back return (0, str(e)) def enableSecretFriends(self, loginName, password, parentPassword, enable=1): """ attempt to enable secret friends returns (int success, string error) you will get: (1, None) --> success, password cleared, operation gperformed (0, None) --> failure, password did not clear, operation not performed (0, '<some message>') --> failure, but not due to bad password, error msg explains what the problem is this function will never intentionally raise an exception """ try: errorMsg = self.talk( 'setSecretChat', data=self.__makeLoginDict(loginName, parentPassword, {'chat': base.cr.secretChatAllowed, 'secretsNeedParentPassword': base.cr.secretChatNeedsParentPassword} ) ) if not errorMsg: return (1, None) # we got an error message; check to see if it's the # 'wrong password' error if self.response.getInt('errorCode') in (5, 72): return (0, None) # some other error, pass it back return (0, errorMsg) except TTAccountException, e: # connection error, bad response, etc. # pass it back return (0, str(e)) def changePassword(self, loginName, password, newPassword): """ change password to newPassword see above for return values """ return self.talk( 'purchase', data=self.__makeLoginDict(loginName, password, {'newPassword': newPassword})) def requestPwdReminder(self, email=None, acctName=None): """ request an email with the password(s) will be sent to the parent/billing email address pass email OR acctName see above for return values """ assert acctName or email assert not (acctName and email) data = {} if email is not None: data['email'] = email else: data['accountName'] = acctName return self.talk('forgotPassword', data) def cancelAccount(self, loginName, password): """ Stop paying. see above for return values """ return self.talk('cancel', data=self.__makeLoginDict(loginName, password)) def getAccountData(self, loginName, password): """ retrieves account fields for a specific account all field values are strings on success, account data is available in self.accountData dictionary see above for return values """ errorMsg = self.talk( 'get', data=self.__makeLoginDict(loginName, password)) # if there was an error msg from the server, return it if errorMsg: self.notify.warning('getAccountData error: %s' % errorMsg) return errorMsg # TODO: check that we got all the expected fields # if there's an error field, print it out if self.response.hasKey('errorMsg'): self.notify.warning("error field is: '%s'" % self.response.getString('errorMsg')) # make an independent copy of the raw result dictionary self.accountData = copy.deepcopy(self.response) fieldNameMap = { 'em': 'email', 'l1': 'addr1', 'l2': 'addr2', 'l3': 'addr3', } # rename some fields dict = self.accountData.dict for fieldName in dict.keys(): if fieldNameMap.has_key(fieldName): dict[fieldNameMap[fieldName]] = dict[fieldName] del dict[fieldName] return None def getLastErrorMsg(self, forceCustServNum=0): """ call this function if you need to show the customer service # unconditionally on all errors, or if you have a threshold condition beyond which the CS # should always be included. For error codes >= 100, we always add the CS #. It might be simpler for the server to add it, but that would waste bandwidth. """ assert self.response.hasKey('errorCode') assert self.response.hasKey('errorMsg') errCode = self.response.getInt('errorCode') if errCode < 100: # these are 'user-fixable' problems # don't show customer service number if # suppress flag is true msg = self.response.getString('errorMsg') if forceCustServNum: # put up an 'if you need help, call...' msg msg += (' ' + OTPLocalizer.TTAccountCustomerServiceHelp % self.cr.accountServerConstants.getString('customerServicePhoneNumber')) elif errCode < 200: # these are non-user fixable, but it's useful # for the user to see what the error is msg = self.response.getString('errorMsg') msg += (' ' + OTPLocalizer.TTAccountCustomerServiceHelp % self.cr.accountServerConstants.getString('customerServicePhoneNumber')) elif errCode >= 500: # these are non-user fixable, and there's no # useful information that we can give to the user msg = OTPLocalizer.TTAccountIntractibleError msg += (' ' + OTPLocalizer.TTAccountCallCustomerService % self.cr.accountServerConstants.getString('customerServicePhoneNumber')) else: # don't know what this range of errors is all about... # log a warning... self.notify.warning("unknown error code class: %s: %s" % (self.response.getInt('errorCode'), self.response.getString('errorMsg'))) # and pass on the server's error msg, with the Cust. Serv. # msg = self.response.getString('errorMsg') msg += (' ' + OTPLocalizer.TTAccountCallCustomerService % self.cr.accountServerConstants.getString('customerServicePhoneNumber')) return msg def __makeLoginDict(self, loginName, password, data=None): """ many of the TTAccount API functions accept a login and password separately from the dict of data fields; this function puts the login and password into a dict, the way talk() wants it """ dict = { 'accountName': loginName, 'password': password } if data: dict.update(data) return dict def makeLoginDict(self, loginName, password, data=None): return self.__makeLoginDict(loginName, password,data) def talk(self, operation, data={}): """ A utility function used by other members of this class. returns: None: no error string: user error msg (bad password...) raises TTAccountException on connection failure, etc. """ self.notify.debug("TTAccount.talk()") # ensure that data contains nothing but strings for key in data.keys(): data[key] = str(data[key]) # assert that 'data' contains all the required data if operation in ('play', 'get', 'cancel', 'authenticateParentPassword', 'authenticateDelete', 'authenticateParentPasswordNewStyle', 'authenticateDeleteNewStyle'): assert PythonUtil.contains( data.keys(), ('accountName', 'password')) elif operation == 'authenticateParentUsernameAndPassword': assert PythonUtil.contains( data.keys(), ('accountName', 'parentUsername', 'parentPasswordNewStyle', 'userid')) elif operation == 'forgotPassword': assert data.has_key('accountName') or data.has_key('email') elif operation == 'setParentPassword': assert PythonUtil.contains( data.keys(), ('accountName', 'password', 'parentPassword',)) elif operation == 'setSecretChat': assert PythonUtil.contains( data.keys(), ('accountName', 'password', 'chat',)) elif operation == 'create': assert PythonUtil.contains( data.keys(), ('accountName', 'password', #'dobYear', #'dobMonth', #'dobDay', #'email', #'referrer', )) elif operation == 'purchase': # is this a password change or a purchase op? if data.has_key('newPassword'): assert PythonUtil.contains( data.keys(), ('accountName', 'password')) else: assert PythonUtil.contains( data.keys(), ('accountName', 'password', 'email', #'dobMonth', #'dobYear', 'ccType', 'ccNumber', 'ccMonth', 'ccYear', 'nameOnCard', 'addr1', 'addr2', 'city', 'state', 'country', 'zip')) else: self.notify.error('Internal TTAccount error: need to add ' '\'required data\' checking for %s operation' % operation) # map operations to php pages op2Php = { 'play': 'play', 'get': 'get', 'cancel': 'cancel', 'create': 'create', 'purchase': 'purchase', 'setParentPassword': 'setSecrets', 'authenticateParentPassword': 'authenticateChat', 'authenticateDelete': 'authDelete', 'setSecretChat': 'setChat', 'forgotPassword': 'forgotPw', # these last 3 are exclusive to the redesigned web site 'authenticateParentPasswordNewStyle' : 'api/authChat', 'authenticateParentUsernameAndPassword' : 'api/authParentChat', 'authenticateDeleteNewStyle' : 'api/authDelete', } newWebOperations = ('authenticateParentPasswordNewStyle', 'authenticateParentUsernameAndPassword', 'authenticateDeleteNewStyle') url = URLSpec(getAccountServer()) if operation in newWebOperations : url.setPath('/%s' % (op2Php[operation])) else: url.setPath('/%s.php' % (op2Php[operation])) body = '' if data.has_key('accountName'): if operation not in newWebOperations: # name is put on url for documentation only url.setQuery('n=%s' % (URLSpec.quote(data['accountName']))) serverFields = { # map: local field name --> server field name 'accountName': 'n', # accountName 'password': 'p', # accountPassword 'parentPassword': 'sp',# parent password 'newPassword': 'np', # new password for password change 'chat': 'chat', # chat enable flag 'email': 'em', # email address 'dobYear': 'doby', # date of birth year 'dobMonth': 'dobm', # date of birth month 'dobDay': 'dobd', # date of birth day 'ccNumber': 'ccn', # credit card number 'ccMonth': 'ccm', # credit card expiration month (1==January) 'ccYear': 'ccy', # credit card expiration year 'nameOnCard': 'noc', # NameOnCard, the credit card owner 'addr1': 'l1', # Address line 1 'addr2': 'l2', # Address line 2 'addr3': 'l3', # Address line 3 'city': 'city', # Billing address city 'state': 'state', # Billing address state 'country': 'country', # Billing address country code 'zip': 'zip', # Billing address zip/postal code 'referrer': 'ref', # referrer code 'secretsNeedParentPassword': 'secretsNeedsParentPassword', # restricted secret chat 'parentPasswordNewStyle' : 'pp', 'parentUsername' : 'pu', 'userid' : 'userid', } ignoredFields = ('ccType',) # add all of the fields in 'data' to the HTTP body # populate a map of serverField:value pairs so that we # can add the fields in alphabetical order outBoundFields = {} for fieldName in data.keys(): if not serverFields.has_key(fieldName): if not fieldName in ignoredFields: # unknown field name self.notify.error( 'unknown data field: %s' % fieldName) else: outBoundFields[serverFields[fieldName]] = data[fieldName] # add the fields to the body in alphabetical order orderedFields = outBoundFields.keys() orderedFields.sort() for fieldName in orderedFields: if len(body): body += '&' body += "%s=%s" % ( fieldName, URLSpec.quotePlus(outBoundFields[fieldName])) self.notify.debug("url="+url.cStr()) # important: the body may contain the password; only print in debug env self.notify.debug("body="+body) if operation in ('get',): expectedHeader = 'ACCOUNT INFO' elif operation in ('play', 'cancel', 'create', 'purchase', 'setParentPassword', 'setSecretChat', 'authenticateParentPassword', 'authenticateDelete', 'forgotPassword', 'authenticateParentPasswordNewStyle', 'authenticateParentUsernameAndPassword', 'authenticateDeleteNewStyle',): expectedHeader = 'ACCOUNT SERVER RESPONSE' else: self.notify.error('Internal TTAccount error: need to set ' 'expected response header for \'%s\' operation' % operation) # In certain circumstances in which the Disney proxy fails to # contact the server, it seems to report a successful # connection and simply returns a bogus response. # Make sure to check for the proper header in the response. self.response = RemoteValueSet.RemoteValueSet( url, self.cr.http, body=body, expectedHeader=expectedHeader) self.notify.debug(" self.response="+str(self.response)) # was there an error? if self.response.hasKey('errorCode'): errorCode = self.response.getInt('errorCode') self.notify.info('account server error code: %s' % errorCode) # if free time has expired, set it on the cr if errorCode == 10: self.cr.freeTimeExpiresAt = 0 # if there's an error message in the response, # pass it back if self.response.hasKey('errorMsg'): # add the customer service # for error messages that # should always have the # return self.getLastErrorMsg() # grab some info out of the response for easy access if operation in ('get', 'forgotPassword', 'authenticateDelete', 'play', 'cancel', 'create', 'purchase', 'setParentPassword', 'authenticateParentPassword', 'authenticateParentPasswordNewStyle', 'authenticateParentUsernameAndPassword', 'authenticateDeleteNewStyle'): # none of these require data from the web anymore pass elif operation == 'setSecretChat': # setSecretChat needs a new playToken self.playToken = self.response.getString('playToken') self.playTokenIsEncrypted=1 else: self.notify.error('Internal TTAccount error: need to extract ' 'useful data for %s operation' % operation) return None # no error def authenticateParentUsernameAndPassword(self, loginName, password, parentUsername, parentPassword): """ try to authenticate the parent password NOTE: this does not actually set any state on the account, it just tests a parent password returns (int success, string error) you will get: (1, None) --> success, password cleared (0, None) --> failure, password did not clear (0, '<some message>') --> failure, but not due to bad password, error msg explains what the problem is this function will never intentionally raise an exception """ try: errorMsg = self.talk( 'authenticateParentUsernameAndPassword', data=self.__makeLoginDict(loginName, password, {'parentUsername': parentUsername, 'parentPasswordNewStyle' : parentPassword, 'userid': loginName})) if not errorMsg: return (1, None) # we got an error message; check to see if it's the # 'wrong password' error if self.response.getInt('errorCode') in (5, 72): return (0, None) # some other error, pass it back return (0, errorMsg) except TTAccountException, e: # connection error, bad response, etc. # pass it back return (0, str(e))
[ "\"\"\"TTAccount.py is for communicating with account servers\"\"\"\n\nfrom pandac.PandaModules import *\nfrom pandac.PandaModules import *\nfrom direct.directnotify import DirectNotifyGlobal\nfrom direct.showbase import PythonUtil\nfrom otp.otpbase import OTPLocalizer\nimport HTTPUtil\nimport RemoteValueSet\nimport copy\n\naccountServer = ''\naccountServer = launcher.getAccountServer()\nprint \"TTAccount: accountServer from launcher: \", (accountServer)\n \nconfigAccountServer = base.config.GetString('account-server', '')\nif configAccountServer:\n accountServer = configAccountServer\n print \"TTAccount: overriding accountServer from config: \", (accountServer)\n\nif not accountServer:\n accountServer = \"https://toontown.go.com\"\n print \"TTAccount: default accountServer: \", (accountServer)\n\naccountServer = URLSpec(accountServer, 1)\n\ndef getAccountServer():\n return accountServer\n\n# TTAccount only raises HTTPUtil exceptions; rename the base\n# exception for easy/handsome client exception catching\nTTAccountException = HTTPUtil.HTTPUtilException\n\nclass TTAccount:\n notify = DirectNotifyGlobal.directNotify.newCategory(\"TTAccount\")\n \n def __init__(self, cr):\n self.cr = cr\n self.response = None\n\n \"\"\"\n UNLESS OTHERWISE SPECIFIED,\n these functions return None on success,\n return an error string on 'normal' failure,\n and raise a TTAccountException on connection problem, bad response, etc.\n \"\"\"\n\n def createAccount(self, loginName, password, data):\n \"\"\"\n Ask the account server to create a new account.\n see talk() for list of required fields in 'data' dict\n see above for return values\n \"\"\"\n return self.talk('create',\n data=self.__makeLoginDict(loginName, password, data))\n\n def authorize(self, loginName, password):\n \"\"\"\n Ask the account server to give us a play token.\n see above for return values\n \"\"\"\n return self.talk('play', data=self.__makeLoginDict(loginName, password))\n \n def createBilling(self, loginName, password, data):\n \"\"\"\n Start paying using a credit card.\n see talk() for list of required fields in 'data' dict\n see above for return values\n \"\"\"\n return self.talk('purchase',\n data=self.__makeLoginDict(loginName, password, data))\n\n def setParentPassword(self, loginName, password, parentPassword):\n \"\"\"\n set the parent password\n see above for return values\n \"\"\"\n return self.talk(\n 'setParentPassword',\n data=self.__makeLoginDict(loginName, password,\n {'parentPassword': parentPassword}))\n\n def supportsParentPassword(self):\n \"\"\"Returns true if authenticateParentPassword is implemented\n and meaningful for this type of account system.\"\"\"\n return 1\n\n def authenticateParentPassword(self, loginName,\n password, parentPassword):\n \"\"\"\n try to authenticate the parent password\n NOTE: this does not actually set any state on the account,\n it just tests a parent password\n returns (int success, string error)\n you will get:\n (1, None) --> success, password cleared\n (0, None) --> failure, password did not clear\n (0, '<some message>') --> failure, but not due to bad password,\n error msg explains what the problem is\n this function will never intentionally raise an exception\n \"\"\"\n try:\n errorMsg = self.talk(\n 'authenticateParentPassword',\n data=self.__makeLoginDict(loginName, parentPassword))\n if not errorMsg:\n return (1, None)\n \n # we got an error message; check to see if it's the\n # 'wrong password' error\n if self.response.getInt('errorCode') in (5, 72):\n return (0, None)\n\n # some other error, pass it back\n return (0, errorMsg)\n except TTAccountException, e:\n # connection error, bad response, etc.\n # pass it back\n return (0, str(e))\n\n def supportsAuthenticateDelete(self):\n \"\"\" Returns true if authenticateDelete is implemented\n for this type of account system \"\"\"\n return 1\n\n def authenticateDelete(self, loginName, password):\n \"\"\"\n authenticate the deletion of a toon\n password can be either the login or parent password\n NOTE: this does not actually set any state on the account,\n it just authenticates the password\n returns (int success, string error)\n you will get:\n (1, None) --> success, password cleared\n (0, None) --> failure, password did not clear\n (0, '<some message>') --> failure, but not due to bad password,\n error msg explains what the problem is\n this function will never intentionally raise an exception\n \"\"\"\n try:\n errorMsg = self.talk(\n 'authenticateDelete',\n data=self.__makeLoginDict(loginName, password))\n if not errorMsg:\n return (1, None)\n \n # we got an error message; check to see if it's the\n # 'wrong password' error\n if self.response.getInt('errorCode') in (5, 72):\n return (0, None)\n\n # some other error, pass it back\n return (0, errorMsg)\n except TTAccountException, e:\n # connection error, bad response, etc.\n # pass it back\n return (0, str(e))\n \n def enableSecretFriends(self, loginName, password,\n parentPassword, enable=1):\n \"\"\"\n attempt to enable secret friends\n returns (int success, string error)\n you will get:\n (1, None) --> success, password cleared, operation gperformed\n (0, None) --> failure, password did not clear, operation not performed\n (0, '<some message>') --> failure, but not due to bad password,\n error msg explains what the problem is\n this function will never intentionally raise an exception\n \"\"\"\n try:\n errorMsg = self.talk(\n 'setSecretChat',\n data=self.__makeLoginDict(loginName, parentPassword,\n {'chat': base.cr.secretChatAllowed,\n 'secretsNeedParentPassword': base.cr.secretChatNeedsParentPassword}\n )\n )\n if not errorMsg:\n return (1, None)\n \n # we got an error message; check to see if it's the\n # 'wrong password' error\n if self.response.getInt('errorCode') in (5, 72):\n return (0, None)\n\n # some other error, pass it back\n return (0, errorMsg)\n except TTAccountException, e:\n # connection error, bad response, etc.\n # pass it back\n return (0, str(e))\n \n def changePassword(self, loginName, password, newPassword):\n \"\"\"\n change password to newPassword\n see above for return values\n \"\"\"\n return self.talk(\n 'purchase',\n data=self.__makeLoginDict(loginName, password,\n {'newPassword': newPassword}))\n\n def requestPwdReminder(self, email=None, acctName=None):\n \"\"\"\n request an email with the password(s)\n will be sent to the parent/billing email address\n\n pass email OR acctName\n see above for return values\n \"\"\"\n assert acctName or email\n assert not (acctName and email)\n data = {}\n if email is not None:\n data['email'] = email\n else:\n data['accountName'] = acctName\n return self.talk('forgotPassword', data)\n \n def cancelAccount(self, loginName, password):\n \"\"\"\n Stop paying.\n see above for return values\n \"\"\"\n return self.talk('cancel',\n data=self.__makeLoginDict(loginName, password))\n\n def getAccountData(self, loginName, password):\n \"\"\"\n retrieves account fields for a specific account\n all field values are strings\n\n on success, account data is available in self.accountData dictionary\n see above for return values\n \"\"\"\n errorMsg = self.talk(\n 'get',\n data=self.__makeLoginDict(loginName, password))\n # if there was an error msg from the server, return it\n if errorMsg:\n self.notify.warning('getAccountData error: %s' % errorMsg)\n return errorMsg\n\n # TODO: check that we got all the expected fields\n\n # if there's an error field, print it out\n if self.response.hasKey('errorMsg'):\n self.notify.warning(\"error field is: '%s'\" %\n self.response.getString('errorMsg'))\n\n # make an independent copy of the raw result dictionary\n self.accountData = copy.deepcopy(self.response)\n\n fieldNameMap = {\n 'em': 'email',\n 'l1': 'addr1',\n 'l2': 'addr2',\n 'l3': 'addr3',\n }\n\n # rename some fields\n dict = self.accountData.dict\n for fieldName in dict.keys():\n if fieldNameMap.has_key(fieldName):\n dict[fieldNameMap[fieldName]] = dict[fieldName]\n del dict[fieldName]\n\n return None\n\n def getLastErrorMsg(self, forceCustServNum=0):\n \"\"\" call this function if you need to show the customer\n service # unconditionally on all errors, or if you\n have a threshold condition beyond which the CS # should\n always be included.\n\n For error codes >= 100, we always add the CS #. It might\n be simpler for the server to add it, but that would waste\n bandwidth.\n \"\"\"\n assert self.response.hasKey('errorCode')\n assert self.response.hasKey('errorMsg')\n errCode = self.response.getInt('errorCode')\n\n if errCode < 100:\n # these are 'user-fixable' problems\n # don't show customer service number if\n # suppress flag is true\n msg = self.response.getString('errorMsg')\n if forceCustServNum:\n # put up an 'if you need help, call...' msg\n msg += (' ' + OTPLocalizer.TTAccountCustomerServiceHelp %\n self.cr.accountServerConstants.getString('customerServicePhoneNumber'))\n elif errCode < 200:\n # these are non-user fixable, but it's useful\n # for the user to see what the error is\n msg = self.response.getString('errorMsg')\n msg += (' ' + OTPLocalizer.TTAccountCustomerServiceHelp %\n self.cr.accountServerConstants.getString('customerServicePhoneNumber'))\n elif errCode >= 500:\n # these are non-user fixable, and there's no\n # useful information that we can give to the user\n msg = OTPLocalizer.TTAccountIntractibleError\n msg += (' ' + OTPLocalizer.TTAccountCallCustomerService %\n self.cr.accountServerConstants.getString('customerServicePhoneNumber'))\n else:\n # don't know what this range of errors is all about...\n # log a warning...\n self.notify.warning(\"unknown error code class: %s: %s\" %\n (self.response.getInt('errorCode'),\n self.response.getString('errorMsg')))\n # and pass on the server's error msg, with the Cust. Serv. #\n msg = self.response.getString('errorMsg')\n msg += (' ' + OTPLocalizer.TTAccountCallCustomerService %\n self.cr.accountServerConstants.getString('customerServicePhoneNumber'))\n\n return msg\n\n def __makeLoginDict(self, loginName, password, data=None):\n \"\"\" many of the TTAccount API functions accept\n a login and password separately from the dict\n of data fields; this function puts the login\n and password into a dict, the way talk() wants\n it \"\"\"\n dict = {\n 'accountName': loginName,\n 'password': password\n }\n if data:\n dict.update(data)\n return dict\n\n def makeLoginDict(self, loginName, password, data=None):\n return self.__makeLoginDict(loginName, password,data)\n\n def talk(self, operation, data={}):\n \"\"\"\n A utility function used by other members of this class.\n returns:\n None: no error\n string: user error msg (bad password...)\n raises TTAccountException on connection failure, etc.\n \"\"\"\n self.notify.debug(\"TTAccount.talk()\")\n\n # ensure that data contains nothing but strings\n for key in data.keys():\n data[key] = str(data[key])\n\n # assert that 'data' contains all the required data\n if operation in ('play', 'get', 'cancel',\n 'authenticateParentPassword',\n 'authenticateDelete',\n 'authenticateParentPasswordNewStyle',\n 'authenticateDeleteNewStyle'):\n assert PythonUtil.contains(\n data.keys(),\n ('accountName',\n 'password'))\n elif operation == 'authenticateParentUsernameAndPassword':\n assert PythonUtil.contains(\n data.keys(),\n ('accountName',\n 'parentUsername',\n 'parentPasswordNewStyle',\n 'userid'))\n elif operation == 'forgotPassword':\n assert data.has_key('accountName') or data.has_key('email')\n elif operation == 'setParentPassword':\n assert PythonUtil.contains(\n data.keys(),\n ('accountName',\n 'password',\n 'parentPassword',))\n elif operation == 'setSecretChat':\n assert PythonUtil.contains(\n data.keys(),\n ('accountName',\n 'password',\n 'chat',))\n elif operation == 'create':\n assert PythonUtil.contains(\n data.keys(),\n ('accountName',\n 'password',\n #'dobYear',\n #'dobMonth',\n #'dobDay',\n #'email',\n #'referrer',\n ))\n elif operation == 'purchase':\n # is this a password change or a purchase op?\n if data.has_key('newPassword'):\n assert PythonUtil.contains(\n data.keys(),\n ('accountName',\n 'password'))\n else:\n assert PythonUtil.contains(\n data.keys(),\n ('accountName',\n 'password',\n 'email', \n #'dobMonth',\n #'dobYear',\n 'ccType',\n 'ccNumber',\n 'ccMonth',\n 'ccYear',\n 'nameOnCard',\n 'addr1',\n 'addr2',\n 'city',\n 'state',\n 'country',\n 'zip'))\n else:\n self.notify.error('Internal TTAccount error: need to add '\n '\\'required data\\' checking for %s operation' %\n operation)\n\n # map operations to php pages\n op2Php = {\n 'play': 'play',\n 'get': 'get',\n 'cancel': 'cancel',\n 'create': 'create',\n 'purchase': 'purchase',\n 'setParentPassword': 'setSecrets',\n 'authenticateParentPassword': 'authenticateChat',\n 'authenticateDelete': 'authDelete',\n 'setSecretChat': 'setChat',\n 'forgotPassword': 'forgotPw',\n # these last 3 are exclusive to the redesigned web site\n 'authenticateParentPasswordNewStyle' : 'api/authChat',\n 'authenticateParentUsernameAndPassword' : 'api/authParentChat',\n 'authenticateDeleteNewStyle' : 'api/authDelete',\n }\n\n newWebOperations = ('authenticateParentPasswordNewStyle',\n 'authenticateParentUsernameAndPassword',\n 'authenticateDeleteNewStyle')\n url = URLSpec(getAccountServer())\n if operation in newWebOperations :\n\n url.setPath('/%s' % (op2Php[operation])) \n else:\n url.setPath('/%s.php' % (op2Php[operation]))\n body = ''\n\n if data.has_key('accountName'):\n if operation not in newWebOperations:\n # name is put on url for documentation only\n url.setQuery('n=%s' % (URLSpec.quote(data['accountName'])))\n\n serverFields = {\n # map: local field name --> server field name\n 'accountName': 'n', # accountName\n 'password': 'p', # accountPassword\n 'parentPassword': 'sp',# parent password\n 'newPassword': 'np', # new password for password change\n 'chat': 'chat', # chat enable flag\n 'email': 'em', # email address\n 'dobYear': 'doby', # date of birth year\n 'dobMonth': 'dobm', # date of birth month\n 'dobDay': 'dobd', # date of birth day\n 'ccNumber': 'ccn', # credit card number\n 'ccMonth': 'ccm', # credit card expiration month (1==January)\n 'ccYear': 'ccy', # credit card expiration year\n 'nameOnCard': 'noc', # NameOnCard, the credit card owner\n 'addr1': 'l1', # Address line 1\n 'addr2': 'l2', # Address line 2\n 'addr3': 'l3', # Address line 3\n 'city': 'city', # Billing address city\n 'state': 'state', # Billing address state\n 'country': 'country', # Billing address country code\n 'zip': 'zip', # Billing address zip/postal code\n 'referrer': 'ref', # referrer code\n 'secretsNeedParentPassword': 'secretsNeedsParentPassword', # restricted secret chat\n 'parentPasswordNewStyle' : 'pp',\n 'parentUsername' : 'pu',\n 'userid' : 'userid',\n }\n ignoredFields = ('ccType',)\n\n # add all of the fields in 'data' to the HTTP body\n\n # populate a map of serverField:value pairs so that we\n # can add the fields in alphabetical order\n outBoundFields = {}\n for fieldName in data.keys():\n if not serverFields.has_key(fieldName):\n if not fieldName in ignoredFields:\n # unknown field name\n self.notify.error(\n 'unknown data field: %s' % fieldName)\n else:\n outBoundFields[serverFields[fieldName]] = data[fieldName]\n\n # add the fields to the body in alphabetical order\n orderedFields = outBoundFields.keys()\n orderedFields.sort()\n for fieldName in orderedFields:\n if len(body):\n body += '&'\n body += \"%s=%s\" % (\n fieldName,\n URLSpec.quotePlus(outBoundFields[fieldName]))\n\n self.notify.debug(\"url=\"+url.cStr())\n # important: the body may contain the password; only print in debug env\n self.notify.debug(\"body=\"+body)\n\n if operation in ('get',):\n expectedHeader = 'ACCOUNT INFO'\n elif operation in ('play', 'cancel', 'create', 'purchase',\n 'setParentPassword', 'setSecretChat',\n 'authenticateParentPassword',\n 'authenticateDelete',\n 'forgotPassword',\n 'authenticateParentPasswordNewStyle',\n 'authenticateParentUsernameAndPassword',\n 'authenticateDeleteNewStyle',):\n expectedHeader = 'ACCOUNT SERVER RESPONSE'\n else:\n self.notify.error('Internal TTAccount error: need to set '\n 'expected response header for \\'%s\\' operation' %\n operation)\n\n # In certain circumstances in which the Disney proxy fails to\n # contact the server, it seems to report a successful\n # connection and simply returns a bogus response.\n # Make sure to check for the proper header in the response.\n self.response = RemoteValueSet.RemoteValueSet(\n url, self.cr.http, body=body, expectedHeader=expectedHeader)\n self.notify.debug(\" self.response=\"+str(self.response))\n\n # was there an error?\n if self.response.hasKey('errorCode'):\n errorCode = self.response.getInt('errorCode')\n\n self.notify.info('account server error code: %s' % errorCode)\n\n # if free time has expired, set it on the cr\n if errorCode == 10:\n self.cr.freeTimeExpiresAt = 0\n\n # if there's an error message in the response,\n # pass it back\n if self.response.hasKey('errorMsg'):\n # add the customer service # for error messages that\n # should always have the #\n return self.getLastErrorMsg()\n\n # grab some info out of the response for easy access\n if operation in ('get', 'forgotPassword', 'authenticateDelete',\n 'play', 'cancel', 'create', 'purchase',\n 'setParentPassword', 'authenticateParentPassword',\n 'authenticateParentPasswordNewStyle',\n 'authenticateParentUsernameAndPassword',\n 'authenticateDeleteNewStyle'):\n # none of these require data from the web anymore\n pass\n elif operation == 'setSecretChat':\n # setSecretChat needs a new playToken\n self.playToken = self.response.getString('playToken')\n self.playTokenIsEncrypted=1\n else:\n self.notify.error('Internal TTAccount error: need to extract '\n 'useful data for %s operation' %\n operation)\n\n return None # no error\n\n\n def authenticateParentUsernameAndPassword(self, loginName,\n password, parentUsername, parentPassword):\n \"\"\"\n try to authenticate the parent password\n NOTE: this does not actually set any state on the account,\n it just tests a parent password\n returns (int success, string error)\n you will get:\n (1, None) --> success, password cleared\n (0, None) --> failure, password did not clear\n (0, '<some message>') --> failure, but not due to bad password,\n error msg explains what the problem is\n this function will never intentionally raise an exception\n \"\"\"\n try:\n errorMsg = self.talk(\n 'authenticateParentUsernameAndPassword',\n data=self.__makeLoginDict(loginName, password,\n {'parentUsername': parentUsername,\n 'parentPasswordNewStyle' : parentPassword,\n 'userid': loginName}))\n \n if not errorMsg:\n return (1, None)\n \n # we got an error message; check to see if it's the\n # 'wrong password' error\n if self.response.getInt('errorCode') in (5, 72):\n return (0, None)\n\n # some other error, pass it back\n return (0, errorMsg)\n except TTAccountException, e:\n # connection error, bad response, etc.\n # pass it back\n return (0, str(e))\n\n" ]
true
98,727
ac887273a56ae000004bf5a6eb36d42edff3b6d0
""" Network-related utility functions. """ # Standard library imports import errno import logging import platform import socket import subprocess # Local imports from brokkr.constants import Errors import brokkr.utils.log import brokkr.utils.misc BUFFER_SIZE_DEFAULT = 4096 MAX_DATA_SIZE = 2**31 - 2 MAX_DATA_PRINT_LENGTH = 1024 TIMEOUT_S_DEFAULT = 2 SUBPROCESS_TIMEOUT_EXTRA = 2 PING_COUNT_PARAM = "-n" if platform.system().lower() == "windows" else "-c" ERROR_CODES_ADDRESS_LINK_DOWN = { getattr(errno, "EADDRNOTAVAIL", None), getattr(errno, "WSAEADDRNOTAVAIL", None), } LOGGER = logging.getLogger(__name__) LOG_HELPER = brokkr.utils.log.LogHelper(LOGGER) def ping( host, count=1, timeout_s=TIMEOUT_S_DEFAULT, record_output=False, ): # Set the correct option for the number of packets based on platform. if platform.system().lower() == "windows": count_param = "-n" else: count_param = "-c" # Build the command, e.g. ping -c 1 -w 1 10.10.10.1 command = ["ping", count_param, str(count), "-w", str(timeout_s), host] LOGGER.debug("Running ping command %s ...", " ".join(command)) if record_output: extra_args = { "stdout": subprocess.PIPE, "stderr": subprocess.PIPE, "encoding": "utf-8", "errors": "surrogateescape", } else: extra_args = { "stdout": subprocess.DEVNULL, "stderr": subprocess.DEVNULL, } ping_output = subprocess.run( command, timeout=timeout_s + SUBPROCESS_TIMEOUT_EXTRA, check=False, **extra_args, ) return ping_output def handle_socket_error(e, errors=Errors.RAISE, **log_kwargs): if errors == Errors.RAISE: raise e if errors in {Errors.WARN, Errors.LOG}: LOGGER.error("%s with socket: %s", type(e).__name__, e) LOG_HELPER.log(socket=log_kwargs) elif errors == Errors.IGNORE: LOGGER.debug("Suppressing %s with socket: %s", type(e).__name__, e) LOG_HELPER.log(log_helper_log_level="debug", socket=log_kwargs) else: error_levels = {"Errors." + errors.name for errors in Errors} LOGGER.critical( "Error level for %s.handle_socket_error must be one of %r, not %r;" " assuming raise", __file__, error_levels, errors) LOGGER.info("Stack trace:", stack_info=True) raise e def setup_socket( # pylint: disable=dangerous-default-value sock, address_tuple, action, timeout_s=None, errors=Errors.RAISE, error_codes_suppress=ERROR_CODES_ADDRESS_LINK_DOWN, ): valid_actions = {"bind", "connect"} if action is not None and action not in valid_actions: LOGGER.critical("Action for %s.setup_socket must be one of %r, not %r", __file__, valid_actions, action) LOGGER.info("Stack trace:", stack_info=True) raise ValueError( f"Action must be one of {valid_actions!r}, not {action!r}") try: sock.settimeout(timeout_s) if action is not None: getattr(sock, action)(address_tuple) except Exception as e: if isinstance(e, OSError): # pylint: disable=no-member, useless-suppression if error_codes_suppress and ( isinstance(e, socket.timeout) or (e.errno and e.errno in error_codes_suppress)): errors = Errors.IGNORE handle_socket_error(e, errors=errors, socket=sock, address=address_tuple, action=action) return None else: LOGGER.debug("Listening on socket %r", sock) return sock def recieve_all( sock, data_length=None, timeout_s=None, errors=Errors.RAISE, buffer_size=BUFFER_SIZE_DEFAULT, ): start_time_recieve = None chunks = [] bytes_remaining = ( data_length if data_length else (MAX_DATA_SIZE - buffer_size)) while (bytes_remaining > 0 and (not start_time_recieve or not timeout_s or (brokkr.utils.misc.monotonic_ns() - start_time_recieve * brokkr.utils.misc.NS_IN_S) <= (timeout_s * brokkr.utils.misc.NS_IN_S))): try: chunk = sock.recv(buffer_size) if not chunks: LOGGER.debug( "First chunk of network data recieved of length %s bytes", len(chunk)) LOGGER.debug( "First %s bytes of first chunk: %r", MAX_DATA_PRINT_LENGTH, chunk[:MAX_DATA_PRINT_LENGTH]) except socket.timeout as e: LOGGER.debug("Socket timed out in %s s while waiting for data", timeout_s) handle_socket_error( e, errors=Errors.IGNORE, socket=sock, data_length=data_length, n_chunks=len(chunks), bytes_remaining=bytes_remaining) break except Exception as e: handle_socket_error( e, errors=errors, socket=sock, data_length=data_length, n_chunks=len(chunks), bytes_remaining=bytes_remaining) return None if start_time_recieve is None: start_time_recieve = brokkr.utils.misc.monotonic_ns() if not chunk: if not data_length: errors = Errors.IGNORE try: raise RuntimeError( f"Null {chunk!r} found in recieved socket data chunk") except RuntimeError as e: handle_socket_error( e, errors=errors, socket=sock, data_length=data_length, n_chunks=len(chunks), bytes_remaining=bytes_remaining) break bytes_remaining -= len(chunk) buffer_size = min([buffer_size, bytes_remaining]) chunks.append(chunk) LOGGER.debug("%s total chunks of network data recieved", len(chunks)) if not chunks: LOGGER.debug("No network data to return") return None data = b"".join(chunks) if data_length: data = data[:data_length] if not data: LOGGER.debug("Null network data recieved: %r", data) else: LOGGER.debug("Network data recieved of length %s bytes", len(data)) LOGGER.debug("First %s bytes: %r", MAX_DATA_PRINT_LENGTH, data[:MAX_DATA_PRINT_LENGTH]) return data def read_socket_data( host, port, action, socket_family=socket.AF_INET, socket_type=socket.SOCK_STREAM, timeout_s=TIMEOUT_S_DEFAULT, errors=Errors.RAISE, shutdown=False, **recieve_kwargs, ): address_tuple = (host, port) LOGGER.debug( "Creating socket of family %r, type %r with host %r, port %r, " "action %r, timeout %r", socket_family, socket_type, host, port, action, timeout_s) with socket.socket(socket_family, socket_type) as sock: LOGGER.debug("Created socket %r", sock) setup_sock = setup_socket( sock, address_tuple, action, timeout_s=timeout_s, errors=errors) if setup_sock is not None: sock = setup_sock LOGGER.debug( "Waiting for data from socket %r with kwargs %r", sock, recieve_kwargs) data = recieve_all( sock, timeout_s=timeout_s, errors=errors, **recieve_kwargs) else: data = None if shutdown: try: LOGGER.debug("Shutting down socket %r", sock) sock.shutdown(socket.SHUT_RDWR) except Exception as e: handle_socket_error(e, errors=Errors.IGNORE, socket=sock, address=address_tuple, action=action) return data def netcat(data_to_send, host, port, recieve_reply=True, timeout_s=1): recieved_data = None address_tuple = (host, port) LOGGER.info( "Running netcat with data %r, host %r, port %r, timeout %r", data_to_send[:MAX_DATA_PRINT_LENGTH], host, port, timeout_s) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: LOGGER.debug("Created socket %r", sock) sock = setup_socket( sock, address_tuple, action="connect", timeout_s=timeout_s, errors=Errors.RAISE, error_codes_suppress=None) LOGGER.debug("Sending data %r to socket %r", data_to_send[:MAX_DATA_PRINT_LENGTH], sock) if data_to_send is not None: sock.sendall(data_to_send) sock.shutdown(socket.SHUT_WR) if recieve_reply: LOGGER.debug("Recieving data from socket %r", sock) recieved_data = recieve_all( sock, timeout_s=timeout_s, errors=Errors.RAISE) sock.shutdown(socket.SHUT_RD) return recieved_data @brokkr.utils.log.basic_logging def netcat_main(data_to_send=None, recieve_reply=True, **netcat_args): if data_to_send is not None: LOGGER.debug("Encoding input data %r to bytes", data_to_send[:MAX_DATA_PRINT_LENGTH]) data_to_send = data_to_send.encode() LOGGER.debug("Encoded data: %r", data_to_send[:MAX_DATA_PRINT_LENGTH].hex()) recieved_data = netcat( data_to_send, recieve_reply=recieve_reply, **netcat_args) if recieve_reply: try: LOGGER.debug("First %s bytes of recieved data: %r", MAX_DATA_PRINT_LENGTH, recieved_data[:MAX_DATA_PRINT_LENGTH].hex()) recieved_data = recieved_data.decode() except Exception: pass LOGGER.info("Recieved responce:\n") print(recieved_data) return recieved_data
[ "\"\"\"\nNetwork-related utility functions.\n\"\"\"\n\n# Standard library imports\nimport errno\nimport logging\nimport platform\nimport socket\nimport subprocess\n\n# Local imports\nfrom brokkr.constants import Errors\nimport brokkr.utils.log\nimport brokkr.utils.misc\n\n\nBUFFER_SIZE_DEFAULT = 4096\nMAX_DATA_SIZE = 2**31 - 2\n\nMAX_DATA_PRINT_LENGTH = 1024\n\nTIMEOUT_S_DEFAULT = 2\nSUBPROCESS_TIMEOUT_EXTRA = 2\n\nPING_COUNT_PARAM = \"-n\" if platform.system().lower() == \"windows\" else \"-c\"\n\nERROR_CODES_ADDRESS_LINK_DOWN = {\n getattr(errno, \"EADDRNOTAVAIL\", None),\n getattr(errno, \"WSAEADDRNOTAVAIL\", None),\n }\n\nLOGGER = logging.getLogger(__name__)\nLOG_HELPER = brokkr.utils.log.LogHelper(LOGGER)\n\n\ndef ping(\n host,\n count=1,\n timeout_s=TIMEOUT_S_DEFAULT,\n record_output=False,\n ):\n # Set the correct option for the number of packets based on platform.\n if platform.system().lower() == \"windows\":\n count_param = \"-n\"\n else:\n count_param = \"-c\"\n\n # Build the command, e.g. ping -c 1 -w 1 10.10.10.1\n command = [\"ping\", count_param, str(count), \"-w\", str(timeout_s), host]\n LOGGER.debug(\"Running ping command %s ...\", \" \".join(command))\n if record_output:\n extra_args = {\n \"stdout\": subprocess.PIPE,\n \"stderr\": subprocess.PIPE,\n \"encoding\": \"utf-8\",\n \"errors\": \"surrogateescape\",\n }\n else:\n extra_args = {\n \"stdout\": subprocess.DEVNULL,\n \"stderr\": subprocess.DEVNULL,\n }\n\n ping_output = subprocess.run(\n command,\n timeout=timeout_s + SUBPROCESS_TIMEOUT_EXTRA,\n check=False,\n **extra_args,\n )\n return ping_output\n\n\ndef handle_socket_error(e, errors=Errors.RAISE, **log_kwargs):\n if errors == Errors.RAISE:\n raise e\n if errors in {Errors.WARN, Errors.LOG}:\n LOGGER.error(\"%s with socket: %s\", type(e).__name__, e)\n LOG_HELPER.log(socket=log_kwargs)\n elif errors == Errors.IGNORE:\n LOGGER.debug(\"Suppressing %s with socket: %s\", type(e).__name__, e)\n LOG_HELPER.log(log_helper_log_level=\"debug\", socket=log_kwargs)\n else:\n error_levels = {\"Errors.\" + errors.name for errors in Errors}\n LOGGER.critical(\n \"Error level for %s.handle_socket_error must be one of %r, not %r;\"\n \" assuming raise\", __file__, error_levels, errors)\n LOGGER.info(\"Stack trace:\", stack_info=True)\n raise e\n\n\ndef setup_socket( # pylint: disable=dangerous-default-value\n sock,\n address_tuple,\n action,\n timeout_s=None,\n errors=Errors.RAISE,\n error_codes_suppress=ERROR_CODES_ADDRESS_LINK_DOWN,\n ):\n valid_actions = {\"bind\", \"connect\"}\n if action is not None and action not in valid_actions:\n LOGGER.critical(\"Action for %s.setup_socket must be one of %r, not %r\",\n __file__, valid_actions, action)\n LOGGER.info(\"Stack trace:\", stack_info=True)\n raise ValueError(\n f\"Action must be one of {valid_actions!r}, not {action!r}\")\n\n try:\n sock.settimeout(timeout_s)\n if action is not None:\n getattr(sock, action)(address_tuple)\n except Exception as e:\n if isinstance(e, OSError):\n # pylint: disable=no-member, useless-suppression\n if error_codes_suppress and (\n isinstance(e, socket.timeout)\n or (e.errno\n and e.errno in error_codes_suppress)):\n errors = Errors.IGNORE\n handle_socket_error(e, errors=errors, socket=sock,\n address=address_tuple, action=action)\n return None\n else:\n LOGGER.debug(\"Listening on socket %r\", sock)\n\n return sock\n\n\ndef recieve_all(\n sock,\n data_length=None,\n timeout_s=None,\n errors=Errors.RAISE,\n buffer_size=BUFFER_SIZE_DEFAULT,\n ):\n start_time_recieve = None\n chunks = []\n bytes_remaining = (\n data_length if data_length else (MAX_DATA_SIZE - buffer_size))\n while (bytes_remaining > 0\n and (not start_time_recieve\n or not timeout_s\n or (brokkr.utils.misc.monotonic_ns()\n - start_time_recieve * brokkr.utils.misc.NS_IN_S)\n <= (timeout_s * brokkr.utils.misc.NS_IN_S))):\n try:\n chunk = sock.recv(buffer_size)\n if not chunks:\n LOGGER.debug(\n \"First chunk of network data recieved of length %s bytes\",\n len(chunk))\n LOGGER.debug(\n \"First %s bytes of first chunk: %r\",\n MAX_DATA_PRINT_LENGTH, chunk[:MAX_DATA_PRINT_LENGTH])\n except socket.timeout as e:\n LOGGER.debug(\"Socket timed out in %s s while waiting for data\",\n timeout_s)\n handle_socket_error(\n e, errors=Errors.IGNORE, socket=sock, data_length=data_length,\n n_chunks=len(chunks), bytes_remaining=bytes_remaining)\n break\n except Exception as e:\n handle_socket_error(\n e, errors=errors, socket=sock, data_length=data_length,\n n_chunks=len(chunks), bytes_remaining=bytes_remaining)\n return None\n if start_time_recieve is None:\n start_time_recieve = brokkr.utils.misc.monotonic_ns()\n if not chunk:\n if not data_length:\n errors = Errors.IGNORE\n try:\n raise RuntimeError(\n f\"Null {chunk!r} found in recieved socket data chunk\")\n except RuntimeError as e:\n handle_socket_error(\n e, errors=errors, socket=sock, data_length=data_length,\n n_chunks=len(chunks), bytes_remaining=bytes_remaining)\n break\n bytes_remaining -= len(chunk)\n buffer_size = min([buffer_size, bytes_remaining])\n chunks.append(chunk)\n\n LOGGER.debug(\"%s total chunks of network data recieved\", len(chunks))\n if not chunks:\n LOGGER.debug(\"No network data to return\")\n return None\n\n data = b\"\".join(chunks)\n if data_length:\n data = data[:data_length]\n\n if not data:\n LOGGER.debug(\"Null network data recieved: %r\", data)\n else:\n LOGGER.debug(\"Network data recieved of length %s bytes\", len(data))\n LOGGER.debug(\"First %s bytes: %r\",\n MAX_DATA_PRINT_LENGTH, data[:MAX_DATA_PRINT_LENGTH])\n\n return data\n\n\ndef read_socket_data(\n host,\n port,\n action,\n socket_family=socket.AF_INET,\n socket_type=socket.SOCK_STREAM,\n timeout_s=TIMEOUT_S_DEFAULT,\n errors=Errors.RAISE,\n shutdown=False,\n **recieve_kwargs,\n ):\n address_tuple = (host, port)\n LOGGER.debug(\n \"Creating socket of family %r, type %r with host %r, port %r, \"\n \"action %r, timeout %r\",\n socket_family, socket_type, host, port, action, timeout_s)\n\n with socket.socket(socket_family, socket_type) as sock:\n LOGGER.debug(\"Created socket %r\", sock)\n setup_sock = setup_socket(\n sock, address_tuple, action, timeout_s=timeout_s, errors=errors)\n\n if setup_sock is not None:\n sock = setup_sock\n LOGGER.debug(\n \"Waiting for data from socket %r with kwargs %r\",\n sock, recieve_kwargs)\n data = recieve_all(\n sock, timeout_s=timeout_s, errors=errors, **recieve_kwargs)\n else:\n data = None\n\n if shutdown:\n try:\n LOGGER.debug(\"Shutting down socket %r\", sock)\n sock.shutdown(socket.SHUT_RDWR)\n except Exception as e:\n handle_socket_error(e, errors=Errors.IGNORE, socket=sock,\n address=address_tuple, action=action)\n\n return data\n\n\ndef netcat(data_to_send, host, port, recieve_reply=True, timeout_s=1):\n recieved_data = None\n address_tuple = (host, port)\n LOGGER.info(\n \"Running netcat with data %r, host %r, port %r, timeout %r\",\n data_to_send[:MAX_DATA_PRINT_LENGTH], host, port, timeout_s)\n\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:\n LOGGER.debug(\"Created socket %r\", sock)\n sock = setup_socket(\n sock, address_tuple, action=\"connect\", timeout_s=timeout_s,\n errors=Errors.RAISE, error_codes_suppress=None)\n LOGGER.debug(\"Sending data %r to socket %r\",\n data_to_send[:MAX_DATA_PRINT_LENGTH], sock)\n if data_to_send is not None:\n sock.sendall(data_to_send)\n sock.shutdown(socket.SHUT_WR)\n\n if recieve_reply:\n LOGGER.debug(\"Recieving data from socket %r\", sock)\n recieved_data = recieve_all(\n sock, timeout_s=timeout_s, errors=Errors.RAISE)\n\n sock.shutdown(socket.SHUT_RD)\n\n return recieved_data\n\n\[email protected]_logging\ndef netcat_main(data_to_send=None, recieve_reply=True, **netcat_args):\n if data_to_send is not None:\n LOGGER.debug(\"Encoding input data %r to bytes\",\n data_to_send[:MAX_DATA_PRINT_LENGTH])\n data_to_send = data_to_send.encode()\n LOGGER.debug(\"Encoded data: %r\",\n data_to_send[:MAX_DATA_PRINT_LENGTH].hex())\n recieved_data = netcat(\n data_to_send, recieve_reply=recieve_reply, **netcat_args)\n if recieve_reply:\n try:\n LOGGER.debug(\"First %s bytes of recieved data: %r\",\n MAX_DATA_PRINT_LENGTH,\n recieved_data[:MAX_DATA_PRINT_LENGTH].hex())\n recieved_data = recieved_data.decode()\n except Exception:\n pass\n LOGGER.info(\"Recieved responce:\\n\")\n print(recieved_data)\n return recieved_data\n", "<docstring token>\nimport errno\nimport logging\nimport platform\nimport socket\nimport subprocess\nfrom brokkr.constants import Errors\nimport brokkr.utils.log\nimport brokkr.utils.misc\nBUFFER_SIZE_DEFAULT = 4096\nMAX_DATA_SIZE = 2 ** 31 - 2\nMAX_DATA_PRINT_LENGTH = 1024\nTIMEOUT_S_DEFAULT = 2\nSUBPROCESS_TIMEOUT_EXTRA = 2\nPING_COUNT_PARAM = '-n' if platform.system().lower() == 'windows' else '-c'\nERROR_CODES_ADDRESS_LINK_DOWN = {getattr(errno, 'EADDRNOTAVAIL', None),\n getattr(errno, 'WSAEADDRNOTAVAIL', None)}\nLOGGER = logging.getLogger(__name__)\nLOG_HELPER = brokkr.utils.log.LogHelper(LOGGER)\n\n\ndef ping(host, count=1, timeout_s=TIMEOUT_S_DEFAULT, record_output=False):\n if platform.system().lower() == 'windows':\n count_param = '-n'\n else:\n count_param = '-c'\n command = ['ping', count_param, str(count), '-w', str(timeout_s), host]\n LOGGER.debug('Running ping command %s ...', ' '.join(command))\n if record_output:\n extra_args = {'stdout': subprocess.PIPE, 'stderr': subprocess.PIPE,\n 'encoding': 'utf-8', 'errors': 'surrogateescape'}\n else:\n extra_args = {'stdout': subprocess.DEVNULL, 'stderr': subprocess.\n DEVNULL}\n ping_output = subprocess.run(command, timeout=timeout_s +\n SUBPROCESS_TIMEOUT_EXTRA, check=False, **extra_args)\n return ping_output\n\n\ndef handle_socket_error(e, errors=Errors.RAISE, **log_kwargs):\n if errors == Errors.RAISE:\n raise e\n if errors in {Errors.WARN, Errors.LOG}:\n LOGGER.error('%s with socket: %s', type(e).__name__, e)\n LOG_HELPER.log(socket=log_kwargs)\n elif errors == Errors.IGNORE:\n LOGGER.debug('Suppressing %s with socket: %s', type(e).__name__, e)\n LOG_HELPER.log(log_helper_log_level='debug', socket=log_kwargs)\n else:\n error_levels = {('Errors.' + errors.name) for errors in Errors}\n LOGGER.critical(\n 'Error level for %s.handle_socket_error must be one of %r, not %r; assuming raise'\n , __file__, error_levels, errors)\n LOGGER.info('Stack trace:', stack_info=True)\n raise e\n\n\ndef setup_socket(sock, address_tuple, action, timeout_s=None, errors=Errors\n .RAISE, error_codes_suppress=ERROR_CODES_ADDRESS_LINK_DOWN):\n valid_actions = {'bind', 'connect'}\n if action is not None and action not in valid_actions:\n LOGGER.critical('Action for %s.setup_socket must be one of %r, not %r',\n __file__, valid_actions, action)\n LOGGER.info('Stack trace:', stack_info=True)\n raise ValueError(\n f'Action must be one of {valid_actions!r}, not {action!r}')\n try:\n sock.settimeout(timeout_s)\n if action is not None:\n getattr(sock, action)(address_tuple)\n except Exception as e:\n if isinstance(e, OSError):\n if error_codes_suppress and (isinstance(e, socket.timeout) or e\n .errno and e.errno in error_codes_suppress):\n errors = Errors.IGNORE\n handle_socket_error(e, errors=errors, socket=sock, address=\n address_tuple, action=action)\n return None\n else:\n LOGGER.debug('Listening on socket %r', sock)\n return sock\n\n\ndef recieve_all(sock, data_length=None, timeout_s=None, errors=Errors.RAISE,\n buffer_size=BUFFER_SIZE_DEFAULT):\n start_time_recieve = None\n chunks = []\n bytes_remaining = (data_length if data_length else MAX_DATA_SIZE -\n buffer_size)\n while bytes_remaining > 0 and (not start_time_recieve or not timeout_s or\n brokkr.utils.misc.monotonic_ns() - start_time_recieve * brokkr.\n utils.misc.NS_IN_S <= timeout_s * brokkr.utils.misc.NS_IN_S):\n try:\n chunk = sock.recv(buffer_size)\n if not chunks:\n LOGGER.debug(\n 'First chunk of network data recieved of length %s bytes',\n len(chunk))\n LOGGER.debug('First %s bytes of first chunk: %r',\n MAX_DATA_PRINT_LENGTH, chunk[:MAX_DATA_PRINT_LENGTH])\n except socket.timeout as e:\n LOGGER.debug('Socket timed out in %s s while waiting for data',\n timeout_s)\n handle_socket_error(e, errors=Errors.IGNORE, socket=sock,\n data_length=data_length, n_chunks=len(chunks),\n bytes_remaining=bytes_remaining)\n break\n except Exception as e:\n handle_socket_error(e, errors=errors, socket=sock, data_length=\n data_length, n_chunks=len(chunks), bytes_remaining=\n bytes_remaining)\n return None\n if start_time_recieve is None:\n start_time_recieve = brokkr.utils.misc.monotonic_ns()\n if not chunk:\n if not data_length:\n errors = Errors.IGNORE\n try:\n raise RuntimeError(\n f'Null {chunk!r} found in recieved socket data chunk')\n except RuntimeError as e:\n handle_socket_error(e, errors=errors, socket=sock,\n data_length=data_length, n_chunks=len(chunks),\n bytes_remaining=bytes_remaining)\n break\n bytes_remaining -= len(chunk)\n buffer_size = min([buffer_size, bytes_remaining])\n chunks.append(chunk)\n LOGGER.debug('%s total chunks of network data recieved', len(chunks))\n if not chunks:\n LOGGER.debug('No network data to return')\n return None\n data = b''.join(chunks)\n if data_length:\n data = data[:data_length]\n if not data:\n LOGGER.debug('Null network data recieved: %r', data)\n else:\n LOGGER.debug('Network data recieved of length %s bytes', len(data))\n LOGGER.debug('First %s bytes: %r', MAX_DATA_PRINT_LENGTH, data[:\n MAX_DATA_PRINT_LENGTH])\n return data\n\n\ndef read_socket_data(host, port, action, socket_family=socket.AF_INET,\n socket_type=socket.SOCK_STREAM, timeout_s=TIMEOUT_S_DEFAULT, errors=\n Errors.RAISE, shutdown=False, **recieve_kwargs):\n address_tuple = host, port\n LOGGER.debug(\n 'Creating socket of family %r, type %r with host %r, port %r, action %r, timeout %r'\n , socket_family, socket_type, host, port, action, timeout_s)\n with socket.socket(socket_family, socket_type) as sock:\n LOGGER.debug('Created socket %r', sock)\n setup_sock = setup_socket(sock, address_tuple, action, timeout_s=\n timeout_s, errors=errors)\n if setup_sock is not None:\n sock = setup_sock\n LOGGER.debug('Waiting for data from socket %r with kwargs %r',\n sock, recieve_kwargs)\n data = recieve_all(sock, timeout_s=timeout_s, errors=errors, **\n recieve_kwargs)\n else:\n data = None\n if shutdown:\n try:\n LOGGER.debug('Shutting down socket %r', sock)\n sock.shutdown(socket.SHUT_RDWR)\n except Exception as e:\n handle_socket_error(e, errors=Errors.IGNORE, socket=sock,\n address=address_tuple, action=action)\n return data\n\n\ndef netcat(data_to_send, host, port, recieve_reply=True, timeout_s=1):\n recieved_data = None\n address_tuple = host, port\n LOGGER.info('Running netcat with data %r, host %r, port %r, timeout %r',\n data_to_send[:MAX_DATA_PRINT_LENGTH], host, port, timeout_s)\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:\n LOGGER.debug('Created socket %r', sock)\n sock = setup_socket(sock, address_tuple, action='connect',\n timeout_s=timeout_s, errors=Errors.RAISE, error_codes_suppress=None\n )\n LOGGER.debug('Sending data %r to socket %r', data_to_send[:\n MAX_DATA_PRINT_LENGTH], sock)\n if data_to_send is not None:\n sock.sendall(data_to_send)\n sock.shutdown(socket.SHUT_WR)\n if recieve_reply:\n LOGGER.debug('Recieving data from socket %r', sock)\n recieved_data = recieve_all(sock, timeout_s=timeout_s, errors=\n Errors.RAISE)\n sock.shutdown(socket.SHUT_RD)\n return recieved_data\n\n\[email protected]_logging\ndef netcat_main(data_to_send=None, recieve_reply=True, **netcat_args):\n if data_to_send is not None:\n LOGGER.debug('Encoding input data %r to bytes', data_to_send[:\n MAX_DATA_PRINT_LENGTH])\n data_to_send = data_to_send.encode()\n LOGGER.debug('Encoded data: %r', data_to_send[:\n MAX_DATA_PRINT_LENGTH].hex())\n recieved_data = netcat(data_to_send, recieve_reply=recieve_reply, **\n netcat_args)\n if recieve_reply:\n try:\n LOGGER.debug('First %s bytes of recieved data: %r',\n MAX_DATA_PRINT_LENGTH, recieved_data[:MAX_DATA_PRINT_LENGTH\n ].hex())\n recieved_data = recieved_data.decode()\n except Exception:\n pass\n LOGGER.info('Recieved responce:\\n')\n print(recieved_data)\n return recieved_data\n", "<docstring token>\n<import token>\nBUFFER_SIZE_DEFAULT = 4096\nMAX_DATA_SIZE = 2 ** 31 - 2\nMAX_DATA_PRINT_LENGTH = 1024\nTIMEOUT_S_DEFAULT = 2\nSUBPROCESS_TIMEOUT_EXTRA = 2\nPING_COUNT_PARAM = '-n' if platform.system().lower() == 'windows' else '-c'\nERROR_CODES_ADDRESS_LINK_DOWN = {getattr(errno, 'EADDRNOTAVAIL', None),\n getattr(errno, 'WSAEADDRNOTAVAIL', None)}\nLOGGER = logging.getLogger(__name__)\nLOG_HELPER = brokkr.utils.log.LogHelper(LOGGER)\n\n\ndef ping(host, count=1, timeout_s=TIMEOUT_S_DEFAULT, record_output=False):\n if platform.system().lower() == 'windows':\n count_param = '-n'\n else:\n count_param = '-c'\n command = ['ping', count_param, str(count), '-w', str(timeout_s), host]\n LOGGER.debug('Running ping command %s ...', ' '.join(command))\n if record_output:\n extra_args = {'stdout': subprocess.PIPE, 'stderr': subprocess.PIPE,\n 'encoding': 'utf-8', 'errors': 'surrogateescape'}\n else:\n extra_args = {'stdout': subprocess.DEVNULL, 'stderr': subprocess.\n DEVNULL}\n ping_output = subprocess.run(command, timeout=timeout_s +\n SUBPROCESS_TIMEOUT_EXTRA, check=False, **extra_args)\n return ping_output\n\n\ndef handle_socket_error(e, errors=Errors.RAISE, **log_kwargs):\n if errors == Errors.RAISE:\n raise e\n if errors in {Errors.WARN, Errors.LOG}:\n LOGGER.error('%s with socket: %s', type(e).__name__, e)\n LOG_HELPER.log(socket=log_kwargs)\n elif errors == Errors.IGNORE:\n LOGGER.debug('Suppressing %s with socket: %s', type(e).__name__, e)\n LOG_HELPER.log(log_helper_log_level='debug', socket=log_kwargs)\n else:\n error_levels = {('Errors.' + errors.name) for errors in Errors}\n LOGGER.critical(\n 'Error level for %s.handle_socket_error must be one of %r, not %r; assuming raise'\n , __file__, error_levels, errors)\n LOGGER.info('Stack trace:', stack_info=True)\n raise e\n\n\ndef setup_socket(sock, address_tuple, action, timeout_s=None, errors=Errors\n .RAISE, error_codes_suppress=ERROR_CODES_ADDRESS_LINK_DOWN):\n valid_actions = {'bind', 'connect'}\n if action is not None and action not in valid_actions:\n LOGGER.critical('Action for %s.setup_socket must be one of %r, not %r',\n __file__, valid_actions, action)\n LOGGER.info('Stack trace:', stack_info=True)\n raise ValueError(\n f'Action must be one of {valid_actions!r}, not {action!r}')\n try:\n sock.settimeout(timeout_s)\n if action is not None:\n getattr(sock, action)(address_tuple)\n except Exception as e:\n if isinstance(e, OSError):\n if error_codes_suppress and (isinstance(e, socket.timeout) or e\n .errno and e.errno in error_codes_suppress):\n errors = Errors.IGNORE\n handle_socket_error(e, errors=errors, socket=sock, address=\n address_tuple, action=action)\n return None\n else:\n LOGGER.debug('Listening on socket %r', sock)\n return sock\n\n\ndef recieve_all(sock, data_length=None, timeout_s=None, errors=Errors.RAISE,\n buffer_size=BUFFER_SIZE_DEFAULT):\n start_time_recieve = None\n chunks = []\n bytes_remaining = (data_length if data_length else MAX_DATA_SIZE -\n buffer_size)\n while bytes_remaining > 0 and (not start_time_recieve or not timeout_s or\n brokkr.utils.misc.monotonic_ns() - start_time_recieve * brokkr.\n utils.misc.NS_IN_S <= timeout_s * brokkr.utils.misc.NS_IN_S):\n try:\n chunk = sock.recv(buffer_size)\n if not chunks:\n LOGGER.debug(\n 'First chunk of network data recieved of length %s bytes',\n len(chunk))\n LOGGER.debug('First %s bytes of first chunk: %r',\n MAX_DATA_PRINT_LENGTH, chunk[:MAX_DATA_PRINT_LENGTH])\n except socket.timeout as e:\n LOGGER.debug('Socket timed out in %s s while waiting for data',\n timeout_s)\n handle_socket_error(e, errors=Errors.IGNORE, socket=sock,\n data_length=data_length, n_chunks=len(chunks),\n bytes_remaining=bytes_remaining)\n break\n except Exception as e:\n handle_socket_error(e, errors=errors, socket=sock, data_length=\n data_length, n_chunks=len(chunks), bytes_remaining=\n bytes_remaining)\n return None\n if start_time_recieve is None:\n start_time_recieve = brokkr.utils.misc.monotonic_ns()\n if not chunk:\n if not data_length:\n errors = Errors.IGNORE\n try:\n raise RuntimeError(\n f'Null {chunk!r} found in recieved socket data chunk')\n except RuntimeError as e:\n handle_socket_error(e, errors=errors, socket=sock,\n data_length=data_length, n_chunks=len(chunks),\n bytes_remaining=bytes_remaining)\n break\n bytes_remaining -= len(chunk)\n buffer_size = min([buffer_size, bytes_remaining])\n chunks.append(chunk)\n LOGGER.debug('%s total chunks of network data recieved', len(chunks))\n if not chunks:\n LOGGER.debug('No network data to return')\n return None\n data = b''.join(chunks)\n if data_length:\n data = data[:data_length]\n if not data:\n LOGGER.debug('Null network data recieved: %r', data)\n else:\n LOGGER.debug('Network data recieved of length %s bytes', len(data))\n LOGGER.debug('First %s bytes: %r', MAX_DATA_PRINT_LENGTH, data[:\n MAX_DATA_PRINT_LENGTH])\n return data\n\n\ndef read_socket_data(host, port, action, socket_family=socket.AF_INET,\n socket_type=socket.SOCK_STREAM, timeout_s=TIMEOUT_S_DEFAULT, errors=\n Errors.RAISE, shutdown=False, **recieve_kwargs):\n address_tuple = host, port\n LOGGER.debug(\n 'Creating socket of family %r, type %r with host %r, port %r, action %r, timeout %r'\n , socket_family, socket_type, host, port, action, timeout_s)\n with socket.socket(socket_family, socket_type) as sock:\n LOGGER.debug('Created socket %r', sock)\n setup_sock = setup_socket(sock, address_tuple, action, timeout_s=\n timeout_s, errors=errors)\n if setup_sock is not None:\n sock = setup_sock\n LOGGER.debug('Waiting for data from socket %r with kwargs %r',\n sock, recieve_kwargs)\n data = recieve_all(sock, timeout_s=timeout_s, errors=errors, **\n recieve_kwargs)\n else:\n data = None\n if shutdown:\n try:\n LOGGER.debug('Shutting down socket %r', sock)\n sock.shutdown(socket.SHUT_RDWR)\n except Exception as e:\n handle_socket_error(e, errors=Errors.IGNORE, socket=sock,\n address=address_tuple, action=action)\n return data\n\n\ndef netcat(data_to_send, host, port, recieve_reply=True, timeout_s=1):\n recieved_data = None\n address_tuple = host, port\n LOGGER.info('Running netcat with data %r, host %r, port %r, timeout %r',\n data_to_send[:MAX_DATA_PRINT_LENGTH], host, port, timeout_s)\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:\n LOGGER.debug('Created socket %r', sock)\n sock = setup_socket(sock, address_tuple, action='connect',\n timeout_s=timeout_s, errors=Errors.RAISE, error_codes_suppress=None\n )\n LOGGER.debug('Sending data %r to socket %r', data_to_send[:\n MAX_DATA_PRINT_LENGTH], sock)\n if data_to_send is not None:\n sock.sendall(data_to_send)\n sock.shutdown(socket.SHUT_WR)\n if recieve_reply:\n LOGGER.debug('Recieving data from socket %r', sock)\n recieved_data = recieve_all(sock, timeout_s=timeout_s, errors=\n Errors.RAISE)\n sock.shutdown(socket.SHUT_RD)\n return recieved_data\n\n\[email protected]_logging\ndef netcat_main(data_to_send=None, recieve_reply=True, **netcat_args):\n if data_to_send is not None:\n LOGGER.debug('Encoding input data %r to bytes', data_to_send[:\n MAX_DATA_PRINT_LENGTH])\n data_to_send = data_to_send.encode()\n LOGGER.debug('Encoded data: %r', data_to_send[:\n MAX_DATA_PRINT_LENGTH].hex())\n recieved_data = netcat(data_to_send, recieve_reply=recieve_reply, **\n netcat_args)\n if recieve_reply:\n try:\n LOGGER.debug('First %s bytes of recieved data: %r',\n MAX_DATA_PRINT_LENGTH, recieved_data[:MAX_DATA_PRINT_LENGTH\n ].hex())\n recieved_data = recieved_data.decode()\n except Exception:\n pass\n LOGGER.info('Recieved responce:\\n')\n print(recieved_data)\n return recieved_data\n", "<docstring token>\n<import token>\n<assignment token>\n\n\ndef ping(host, count=1, timeout_s=TIMEOUT_S_DEFAULT, record_output=False):\n if platform.system().lower() == 'windows':\n count_param = '-n'\n else:\n count_param = '-c'\n command = ['ping', count_param, str(count), '-w', str(timeout_s), host]\n LOGGER.debug('Running ping command %s ...', ' '.join(command))\n if record_output:\n extra_args = {'stdout': subprocess.PIPE, 'stderr': subprocess.PIPE,\n 'encoding': 'utf-8', 'errors': 'surrogateescape'}\n else:\n extra_args = {'stdout': subprocess.DEVNULL, 'stderr': subprocess.\n DEVNULL}\n ping_output = subprocess.run(command, timeout=timeout_s +\n SUBPROCESS_TIMEOUT_EXTRA, check=False, **extra_args)\n return ping_output\n\n\ndef handle_socket_error(e, errors=Errors.RAISE, **log_kwargs):\n if errors == Errors.RAISE:\n raise e\n if errors in {Errors.WARN, Errors.LOG}:\n LOGGER.error('%s with socket: %s', type(e).__name__, e)\n LOG_HELPER.log(socket=log_kwargs)\n elif errors == Errors.IGNORE:\n LOGGER.debug('Suppressing %s with socket: %s', type(e).__name__, e)\n LOG_HELPER.log(log_helper_log_level='debug', socket=log_kwargs)\n else:\n error_levels = {('Errors.' + errors.name) for errors in Errors}\n LOGGER.critical(\n 'Error level for %s.handle_socket_error must be one of %r, not %r; assuming raise'\n , __file__, error_levels, errors)\n LOGGER.info('Stack trace:', stack_info=True)\n raise e\n\n\ndef setup_socket(sock, address_tuple, action, timeout_s=None, errors=Errors\n .RAISE, error_codes_suppress=ERROR_CODES_ADDRESS_LINK_DOWN):\n valid_actions = {'bind', 'connect'}\n if action is not None and action not in valid_actions:\n LOGGER.critical('Action for %s.setup_socket must be one of %r, not %r',\n __file__, valid_actions, action)\n LOGGER.info('Stack trace:', stack_info=True)\n raise ValueError(\n f'Action must be one of {valid_actions!r}, not {action!r}')\n try:\n sock.settimeout(timeout_s)\n if action is not None:\n getattr(sock, action)(address_tuple)\n except Exception as e:\n if isinstance(e, OSError):\n if error_codes_suppress and (isinstance(e, socket.timeout) or e\n .errno and e.errno in error_codes_suppress):\n errors = Errors.IGNORE\n handle_socket_error(e, errors=errors, socket=sock, address=\n address_tuple, action=action)\n return None\n else:\n LOGGER.debug('Listening on socket %r', sock)\n return sock\n\n\ndef recieve_all(sock, data_length=None, timeout_s=None, errors=Errors.RAISE,\n buffer_size=BUFFER_SIZE_DEFAULT):\n start_time_recieve = None\n chunks = []\n bytes_remaining = (data_length if data_length else MAX_DATA_SIZE -\n buffer_size)\n while bytes_remaining > 0 and (not start_time_recieve or not timeout_s or\n brokkr.utils.misc.monotonic_ns() - start_time_recieve * brokkr.\n utils.misc.NS_IN_S <= timeout_s * brokkr.utils.misc.NS_IN_S):\n try:\n chunk = sock.recv(buffer_size)\n if not chunks:\n LOGGER.debug(\n 'First chunk of network data recieved of length %s bytes',\n len(chunk))\n LOGGER.debug('First %s bytes of first chunk: %r',\n MAX_DATA_PRINT_LENGTH, chunk[:MAX_DATA_PRINT_LENGTH])\n except socket.timeout as e:\n LOGGER.debug('Socket timed out in %s s while waiting for data',\n timeout_s)\n handle_socket_error(e, errors=Errors.IGNORE, socket=sock,\n data_length=data_length, n_chunks=len(chunks),\n bytes_remaining=bytes_remaining)\n break\n except Exception as e:\n handle_socket_error(e, errors=errors, socket=sock, data_length=\n data_length, n_chunks=len(chunks), bytes_remaining=\n bytes_remaining)\n return None\n if start_time_recieve is None:\n start_time_recieve = brokkr.utils.misc.monotonic_ns()\n if not chunk:\n if not data_length:\n errors = Errors.IGNORE\n try:\n raise RuntimeError(\n f'Null {chunk!r} found in recieved socket data chunk')\n except RuntimeError as e:\n handle_socket_error(e, errors=errors, socket=sock,\n data_length=data_length, n_chunks=len(chunks),\n bytes_remaining=bytes_remaining)\n break\n bytes_remaining -= len(chunk)\n buffer_size = min([buffer_size, bytes_remaining])\n chunks.append(chunk)\n LOGGER.debug('%s total chunks of network data recieved', len(chunks))\n if not chunks:\n LOGGER.debug('No network data to return')\n return None\n data = b''.join(chunks)\n if data_length:\n data = data[:data_length]\n if not data:\n LOGGER.debug('Null network data recieved: %r', data)\n else:\n LOGGER.debug('Network data recieved of length %s bytes', len(data))\n LOGGER.debug('First %s bytes: %r', MAX_DATA_PRINT_LENGTH, data[:\n MAX_DATA_PRINT_LENGTH])\n return data\n\n\ndef read_socket_data(host, port, action, socket_family=socket.AF_INET,\n socket_type=socket.SOCK_STREAM, timeout_s=TIMEOUT_S_DEFAULT, errors=\n Errors.RAISE, shutdown=False, **recieve_kwargs):\n address_tuple = host, port\n LOGGER.debug(\n 'Creating socket of family %r, type %r with host %r, port %r, action %r, timeout %r'\n , socket_family, socket_type, host, port, action, timeout_s)\n with socket.socket(socket_family, socket_type) as sock:\n LOGGER.debug('Created socket %r', sock)\n setup_sock = setup_socket(sock, address_tuple, action, timeout_s=\n timeout_s, errors=errors)\n if setup_sock is not None:\n sock = setup_sock\n LOGGER.debug('Waiting for data from socket %r with kwargs %r',\n sock, recieve_kwargs)\n data = recieve_all(sock, timeout_s=timeout_s, errors=errors, **\n recieve_kwargs)\n else:\n data = None\n if shutdown:\n try:\n LOGGER.debug('Shutting down socket %r', sock)\n sock.shutdown(socket.SHUT_RDWR)\n except Exception as e:\n handle_socket_error(e, errors=Errors.IGNORE, socket=sock,\n address=address_tuple, action=action)\n return data\n\n\ndef netcat(data_to_send, host, port, recieve_reply=True, timeout_s=1):\n recieved_data = None\n address_tuple = host, port\n LOGGER.info('Running netcat with data %r, host %r, port %r, timeout %r',\n data_to_send[:MAX_DATA_PRINT_LENGTH], host, port, timeout_s)\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:\n LOGGER.debug('Created socket %r', sock)\n sock = setup_socket(sock, address_tuple, action='connect',\n timeout_s=timeout_s, errors=Errors.RAISE, error_codes_suppress=None\n )\n LOGGER.debug('Sending data %r to socket %r', data_to_send[:\n MAX_DATA_PRINT_LENGTH], sock)\n if data_to_send is not None:\n sock.sendall(data_to_send)\n sock.shutdown(socket.SHUT_WR)\n if recieve_reply:\n LOGGER.debug('Recieving data from socket %r', sock)\n recieved_data = recieve_all(sock, timeout_s=timeout_s, errors=\n Errors.RAISE)\n sock.shutdown(socket.SHUT_RD)\n return recieved_data\n\n\[email protected]_logging\ndef netcat_main(data_to_send=None, recieve_reply=True, **netcat_args):\n if data_to_send is not None:\n LOGGER.debug('Encoding input data %r to bytes', data_to_send[:\n MAX_DATA_PRINT_LENGTH])\n data_to_send = data_to_send.encode()\n LOGGER.debug('Encoded data: %r', data_to_send[:\n MAX_DATA_PRINT_LENGTH].hex())\n recieved_data = netcat(data_to_send, recieve_reply=recieve_reply, **\n netcat_args)\n if recieve_reply:\n try:\n LOGGER.debug('First %s bytes of recieved data: %r',\n MAX_DATA_PRINT_LENGTH, recieved_data[:MAX_DATA_PRINT_LENGTH\n ].hex())\n recieved_data = recieved_data.decode()\n except Exception:\n pass\n LOGGER.info('Recieved responce:\\n')\n print(recieved_data)\n return recieved_data\n", "<docstring token>\n<import token>\n<assignment token>\n\n\ndef ping(host, count=1, timeout_s=TIMEOUT_S_DEFAULT, record_output=False):\n if platform.system().lower() == 'windows':\n count_param = '-n'\n else:\n count_param = '-c'\n command = ['ping', count_param, str(count), '-w', str(timeout_s), host]\n LOGGER.debug('Running ping command %s ...', ' '.join(command))\n if record_output:\n extra_args = {'stdout': subprocess.PIPE, 'stderr': subprocess.PIPE,\n 'encoding': 'utf-8', 'errors': 'surrogateescape'}\n else:\n extra_args = {'stdout': subprocess.DEVNULL, 'stderr': subprocess.\n DEVNULL}\n ping_output = subprocess.run(command, timeout=timeout_s +\n SUBPROCESS_TIMEOUT_EXTRA, check=False, **extra_args)\n return ping_output\n\n\n<function token>\n\n\ndef setup_socket(sock, address_tuple, action, timeout_s=None, errors=Errors\n .RAISE, error_codes_suppress=ERROR_CODES_ADDRESS_LINK_DOWN):\n valid_actions = {'bind', 'connect'}\n if action is not None and action not in valid_actions:\n LOGGER.critical('Action for %s.setup_socket must be one of %r, not %r',\n __file__, valid_actions, action)\n LOGGER.info('Stack trace:', stack_info=True)\n raise ValueError(\n f'Action must be one of {valid_actions!r}, not {action!r}')\n try:\n sock.settimeout(timeout_s)\n if action is not None:\n getattr(sock, action)(address_tuple)\n except Exception as e:\n if isinstance(e, OSError):\n if error_codes_suppress and (isinstance(e, socket.timeout) or e\n .errno and e.errno in error_codes_suppress):\n errors = Errors.IGNORE\n handle_socket_error(e, errors=errors, socket=sock, address=\n address_tuple, action=action)\n return None\n else:\n LOGGER.debug('Listening on socket %r', sock)\n return sock\n\n\ndef recieve_all(sock, data_length=None, timeout_s=None, errors=Errors.RAISE,\n buffer_size=BUFFER_SIZE_DEFAULT):\n start_time_recieve = None\n chunks = []\n bytes_remaining = (data_length if data_length else MAX_DATA_SIZE -\n buffer_size)\n while bytes_remaining > 0 and (not start_time_recieve or not timeout_s or\n brokkr.utils.misc.monotonic_ns() - start_time_recieve * brokkr.\n utils.misc.NS_IN_S <= timeout_s * brokkr.utils.misc.NS_IN_S):\n try:\n chunk = sock.recv(buffer_size)\n if not chunks:\n LOGGER.debug(\n 'First chunk of network data recieved of length %s bytes',\n len(chunk))\n LOGGER.debug('First %s bytes of first chunk: %r',\n MAX_DATA_PRINT_LENGTH, chunk[:MAX_DATA_PRINT_LENGTH])\n except socket.timeout as e:\n LOGGER.debug('Socket timed out in %s s while waiting for data',\n timeout_s)\n handle_socket_error(e, errors=Errors.IGNORE, socket=sock,\n data_length=data_length, n_chunks=len(chunks),\n bytes_remaining=bytes_remaining)\n break\n except Exception as e:\n handle_socket_error(e, errors=errors, socket=sock, data_length=\n data_length, n_chunks=len(chunks), bytes_remaining=\n bytes_remaining)\n return None\n if start_time_recieve is None:\n start_time_recieve = brokkr.utils.misc.monotonic_ns()\n if not chunk:\n if not data_length:\n errors = Errors.IGNORE\n try:\n raise RuntimeError(\n f'Null {chunk!r} found in recieved socket data chunk')\n except RuntimeError as e:\n handle_socket_error(e, errors=errors, socket=sock,\n data_length=data_length, n_chunks=len(chunks),\n bytes_remaining=bytes_remaining)\n break\n bytes_remaining -= len(chunk)\n buffer_size = min([buffer_size, bytes_remaining])\n chunks.append(chunk)\n LOGGER.debug('%s total chunks of network data recieved', len(chunks))\n if not chunks:\n LOGGER.debug('No network data to return')\n return None\n data = b''.join(chunks)\n if data_length:\n data = data[:data_length]\n if not data:\n LOGGER.debug('Null network data recieved: %r', data)\n else:\n LOGGER.debug('Network data recieved of length %s bytes', len(data))\n LOGGER.debug('First %s bytes: %r', MAX_DATA_PRINT_LENGTH, data[:\n MAX_DATA_PRINT_LENGTH])\n return data\n\n\ndef read_socket_data(host, port, action, socket_family=socket.AF_INET,\n socket_type=socket.SOCK_STREAM, timeout_s=TIMEOUT_S_DEFAULT, errors=\n Errors.RAISE, shutdown=False, **recieve_kwargs):\n address_tuple = host, port\n LOGGER.debug(\n 'Creating socket of family %r, type %r with host %r, port %r, action %r, timeout %r'\n , socket_family, socket_type, host, port, action, timeout_s)\n with socket.socket(socket_family, socket_type) as sock:\n LOGGER.debug('Created socket %r', sock)\n setup_sock = setup_socket(sock, address_tuple, action, timeout_s=\n timeout_s, errors=errors)\n if setup_sock is not None:\n sock = setup_sock\n LOGGER.debug('Waiting for data from socket %r with kwargs %r',\n sock, recieve_kwargs)\n data = recieve_all(sock, timeout_s=timeout_s, errors=errors, **\n recieve_kwargs)\n else:\n data = None\n if shutdown:\n try:\n LOGGER.debug('Shutting down socket %r', sock)\n sock.shutdown(socket.SHUT_RDWR)\n except Exception as e:\n handle_socket_error(e, errors=Errors.IGNORE, socket=sock,\n address=address_tuple, action=action)\n return data\n\n\ndef netcat(data_to_send, host, port, recieve_reply=True, timeout_s=1):\n recieved_data = None\n address_tuple = host, port\n LOGGER.info('Running netcat with data %r, host %r, port %r, timeout %r',\n data_to_send[:MAX_DATA_PRINT_LENGTH], host, port, timeout_s)\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:\n LOGGER.debug('Created socket %r', sock)\n sock = setup_socket(sock, address_tuple, action='connect',\n timeout_s=timeout_s, errors=Errors.RAISE, error_codes_suppress=None\n )\n LOGGER.debug('Sending data %r to socket %r', data_to_send[:\n MAX_DATA_PRINT_LENGTH], sock)\n if data_to_send is not None:\n sock.sendall(data_to_send)\n sock.shutdown(socket.SHUT_WR)\n if recieve_reply:\n LOGGER.debug('Recieving data from socket %r', sock)\n recieved_data = recieve_all(sock, timeout_s=timeout_s, errors=\n Errors.RAISE)\n sock.shutdown(socket.SHUT_RD)\n return recieved_data\n\n\[email protected]_logging\ndef netcat_main(data_to_send=None, recieve_reply=True, **netcat_args):\n if data_to_send is not None:\n LOGGER.debug('Encoding input data %r to bytes', data_to_send[:\n MAX_DATA_PRINT_LENGTH])\n data_to_send = data_to_send.encode()\n LOGGER.debug('Encoded data: %r', data_to_send[:\n MAX_DATA_PRINT_LENGTH].hex())\n recieved_data = netcat(data_to_send, recieve_reply=recieve_reply, **\n netcat_args)\n if recieve_reply:\n try:\n LOGGER.debug('First %s bytes of recieved data: %r',\n MAX_DATA_PRINT_LENGTH, recieved_data[:MAX_DATA_PRINT_LENGTH\n ].hex())\n recieved_data = recieved_data.decode()\n except Exception:\n pass\n LOGGER.info('Recieved responce:\\n')\n print(recieved_data)\n return recieved_data\n", "<docstring token>\n<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef setup_socket(sock, address_tuple, action, timeout_s=None, errors=Errors\n .RAISE, error_codes_suppress=ERROR_CODES_ADDRESS_LINK_DOWN):\n valid_actions = {'bind', 'connect'}\n if action is not None and action not in valid_actions:\n LOGGER.critical('Action for %s.setup_socket must be one of %r, not %r',\n __file__, valid_actions, action)\n LOGGER.info('Stack trace:', stack_info=True)\n raise ValueError(\n f'Action must be one of {valid_actions!r}, not {action!r}')\n try:\n sock.settimeout(timeout_s)\n if action is not None:\n getattr(sock, action)(address_tuple)\n except Exception as e:\n if isinstance(e, OSError):\n if error_codes_suppress and (isinstance(e, socket.timeout) or e\n .errno and e.errno in error_codes_suppress):\n errors = Errors.IGNORE\n handle_socket_error(e, errors=errors, socket=sock, address=\n address_tuple, action=action)\n return None\n else:\n LOGGER.debug('Listening on socket %r', sock)\n return sock\n\n\ndef recieve_all(sock, data_length=None, timeout_s=None, errors=Errors.RAISE,\n buffer_size=BUFFER_SIZE_DEFAULT):\n start_time_recieve = None\n chunks = []\n bytes_remaining = (data_length if data_length else MAX_DATA_SIZE -\n buffer_size)\n while bytes_remaining > 0 and (not start_time_recieve or not timeout_s or\n brokkr.utils.misc.monotonic_ns() - start_time_recieve * brokkr.\n utils.misc.NS_IN_S <= timeout_s * brokkr.utils.misc.NS_IN_S):\n try:\n chunk = sock.recv(buffer_size)\n if not chunks:\n LOGGER.debug(\n 'First chunk of network data recieved of length %s bytes',\n len(chunk))\n LOGGER.debug('First %s bytes of first chunk: %r',\n MAX_DATA_PRINT_LENGTH, chunk[:MAX_DATA_PRINT_LENGTH])\n except socket.timeout as e:\n LOGGER.debug('Socket timed out in %s s while waiting for data',\n timeout_s)\n handle_socket_error(e, errors=Errors.IGNORE, socket=sock,\n data_length=data_length, n_chunks=len(chunks),\n bytes_remaining=bytes_remaining)\n break\n except Exception as e:\n handle_socket_error(e, errors=errors, socket=sock, data_length=\n data_length, n_chunks=len(chunks), bytes_remaining=\n bytes_remaining)\n return None\n if start_time_recieve is None:\n start_time_recieve = brokkr.utils.misc.monotonic_ns()\n if not chunk:\n if not data_length:\n errors = Errors.IGNORE\n try:\n raise RuntimeError(\n f'Null {chunk!r} found in recieved socket data chunk')\n except RuntimeError as e:\n handle_socket_error(e, errors=errors, socket=sock,\n data_length=data_length, n_chunks=len(chunks),\n bytes_remaining=bytes_remaining)\n break\n bytes_remaining -= len(chunk)\n buffer_size = min([buffer_size, bytes_remaining])\n chunks.append(chunk)\n LOGGER.debug('%s total chunks of network data recieved', len(chunks))\n if not chunks:\n LOGGER.debug('No network data to return')\n return None\n data = b''.join(chunks)\n if data_length:\n data = data[:data_length]\n if not data:\n LOGGER.debug('Null network data recieved: %r', data)\n else:\n LOGGER.debug('Network data recieved of length %s bytes', len(data))\n LOGGER.debug('First %s bytes: %r', MAX_DATA_PRINT_LENGTH, data[:\n MAX_DATA_PRINT_LENGTH])\n return data\n\n\ndef read_socket_data(host, port, action, socket_family=socket.AF_INET,\n socket_type=socket.SOCK_STREAM, timeout_s=TIMEOUT_S_DEFAULT, errors=\n Errors.RAISE, shutdown=False, **recieve_kwargs):\n address_tuple = host, port\n LOGGER.debug(\n 'Creating socket of family %r, type %r with host %r, port %r, action %r, timeout %r'\n , socket_family, socket_type, host, port, action, timeout_s)\n with socket.socket(socket_family, socket_type) as sock:\n LOGGER.debug('Created socket %r', sock)\n setup_sock = setup_socket(sock, address_tuple, action, timeout_s=\n timeout_s, errors=errors)\n if setup_sock is not None:\n sock = setup_sock\n LOGGER.debug('Waiting for data from socket %r with kwargs %r',\n sock, recieve_kwargs)\n data = recieve_all(sock, timeout_s=timeout_s, errors=errors, **\n recieve_kwargs)\n else:\n data = None\n if shutdown:\n try:\n LOGGER.debug('Shutting down socket %r', sock)\n sock.shutdown(socket.SHUT_RDWR)\n except Exception as e:\n handle_socket_error(e, errors=Errors.IGNORE, socket=sock,\n address=address_tuple, action=action)\n return data\n\n\ndef netcat(data_to_send, host, port, recieve_reply=True, timeout_s=1):\n recieved_data = None\n address_tuple = host, port\n LOGGER.info('Running netcat with data %r, host %r, port %r, timeout %r',\n data_to_send[:MAX_DATA_PRINT_LENGTH], host, port, timeout_s)\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:\n LOGGER.debug('Created socket %r', sock)\n sock = setup_socket(sock, address_tuple, action='connect',\n timeout_s=timeout_s, errors=Errors.RAISE, error_codes_suppress=None\n )\n LOGGER.debug('Sending data %r to socket %r', data_to_send[:\n MAX_DATA_PRINT_LENGTH], sock)\n if data_to_send is not None:\n sock.sendall(data_to_send)\n sock.shutdown(socket.SHUT_WR)\n if recieve_reply:\n LOGGER.debug('Recieving data from socket %r', sock)\n recieved_data = recieve_all(sock, timeout_s=timeout_s, errors=\n Errors.RAISE)\n sock.shutdown(socket.SHUT_RD)\n return recieved_data\n\n\[email protected]_logging\ndef netcat_main(data_to_send=None, recieve_reply=True, **netcat_args):\n if data_to_send is not None:\n LOGGER.debug('Encoding input data %r to bytes', data_to_send[:\n MAX_DATA_PRINT_LENGTH])\n data_to_send = data_to_send.encode()\n LOGGER.debug('Encoded data: %r', data_to_send[:\n MAX_DATA_PRINT_LENGTH].hex())\n recieved_data = netcat(data_to_send, recieve_reply=recieve_reply, **\n netcat_args)\n if recieve_reply:\n try:\n LOGGER.debug('First %s bytes of recieved data: %r',\n MAX_DATA_PRINT_LENGTH, recieved_data[:MAX_DATA_PRINT_LENGTH\n ].hex())\n recieved_data = recieved_data.decode()\n except Exception:\n pass\n LOGGER.info('Recieved responce:\\n')\n print(recieved_data)\n return recieved_data\n", "<docstring token>\n<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef setup_socket(sock, address_tuple, action, timeout_s=None, errors=Errors\n .RAISE, error_codes_suppress=ERROR_CODES_ADDRESS_LINK_DOWN):\n valid_actions = {'bind', 'connect'}\n if action is not None and action not in valid_actions:\n LOGGER.critical('Action for %s.setup_socket must be one of %r, not %r',\n __file__, valid_actions, action)\n LOGGER.info('Stack trace:', stack_info=True)\n raise ValueError(\n f'Action must be one of {valid_actions!r}, not {action!r}')\n try:\n sock.settimeout(timeout_s)\n if action is not None:\n getattr(sock, action)(address_tuple)\n except Exception as e:\n if isinstance(e, OSError):\n if error_codes_suppress and (isinstance(e, socket.timeout) or e\n .errno and e.errno in error_codes_suppress):\n errors = Errors.IGNORE\n handle_socket_error(e, errors=errors, socket=sock, address=\n address_tuple, action=action)\n return None\n else:\n LOGGER.debug('Listening on socket %r', sock)\n return sock\n\n\ndef recieve_all(sock, data_length=None, timeout_s=None, errors=Errors.RAISE,\n buffer_size=BUFFER_SIZE_DEFAULT):\n start_time_recieve = None\n chunks = []\n bytes_remaining = (data_length if data_length else MAX_DATA_SIZE -\n buffer_size)\n while bytes_remaining > 0 and (not start_time_recieve or not timeout_s or\n brokkr.utils.misc.monotonic_ns() - start_time_recieve * brokkr.\n utils.misc.NS_IN_S <= timeout_s * brokkr.utils.misc.NS_IN_S):\n try:\n chunk = sock.recv(buffer_size)\n if not chunks:\n LOGGER.debug(\n 'First chunk of network data recieved of length %s bytes',\n len(chunk))\n LOGGER.debug('First %s bytes of first chunk: %r',\n MAX_DATA_PRINT_LENGTH, chunk[:MAX_DATA_PRINT_LENGTH])\n except socket.timeout as e:\n LOGGER.debug('Socket timed out in %s s while waiting for data',\n timeout_s)\n handle_socket_error(e, errors=Errors.IGNORE, socket=sock,\n data_length=data_length, n_chunks=len(chunks),\n bytes_remaining=bytes_remaining)\n break\n except Exception as e:\n handle_socket_error(e, errors=errors, socket=sock, data_length=\n data_length, n_chunks=len(chunks), bytes_remaining=\n bytes_remaining)\n return None\n if start_time_recieve is None:\n start_time_recieve = brokkr.utils.misc.monotonic_ns()\n if not chunk:\n if not data_length:\n errors = Errors.IGNORE\n try:\n raise RuntimeError(\n f'Null {chunk!r} found in recieved socket data chunk')\n except RuntimeError as e:\n handle_socket_error(e, errors=errors, socket=sock,\n data_length=data_length, n_chunks=len(chunks),\n bytes_remaining=bytes_remaining)\n break\n bytes_remaining -= len(chunk)\n buffer_size = min([buffer_size, bytes_remaining])\n chunks.append(chunk)\n LOGGER.debug('%s total chunks of network data recieved', len(chunks))\n if not chunks:\n LOGGER.debug('No network data to return')\n return None\n data = b''.join(chunks)\n if data_length:\n data = data[:data_length]\n if not data:\n LOGGER.debug('Null network data recieved: %r', data)\n else:\n LOGGER.debug('Network data recieved of length %s bytes', len(data))\n LOGGER.debug('First %s bytes: %r', MAX_DATA_PRINT_LENGTH, data[:\n MAX_DATA_PRINT_LENGTH])\n return data\n\n\ndef read_socket_data(host, port, action, socket_family=socket.AF_INET,\n socket_type=socket.SOCK_STREAM, timeout_s=TIMEOUT_S_DEFAULT, errors=\n Errors.RAISE, shutdown=False, **recieve_kwargs):\n address_tuple = host, port\n LOGGER.debug(\n 'Creating socket of family %r, type %r with host %r, port %r, action %r, timeout %r'\n , socket_family, socket_type, host, port, action, timeout_s)\n with socket.socket(socket_family, socket_type) as sock:\n LOGGER.debug('Created socket %r', sock)\n setup_sock = setup_socket(sock, address_tuple, action, timeout_s=\n timeout_s, errors=errors)\n if setup_sock is not None:\n sock = setup_sock\n LOGGER.debug('Waiting for data from socket %r with kwargs %r',\n sock, recieve_kwargs)\n data = recieve_all(sock, timeout_s=timeout_s, errors=errors, **\n recieve_kwargs)\n else:\n data = None\n if shutdown:\n try:\n LOGGER.debug('Shutting down socket %r', sock)\n sock.shutdown(socket.SHUT_RDWR)\n except Exception as e:\n handle_socket_error(e, errors=Errors.IGNORE, socket=sock,\n address=address_tuple, action=action)\n return data\n\n\n<function token>\n\n\[email protected]_logging\ndef netcat_main(data_to_send=None, recieve_reply=True, **netcat_args):\n if data_to_send is not None:\n LOGGER.debug('Encoding input data %r to bytes', data_to_send[:\n MAX_DATA_PRINT_LENGTH])\n data_to_send = data_to_send.encode()\n LOGGER.debug('Encoded data: %r', data_to_send[:\n MAX_DATA_PRINT_LENGTH].hex())\n recieved_data = netcat(data_to_send, recieve_reply=recieve_reply, **\n netcat_args)\n if recieve_reply:\n try:\n LOGGER.debug('First %s bytes of recieved data: %r',\n MAX_DATA_PRINT_LENGTH, recieved_data[:MAX_DATA_PRINT_LENGTH\n ].hex())\n recieved_data = recieved_data.decode()\n except Exception:\n pass\n LOGGER.info('Recieved responce:\\n')\n print(recieved_data)\n return recieved_data\n", "<docstring token>\n<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef setup_socket(sock, address_tuple, action, timeout_s=None, errors=Errors\n .RAISE, error_codes_suppress=ERROR_CODES_ADDRESS_LINK_DOWN):\n valid_actions = {'bind', 'connect'}\n if action is not None and action not in valid_actions:\n LOGGER.critical('Action for %s.setup_socket must be one of %r, not %r',\n __file__, valid_actions, action)\n LOGGER.info('Stack trace:', stack_info=True)\n raise ValueError(\n f'Action must be one of {valid_actions!r}, not {action!r}')\n try:\n sock.settimeout(timeout_s)\n if action is not None:\n getattr(sock, action)(address_tuple)\n except Exception as e:\n if isinstance(e, OSError):\n if error_codes_suppress and (isinstance(e, socket.timeout) or e\n .errno and e.errno in error_codes_suppress):\n errors = Errors.IGNORE\n handle_socket_error(e, errors=errors, socket=sock, address=\n address_tuple, action=action)\n return None\n else:\n LOGGER.debug('Listening on socket %r', sock)\n return sock\n\n\n<function token>\n\n\ndef read_socket_data(host, port, action, socket_family=socket.AF_INET,\n socket_type=socket.SOCK_STREAM, timeout_s=TIMEOUT_S_DEFAULT, errors=\n Errors.RAISE, shutdown=False, **recieve_kwargs):\n address_tuple = host, port\n LOGGER.debug(\n 'Creating socket of family %r, type %r with host %r, port %r, action %r, timeout %r'\n , socket_family, socket_type, host, port, action, timeout_s)\n with socket.socket(socket_family, socket_type) as sock:\n LOGGER.debug('Created socket %r', sock)\n setup_sock = setup_socket(sock, address_tuple, action, timeout_s=\n timeout_s, errors=errors)\n if setup_sock is not None:\n sock = setup_sock\n LOGGER.debug('Waiting for data from socket %r with kwargs %r',\n sock, recieve_kwargs)\n data = recieve_all(sock, timeout_s=timeout_s, errors=errors, **\n recieve_kwargs)\n else:\n data = None\n if shutdown:\n try:\n LOGGER.debug('Shutting down socket %r', sock)\n sock.shutdown(socket.SHUT_RDWR)\n except Exception as e:\n handle_socket_error(e, errors=Errors.IGNORE, socket=sock,\n address=address_tuple, action=action)\n return data\n\n\n<function token>\n\n\[email protected]_logging\ndef netcat_main(data_to_send=None, recieve_reply=True, **netcat_args):\n if data_to_send is not None:\n LOGGER.debug('Encoding input data %r to bytes', data_to_send[:\n MAX_DATA_PRINT_LENGTH])\n data_to_send = data_to_send.encode()\n LOGGER.debug('Encoded data: %r', data_to_send[:\n MAX_DATA_PRINT_LENGTH].hex())\n recieved_data = netcat(data_to_send, recieve_reply=recieve_reply, **\n netcat_args)\n if recieve_reply:\n try:\n LOGGER.debug('First %s bytes of recieved data: %r',\n MAX_DATA_PRINT_LENGTH, recieved_data[:MAX_DATA_PRINT_LENGTH\n ].hex())\n recieved_data = recieved_data.decode()\n except Exception:\n pass\n LOGGER.info('Recieved responce:\\n')\n print(recieved_data)\n return recieved_data\n", "<docstring token>\n<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef read_socket_data(host, port, action, socket_family=socket.AF_INET,\n socket_type=socket.SOCK_STREAM, timeout_s=TIMEOUT_S_DEFAULT, errors=\n Errors.RAISE, shutdown=False, **recieve_kwargs):\n address_tuple = host, port\n LOGGER.debug(\n 'Creating socket of family %r, type %r with host %r, port %r, action %r, timeout %r'\n , socket_family, socket_type, host, port, action, timeout_s)\n with socket.socket(socket_family, socket_type) as sock:\n LOGGER.debug('Created socket %r', sock)\n setup_sock = setup_socket(sock, address_tuple, action, timeout_s=\n timeout_s, errors=errors)\n if setup_sock is not None:\n sock = setup_sock\n LOGGER.debug('Waiting for data from socket %r with kwargs %r',\n sock, recieve_kwargs)\n data = recieve_all(sock, timeout_s=timeout_s, errors=errors, **\n recieve_kwargs)\n else:\n data = None\n if shutdown:\n try:\n LOGGER.debug('Shutting down socket %r', sock)\n sock.shutdown(socket.SHUT_RDWR)\n except Exception as e:\n handle_socket_error(e, errors=Errors.IGNORE, socket=sock,\n address=address_tuple, action=action)\n return data\n\n\n<function token>\n\n\[email protected]_logging\ndef netcat_main(data_to_send=None, recieve_reply=True, **netcat_args):\n if data_to_send is not None:\n LOGGER.debug('Encoding input data %r to bytes', data_to_send[:\n MAX_DATA_PRINT_LENGTH])\n data_to_send = data_to_send.encode()\n LOGGER.debug('Encoded data: %r', data_to_send[:\n MAX_DATA_PRINT_LENGTH].hex())\n recieved_data = netcat(data_to_send, recieve_reply=recieve_reply, **\n netcat_args)\n if recieve_reply:\n try:\n LOGGER.debug('First %s bytes of recieved data: %r',\n MAX_DATA_PRINT_LENGTH, recieved_data[:MAX_DATA_PRINT_LENGTH\n ].hex())\n recieved_data = recieved_data.decode()\n except Exception:\n pass\n LOGGER.info('Recieved responce:\\n')\n print(recieved_data)\n return recieved_data\n", "<docstring token>\n<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef read_socket_data(host, port, action, socket_family=socket.AF_INET,\n socket_type=socket.SOCK_STREAM, timeout_s=TIMEOUT_S_DEFAULT, errors=\n Errors.RAISE, shutdown=False, **recieve_kwargs):\n address_tuple = host, port\n LOGGER.debug(\n 'Creating socket of family %r, type %r with host %r, port %r, action %r, timeout %r'\n , socket_family, socket_type, host, port, action, timeout_s)\n with socket.socket(socket_family, socket_type) as sock:\n LOGGER.debug('Created socket %r', sock)\n setup_sock = setup_socket(sock, address_tuple, action, timeout_s=\n timeout_s, errors=errors)\n if setup_sock is not None:\n sock = setup_sock\n LOGGER.debug('Waiting for data from socket %r with kwargs %r',\n sock, recieve_kwargs)\n data = recieve_all(sock, timeout_s=timeout_s, errors=errors, **\n recieve_kwargs)\n else:\n data = None\n if shutdown:\n try:\n LOGGER.debug('Shutting down socket %r', sock)\n sock.shutdown(socket.SHUT_RDWR)\n except Exception as e:\n handle_socket_error(e, errors=Errors.IGNORE, socket=sock,\n address=address_tuple, action=action)\n return data\n\n\n<function token>\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n" ]
false
98,728
209d4e8b2ab80799f21df756069fd2a4a598ff46
import re import os import subprocess import gzip repeat = '/mnt/gluster/home/sonal.singhal1/reference/taeGut1.repeatMaskerBlast.repeatLibrary20140131.out' vcf = '/mnt/gluster/home/sonal.singhal1/ZF/after_vqsr/by_chr/gatk.ug.all_zf.%s.coverage.filtered.vqsr.vcf.gz' chrs = { 'chr10': 20806668, 'chr11': 21403021, 'chr12': 21576510, 'chr13': 16962381, 'chr14': 16419078, 'chr15': 14428146, 'chr16': 9909, 'chr17': 11648728, 'chr18': 11201131, 'chr19': 11587733, 'chr1A': 73657157, 'chr1B': 1083483, 'chr1': 118548696, 'chr20': 15652063, 'chr21': 5979137, 'chr22': 3370227, 'chr23': 6196912, 'chr24': 8021379, 'chr25': 1275379, 'chr26': 4907541, 'chr27': 4618897, 'chr28': 4963201, 'chr2': 156412533, 'chr3': 112617285, 'chr4A': 20704505, 'chr4': 69780378, 'chr5': 62374962, 'chr6': 36305782, 'chr7': 39844632, 'chr8': 27993427, 'chr9': 27241186, 'chrLG2': 109741, 'chrLG5': 16416, 'chrLGE22': 883365, 'chrZ': 72861351} repeats = {} f = open(repeat, 'r') for l in f: if re.search('^\s+\d+', l): d = re.split('\s+', l.rstrip()) if d[5] in chrs: if d[5] not in repeats: repeats[d[5]] = {} start = int(d[6]) end = int(d[7]) + 1 for pos in range(start, end): repeats[d[5]][str(pos)] = 1 f.close() for chr in chrs: vcffile = vcf % chr out = vcffile.replace('coverage.filtered', 'coverage.filtered.repeatmasked') f = gzip.open(vcffile, 'r') o = gzip.open(out, 'w') for l in f: l = l.rstrip() if re.search('^#', l): o.write(l + '\n') else: if re.search('PASS', l): d = re.split('\t', l) if d[0] in repeats: if d[1] not in repeats[d[0]]: o.write(l + '\n') else: o.write(l + '\n') f.close() o.close()
[ "import re\nimport os\nimport subprocess\nimport gzip\n\nrepeat = '/mnt/gluster/home/sonal.singhal1/reference/taeGut1.repeatMaskerBlast.repeatLibrary20140131.out'\nvcf = '/mnt/gluster/home/sonal.singhal1/ZF/after_vqsr/by_chr/gatk.ug.all_zf.%s.coverage.filtered.vqsr.vcf.gz' \n\nchrs = { 'chr10': 20806668, 'chr11': 21403021, 'chr12': 21576510, 'chr13': 16962381,\n 'chr14': 16419078, 'chr15': 14428146, 'chr16': 9909, 'chr17': 11648728,\n 'chr18': 11201131, 'chr19': 11587733, 'chr1A': 73657157, 'chr1B': 1083483,\n 'chr1': 118548696, 'chr20': 15652063, 'chr21': 5979137, 'chr22': 3370227,\n 'chr23': 6196912, 'chr24': 8021379, 'chr25': 1275379, 'chr26': 4907541,\n 'chr27': 4618897, 'chr28': 4963201, 'chr2': 156412533, 'chr3': 112617285,\n 'chr4A': 20704505, 'chr4': 69780378, 'chr5': 62374962, 'chr6': 36305782,\n 'chr7': 39844632, 'chr8': 27993427, 'chr9': 27241186, 'chrLG2': 109741,\n 'chrLG5': 16416, 'chrLGE22': 883365, 'chrZ': 72861351}\n\nrepeats = {}\nf = open(repeat, 'r')\nfor l in f:\n\tif re.search('^\\s+\\d+', l):\n\t\td = re.split('\\s+', l.rstrip())\n\t\tif d[5] in chrs:\n\t\t\tif d[5] not in repeats:\n\t\t\t\trepeats[d[5]] = {}\n\t\t\tstart = int(d[6])\n\t\t\tend = int(d[7]) + 1\n\n\t\t\tfor pos in range(start, end):\n\t\t\t\trepeats[d[5]][str(pos)] = 1\nf.close()\n\nfor chr in chrs:\n\tvcffile = vcf % chr\n\tout = vcffile.replace('coverage.filtered', 'coverage.filtered.repeatmasked')\n\t\n\tf = gzip.open(vcffile, 'r')\n\to = gzip.open(out, 'w')\n\t\n\tfor l in f:\n\t\tl = l.rstrip()\n\t\tif re.search('^#', l):\n\t\t\to.write(l + '\\n')\n\t\telse:\n\t\t\tif re.search('PASS', l):\n\t\t\t\td = re.split('\\t', l)\n\t\t\t\tif d[0] in repeats:\n\t\t\t\t\tif d[1] not in repeats[d[0]]:\n\t\t\t\t\t\to.write(l + '\\n')\n\t\t\t\telse:\n\t\t\t\t\to.write(l + '\\n')\n\tf.close()\n\to.close()\n", "import re\nimport os\nimport subprocess\nimport gzip\nrepeat = (\n '/mnt/gluster/home/sonal.singhal1/reference/taeGut1.repeatMaskerBlast.repeatLibrary20140131.out'\n )\nvcf = (\n '/mnt/gluster/home/sonal.singhal1/ZF/after_vqsr/by_chr/gatk.ug.all_zf.%s.coverage.filtered.vqsr.vcf.gz'\n )\nchrs = {'chr10': 20806668, 'chr11': 21403021, 'chr12': 21576510, 'chr13': \n 16962381, 'chr14': 16419078, 'chr15': 14428146, 'chr16': 9909, 'chr17':\n 11648728, 'chr18': 11201131, 'chr19': 11587733, 'chr1A': 73657157,\n 'chr1B': 1083483, 'chr1': 118548696, 'chr20': 15652063, 'chr21': \n 5979137, 'chr22': 3370227, 'chr23': 6196912, 'chr24': 8021379, 'chr25':\n 1275379, 'chr26': 4907541, 'chr27': 4618897, 'chr28': 4963201, 'chr2': \n 156412533, 'chr3': 112617285, 'chr4A': 20704505, 'chr4': 69780378,\n 'chr5': 62374962, 'chr6': 36305782, 'chr7': 39844632, 'chr8': 27993427,\n 'chr9': 27241186, 'chrLG2': 109741, 'chrLG5': 16416, 'chrLGE22': 883365,\n 'chrZ': 72861351}\nrepeats = {}\nf = open(repeat, 'r')\nfor l in f:\n if re.search('^\\\\s+\\\\d+', l):\n d = re.split('\\\\s+', l.rstrip())\n if d[5] in chrs:\n if d[5] not in repeats:\n repeats[d[5]] = {}\n start = int(d[6])\n end = int(d[7]) + 1\n for pos in range(start, end):\n repeats[d[5]][str(pos)] = 1\nf.close()\nfor chr in chrs:\n vcffile = vcf % chr\n out = vcffile.replace('coverage.filtered', 'coverage.filtered.repeatmasked'\n )\n f = gzip.open(vcffile, 'r')\n o = gzip.open(out, 'w')\n for l in f:\n l = l.rstrip()\n if re.search('^#', l):\n o.write(l + '\\n')\n elif re.search('PASS', l):\n d = re.split('\\t', l)\n if d[0] in repeats:\n if d[1] not in repeats[d[0]]:\n o.write(l + '\\n')\n else:\n o.write(l + '\\n')\n f.close()\n o.close()\n", "<import token>\nrepeat = (\n '/mnt/gluster/home/sonal.singhal1/reference/taeGut1.repeatMaskerBlast.repeatLibrary20140131.out'\n )\nvcf = (\n '/mnt/gluster/home/sonal.singhal1/ZF/after_vqsr/by_chr/gatk.ug.all_zf.%s.coverage.filtered.vqsr.vcf.gz'\n )\nchrs = {'chr10': 20806668, 'chr11': 21403021, 'chr12': 21576510, 'chr13': \n 16962381, 'chr14': 16419078, 'chr15': 14428146, 'chr16': 9909, 'chr17':\n 11648728, 'chr18': 11201131, 'chr19': 11587733, 'chr1A': 73657157,\n 'chr1B': 1083483, 'chr1': 118548696, 'chr20': 15652063, 'chr21': \n 5979137, 'chr22': 3370227, 'chr23': 6196912, 'chr24': 8021379, 'chr25':\n 1275379, 'chr26': 4907541, 'chr27': 4618897, 'chr28': 4963201, 'chr2': \n 156412533, 'chr3': 112617285, 'chr4A': 20704505, 'chr4': 69780378,\n 'chr5': 62374962, 'chr6': 36305782, 'chr7': 39844632, 'chr8': 27993427,\n 'chr9': 27241186, 'chrLG2': 109741, 'chrLG5': 16416, 'chrLGE22': 883365,\n 'chrZ': 72861351}\nrepeats = {}\nf = open(repeat, 'r')\nfor l in f:\n if re.search('^\\\\s+\\\\d+', l):\n d = re.split('\\\\s+', l.rstrip())\n if d[5] in chrs:\n if d[5] not in repeats:\n repeats[d[5]] = {}\n start = int(d[6])\n end = int(d[7]) + 1\n for pos in range(start, end):\n repeats[d[5]][str(pos)] = 1\nf.close()\nfor chr in chrs:\n vcffile = vcf % chr\n out = vcffile.replace('coverage.filtered', 'coverage.filtered.repeatmasked'\n )\n f = gzip.open(vcffile, 'r')\n o = gzip.open(out, 'w')\n for l in f:\n l = l.rstrip()\n if re.search('^#', l):\n o.write(l + '\\n')\n elif re.search('PASS', l):\n d = re.split('\\t', l)\n if d[0] in repeats:\n if d[1] not in repeats[d[0]]:\n o.write(l + '\\n')\n else:\n o.write(l + '\\n')\n f.close()\n o.close()\n", "<import token>\n<assignment token>\nfor l in f:\n if re.search('^\\\\s+\\\\d+', l):\n d = re.split('\\\\s+', l.rstrip())\n if d[5] in chrs:\n if d[5] not in repeats:\n repeats[d[5]] = {}\n start = int(d[6])\n end = int(d[7]) + 1\n for pos in range(start, end):\n repeats[d[5]][str(pos)] = 1\nf.close()\nfor chr in chrs:\n vcffile = vcf % chr\n out = vcffile.replace('coverage.filtered', 'coverage.filtered.repeatmasked'\n )\n f = gzip.open(vcffile, 'r')\n o = gzip.open(out, 'w')\n for l in f:\n l = l.rstrip()\n if re.search('^#', l):\n o.write(l + '\\n')\n elif re.search('PASS', l):\n d = re.split('\\t', l)\n if d[0] in repeats:\n if d[1] not in repeats[d[0]]:\n o.write(l + '\\n')\n else:\n o.write(l + '\\n')\n f.close()\n o.close()\n", "<import token>\n<assignment token>\n<code token>\n" ]
false
98,729
27bc4e498763b1d26daea3a86fdac8a96c544f61
if __name__ == "__main__": t = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) #s = "cats" #print("".join(tuple(list(s)))) t2 = ("cats",) print(t2[0])
[ "if __name__ == \"__main__\":\n t = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)\n #s = \"cats\"\n #print(\"\".join(tuple(list(s))))\n t2 = (\"cats\",)\n print(t2[0])\n", "if __name__ == '__main__':\n t = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9\n t2 = 'cats',\n print(t2[0])\n", "<code token>\n" ]
false
98,730
00c2018e1b9e2604fed4f87867414681e8eb4e12
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import SubsetRandomSampler, DataLoader from torch.autograd import Variable import argparse from tqdm import trange, tqdm import os import wandb import numpy as np from data.dataset import Concrete from model import feedforward, MyEnsemble, cnn, feedforward_50, RMSELoss from cross_val import cross_val # *Argument parser parser = argparse.ArgumentParser( description='Conditional Text Generation: Train Discriminator' ) parser.add_argument('--maxepoch', default=1000, help='maximum iteration (default=1000)') parser.add_argument('--agr_maxepoch', default=1000, help='maximum aggregate iteration (default=1000)') parser.add_argument('--lr', default=0.1, help='learing rate (default=0.1)') parser.add_argument('--batch', default=32, help='minibatch size (default=32)') parser.add_argument('--b', default=2, help='number of bag (default=2)') parser.add_argument('--seed', default=2, help='number of bag (default=2)') parser.add_argument('--bsize', default=100, help='number of bag size sample (default=100)') parser.add_argument('--local', default=False, action='store_true') parser.add_argument('--wandb', default=False, action='store_true') parser.add_argument('--trainable_bag', default=False, action='store_true') parser.add_argument('--b_max', default=2) parser.add_argument('--k', default=10) parser.add_argument('--model', default='feedforward') parser.add_argument('--quiet', default=False, action='store_true') args = parser.parse_args() cloud_dir = '/content/gdrive/My Drive/' saved_model_path = f'trained' if not args.local: saved_model_path = cloud_dir + saved_model_path if not os.path.exists(saved_model_path): os.makedirs(saved_model_path) b = int(args.b) b_max = int(args.b_max) random_seed = int(args.seed) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') np.random.seed(random_seed) torch.manual_seed(random_seed) random_seed = np.random.randint(100, size=b_max) # Creating dataset batch_size = int(args.batch) val_batch_size = int(args.batch) validation_split = .8 dataset_folder = 'data/' # data = Concrete(dataset_folder+'concrete.csv', args.model) data = Concrete(dataset_folder+'concrete_no_day1.csv', args.model) # Creating dataset split data_size = len(data) indices = list(range(data_size)) split = int(np.floor(validation_split * data_size)) np.random.shuffle(indices) if args.wandb: wandb.init(project="concrete-mix-design", name=f'bootstrap', notes=f'{b}') # Creating PT data samplers and loaders: train_indices, test_indices = indices[:split], indices[split:] np.random.seed(random_seed[int(args.b)]) data.X_mean = data.X[train_indices[:]].mean(dim=0) data.X_std = data.X[train_indices[:]].std(dim=0) data.y_mean = data.y[train_indices[:]].mean(dim=0) data.y_std = data.y[train_indices[:]].std(dim=0) train_indices = np.random.choice(train_indices, size=int(np.floor(len(train_indices) * .7))) # Hyperparameter learning_rate = float(args.lr) max_epoch = int(args.maxepoch) momentum=0.1 k = int(args.k) if args.model == 'feedforward': model = feedforward() elif args.model == 'feedforward_50': model = feedforward_50() else: model = cnn() model.to(device) optimizer = optim.Adadelta(model.parameters(), lr=learning_rate, rho=0.99, eps=1.0e-8) criterion = nn.MSELoss() best_params = cross_val(train_indices, optimizer, criterion, model, data, batch_size, k, max_epoch) model.load_state_dict(best_params) # if args.wandb: wandb.watch(model) # for epoch in trange(0, max_epoch, total=max_epoch, initial=0): # model.train() # for it, (X, y) in enumerate(train_loader): # model.zero_grad() # inputs = Variable(X, requires_grad=True).to(device) # output = model.forward(inputs) # target = Variable(y.unsqueeze(1)).to(device) # loss = criterion(output, target) # # l1_norm = 0. # # for p in model.parameters(): # # l1_norm += 1.0e-5*torch.norm(p, p=1) # # loss += l1_norm # loss.backward() # # nn.utils.clip_grad_value_(model.parameters(), 10) # if args.wandb: # wandb.log({"Train Loss": loss.data.cpu().item()}, step=epoch) # if it == 0 and not args.quiet: # tqdm.write(f'{float(output[0].cpu().data)} ==> {float(target[0].cpu().data)}') # optimizer.step() # optimizer.zero_grad() # model.eval() # val_loss = 0. # for it, (X, y) in enumerate(validation_loader): # model.zero_grad() # inputs = Variable(X, requires_grad=True).to(device) # output = model.forward(inputs) # target = Variable(y.unsqueeze(1)).to(device) # val_loss += F.mse_loss(output, target, reduction='sum').sum().data.cpu().item() # if args.wandb: wandb.log({"Validation Loss": val_loss/len(val_indices)}, step=epoch) if args.wandb: train_loss = np.loadtxt('train.csv') validation_loss = np.loadtxt('validation.csv') for i, (t, v) in enumerate(zip(train_loss, validation_loss)): wandb.log({"Train Loss": t}, step=i+1) wandb.log({"Validation Loss": v}, step=i+1) torch.save(model.state_dict(), f'{saved_model_path}/model-{b}.pth')
[ "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils.data import SubsetRandomSampler, DataLoader\nfrom torch.autograd import Variable\n\nimport argparse\nfrom tqdm import trange, tqdm\nimport os\nimport wandb\n\nimport numpy as np\n\nfrom data.dataset import Concrete\nfrom model import feedforward, MyEnsemble, cnn, feedforward_50, RMSELoss\n\nfrom cross_val import cross_val\n\n# *Argument parser\nparser = argparse.ArgumentParser(\n description='Conditional Text Generation: Train Discriminator'\n)\n\nparser.add_argument('--maxepoch', default=1000, help='maximum iteration (default=1000)')\nparser.add_argument('--agr_maxepoch', default=1000, help='maximum aggregate iteration (default=1000)')\nparser.add_argument('--lr', default=0.1, help='learing rate (default=0.1)')\nparser.add_argument('--batch', default=32, help='minibatch size (default=32)')\nparser.add_argument('--b', default=2, help='number of bag (default=2)')\nparser.add_argument('--seed', default=2, help='number of bag (default=2)')\nparser.add_argument('--bsize', default=100, help='number of bag size sample (default=100)')\nparser.add_argument('--local', default=False, action='store_true')\nparser.add_argument('--wandb', default=False, action='store_true')\nparser.add_argument('--trainable_bag', default=False, action='store_true')\nparser.add_argument('--b_max', default=2)\nparser.add_argument('--k', default=10)\nparser.add_argument('--model', default='feedforward')\nparser.add_argument('--quiet', default=False, action='store_true')\n\n\nargs = parser.parse_args()\ncloud_dir = '/content/gdrive/My Drive/'\nsaved_model_path = f'trained'\nif not args.local: saved_model_path = cloud_dir + saved_model_path\nif not os.path.exists(saved_model_path): os.makedirs(saved_model_path)\nb = int(args.b)\nb_max = int(args.b_max)\nrandom_seed = int(args.seed)\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nnp.random.seed(random_seed)\ntorch.manual_seed(random_seed)\n\nrandom_seed = np.random.randint(100, size=b_max)\n\n# Creating dataset\nbatch_size = int(args.batch)\nval_batch_size = int(args.batch)\nvalidation_split = .8\ndataset_folder = 'data/'\n# data = Concrete(dataset_folder+'concrete.csv', args.model)\ndata = Concrete(dataset_folder+'concrete_no_day1.csv', args.model)\n\n# Creating dataset split\ndata_size = len(data)\nindices = list(range(data_size))\nsplit = int(np.floor(validation_split * data_size))\nnp.random.shuffle(indices)\n\nif args.wandb: wandb.init(project=\"concrete-mix-design\", name=f'bootstrap', notes=f'{b}')\n\n# Creating PT data samplers and loaders:\ntrain_indices, test_indices = indices[:split], indices[split:]\nnp.random.seed(random_seed[int(args.b)])\n\ndata.X_mean = data.X[train_indices[:]].mean(dim=0)\ndata.X_std = data.X[train_indices[:]].std(dim=0)\n\ndata.y_mean = data.y[train_indices[:]].mean(dim=0)\ndata.y_std = data.y[train_indices[:]].std(dim=0)\n\ntrain_indices = np.random.choice(train_indices, size=int(np.floor(len(train_indices) * .7)))\n\n# Hyperparameter\nlearning_rate = float(args.lr)\nmax_epoch = int(args.maxepoch)\nmomentum=0.1\nk = int(args.k)\n\nif args.model == 'feedforward':\n model = feedforward()\nelif args.model == 'feedforward_50':\n model = feedforward_50()\nelse:\n model = cnn()\nmodel.to(device)\n\noptimizer = optim.Adadelta(model.parameters(), lr=learning_rate, rho=0.99, eps=1.0e-8)\ncriterion = nn.MSELoss()\n\nbest_params = cross_val(train_indices, optimizer, criterion, model, data, batch_size, k, max_epoch)\nmodel.load_state_dict(best_params)\n# if args.wandb: wandb.watch(model)\n\n# for epoch in trange(0, max_epoch, total=max_epoch, initial=0):\n# model.train()\n# for it, (X, y) in enumerate(train_loader):\n# model.zero_grad()\n# inputs = Variable(X, requires_grad=True).to(device)\n# output = model.forward(inputs)\n# target = Variable(y.unsqueeze(1)).to(device)\n# loss = criterion(output, target)\n# # l1_norm = 0.\n# # for p in model.parameters():\n# # l1_norm += 1.0e-5*torch.norm(p, p=1)\n# # loss += l1_norm\n# loss.backward()\n# # nn.utils.clip_grad_value_(model.parameters(), 10)\n# if args.wandb:\n# wandb.log({\"Train Loss\": loss.data.cpu().item()}, step=epoch)\n# if it == 0 and not args.quiet:\n# tqdm.write(f'{float(output[0].cpu().data)} ==> {float(target[0].cpu().data)}')\n\n# optimizer.step()\n# optimizer.zero_grad()\n\n# model.eval()\n# val_loss = 0.\n# for it, (X, y) in enumerate(validation_loader):\n# model.zero_grad()\n# inputs = Variable(X, requires_grad=True).to(device)\n# output = model.forward(inputs)\n# target = Variable(y.unsqueeze(1)).to(device)\n# val_loss += F.mse_loss(output, target, reduction='sum').sum().data.cpu().item()\n# if args.wandb: wandb.log({\"Validation Loss\": val_loss/len(val_indices)}, step=epoch)\nif args.wandb:\n train_loss = np.loadtxt('train.csv')\n validation_loss = np.loadtxt('validation.csv')\n for i, (t, v) in enumerate(zip(train_loss, validation_loss)):\n wandb.log({\"Train Loss\": t}, step=i+1)\n wandb.log({\"Validation Loss\": v}, step=i+1)\n \ntorch.save(model.state_dict(), f'{saved_model_path}/model-{b}.pth')\n\n", "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils.data import SubsetRandomSampler, DataLoader\nfrom torch.autograd import Variable\nimport argparse\nfrom tqdm import trange, tqdm\nimport os\nimport wandb\nimport numpy as np\nfrom data.dataset import Concrete\nfrom model import feedforward, MyEnsemble, cnn, feedforward_50, RMSELoss\nfrom cross_val import cross_val\nparser = argparse.ArgumentParser(description=\n 'Conditional Text Generation: Train Discriminator')\nparser.add_argument('--maxepoch', default=1000, help=\n 'maximum iteration (default=1000)')\nparser.add_argument('--agr_maxepoch', default=1000, help=\n 'maximum aggregate iteration (default=1000)')\nparser.add_argument('--lr', default=0.1, help='learing rate (default=0.1)')\nparser.add_argument('--batch', default=32, help='minibatch size (default=32)')\nparser.add_argument('--b', default=2, help='number of bag (default=2)')\nparser.add_argument('--seed', default=2, help='number of bag (default=2)')\nparser.add_argument('--bsize', default=100, help=\n 'number of bag size sample (default=100)')\nparser.add_argument('--local', default=False, action='store_true')\nparser.add_argument('--wandb', default=False, action='store_true')\nparser.add_argument('--trainable_bag', default=False, action='store_true')\nparser.add_argument('--b_max', default=2)\nparser.add_argument('--k', default=10)\nparser.add_argument('--model', default='feedforward')\nparser.add_argument('--quiet', default=False, action='store_true')\nargs = parser.parse_args()\ncloud_dir = '/content/gdrive/My Drive/'\nsaved_model_path = f'trained'\nif not args.local:\n saved_model_path = cloud_dir + saved_model_path\nif not os.path.exists(saved_model_path):\n os.makedirs(saved_model_path)\nb = int(args.b)\nb_max = int(args.b_max)\nrandom_seed = int(args.seed)\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nnp.random.seed(random_seed)\ntorch.manual_seed(random_seed)\nrandom_seed = np.random.randint(100, size=b_max)\nbatch_size = int(args.batch)\nval_batch_size = int(args.batch)\nvalidation_split = 0.8\ndataset_folder = 'data/'\ndata = Concrete(dataset_folder + 'concrete_no_day1.csv', args.model)\ndata_size = len(data)\nindices = list(range(data_size))\nsplit = int(np.floor(validation_split * data_size))\nnp.random.shuffle(indices)\nif args.wandb:\n wandb.init(project='concrete-mix-design', name=f'bootstrap', notes=f'{b}')\ntrain_indices, test_indices = indices[:split], indices[split:]\nnp.random.seed(random_seed[int(args.b)])\ndata.X_mean = data.X[train_indices[:]].mean(dim=0)\ndata.X_std = data.X[train_indices[:]].std(dim=0)\ndata.y_mean = data.y[train_indices[:]].mean(dim=0)\ndata.y_std = data.y[train_indices[:]].std(dim=0)\ntrain_indices = np.random.choice(train_indices, size=int(np.floor(len(\n train_indices) * 0.7)))\nlearning_rate = float(args.lr)\nmax_epoch = int(args.maxepoch)\nmomentum = 0.1\nk = int(args.k)\nif args.model == 'feedforward':\n model = feedforward()\nelif args.model == 'feedforward_50':\n model = feedforward_50()\nelse:\n model = cnn()\nmodel.to(device)\noptimizer = optim.Adadelta(model.parameters(), lr=learning_rate, rho=0.99,\n eps=1e-08)\ncriterion = nn.MSELoss()\nbest_params = cross_val(train_indices, optimizer, criterion, model, data,\n batch_size, k, max_epoch)\nmodel.load_state_dict(best_params)\nif args.wandb:\n train_loss = np.loadtxt('train.csv')\n validation_loss = np.loadtxt('validation.csv')\n for i, (t, v) in enumerate(zip(train_loss, validation_loss)):\n wandb.log({'Train Loss': t}, step=i + 1)\n wandb.log({'Validation Loss': v}, step=i + 1)\ntorch.save(model.state_dict(), f'{saved_model_path}/model-{b}.pth')\n", "<import token>\nparser = argparse.ArgumentParser(description=\n 'Conditional Text Generation: Train Discriminator')\nparser.add_argument('--maxepoch', default=1000, help=\n 'maximum iteration (default=1000)')\nparser.add_argument('--agr_maxepoch', default=1000, help=\n 'maximum aggregate iteration (default=1000)')\nparser.add_argument('--lr', default=0.1, help='learing rate (default=0.1)')\nparser.add_argument('--batch', default=32, help='minibatch size (default=32)')\nparser.add_argument('--b', default=2, help='number of bag (default=2)')\nparser.add_argument('--seed', default=2, help='number of bag (default=2)')\nparser.add_argument('--bsize', default=100, help=\n 'number of bag size sample (default=100)')\nparser.add_argument('--local', default=False, action='store_true')\nparser.add_argument('--wandb', default=False, action='store_true')\nparser.add_argument('--trainable_bag', default=False, action='store_true')\nparser.add_argument('--b_max', default=2)\nparser.add_argument('--k', default=10)\nparser.add_argument('--model', default='feedforward')\nparser.add_argument('--quiet', default=False, action='store_true')\nargs = parser.parse_args()\ncloud_dir = '/content/gdrive/My Drive/'\nsaved_model_path = f'trained'\nif not args.local:\n saved_model_path = cloud_dir + saved_model_path\nif not os.path.exists(saved_model_path):\n os.makedirs(saved_model_path)\nb = int(args.b)\nb_max = int(args.b_max)\nrandom_seed = int(args.seed)\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nnp.random.seed(random_seed)\ntorch.manual_seed(random_seed)\nrandom_seed = np.random.randint(100, size=b_max)\nbatch_size = int(args.batch)\nval_batch_size = int(args.batch)\nvalidation_split = 0.8\ndataset_folder = 'data/'\ndata = Concrete(dataset_folder + 'concrete_no_day1.csv', args.model)\ndata_size = len(data)\nindices = list(range(data_size))\nsplit = int(np.floor(validation_split * data_size))\nnp.random.shuffle(indices)\nif args.wandb:\n wandb.init(project='concrete-mix-design', name=f'bootstrap', notes=f'{b}')\ntrain_indices, test_indices = indices[:split], indices[split:]\nnp.random.seed(random_seed[int(args.b)])\ndata.X_mean = data.X[train_indices[:]].mean(dim=0)\ndata.X_std = data.X[train_indices[:]].std(dim=0)\ndata.y_mean = data.y[train_indices[:]].mean(dim=0)\ndata.y_std = data.y[train_indices[:]].std(dim=0)\ntrain_indices = np.random.choice(train_indices, size=int(np.floor(len(\n train_indices) * 0.7)))\nlearning_rate = float(args.lr)\nmax_epoch = int(args.maxepoch)\nmomentum = 0.1\nk = int(args.k)\nif args.model == 'feedforward':\n model = feedforward()\nelif args.model == 'feedforward_50':\n model = feedforward_50()\nelse:\n model = cnn()\nmodel.to(device)\noptimizer = optim.Adadelta(model.parameters(), lr=learning_rate, rho=0.99,\n eps=1e-08)\ncriterion = nn.MSELoss()\nbest_params = cross_val(train_indices, optimizer, criterion, model, data,\n batch_size, k, max_epoch)\nmodel.load_state_dict(best_params)\nif args.wandb:\n train_loss = np.loadtxt('train.csv')\n validation_loss = np.loadtxt('validation.csv')\n for i, (t, v) in enumerate(zip(train_loss, validation_loss)):\n wandb.log({'Train Loss': t}, step=i + 1)\n wandb.log({'Validation Loss': v}, step=i + 1)\ntorch.save(model.state_dict(), f'{saved_model_path}/model-{b}.pth')\n", "<import token>\n<assignment token>\nparser.add_argument('--maxepoch', default=1000, help=\n 'maximum iteration (default=1000)')\nparser.add_argument('--agr_maxepoch', default=1000, help=\n 'maximum aggregate iteration (default=1000)')\nparser.add_argument('--lr', default=0.1, help='learing rate (default=0.1)')\nparser.add_argument('--batch', default=32, help='minibatch size (default=32)')\nparser.add_argument('--b', default=2, help='number of bag (default=2)')\nparser.add_argument('--seed', default=2, help='number of bag (default=2)')\nparser.add_argument('--bsize', default=100, help=\n 'number of bag size sample (default=100)')\nparser.add_argument('--local', default=False, action='store_true')\nparser.add_argument('--wandb', default=False, action='store_true')\nparser.add_argument('--trainable_bag', default=False, action='store_true')\nparser.add_argument('--b_max', default=2)\nparser.add_argument('--k', default=10)\nparser.add_argument('--model', default='feedforward')\nparser.add_argument('--quiet', default=False, action='store_true')\n<assignment token>\nif not args.local:\n saved_model_path = cloud_dir + saved_model_path\nif not os.path.exists(saved_model_path):\n os.makedirs(saved_model_path)\n<assignment token>\nnp.random.seed(random_seed)\ntorch.manual_seed(random_seed)\n<assignment token>\nnp.random.shuffle(indices)\nif args.wandb:\n wandb.init(project='concrete-mix-design', name=f'bootstrap', notes=f'{b}')\n<assignment token>\nnp.random.seed(random_seed[int(args.b)])\n<assignment token>\nif args.model == 'feedforward':\n model = feedforward()\nelif args.model == 'feedforward_50':\n model = feedforward_50()\nelse:\n model = cnn()\nmodel.to(device)\n<assignment token>\nmodel.load_state_dict(best_params)\nif args.wandb:\n train_loss = np.loadtxt('train.csv')\n validation_loss = np.loadtxt('validation.csv')\n for i, (t, v) in enumerate(zip(train_loss, validation_loss)):\n wandb.log({'Train Loss': t}, step=i + 1)\n wandb.log({'Validation Loss': v}, step=i + 1)\ntorch.save(model.state_dict(), f'{saved_model_path}/model-{b}.pth')\n", "<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
98,731
3a4ed23272729614c36735048c8940e8d910217f
# coding=utf-8 # Copyright (C) 2020 NumS Development Team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import boto3 import numpy as np from moto import mock_s3 from nums.core.array.application import ArrayApplication from nums.core.array.blockarray import BlockArray from nums.core.grid.grid import ArrayGrid from nums.core.storage.storage import StoredArrayS3 # pylint: disable = import-outside-toplevel, import-error @mock_s3 def test_rwd(app_inst_s3: ArrayApplication): conn = boto3.resource("s3", region_name="us-east-1") assert conn.Bucket("darrays") not in conn.buckets.all() conn.create_bucket(Bucket="darrays") array: np.ndarray = np.random.random(35).reshape(7, 5) ba: BlockArray = app_inst_s3.array(array, block_shape=(3, 4)) filename = "darrays/read_write_delete_array_test" write_result: BlockArray = app_inst_s3.write_s3(ba, filename) write_result_arr = app_inst_s3.get(write_result) for grid_entry in write_result.grid.get_entry_iterator(): assert "ETag" in write_result_arr[grid_entry] ba_read: BlockArray = app_inst_s3.read_s3(filename) assert app_inst_s3.get(app_inst_s3.allclose(ba, ba_read)) delete_result: BlockArray = app_inst_s3.delete_s3(filename) delete_result_arr = app_inst_s3.get(delete_result) for grid_entry in delete_result.grid.get_entry_iterator(): deleted_key = delete_result_arr[grid_entry]["Deleted"][0]["Key"] assert deleted_key == StoredArrayS3(filename, delete_result.grid).get_key( grid_entry ) @mock_s3 def test_array_rwd(): conn = boto3.resource("s3", region_name="us-east-1") assert conn.Bucket("darrays") not in conn.buckets.all() conn.create_bucket(Bucket="darrays") X: np.ndarray = np.random.random(3) stored_X = StoredArrayS3("darrays/%s_X" % "__test__") stored_X.put_grid( ArrayGrid(shape=X.shape, block_shape=X.shape, dtype=np.float64.__name__) ) stored_X.init_grid() stored_X.put_array(X) assert np.allclose(X, stored_X.get_array()) stored_X.del_array() stored_X.delete_grid() def test_grid_copy(): grid = ArrayGrid(shape=(1, 2), block_shape=(1, 2), dtype=np.float64.__name__) assert grid.copy() is not grid if __name__ == "__main__": # pylint: disable=import-error, no-member from tests import conftest app_inst = conftest.get_app("serial") test_rwd(app_inst) test_array_rwd() test_grid_copy()
[ "# coding=utf-8\n# Copyright (C) 2020 NumS Development Team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport boto3\nimport numpy as np\nfrom moto import mock_s3\n\nfrom nums.core.array.application import ArrayApplication\nfrom nums.core.array.blockarray import BlockArray\nfrom nums.core.grid.grid import ArrayGrid\nfrom nums.core.storage.storage import StoredArrayS3\n\n\n# pylint: disable = import-outside-toplevel, import-error\n\n\n@mock_s3\ndef test_rwd(app_inst_s3: ArrayApplication):\n\n conn = boto3.resource(\"s3\", region_name=\"us-east-1\")\n assert conn.Bucket(\"darrays\") not in conn.buckets.all()\n conn.create_bucket(Bucket=\"darrays\")\n\n array: np.ndarray = np.random.random(35).reshape(7, 5)\n ba: BlockArray = app_inst_s3.array(array, block_shape=(3, 4))\n filename = \"darrays/read_write_delete_array_test\"\n write_result: BlockArray = app_inst_s3.write_s3(ba, filename)\n write_result_arr = app_inst_s3.get(write_result)\n for grid_entry in write_result.grid.get_entry_iterator():\n assert \"ETag\" in write_result_arr[grid_entry]\n ba_read: BlockArray = app_inst_s3.read_s3(filename)\n assert app_inst_s3.get(app_inst_s3.allclose(ba, ba_read))\n delete_result: BlockArray = app_inst_s3.delete_s3(filename)\n delete_result_arr = app_inst_s3.get(delete_result)\n for grid_entry in delete_result.grid.get_entry_iterator():\n deleted_key = delete_result_arr[grid_entry][\"Deleted\"][0][\"Key\"]\n assert deleted_key == StoredArrayS3(filename, delete_result.grid).get_key(\n grid_entry\n )\n\n\n@mock_s3\ndef test_array_rwd():\n conn = boto3.resource(\"s3\", region_name=\"us-east-1\")\n assert conn.Bucket(\"darrays\") not in conn.buckets.all()\n conn.create_bucket(Bucket=\"darrays\")\n\n X: np.ndarray = np.random.random(3)\n stored_X = StoredArrayS3(\"darrays/%s_X\" % \"__test__\")\n stored_X.put_grid(\n ArrayGrid(shape=X.shape, block_shape=X.shape, dtype=np.float64.__name__)\n )\n stored_X.init_grid()\n stored_X.put_array(X)\n assert np.allclose(X, stored_X.get_array())\n stored_X.del_array()\n stored_X.delete_grid()\n\n\ndef test_grid_copy():\n grid = ArrayGrid(shape=(1, 2), block_shape=(1, 2), dtype=np.float64.__name__)\n assert grid.copy() is not grid\n\n\nif __name__ == \"__main__\":\n # pylint: disable=import-error, no-member\n from tests import conftest\n\n app_inst = conftest.get_app(\"serial\")\n\n test_rwd(app_inst)\n test_array_rwd()\n test_grid_copy()\n", "import boto3\nimport numpy as np\nfrom moto import mock_s3\nfrom nums.core.array.application import ArrayApplication\nfrom nums.core.array.blockarray import BlockArray\nfrom nums.core.grid.grid import ArrayGrid\nfrom nums.core.storage.storage import StoredArrayS3\n\n\n@mock_s3\ndef test_rwd(app_inst_s3: ArrayApplication):\n conn = boto3.resource('s3', region_name='us-east-1')\n assert conn.Bucket('darrays') not in conn.buckets.all()\n conn.create_bucket(Bucket='darrays')\n array: np.ndarray = np.random.random(35).reshape(7, 5)\n ba: BlockArray = app_inst_s3.array(array, block_shape=(3, 4))\n filename = 'darrays/read_write_delete_array_test'\n write_result: BlockArray = app_inst_s3.write_s3(ba, filename)\n write_result_arr = app_inst_s3.get(write_result)\n for grid_entry in write_result.grid.get_entry_iterator():\n assert 'ETag' in write_result_arr[grid_entry]\n ba_read: BlockArray = app_inst_s3.read_s3(filename)\n assert app_inst_s3.get(app_inst_s3.allclose(ba, ba_read))\n delete_result: BlockArray = app_inst_s3.delete_s3(filename)\n delete_result_arr = app_inst_s3.get(delete_result)\n for grid_entry in delete_result.grid.get_entry_iterator():\n deleted_key = delete_result_arr[grid_entry]['Deleted'][0]['Key']\n assert deleted_key == StoredArrayS3(filename, delete_result.grid\n ).get_key(grid_entry)\n\n\n@mock_s3\ndef test_array_rwd():\n conn = boto3.resource('s3', region_name='us-east-1')\n assert conn.Bucket('darrays') not in conn.buckets.all()\n conn.create_bucket(Bucket='darrays')\n X: np.ndarray = np.random.random(3)\n stored_X = StoredArrayS3('darrays/%s_X' % '__test__')\n stored_X.put_grid(ArrayGrid(shape=X.shape, block_shape=X.shape, dtype=\n np.float64.__name__))\n stored_X.init_grid()\n stored_X.put_array(X)\n assert np.allclose(X, stored_X.get_array())\n stored_X.del_array()\n stored_X.delete_grid()\n\n\ndef test_grid_copy():\n grid = ArrayGrid(shape=(1, 2), block_shape=(1, 2), dtype=np.float64.\n __name__)\n assert grid.copy() is not grid\n\n\nif __name__ == '__main__':\n from tests import conftest\n app_inst = conftest.get_app('serial')\n test_rwd(app_inst)\n test_array_rwd()\n test_grid_copy()\n", "<import token>\n\n\n@mock_s3\ndef test_rwd(app_inst_s3: ArrayApplication):\n conn = boto3.resource('s3', region_name='us-east-1')\n assert conn.Bucket('darrays') not in conn.buckets.all()\n conn.create_bucket(Bucket='darrays')\n array: np.ndarray = np.random.random(35).reshape(7, 5)\n ba: BlockArray = app_inst_s3.array(array, block_shape=(3, 4))\n filename = 'darrays/read_write_delete_array_test'\n write_result: BlockArray = app_inst_s3.write_s3(ba, filename)\n write_result_arr = app_inst_s3.get(write_result)\n for grid_entry in write_result.grid.get_entry_iterator():\n assert 'ETag' in write_result_arr[grid_entry]\n ba_read: BlockArray = app_inst_s3.read_s3(filename)\n assert app_inst_s3.get(app_inst_s3.allclose(ba, ba_read))\n delete_result: BlockArray = app_inst_s3.delete_s3(filename)\n delete_result_arr = app_inst_s3.get(delete_result)\n for grid_entry in delete_result.grid.get_entry_iterator():\n deleted_key = delete_result_arr[grid_entry]['Deleted'][0]['Key']\n assert deleted_key == StoredArrayS3(filename, delete_result.grid\n ).get_key(grid_entry)\n\n\n@mock_s3\ndef test_array_rwd():\n conn = boto3.resource('s3', region_name='us-east-1')\n assert conn.Bucket('darrays') not in conn.buckets.all()\n conn.create_bucket(Bucket='darrays')\n X: np.ndarray = np.random.random(3)\n stored_X = StoredArrayS3('darrays/%s_X' % '__test__')\n stored_X.put_grid(ArrayGrid(shape=X.shape, block_shape=X.shape, dtype=\n np.float64.__name__))\n stored_X.init_grid()\n stored_X.put_array(X)\n assert np.allclose(X, stored_X.get_array())\n stored_X.del_array()\n stored_X.delete_grid()\n\n\ndef test_grid_copy():\n grid = ArrayGrid(shape=(1, 2), block_shape=(1, 2), dtype=np.float64.\n __name__)\n assert grid.copy() is not grid\n\n\nif __name__ == '__main__':\n from tests import conftest\n app_inst = conftest.get_app('serial')\n test_rwd(app_inst)\n test_array_rwd()\n test_grid_copy()\n", "<import token>\n\n\n@mock_s3\ndef test_rwd(app_inst_s3: ArrayApplication):\n conn = boto3.resource('s3', region_name='us-east-1')\n assert conn.Bucket('darrays') not in conn.buckets.all()\n conn.create_bucket(Bucket='darrays')\n array: np.ndarray = np.random.random(35).reshape(7, 5)\n ba: BlockArray = app_inst_s3.array(array, block_shape=(3, 4))\n filename = 'darrays/read_write_delete_array_test'\n write_result: BlockArray = app_inst_s3.write_s3(ba, filename)\n write_result_arr = app_inst_s3.get(write_result)\n for grid_entry in write_result.grid.get_entry_iterator():\n assert 'ETag' in write_result_arr[grid_entry]\n ba_read: BlockArray = app_inst_s3.read_s3(filename)\n assert app_inst_s3.get(app_inst_s3.allclose(ba, ba_read))\n delete_result: BlockArray = app_inst_s3.delete_s3(filename)\n delete_result_arr = app_inst_s3.get(delete_result)\n for grid_entry in delete_result.grid.get_entry_iterator():\n deleted_key = delete_result_arr[grid_entry]['Deleted'][0]['Key']\n assert deleted_key == StoredArrayS3(filename, delete_result.grid\n ).get_key(grid_entry)\n\n\n@mock_s3\ndef test_array_rwd():\n conn = boto3.resource('s3', region_name='us-east-1')\n assert conn.Bucket('darrays') not in conn.buckets.all()\n conn.create_bucket(Bucket='darrays')\n X: np.ndarray = np.random.random(3)\n stored_X = StoredArrayS3('darrays/%s_X' % '__test__')\n stored_X.put_grid(ArrayGrid(shape=X.shape, block_shape=X.shape, dtype=\n np.float64.__name__))\n stored_X.init_grid()\n stored_X.put_array(X)\n assert np.allclose(X, stored_X.get_array())\n stored_X.del_array()\n stored_X.delete_grid()\n\n\ndef test_grid_copy():\n grid = ArrayGrid(shape=(1, 2), block_shape=(1, 2), dtype=np.float64.\n __name__)\n assert grid.copy() is not grid\n\n\n<code token>\n", "<import token>\n\n\n@mock_s3\ndef test_rwd(app_inst_s3: ArrayApplication):\n conn = boto3.resource('s3', region_name='us-east-1')\n assert conn.Bucket('darrays') not in conn.buckets.all()\n conn.create_bucket(Bucket='darrays')\n array: np.ndarray = np.random.random(35).reshape(7, 5)\n ba: BlockArray = app_inst_s3.array(array, block_shape=(3, 4))\n filename = 'darrays/read_write_delete_array_test'\n write_result: BlockArray = app_inst_s3.write_s3(ba, filename)\n write_result_arr = app_inst_s3.get(write_result)\n for grid_entry in write_result.grid.get_entry_iterator():\n assert 'ETag' in write_result_arr[grid_entry]\n ba_read: BlockArray = app_inst_s3.read_s3(filename)\n assert app_inst_s3.get(app_inst_s3.allclose(ba, ba_read))\n delete_result: BlockArray = app_inst_s3.delete_s3(filename)\n delete_result_arr = app_inst_s3.get(delete_result)\n for grid_entry in delete_result.grid.get_entry_iterator():\n deleted_key = delete_result_arr[grid_entry]['Deleted'][0]['Key']\n assert deleted_key == StoredArrayS3(filename, delete_result.grid\n ).get_key(grid_entry)\n\n\n@mock_s3\ndef test_array_rwd():\n conn = boto3.resource('s3', region_name='us-east-1')\n assert conn.Bucket('darrays') not in conn.buckets.all()\n conn.create_bucket(Bucket='darrays')\n X: np.ndarray = np.random.random(3)\n stored_X = StoredArrayS3('darrays/%s_X' % '__test__')\n stored_X.put_grid(ArrayGrid(shape=X.shape, block_shape=X.shape, dtype=\n np.float64.__name__))\n stored_X.init_grid()\n stored_X.put_array(X)\n assert np.allclose(X, stored_X.get_array())\n stored_X.del_array()\n stored_X.delete_grid()\n\n\n<function token>\n<code token>\n", "<import token>\n<function token>\n\n\n@mock_s3\ndef test_array_rwd():\n conn = boto3.resource('s3', region_name='us-east-1')\n assert conn.Bucket('darrays') not in conn.buckets.all()\n conn.create_bucket(Bucket='darrays')\n X: np.ndarray = np.random.random(3)\n stored_X = StoredArrayS3('darrays/%s_X' % '__test__')\n stored_X.put_grid(ArrayGrid(shape=X.shape, block_shape=X.shape, dtype=\n np.float64.__name__))\n stored_X.init_grid()\n stored_X.put_array(X)\n assert np.allclose(X, stored_X.get_array())\n stored_X.del_array()\n stored_X.delete_grid()\n\n\n<function token>\n<code token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<code token>\n" ]
false
98,732
82e62f7b6cd67bfbce0131d0f8f423440dcba941
""" Comparison of original xtcav calibration constants with the same constants saved and retrieved in CDB. """ import sys #from psana.pscalib.calib.XtcavConstants import Load, dict_from_xtcav_calib_object, compare_dicts from psana.pscalib.calib.XtcavUtils import Load, dict_from_xtcav_calib_object import psana.pscalib.calib.MDBUtils as dbu from psana.pscalib.calib.CalibUtils import parse_calib_file_name #history_dict_for_file, history_list_of_dicts from psana.pscalib.calib.MDBConvertLCLS1 import detname_conversion from psana.pscalib.calib.MDBConvertUtils import compare_dicts from psana.pscalib.calib.CalibConstants import HOST, PORT #------------------------------ def usage(fname) : msg = 'Usage: python lcls2/psana/psana/pscalib/examples/ex07-cdb-xtcav.py [<full-path-to-calib-file>]'\ '\n by default calib file is %s' % fname print(msg) #------------------------------ def test_xtcav_calib_constants(fname= '/reg/d/psdm/XPP/xpptut15/calib/Xtcav::CalibV1/XrayTransportDiagnostic.0:Opal1000.0/pedestals/101-102.data',\ add_constants_to_db=False) : _, exp, _, cvers, detname, ctype, cfname = fname.rsplit('/',6) resp = parse_calib_file_name(cfname) begin, end, ext = resp if resp is not None else (None, None, None) det = detname_conversion(detname) run = begin dbname_exp = dbu.db_prefixed_name(exp) dbname_det = dbu.db_prefixed_name(det) print('LCLS1 Xtcav calibration file: %s' % fname) print('Parameters form path: exp:%s det:%s ctype:%s run:%s dbname_exp:%s dbname_det:%s'%\ (exp, det, ctype, run, dbname_exp, dbname_det)) #Save(ct,fname) o1 = Load(fname) d1 = dict_from_xtcav_calib_object(o1) print('Xtcav calibration constants as dict:\n', d1) if not add_constants_to_db : return #================================== #---- Delete databases for experiment and detector client = dbu.connect_to_server(HOST, PORT) print('Open client on host:%s port:%s' % (HOST, PORT)) print('Delete database %s'% dbname_exp) dbu.delete_database(client, dbname_exp) print('Delete database %s'% dbname_det) dbu.delete_database(client, dbname_det) #---- Add data to experiment and detector dbs print('Add Xtcav constants') kwargs = {'host' : HOST,\ 'port' : PORT,\ 'version' : 'V01',\ 'comment' : 'test of add-retrieve xtcav constants' } #insert_calib_data(data, *kwargs) dbu.insert_constants(o1, exp, det, ctype, run, time_sec='1000000000', **kwargs) #msg = dbu.database_info(client, dbname_exp, level=10) #print(msg) print('Xtcav constants inserted, now retrieve them from db:%s collection:%s' % (dbname_exp, det)) db, fs = dbu.db_and_fs(client, dbname_exp) col = dbu.collection(db, det) #for doc in col.find() : # print(doc) doc = dbu.find_doc(col, query={'ctype':ctype, 'run':run}) print('Found doc:\n', doc) o2 = dbu.get_data_for_doc(fs, doc) d2 = dict_from_xtcav_calib_object(o2) print('Xtcav calib object converted to dict:\n', d2) #print('cmp(d1,d2) :', str(d1==d2)) print('\nCompare dictionaries for Xtcav calib objects loaded directly from calib file and passed through the CDB') compare_dicts(d1,d2) client.close() return #------------------------------ if __name__ == "__main__": path='/reg/d/psdm/XPP/xpptut15/calib/Xtcav::CalibV1/XrayTransportDiagnostic.0:Opal1000.0/pedestals/101-102.data' #path='/reg/d/psdm/XCS/xcsm9816/calib/Xtcav::CalibV1/XrayTransportDiagnostic.0:Opal1000.0/lasingoffreference/31-end.data' #path='/reg/d/psdm/XCS/xcsm9816/calib/Xtcav::CalibV1/XrayTransportDiagnostic.0:Opal1000.0/pedestals/30-end.data' fname = sys.argv[1] if len(sys.argv) > 1 else path add_consts_to_cdb = True if len(sys.argv) > 2 else False test_xtcav_calib_constants(fname, add_consts_to_cdb) usage(path) #------------------------------
[ "\"\"\"\nComparison of original xtcav calibration constants \nwith the same constants saved and retrieved in CDB.\n\"\"\"\nimport sys\n#from psana.pscalib.calib.XtcavConstants import Load, dict_from_xtcav_calib_object, compare_dicts\nfrom psana.pscalib.calib.XtcavUtils import Load, dict_from_xtcav_calib_object\nimport psana.pscalib.calib.MDBUtils as dbu\nfrom psana.pscalib.calib.CalibUtils import parse_calib_file_name #history_dict_for_file, history_list_of_dicts\nfrom psana.pscalib.calib.MDBConvertLCLS1 import detname_conversion\nfrom psana.pscalib.calib.MDBConvertUtils import compare_dicts\nfrom psana.pscalib.calib.CalibConstants import HOST, PORT\n\n#------------------------------\n\ndef usage(fname) :\n msg = 'Usage: python lcls2/psana/psana/pscalib/examples/ex07-cdb-xtcav.py [<full-path-to-calib-file>]'\\\n '\\n by default calib file is %s' % fname\n print(msg)\n\n#------------------------------\n\ndef test_xtcav_calib_constants(fname=\n '/reg/d/psdm/XPP/xpptut15/calib/Xtcav::CalibV1/XrayTransportDiagnostic.0:Opal1000.0/pedestals/101-102.data',\\\n add_constants_to_db=False) :\n\n _, exp, _, cvers, detname, ctype, cfname = fname.rsplit('/',6) \n resp = parse_calib_file_name(cfname)\n begin, end, ext = resp if resp is not None else (None, None, None)\n det = detname_conversion(detname)\n run = begin\n dbname_exp = dbu.db_prefixed_name(exp)\n dbname_det = dbu.db_prefixed_name(det)\n\n print('LCLS1 Xtcav calibration file: %s' % fname)\n print('Parameters form path: exp:%s det:%s ctype:%s run:%s dbname_exp:%s dbname_det:%s'%\\\n (exp, det, ctype, run, dbname_exp, dbname_det))\n\n #Save(ct,fname)\n o1 = Load(fname)\n d1 = dict_from_xtcav_calib_object(o1)\n print('Xtcav calibration constants as dict:\\n', d1)\n\n if not add_constants_to_db : return\n #==================================\n\n #---- Delete databases for experiment and detector\n\n client = dbu.connect_to_server(HOST, PORT)\n print('Open client on host:%s port:%s' % (HOST, PORT))\n\n print('Delete database %s'% dbname_exp)\n dbu.delete_database(client, dbname_exp)\n\n print('Delete database %s'% dbname_det)\n dbu.delete_database(client, dbname_det)\n\n #---- Add data to experiment and detector dbs\n print('Add Xtcav constants') \n\n kwargs = {'host' : HOST,\\\n 'port' : PORT,\\\n 'version' : 'V01',\\\n 'comment' : 'test of add-retrieve xtcav constants'\n }\n #insert_calib_data(data, *kwargs)\n dbu.insert_constants(o1, exp, det, ctype, run, time_sec='1000000000', **kwargs)\n\n #msg = dbu.database_info(client, dbname_exp, level=10)\n #print(msg)\n\n print('Xtcav constants inserted, now retrieve them from db:%s collection:%s' % (dbname_exp, det))\n\n db, fs = dbu.db_and_fs(client, dbname_exp)\n col = dbu.collection(db, det)\n\n #for doc in col.find() :\n # print(doc)\n\n doc = dbu.find_doc(col, query={'ctype':ctype, 'run':run})\n print('Found doc:\\n', doc)\n\n o2 = dbu.get_data_for_doc(fs, doc)\n d2 = dict_from_xtcav_calib_object(o2)\n print('Xtcav calib object converted to dict:\\n', d2)\n\n #print('cmp(d1,d2) :', str(d1==d2))\n\n print('\\nCompare dictionaries for Xtcav calib objects loaded directly from calib file and passed through the CDB')\n compare_dicts(d1,d2)\n\n client.close()\n return\n\n\n#------------------------------\n\nif __name__ == \"__main__\":\n path='/reg/d/psdm/XPP/xpptut15/calib/Xtcav::CalibV1/XrayTransportDiagnostic.0:Opal1000.0/pedestals/101-102.data'\n #path='/reg/d/psdm/XCS/xcsm9816/calib/Xtcav::CalibV1/XrayTransportDiagnostic.0:Opal1000.0/lasingoffreference/31-end.data'\n #path='/reg/d/psdm/XCS/xcsm9816/calib/Xtcav::CalibV1/XrayTransportDiagnostic.0:Opal1000.0/pedestals/30-end.data'\n\n fname = sys.argv[1] if len(sys.argv) > 1 else path\n add_consts_to_cdb = True if len(sys.argv) > 2 else False\n\n test_xtcav_calib_constants(fname, add_consts_to_cdb)\n usage(path)\n\n#------------------------------\n", "<docstring token>\nimport sys\nfrom psana.pscalib.calib.XtcavUtils import Load, dict_from_xtcav_calib_object\nimport psana.pscalib.calib.MDBUtils as dbu\nfrom psana.pscalib.calib.CalibUtils import parse_calib_file_name\nfrom psana.pscalib.calib.MDBConvertLCLS1 import detname_conversion\nfrom psana.pscalib.calib.MDBConvertUtils import compare_dicts\nfrom psana.pscalib.calib.CalibConstants import HOST, PORT\n\n\ndef usage(fname):\n msg = (\n \"\"\"Usage: python lcls2/psana/psana/pscalib/examples/ex07-cdb-xtcav.py [<full-path-to-calib-file>]\n by default calib file is %s\"\"\"\n % fname)\n print(msg)\n\n\ndef test_xtcav_calib_constants(fname=\n '/reg/d/psdm/XPP/xpptut15/calib/Xtcav::CalibV1/XrayTransportDiagnostic.0:Opal1000.0/pedestals/101-102.data'\n , add_constants_to_db=False):\n _, exp, _, cvers, detname, ctype, cfname = fname.rsplit('/', 6)\n resp = parse_calib_file_name(cfname)\n begin, end, ext = resp if resp is not None else (None, None, None)\n det = detname_conversion(detname)\n run = begin\n dbname_exp = dbu.db_prefixed_name(exp)\n dbname_det = dbu.db_prefixed_name(det)\n print('LCLS1 Xtcav calibration file: %s' % fname)\n print(\n 'Parameters form path: exp:%s det:%s ctype:%s run:%s dbname_exp:%s dbname_det:%s'\n % (exp, det, ctype, run, dbname_exp, dbname_det))\n o1 = Load(fname)\n d1 = dict_from_xtcav_calib_object(o1)\n print('Xtcav calibration constants as dict:\\n', d1)\n if not add_constants_to_db:\n return\n client = dbu.connect_to_server(HOST, PORT)\n print('Open client on host:%s port:%s' % (HOST, PORT))\n print('Delete database %s' % dbname_exp)\n dbu.delete_database(client, dbname_exp)\n print('Delete database %s' % dbname_det)\n dbu.delete_database(client, dbname_det)\n print('Add Xtcav constants')\n kwargs = {'host': HOST, 'port': PORT, 'version': 'V01', 'comment':\n 'test of add-retrieve xtcav constants'}\n dbu.insert_constants(o1, exp, det, ctype, run, time_sec='1000000000',\n **kwargs)\n print(\n 'Xtcav constants inserted, now retrieve them from db:%s collection:%s'\n % (dbname_exp, det))\n db, fs = dbu.db_and_fs(client, dbname_exp)\n col = dbu.collection(db, det)\n doc = dbu.find_doc(col, query={'ctype': ctype, 'run': run})\n print('Found doc:\\n', doc)\n o2 = dbu.get_data_for_doc(fs, doc)\n d2 = dict_from_xtcav_calib_object(o2)\n print('Xtcav calib object converted to dict:\\n', d2)\n print(\n \"\"\"\nCompare dictionaries for Xtcav calib objects loaded directly from calib file and passed through the CDB\"\"\"\n )\n compare_dicts(d1, d2)\n client.close()\n return\n\n\nif __name__ == '__main__':\n path = (\n '/reg/d/psdm/XPP/xpptut15/calib/Xtcav::CalibV1/XrayTransportDiagnostic.0:Opal1000.0/pedestals/101-102.data'\n )\n fname = sys.argv[1] if len(sys.argv) > 1 else path\n add_consts_to_cdb = True if len(sys.argv) > 2 else False\n test_xtcav_calib_constants(fname, add_consts_to_cdb)\n usage(path)\n", "<docstring token>\n<import token>\n\n\ndef usage(fname):\n msg = (\n \"\"\"Usage: python lcls2/psana/psana/pscalib/examples/ex07-cdb-xtcav.py [<full-path-to-calib-file>]\n by default calib file is %s\"\"\"\n % fname)\n print(msg)\n\n\ndef test_xtcav_calib_constants(fname=\n '/reg/d/psdm/XPP/xpptut15/calib/Xtcav::CalibV1/XrayTransportDiagnostic.0:Opal1000.0/pedestals/101-102.data'\n , add_constants_to_db=False):\n _, exp, _, cvers, detname, ctype, cfname = fname.rsplit('/', 6)\n resp = parse_calib_file_name(cfname)\n begin, end, ext = resp if resp is not None else (None, None, None)\n det = detname_conversion(detname)\n run = begin\n dbname_exp = dbu.db_prefixed_name(exp)\n dbname_det = dbu.db_prefixed_name(det)\n print('LCLS1 Xtcav calibration file: %s' % fname)\n print(\n 'Parameters form path: exp:%s det:%s ctype:%s run:%s dbname_exp:%s dbname_det:%s'\n % (exp, det, ctype, run, dbname_exp, dbname_det))\n o1 = Load(fname)\n d1 = dict_from_xtcav_calib_object(o1)\n print('Xtcav calibration constants as dict:\\n', d1)\n if not add_constants_to_db:\n return\n client = dbu.connect_to_server(HOST, PORT)\n print('Open client on host:%s port:%s' % (HOST, PORT))\n print('Delete database %s' % dbname_exp)\n dbu.delete_database(client, dbname_exp)\n print('Delete database %s' % dbname_det)\n dbu.delete_database(client, dbname_det)\n print('Add Xtcav constants')\n kwargs = {'host': HOST, 'port': PORT, 'version': 'V01', 'comment':\n 'test of add-retrieve xtcav constants'}\n dbu.insert_constants(o1, exp, det, ctype, run, time_sec='1000000000',\n **kwargs)\n print(\n 'Xtcav constants inserted, now retrieve them from db:%s collection:%s'\n % (dbname_exp, det))\n db, fs = dbu.db_and_fs(client, dbname_exp)\n col = dbu.collection(db, det)\n doc = dbu.find_doc(col, query={'ctype': ctype, 'run': run})\n print('Found doc:\\n', doc)\n o2 = dbu.get_data_for_doc(fs, doc)\n d2 = dict_from_xtcav_calib_object(o2)\n print('Xtcav calib object converted to dict:\\n', d2)\n print(\n \"\"\"\nCompare dictionaries for Xtcav calib objects loaded directly from calib file and passed through the CDB\"\"\"\n )\n compare_dicts(d1, d2)\n client.close()\n return\n\n\nif __name__ == '__main__':\n path = (\n '/reg/d/psdm/XPP/xpptut15/calib/Xtcav::CalibV1/XrayTransportDiagnostic.0:Opal1000.0/pedestals/101-102.data'\n )\n fname = sys.argv[1] if len(sys.argv) > 1 else path\n add_consts_to_cdb = True if len(sys.argv) > 2 else False\n test_xtcav_calib_constants(fname, add_consts_to_cdb)\n usage(path)\n", "<docstring token>\n<import token>\n\n\ndef usage(fname):\n msg = (\n \"\"\"Usage: python lcls2/psana/psana/pscalib/examples/ex07-cdb-xtcav.py [<full-path-to-calib-file>]\n by default calib file is %s\"\"\"\n % fname)\n print(msg)\n\n\ndef test_xtcav_calib_constants(fname=\n '/reg/d/psdm/XPP/xpptut15/calib/Xtcav::CalibV1/XrayTransportDiagnostic.0:Opal1000.0/pedestals/101-102.data'\n , add_constants_to_db=False):\n _, exp, _, cvers, detname, ctype, cfname = fname.rsplit('/', 6)\n resp = parse_calib_file_name(cfname)\n begin, end, ext = resp if resp is not None else (None, None, None)\n det = detname_conversion(detname)\n run = begin\n dbname_exp = dbu.db_prefixed_name(exp)\n dbname_det = dbu.db_prefixed_name(det)\n print('LCLS1 Xtcav calibration file: %s' % fname)\n print(\n 'Parameters form path: exp:%s det:%s ctype:%s run:%s dbname_exp:%s dbname_det:%s'\n % (exp, det, ctype, run, dbname_exp, dbname_det))\n o1 = Load(fname)\n d1 = dict_from_xtcav_calib_object(o1)\n print('Xtcav calibration constants as dict:\\n', d1)\n if not add_constants_to_db:\n return\n client = dbu.connect_to_server(HOST, PORT)\n print('Open client on host:%s port:%s' % (HOST, PORT))\n print('Delete database %s' % dbname_exp)\n dbu.delete_database(client, dbname_exp)\n print('Delete database %s' % dbname_det)\n dbu.delete_database(client, dbname_det)\n print('Add Xtcav constants')\n kwargs = {'host': HOST, 'port': PORT, 'version': 'V01', 'comment':\n 'test of add-retrieve xtcav constants'}\n dbu.insert_constants(o1, exp, det, ctype, run, time_sec='1000000000',\n **kwargs)\n print(\n 'Xtcav constants inserted, now retrieve them from db:%s collection:%s'\n % (dbname_exp, det))\n db, fs = dbu.db_and_fs(client, dbname_exp)\n col = dbu.collection(db, det)\n doc = dbu.find_doc(col, query={'ctype': ctype, 'run': run})\n print('Found doc:\\n', doc)\n o2 = dbu.get_data_for_doc(fs, doc)\n d2 = dict_from_xtcav_calib_object(o2)\n print('Xtcav calib object converted to dict:\\n', d2)\n print(\n \"\"\"\nCompare dictionaries for Xtcav calib objects loaded directly from calib file and passed through the CDB\"\"\"\n )\n compare_dicts(d1, d2)\n client.close()\n return\n\n\n<code token>\n", "<docstring token>\n<import token>\n<function token>\n\n\ndef test_xtcav_calib_constants(fname=\n '/reg/d/psdm/XPP/xpptut15/calib/Xtcav::CalibV1/XrayTransportDiagnostic.0:Opal1000.0/pedestals/101-102.data'\n , add_constants_to_db=False):\n _, exp, _, cvers, detname, ctype, cfname = fname.rsplit('/', 6)\n resp = parse_calib_file_name(cfname)\n begin, end, ext = resp if resp is not None else (None, None, None)\n det = detname_conversion(detname)\n run = begin\n dbname_exp = dbu.db_prefixed_name(exp)\n dbname_det = dbu.db_prefixed_name(det)\n print('LCLS1 Xtcav calibration file: %s' % fname)\n print(\n 'Parameters form path: exp:%s det:%s ctype:%s run:%s dbname_exp:%s dbname_det:%s'\n % (exp, det, ctype, run, dbname_exp, dbname_det))\n o1 = Load(fname)\n d1 = dict_from_xtcav_calib_object(o1)\n print('Xtcav calibration constants as dict:\\n', d1)\n if not add_constants_to_db:\n return\n client = dbu.connect_to_server(HOST, PORT)\n print('Open client on host:%s port:%s' % (HOST, PORT))\n print('Delete database %s' % dbname_exp)\n dbu.delete_database(client, dbname_exp)\n print('Delete database %s' % dbname_det)\n dbu.delete_database(client, dbname_det)\n print('Add Xtcav constants')\n kwargs = {'host': HOST, 'port': PORT, 'version': 'V01', 'comment':\n 'test of add-retrieve xtcav constants'}\n dbu.insert_constants(o1, exp, det, ctype, run, time_sec='1000000000',\n **kwargs)\n print(\n 'Xtcav constants inserted, now retrieve them from db:%s collection:%s'\n % (dbname_exp, det))\n db, fs = dbu.db_and_fs(client, dbname_exp)\n col = dbu.collection(db, det)\n doc = dbu.find_doc(col, query={'ctype': ctype, 'run': run})\n print('Found doc:\\n', doc)\n o2 = dbu.get_data_for_doc(fs, doc)\n d2 = dict_from_xtcav_calib_object(o2)\n print('Xtcav calib object converted to dict:\\n', d2)\n print(\n \"\"\"\nCompare dictionaries for Xtcav calib objects loaded directly from calib file and passed through the CDB\"\"\"\n )\n compare_dicts(d1, d2)\n client.close()\n return\n\n\n<code token>\n", "<docstring token>\n<import token>\n<function token>\n<function token>\n<code token>\n" ]
false
98,733
8968c129194262355366a6ca563b0713c140cb42
### ### Copyright (C) 2018-2019 Intel Corporation ### ### SPDX-License-Identifier: BSD-3-Clause ### from ....lib import * from .util import * import os @slash.requires(have_gst) @slash.requires(*have_gst_element("msdk")) @slash.requires(*have_gst_element("checksumsink2")) @slash.requires(using_compatible_driver) class TranscoderTest(slash.Test): requirements = dict( decode = { "avc" : dict( sw = (dict(maxres = (16384, 16384)), have_gst_element("avdec_h264"), "h264parse ! avdec_h264"), hw = (platform.get_caps("decode", "avc"), have_gst_element("msdkh264dec"), "h264parse ! msdkh264dec"), ), "hevc-8" : dict( sw = (dict(maxres = (16384, 16384)), have_gst_element("avdec_h265"), "h265parse ! avdec_h265"), hw = (platform.get_caps("decode", "hevc_8"), have_gst_element("msdkh265dec"), "h265parse ! msdkh265dec"), ), "mpeg2" : dict( sw = (dict(maxres = (2048, 2048)), have_gst_element("avdec_mpeg2video"), "mpegvideoparse ! avdec_mpeg2video"), hw = (platform.get_caps("decode", "mpeg2"), have_gst_element("msdkmpeg2dec"), "mpegvideoparse ! msdkmpeg2dec"), ), "mjpeg" : dict( sw = (dict(maxres = (16384, 16384)), have_gst_element("jpegdec"), "jpegparse ! jpegdec"), hw = (platform.get_caps("decode", "jpeg"), have_gst_element("msdkmjpegdec"), "jpegparse ! msdkmjpegdec"), ), "vc1" : dict( sw = ( dict(maxres = (16384, 16384)), have_gst_element("avdec_vc1"), "'video/x-wmv,profile=(string)advanced'" ",width={width},height={height},framerate=14/1 ! avdec_vc1" ), hw = ( platform.get_caps("decode", "vc1"), have_gst_element("msdkvc1dec"), "'video/x-wmv,profile=(string)advanced'" ",width={width},height={height},framerate=14/1 ! msdkvc1dec" ), ), }, encode = { "avc" : dict( sw = (dict(maxres = (16384, 16384)), have_gst_element("x264enc"), "x264enc ! video/x-h264,profile=main ! h264parse"), hw = (platform.get_caps("encode", "avc"), have_gst_element("msdkh264enc"), "msdkh264enc ! video/x-h264,profile=main ! h264parse"), ), "hevc-8" : dict( sw = (dict(maxres = (16384, 16384)), have_gst_element("x265enc"), "videoconvert chroma-mode=none dither=0 ! video/x-raw,format=I420 ! x265enc ! video/x-h265,profile=main ! h265parse"), hw = (platform.get_caps("encode", "hevc_8"), have_gst_element("msdkh265enc"), "msdkh265enc ! video/x-h265,profile=main ! h265parse"), ), "mpeg2" : dict( sw = (dict(maxres = (2048, 2048)), have_gst_element("avenc_mpeg2video"), "avenc_mpeg2video ! mpegvideoparse"), hw = (platform.get_caps("encode", "mpeg2"), have_gst_element("msdkmpeg2enc"), "msdkmpeg2enc ! mpegvideoparse"), ), "mjpeg" : dict( sw = (dict(maxres = (16384, 16384)), have_gst_element("jpegenc"), "jpegenc ! jpegparse"), hw = (platform.get_caps("vdenc", "jpeg"), have_gst_element("msdkmjpegenc"), "msdkmjpegenc ! jpegparse"), ), }, vpp = { "scale" : dict( sw = (True, have_gst_element("videoscale"), "videoscale ! video/x-raw,width={width},height={height}"), hw = (platform.get_caps("vpp", "scale"), have_gst_element("msdkvpp"), "msdkvpp hardware=true scaling-mode=1 ! video/x-raw,format={format},width={width},height={height}"), ), }, ) # hevc implies hevc 8 bit requirements["encode"]["hevc"] = requirements["encode"]["hevc-8"] requirements["decode"]["hevc"] = requirements["decode"]["hevc-8"] def before(self): self.refctx = [] def get_requirements_data(self, ttype, codec, mode): return self.requirements[ttype].get( codec, {}).get( mode, (None, (False, "{}:{}:{}".format(ttype, codec, mode)), None)) def get_decoder(self, codec, mode): _, _, decoder = self.get_requirements_data("decode", codec, mode) assert decoder is not None, "failed to find a suitable decoder: {}:{}".format(codec, mode) return decoder.format(**vars(self)) def get_encoder(self, codec, mode): _, _, encoder = self.get_requirements_data("encode", codec, mode) assert encoder is not None, "failed to find a suitable encoder: {}:{}".format(codec, mode) return encoder.format(**vars(self)) def get_vpp_scale(self, width, height, mode): if width is None and height is None: return None _, _, scale = self.get_requirements_data("vpp", "scale", mode) assert scale is not None, "failed to find a suitable vpp scaler: {}".format(mode) return scale.format(width = width or self.width, height = height or self.height, format = self.format) def get_file_ext(self, codec): return { "avc" : "h264", "hevc" : "h265", "hevc-8" : "h265", "mpeg2" : "m2v", "mjpeg" : "mjpeg", }.get(codec, "???") def validate_caps(self): assert len(self.outputs), "Invalid test case specification, outputs data empty" assert self.mode in ["sw", "hw"], "Invalid test case specification as mode type not valid" icaps, ireq, _ = self.get_requirements_data("decode", self.codec, self.mode) requires = [ireq,] if icaps is None: slash.skip_test( "decode.{codec}.{mode} unsupported".format(**vars(self))) maxw, maxh = icaps["maxres"] if self.width > maxw or self.height > maxh: slash.skip_test( "decode.{codec}.{mode}.{width}x{height} unsupported".format(**vars(self))) for output in self.outputs: codec = output["codec"] mode = output["mode"] assert mode in ["sw", "hw"], "Invalid test case specification as output mode type not valid" ocaps, oreq, _ = self.get_requirements_data("encode", codec, mode) requires.append(oreq) if ocaps is None: slash.skip_test( "encode.{codec}.{mode} unsupported".format(codec = codec, mode = mode)) maxw, maxh = ocaps["maxres"] w = output.get("width", None) h = output.get("height", None) if (w or self.width) > maxw or (h or self.height) > maxh: slash.skip_test( "encode.{codec}.{mode}.{width}x{height} unsupported".format( codec = codec, mode = mode, width = (w or self.width), height = (h or self.height))) if w is not None or h is not None: ocaps, oreq, _ = self.get_requirements_data("vpp", "scale", mode) requires.append(oreq) if ocaps is None: slash.skip_test( "vpp.scale.{mode} unsupported".format(mode = mode)) unmet = set([m for t,m in requires if not t]) if len(unmet) != 0: slash.skip_test( "Missing one or more required gstreamer elements: {}".format(list(unmet))) self.format = vars(self).get("format", "NV12") def gen_input_opts(self): opts = "filesrc location={source}" opts += " ! " + self.get_decoder(self.codec, self.mode) opts += " ! video/x-raw,format={format}" return opts.format(**vars(self)) def gen_output_opts(self): self.goutputs = dict() opts = "tee name=transcoder" for n, output in enumerate(self.outputs): codec = output["codec"] mode = output["mode"] encoder = self.get_encoder(codec, mode) ext = self.get_file_ext(codec) vppscale = self.get_vpp_scale( output.get("width", None), output.get("height", None), mode) for channel in range(output.get("channels", 1)): ofile = get_media()._test_artifact( "{}_{}_{}.{}".format(self.case, n, channel, ext)) self.goutputs.setdefault(n, list()).append(ofile) opts += " ! queue max-size-buffers=0 max-size-bytes=0 max-size-time=0" if vppscale is not None: opts += " ! {}".format(vppscale) opts += " ! {}".format(encoder) opts += " ! filesink location={} transcoder.".format(ofile) # dump decoded source to yuv for reference comparison self.srcyuv = get_media()._test_artifact( "src_{case}.yuv".format(**vars(self))) opts += " ! queue max-size-buffers=0 max-size-bytes=0 max-size-time=0" opts += " ! checksumsink2 file-checksum=false qos=false" opts += " frame-checksum=false plane-checksum=false dump-output=true" opts += " dump-location={srcyuv}" return opts.format(**vars(self)) @timefn("gst") def call_gst(self, iopts, oopts): call("gst-launch-1.0 -vf {iopts} ! {oopts}".format( iopts = iopts, oopts = oopts)) def transcode(self): self.validate_caps() iopts = self.gen_input_opts() oopts = self.gen_output_opts() get_media().test_call_timeout = vars(self).get("call_timeout", 0) self.call_gst(iopts, oopts) for n, output in enumerate(self.outputs): get_media()._set_test_details(**{"output.{}".format(n) : output}) for channel in range(output.get("channels", 1)): encoded = self.goutputs[n][channel] yuv = get_media()._test_artifact( "{}_{}_{}.yuv".format(self.case, n, channel)) iopts = "filesrc location={} ! {}" oopts = self.get_vpp_scale(self.width, self.height, "hw") oopts += " ! checksumsink2 file-checksum=false qos=false" oopts += " frame-checksum=false plane-checksum=false dump-output=true" oopts += " dump-location={}" self.call_gst( iopts.format(encoded, self.get_decoder(output["codec"], "hw")), oopts.format(yuv)) self.check_metrics(yuv, refctx = [(n, channel)]) get_media()._purge_test_artifact(yuv) def check_metrics(self, yuv, refctx): get_media().baseline.check_psnr( psnr = calculate_psnr( self.srcyuv, yuv, self.width, self.height, self.frames, self.format), context = self.refctx + refctx, )
[ "###\n### Copyright (C) 2018-2019 Intel Corporation\n###\n### SPDX-License-Identifier: BSD-3-Clause\n###\n\nfrom ....lib import *\nfrom .util import *\nimport os\n\[email protected](have_gst)\[email protected](*have_gst_element(\"msdk\"))\[email protected](*have_gst_element(\"checksumsink2\"))\[email protected](using_compatible_driver)\nclass TranscoderTest(slash.Test):\n requirements = dict(\n decode = {\n \"avc\" : dict(\n sw = (dict(maxres = (16384, 16384)), have_gst_element(\"avdec_h264\"), \"h264parse ! avdec_h264\"),\n hw = (platform.get_caps(\"decode\", \"avc\"), have_gst_element(\"msdkh264dec\"), \"h264parse ! msdkh264dec\"),\n ),\n \"hevc-8\" : dict(\n sw = (dict(maxres = (16384, 16384)), have_gst_element(\"avdec_h265\"), \"h265parse ! avdec_h265\"),\n hw = (platform.get_caps(\"decode\", \"hevc_8\"), have_gst_element(\"msdkh265dec\"), \"h265parse ! msdkh265dec\"),\n ),\n \"mpeg2\" : dict(\n sw = (dict(maxres = (2048, 2048)), have_gst_element(\"avdec_mpeg2video\"), \"mpegvideoparse ! avdec_mpeg2video\"),\n hw = (platform.get_caps(\"decode\", \"mpeg2\"), have_gst_element(\"msdkmpeg2dec\"), \"mpegvideoparse ! msdkmpeg2dec\"),\n ),\n \"mjpeg\" : dict(\n sw = (dict(maxres = (16384, 16384)), have_gst_element(\"jpegdec\"), \"jpegparse ! jpegdec\"),\n hw = (platform.get_caps(\"decode\", \"jpeg\"), have_gst_element(\"msdkmjpegdec\"), \"jpegparse ! msdkmjpegdec\"),\n ),\n \"vc1\" : dict(\n sw = (\n dict(maxres = (16384, 16384)), have_gst_element(\"avdec_vc1\"),\n \"'video/x-wmv,profile=(string)advanced'\"\n \",width={width},height={height},framerate=14/1 ! avdec_vc1\"\n ),\n hw = (\n platform.get_caps(\"decode\", \"vc1\"), have_gst_element(\"msdkvc1dec\"),\n \"'video/x-wmv,profile=(string)advanced'\"\n \",width={width},height={height},framerate=14/1 ! msdkvc1dec\"\n ),\n ),\n },\n encode = {\n \"avc\" : dict(\n sw = (dict(maxres = (16384, 16384)), have_gst_element(\"x264enc\"), \"x264enc ! video/x-h264,profile=main ! h264parse\"),\n hw = (platform.get_caps(\"encode\", \"avc\"), have_gst_element(\"msdkh264enc\"), \"msdkh264enc ! video/x-h264,profile=main ! h264parse\"),\n ),\n \"hevc-8\" : dict(\n sw = (dict(maxres = (16384, 16384)), have_gst_element(\"x265enc\"), \"videoconvert chroma-mode=none dither=0 ! video/x-raw,format=I420 ! x265enc ! video/x-h265,profile=main ! h265parse\"),\n hw = (platform.get_caps(\"encode\", \"hevc_8\"), have_gst_element(\"msdkh265enc\"), \"msdkh265enc ! video/x-h265,profile=main ! h265parse\"),\n ),\n \"mpeg2\" : dict(\n sw = (dict(maxres = (2048, 2048)), have_gst_element(\"avenc_mpeg2video\"), \"avenc_mpeg2video ! mpegvideoparse\"),\n hw = (platform.get_caps(\"encode\", \"mpeg2\"), have_gst_element(\"msdkmpeg2enc\"), \"msdkmpeg2enc ! mpegvideoparse\"),\n ),\n \"mjpeg\" : dict(\n sw = (dict(maxres = (16384, 16384)), have_gst_element(\"jpegenc\"), \"jpegenc ! jpegparse\"),\n hw = (platform.get_caps(\"vdenc\", \"jpeg\"), have_gst_element(\"msdkmjpegenc\"), \"msdkmjpegenc ! jpegparse\"),\n ),\n },\n vpp = {\n \"scale\" : dict(\n sw = (True, have_gst_element(\"videoscale\"), \"videoscale ! video/x-raw,width={width},height={height}\"),\n hw = (platform.get_caps(\"vpp\", \"scale\"), have_gst_element(\"msdkvpp\"), \"msdkvpp hardware=true scaling-mode=1 ! video/x-raw,format={format},width={width},height={height}\"),\n ),\n },\n )\n\n # hevc implies hevc 8 bit\n requirements[\"encode\"][\"hevc\"] = requirements[\"encode\"][\"hevc-8\"]\n requirements[\"decode\"][\"hevc\"] = requirements[\"decode\"][\"hevc-8\"]\n\n def before(self):\n self.refctx = []\n\n def get_requirements_data(self, ttype, codec, mode):\n return self.requirements[ttype].get(\n codec, {}).get(\n mode, (None, (False, \"{}:{}:{}\".format(ttype, codec, mode)), None))\n\n def get_decoder(self, codec, mode):\n _, _, decoder = self.get_requirements_data(\"decode\", codec, mode)\n assert decoder is not None, \"failed to find a suitable decoder: {}:{}\".format(codec, mode)\n return decoder.format(**vars(self))\n\n def get_encoder(self, codec, mode):\n _, _, encoder = self.get_requirements_data(\"encode\", codec, mode)\n assert encoder is not None, \"failed to find a suitable encoder: {}:{}\".format(codec, mode)\n return encoder.format(**vars(self))\n\n def get_vpp_scale(self, width, height, mode):\n if width is None and height is None:\n return None\n _, _, scale = self.get_requirements_data(\"vpp\", \"scale\", mode)\n assert scale is not None, \"failed to find a suitable vpp scaler: {}\".format(mode)\n return scale.format(width = width or self.width, height = height or self.height, format = self.format)\n\n def get_file_ext(self, codec):\n return {\n \"avc\" : \"h264\",\n \"hevc\" : \"h265\",\n \"hevc-8\" : \"h265\",\n \"mpeg2\" : \"m2v\",\n \"mjpeg\" : \"mjpeg\",\n }.get(codec, \"???\")\n\n def validate_caps(self):\n assert len(self.outputs), \"Invalid test case specification, outputs data empty\"\n assert self.mode in [\"sw\", \"hw\"], \"Invalid test case specification as mode type not valid\"\n\n icaps, ireq, _ = self.get_requirements_data(\"decode\", self.codec, self.mode)\n requires = [ireq,]\n\n if icaps is None:\n slash.skip_test(\n \"decode.{codec}.{mode} unsupported\".format(**vars(self)))\n\n maxw, maxh = icaps[\"maxres\"]\n if self.width > maxw or self.height > maxh:\n slash.skip_test(\n \"decode.{codec}.{mode}.{width}x{height} unsupported\".format(**vars(self)))\n\n for output in self.outputs:\n codec = output[\"codec\"]\n mode = output[\"mode\"]\n assert mode in [\"sw\", \"hw\"], \"Invalid test case specification as output mode type not valid\"\n ocaps, oreq, _ = self.get_requirements_data(\"encode\", codec, mode)\n requires.append(oreq)\n\n if ocaps is None:\n slash.skip_test(\n \"encode.{codec}.{mode} unsupported\".format(codec = codec, mode = mode))\n\n maxw, maxh = ocaps[\"maxres\"]\n w = output.get(\"width\", None)\n h = output.get(\"height\", None)\n if (w or self.width) > maxw or (h or self.height) > maxh:\n slash.skip_test(\n \"encode.{codec}.{mode}.{width}x{height} unsupported\".format(\n codec = codec, mode = mode,\n width = (w or self.width),\n height = (h or self.height)))\n\n if w is not None or h is not None:\n ocaps, oreq, _ = self.get_requirements_data(\"vpp\", \"scale\", mode)\n requires.append(oreq)\n\n if ocaps is None:\n slash.skip_test(\n \"vpp.scale.{mode} unsupported\".format(mode = mode))\n\n unmet = set([m for t,m in requires if not t])\n if len(unmet) != 0:\n slash.skip_test(\n \"Missing one or more required gstreamer elements: {}\".format(list(unmet)))\n\n self.format = vars(self).get(\"format\", \"NV12\")\n\n def gen_input_opts(self):\n opts = \"filesrc location={source}\"\n opts += \" ! \" + self.get_decoder(self.codec, self.mode)\n opts += \" ! video/x-raw,format={format}\"\n return opts.format(**vars(self))\n\n def gen_output_opts(self):\n self.goutputs = dict()\n opts = \"tee name=transcoder\"\n\n for n, output in enumerate(self.outputs):\n codec = output[\"codec\"]\n mode = output[\"mode\"]\n encoder = self.get_encoder(codec, mode)\n ext = self.get_file_ext(codec)\n\n vppscale = self.get_vpp_scale(\n output.get(\"width\", None), output.get(\"height\", None), mode)\n\n for channel in range(output.get(\"channels\", 1)):\n ofile = get_media()._test_artifact(\n \"{}_{}_{}.{}\".format(self.case, n, channel, ext))\n self.goutputs.setdefault(n, list()).append(ofile)\n\n opts += \" ! queue max-size-buffers=0 max-size-bytes=0 max-size-time=0\"\n if vppscale is not None:\n opts += \" ! {}\".format(vppscale)\n opts += \" ! {}\".format(encoder)\n opts += \" ! filesink location={} transcoder.\".format(ofile)\n\n # dump decoded source to yuv for reference comparison\n self.srcyuv = get_media()._test_artifact(\n \"src_{case}.yuv\".format(**vars(self)))\n opts += \" ! queue max-size-buffers=0 max-size-bytes=0 max-size-time=0\"\n opts += \" ! checksumsink2 file-checksum=false qos=false\"\n opts += \" frame-checksum=false plane-checksum=false dump-output=true\"\n opts += \" dump-location={srcyuv}\"\n\n return opts.format(**vars(self))\n\n @timefn(\"gst\")\n def call_gst(self, iopts, oopts):\n call(\"gst-launch-1.0 -vf {iopts} ! {oopts}\".format(\n iopts = iopts, oopts = oopts))\n\n def transcode(self):\n self.validate_caps()\n iopts = self.gen_input_opts()\n oopts = self.gen_output_opts()\n\n get_media().test_call_timeout = vars(self).get(\"call_timeout\", 0)\n\n self.call_gst(iopts, oopts)\n\n for n, output in enumerate(self.outputs):\n get_media()._set_test_details(**{\"output.{}\".format(n) : output})\n for channel in range(output.get(\"channels\", 1)):\n encoded = self.goutputs[n][channel]\n yuv = get_media()._test_artifact(\n \"{}_{}_{}.yuv\".format(self.case, n, channel))\n iopts = \"filesrc location={} ! {}\"\n oopts = self.get_vpp_scale(self.width, self.height, \"hw\")\n oopts += \" ! checksumsink2 file-checksum=false qos=false\"\n oopts += \" frame-checksum=false plane-checksum=false dump-output=true\"\n oopts += \" dump-location={}\"\n self.call_gst(\n iopts.format(encoded, self.get_decoder(output[\"codec\"], \"hw\")),\n oopts.format(yuv))\n self.check_metrics(yuv, refctx = [(n, channel)])\n get_media()._purge_test_artifact(yuv)\n\n def check_metrics(self, yuv, refctx):\n get_media().baseline.check_psnr(\n psnr = calculate_psnr(\n self.srcyuv, yuv,\n self.width, self.height,\n self.frames, self.format),\n context = self.refctx + refctx,\n )\n", "from ....lib import *\nfrom .util import *\nimport os\n\n\[email protected](have_gst)\[email protected](*have_gst_element('msdk'))\[email protected](*have_gst_element('checksumsink2'))\[email protected](using_compatible_driver)\nclass TranscoderTest(slash.Test):\n requirements = dict(decode={'avc': dict(sw=(dict(maxres=(16384, 16384)),\n have_gst_element('avdec_h264'), 'h264parse ! avdec_h264'), hw=(\n platform.get_caps('decode', 'avc'), have_gst_element('msdkh264dec'),\n 'h264parse ! msdkh264dec')), 'hevc-8': dict(sw=(dict(maxres=(16384,\n 16384)), have_gst_element('avdec_h265'), 'h265parse ! avdec_h265'),\n hw=(platform.get_caps('decode', 'hevc_8'), have_gst_element(\n 'msdkh265dec'), 'h265parse ! msdkh265dec')), 'mpeg2': dict(sw=(dict\n (maxres=(2048, 2048)), have_gst_element('avdec_mpeg2video'),\n 'mpegvideoparse ! avdec_mpeg2video'), hw=(platform.get_caps(\n 'decode', 'mpeg2'), have_gst_element('msdkmpeg2dec'),\n 'mpegvideoparse ! msdkmpeg2dec')), 'mjpeg': dict(sw=(dict(maxres=(\n 16384, 16384)), have_gst_element('jpegdec'), 'jpegparse ! jpegdec'),\n hw=(platform.get_caps('decode', 'jpeg'), have_gst_element(\n 'msdkmjpegdec'), 'jpegparse ! msdkmjpegdec')), 'vc1': dict(sw=(dict\n (maxres=(16384, 16384)), have_gst_element('avdec_vc1'),\n \"'video/x-wmv,profile=(string)advanced',width={width},height={height},framerate=14/1 ! avdec_vc1\"\n ), hw=(platform.get_caps('decode', 'vc1'), have_gst_element(\n 'msdkvc1dec'),\n \"'video/x-wmv,profile=(string)advanced',width={width},height={height},framerate=14/1 ! msdkvc1dec\"\n ))}, encode={'avc': dict(sw=(dict(maxres=(16384, 16384)),\n have_gst_element('x264enc'),\n 'x264enc ! video/x-h264,profile=main ! h264parse'), hw=(platform.\n get_caps('encode', 'avc'), have_gst_element('msdkh264enc'),\n 'msdkh264enc ! video/x-h264,profile=main ! h264parse')), 'hevc-8':\n dict(sw=(dict(maxres=(16384, 16384)), have_gst_element('x265enc'),\n 'videoconvert chroma-mode=none dither=0 ! video/x-raw,format=I420 ! x265enc ! video/x-h265,profile=main ! h265parse'\n ), hw=(platform.get_caps('encode', 'hevc_8'), have_gst_element(\n 'msdkh265enc'),\n 'msdkh265enc ! video/x-h265,profile=main ! h265parse')), 'mpeg2':\n dict(sw=(dict(maxres=(2048, 2048)), have_gst_element(\n 'avenc_mpeg2video'), 'avenc_mpeg2video ! mpegvideoparse'), hw=(\n platform.get_caps('encode', 'mpeg2'), have_gst_element(\n 'msdkmpeg2enc'), 'msdkmpeg2enc ! mpegvideoparse')), 'mjpeg': dict(\n sw=(dict(maxres=(16384, 16384)), have_gst_element('jpegenc'),\n 'jpegenc ! jpegparse'), hw=(platform.get_caps('vdenc', 'jpeg'),\n have_gst_element('msdkmjpegenc'), 'msdkmjpegenc ! jpegparse'))},\n vpp={'scale': dict(sw=(True, have_gst_element('videoscale'),\n 'videoscale ! video/x-raw,width={width},height={height}'), hw=(\n platform.get_caps('vpp', 'scale'), have_gst_element('msdkvpp'),\n 'msdkvpp hardware=true scaling-mode=1 ! video/x-raw,format={format},width={width},height={height}'\n ))})\n requirements['encode']['hevc'] = requirements['encode']['hevc-8']\n requirements['decode']['hevc'] = requirements['decode']['hevc-8']\n\n def before(self):\n self.refctx = []\n\n def get_requirements_data(self, ttype, codec, mode):\n return self.requirements[ttype].get(codec, {}).get(mode, (None, (\n False, '{}:{}:{}'.format(ttype, codec, mode)), None))\n\n def get_decoder(self, codec, mode):\n _, _, decoder = self.get_requirements_data('decode', codec, mode)\n assert decoder is not None, 'failed to find a suitable decoder: {}:{}'.format(\n codec, mode)\n return decoder.format(**vars(self))\n\n def get_encoder(self, codec, mode):\n _, _, encoder = self.get_requirements_data('encode', codec, mode)\n assert encoder is not None, 'failed to find a suitable encoder: {}:{}'.format(\n codec, mode)\n return encoder.format(**vars(self))\n\n def get_vpp_scale(self, width, height, mode):\n if width is None and height is None:\n return None\n _, _, scale = self.get_requirements_data('vpp', 'scale', mode)\n assert scale is not None, 'failed to find a suitable vpp scaler: {}'.format(\n mode)\n return scale.format(width=width or self.width, height=height or\n self.height, format=self.format)\n\n def get_file_ext(self, codec):\n return {'avc': 'h264', 'hevc': 'h265', 'hevc-8': 'h265', 'mpeg2':\n 'm2v', 'mjpeg': 'mjpeg'}.get(codec, '???')\n\n def validate_caps(self):\n assert len(self.outputs\n ), 'Invalid test case specification, outputs data empty'\n assert self.mode in ['sw', 'hw'\n ], 'Invalid test case specification as mode type not valid'\n icaps, ireq, _ = self.get_requirements_data('decode', self.codec,\n self.mode)\n requires = [ireq]\n if icaps is None:\n slash.skip_test('decode.{codec}.{mode} unsupported'.format(**\n vars(self)))\n maxw, maxh = icaps['maxres']\n if self.width > maxw or self.height > maxh:\n slash.skip_test(\n 'decode.{codec}.{mode}.{width}x{height} unsupported'.format\n (**vars(self)))\n for output in self.outputs:\n codec = output['codec']\n mode = output['mode']\n assert mode in ['sw', 'hw'\n ], 'Invalid test case specification as output mode type not valid'\n ocaps, oreq, _ = self.get_requirements_data('encode', codec, mode)\n requires.append(oreq)\n if ocaps is None:\n slash.skip_test('encode.{codec}.{mode} unsupported'.format(\n codec=codec, mode=mode))\n maxw, maxh = ocaps['maxres']\n w = output.get('width', None)\n h = output.get('height', None)\n if (w or self.width) > maxw or (h or self.height) > maxh:\n slash.skip_test(\n 'encode.{codec}.{mode}.{width}x{height} unsupported'.\n format(codec=codec, mode=mode, width=w or self.width,\n height=h or self.height))\n if w is not None or h is not None:\n ocaps, oreq, _ = self.get_requirements_data('vpp', 'scale',\n mode)\n requires.append(oreq)\n if ocaps is None:\n slash.skip_test('vpp.scale.{mode} unsupported'.format(\n mode=mode))\n unmet = set([m for t, m in requires if not t])\n if len(unmet) != 0:\n slash.skip_test(\n 'Missing one or more required gstreamer elements: {}'.\n format(list(unmet)))\n self.format = vars(self).get('format', 'NV12')\n\n def gen_input_opts(self):\n opts = 'filesrc location={source}'\n opts += ' ! ' + self.get_decoder(self.codec, self.mode)\n opts += ' ! video/x-raw,format={format}'\n return opts.format(**vars(self))\n\n def gen_output_opts(self):\n self.goutputs = dict()\n opts = 'tee name=transcoder'\n for n, output in enumerate(self.outputs):\n codec = output['codec']\n mode = output['mode']\n encoder = self.get_encoder(codec, mode)\n ext = self.get_file_ext(codec)\n vppscale = self.get_vpp_scale(output.get('width', None), output\n .get('height', None), mode)\n for channel in range(output.get('channels', 1)):\n ofile = get_media()._test_artifact('{}_{}_{}.{}'.format(\n self.case, n, channel, ext))\n self.goutputs.setdefault(n, list()).append(ofile)\n opts += (\n ' ! queue max-size-buffers=0 max-size-bytes=0 max-size-time=0'\n )\n if vppscale is not None:\n opts += ' ! {}'.format(vppscale)\n opts += ' ! {}'.format(encoder)\n opts += ' ! filesink location={} transcoder.'.format(ofile)\n self.srcyuv = get_media()._test_artifact('src_{case}.yuv'.format(**\n vars(self)))\n opts += ' ! queue max-size-buffers=0 max-size-bytes=0 max-size-time=0'\n opts += ' ! checksumsink2 file-checksum=false qos=false'\n opts += ' frame-checksum=false plane-checksum=false dump-output=true'\n opts += ' dump-location={srcyuv}'\n return opts.format(**vars(self))\n\n @timefn('gst')\n def call_gst(self, iopts, oopts):\n call('gst-launch-1.0 -vf {iopts} ! {oopts}'.format(iopts=iopts,\n oopts=oopts))\n\n def transcode(self):\n self.validate_caps()\n iopts = self.gen_input_opts()\n oopts = self.gen_output_opts()\n get_media().test_call_timeout = vars(self).get('call_timeout', 0)\n self.call_gst(iopts, oopts)\n for n, output in enumerate(self.outputs):\n get_media()._set_test_details(**{'output.{}'.format(n): output})\n for channel in range(output.get('channels', 1)):\n encoded = self.goutputs[n][channel]\n yuv = get_media()._test_artifact('{}_{}_{}.yuv'.format(self\n .case, n, channel))\n iopts = 'filesrc location={} ! {}'\n oopts = self.get_vpp_scale(self.width, self.height, 'hw')\n oopts += ' ! checksumsink2 file-checksum=false qos=false'\n oopts += (\n ' frame-checksum=false plane-checksum=false dump-output=true'\n )\n oopts += ' dump-location={}'\n self.call_gst(iopts.format(encoded, self.get_decoder(output\n ['codec'], 'hw')), oopts.format(yuv))\n self.check_metrics(yuv, refctx=[(n, channel)])\n get_media()._purge_test_artifact(yuv)\n\n def check_metrics(self, yuv, refctx):\n get_media().baseline.check_psnr(psnr=calculate_psnr(self.srcyuv,\n yuv, self.width, self.height, self.frames, self.format),\n context=self.refctx + refctx)\n", "<import token>\n\n\[email protected](have_gst)\[email protected](*have_gst_element('msdk'))\[email protected](*have_gst_element('checksumsink2'))\[email protected](using_compatible_driver)\nclass TranscoderTest(slash.Test):\n requirements = dict(decode={'avc': dict(sw=(dict(maxres=(16384, 16384)),\n have_gst_element('avdec_h264'), 'h264parse ! avdec_h264'), hw=(\n platform.get_caps('decode', 'avc'), have_gst_element('msdkh264dec'),\n 'h264parse ! msdkh264dec')), 'hevc-8': dict(sw=(dict(maxres=(16384,\n 16384)), have_gst_element('avdec_h265'), 'h265parse ! avdec_h265'),\n hw=(platform.get_caps('decode', 'hevc_8'), have_gst_element(\n 'msdkh265dec'), 'h265parse ! msdkh265dec')), 'mpeg2': dict(sw=(dict\n (maxres=(2048, 2048)), have_gst_element('avdec_mpeg2video'),\n 'mpegvideoparse ! avdec_mpeg2video'), hw=(platform.get_caps(\n 'decode', 'mpeg2'), have_gst_element('msdkmpeg2dec'),\n 'mpegvideoparse ! msdkmpeg2dec')), 'mjpeg': dict(sw=(dict(maxres=(\n 16384, 16384)), have_gst_element('jpegdec'), 'jpegparse ! jpegdec'),\n hw=(platform.get_caps('decode', 'jpeg'), have_gst_element(\n 'msdkmjpegdec'), 'jpegparse ! msdkmjpegdec')), 'vc1': dict(sw=(dict\n (maxres=(16384, 16384)), have_gst_element('avdec_vc1'),\n \"'video/x-wmv,profile=(string)advanced',width={width},height={height},framerate=14/1 ! avdec_vc1\"\n ), hw=(platform.get_caps('decode', 'vc1'), have_gst_element(\n 'msdkvc1dec'),\n \"'video/x-wmv,profile=(string)advanced',width={width},height={height},framerate=14/1 ! msdkvc1dec\"\n ))}, encode={'avc': dict(sw=(dict(maxres=(16384, 16384)),\n have_gst_element('x264enc'),\n 'x264enc ! video/x-h264,profile=main ! h264parse'), hw=(platform.\n get_caps('encode', 'avc'), have_gst_element('msdkh264enc'),\n 'msdkh264enc ! video/x-h264,profile=main ! h264parse')), 'hevc-8':\n dict(sw=(dict(maxres=(16384, 16384)), have_gst_element('x265enc'),\n 'videoconvert chroma-mode=none dither=0 ! video/x-raw,format=I420 ! x265enc ! video/x-h265,profile=main ! h265parse'\n ), hw=(platform.get_caps('encode', 'hevc_8'), have_gst_element(\n 'msdkh265enc'),\n 'msdkh265enc ! video/x-h265,profile=main ! h265parse')), 'mpeg2':\n dict(sw=(dict(maxres=(2048, 2048)), have_gst_element(\n 'avenc_mpeg2video'), 'avenc_mpeg2video ! mpegvideoparse'), hw=(\n platform.get_caps('encode', 'mpeg2'), have_gst_element(\n 'msdkmpeg2enc'), 'msdkmpeg2enc ! mpegvideoparse')), 'mjpeg': dict(\n sw=(dict(maxres=(16384, 16384)), have_gst_element('jpegenc'),\n 'jpegenc ! jpegparse'), hw=(platform.get_caps('vdenc', 'jpeg'),\n have_gst_element('msdkmjpegenc'), 'msdkmjpegenc ! jpegparse'))},\n vpp={'scale': dict(sw=(True, have_gst_element('videoscale'),\n 'videoscale ! video/x-raw,width={width},height={height}'), hw=(\n platform.get_caps('vpp', 'scale'), have_gst_element('msdkvpp'),\n 'msdkvpp hardware=true scaling-mode=1 ! video/x-raw,format={format},width={width},height={height}'\n ))})\n requirements['encode']['hevc'] = requirements['encode']['hevc-8']\n requirements['decode']['hevc'] = requirements['decode']['hevc-8']\n\n def before(self):\n self.refctx = []\n\n def get_requirements_data(self, ttype, codec, mode):\n return self.requirements[ttype].get(codec, {}).get(mode, (None, (\n False, '{}:{}:{}'.format(ttype, codec, mode)), None))\n\n def get_decoder(self, codec, mode):\n _, _, decoder = self.get_requirements_data('decode', codec, mode)\n assert decoder is not None, 'failed to find a suitable decoder: {}:{}'.format(\n codec, mode)\n return decoder.format(**vars(self))\n\n def get_encoder(self, codec, mode):\n _, _, encoder = self.get_requirements_data('encode', codec, mode)\n assert encoder is not None, 'failed to find a suitable encoder: {}:{}'.format(\n codec, mode)\n return encoder.format(**vars(self))\n\n def get_vpp_scale(self, width, height, mode):\n if width is None and height is None:\n return None\n _, _, scale = self.get_requirements_data('vpp', 'scale', mode)\n assert scale is not None, 'failed to find a suitable vpp scaler: {}'.format(\n mode)\n return scale.format(width=width or self.width, height=height or\n self.height, format=self.format)\n\n def get_file_ext(self, codec):\n return {'avc': 'h264', 'hevc': 'h265', 'hevc-8': 'h265', 'mpeg2':\n 'm2v', 'mjpeg': 'mjpeg'}.get(codec, '???')\n\n def validate_caps(self):\n assert len(self.outputs\n ), 'Invalid test case specification, outputs data empty'\n assert self.mode in ['sw', 'hw'\n ], 'Invalid test case specification as mode type not valid'\n icaps, ireq, _ = self.get_requirements_data('decode', self.codec,\n self.mode)\n requires = [ireq]\n if icaps is None:\n slash.skip_test('decode.{codec}.{mode} unsupported'.format(**\n vars(self)))\n maxw, maxh = icaps['maxres']\n if self.width > maxw or self.height > maxh:\n slash.skip_test(\n 'decode.{codec}.{mode}.{width}x{height} unsupported'.format\n (**vars(self)))\n for output in self.outputs:\n codec = output['codec']\n mode = output['mode']\n assert mode in ['sw', 'hw'\n ], 'Invalid test case specification as output mode type not valid'\n ocaps, oreq, _ = self.get_requirements_data('encode', codec, mode)\n requires.append(oreq)\n if ocaps is None:\n slash.skip_test('encode.{codec}.{mode} unsupported'.format(\n codec=codec, mode=mode))\n maxw, maxh = ocaps['maxres']\n w = output.get('width', None)\n h = output.get('height', None)\n if (w or self.width) > maxw or (h or self.height) > maxh:\n slash.skip_test(\n 'encode.{codec}.{mode}.{width}x{height} unsupported'.\n format(codec=codec, mode=mode, width=w or self.width,\n height=h or self.height))\n if w is not None or h is not None:\n ocaps, oreq, _ = self.get_requirements_data('vpp', 'scale',\n mode)\n requires.append(oreq)\n if ocaps is None:\n slash.skip_test('vpp.scale.{mode} unsupported'.format(\n mode=mode))\n unmet = set([m for t, m in requires if not t])\n if len(unmet) != 0:\n slash.skip_test(\n 'Missing one or more required gstreamer elements: {}'.\n format(list(unmet)))\n self.format = vars(self).get('format', 'NV12')\n\n def gen_input_opts(self):\n opts = 'filesrc location={source}'\n opts += ' ! ' + self.get_decoder(self.codec, self.mode)\n opts += ' ! video/x-raw,format={format}'\n return opts.format(**vars(self))\n\n def gen_output_opts(self):\n self.goutputs = dict()\n opts = 'tee name=transcoder'\n for n, output in enumerate(self.outputs):\n codec = output['codec']\n mode = output['mode']\n encoder = self.get_encoder(codec, mode)\n ext = self.get_file_ext(codec)\n vppscale = self.get_vpp_scale(output.get('width', None), output\n .get('height', None), mode)\n for channel in range(output.get('channels', 1)):\n ofile = get_media()._test_artifact('{}_{}_{}.{}'.format(\n self.case, n, channel, ext))\n self.goutputs.setdefault(n, list()).append(ofile)\n opts += (\n ' ! queue max-size-buffers=0 max-size-bytes=0 max-size-time=0'\n )\n if vppscale is not None:\n opts += ' ! {}'.format(vppscale)\n opts += ' ! {}'.format(encoder)\n opts += ' ! filesink location={} transcoder.'.format(ofile)\n self.srcyuv = get_media()._test_artifact('src_{case}.yuv'.format(**\n vars(self)))\n opts += ' ! queue max-size-buffers=0 max-size-bytes=0 max-size-time=0'\n opts += ' ! checksumsink2 file-checksum=false qos=false'\n opts += ' frame-checksum=false plane-checksum=false dump-output=true'\n opts += ' dump-location={srcyuv}'\n return opts.format(**vars(self))\n\n @timefn('gst')\n def call_gst(self, iopts, oopts):\n call('gst-launch-1.0 -vf {iopts} ! {oopts}'.format(iopts=iopts,\n oopts=oopts))\n\n def transcode(self):\n self.validate_caps()\n iopts = self.gen_input_opts()\n oopts = self.gen_output_opts()\n get_media().test_call_timeout = vars(self).get('call_timeout', 0)\n self.call_gst(iopts, oopts)\n for n, output in enumerate(self.outputs):\n get_media()._set_test_details(**{'output.{}'.format(n): output})\n for channel in range(output.get('channels', 1)):\n encoded = self.goutputs[n][channel]\n yuv = get_media()._test_artifact('{}_{}_{}.yuv'.format(self\n .case, n, channel))\n iopts = 'filesrc location={} ! {}'\n oopts = self.get_vpp_scale(self.width, self.height, 'hw')\n oopts += ' ! checksumsink2 file-checksum=false qos=false'\n oopts += (\n ' frame-checksum=false plane-checksum=false dump-output=true'\n )\n oopts += ' dump-location={}'\n self.call_gst(iopts.format(encoded, self.get_decoder(output\n ['codec'], 'hw')), oopts.format(yuv))\n self.check_metrics(yuv, refctx=[(n, channel)])\n get_media()._purge_test_artifact(yuv)\n\n def check_metrics(self, yuv, refctx):\n get_media().baseline.check_psnr(psnr=calculate_psnr(self.srcyuv,\n yuv, self.width, self.height, self.frames, self.format),\n context=self.refctx + refctx)\n", "<import token>\n\n\[email protected](have_gst)\[email protected](*have_gst_element('msdk'))\[email protected](*have_gst_element('checksumsink2'))\[email protected](using_compatible_driver)\nclass TranscoderTest(slash.Test):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def before(self):\n self.refctx = []\n\n def get_requirements_data(self, ttype, codec, mode):\n return self.requirements[ttype].get(codec, {}).get(mode, (None, (\n False, '{}:{}:{}'.format(ttype, codec, mode)), None))\n\n def get_decoder(self, codec, mode):\n _, _, decoder = self.get_requirements_data('decode', codec, mode)\n assert decoder is not None, 'failed to find a suitable decoder: {}:{}'.format(\n codec, mode)\n return decoder.format(**vars(self))\n\n def get_encoder(self, codec, mode):\n _, _, encoder = self.get_requirements_data('encode', codec, mode)\n assert encoder is not None, 'failed to find a suitable encoder: {}:{}'.format(\n codec, mode)\n return encoder.format(**vars(self))\n\n def get_vpp_scale(self, width, height, mode):\n if width is None and height is None:\n return None\n _, _, scale = self.get_requirements_data('vpp', 'scale', mode)\n assert scale is not None, 'failed to find a suitable vpp scaler: {}'.format(\n mode)\n return scale.format(width=width or self.width, height=height or\n self.height, format=self.format)\n\n def get_file_ext(self, codec):\n return {'avc': 'h264', 'hevc': 'h265', 'hevc-8': 'h265', 'mpeg2':\n 'm2v', 'mjpeg': 'mjpeg'}.get(codec, '???')\n\n def validate_caps(self):\n assert len(self.outputs\n ), 'Invalid test case specification, outputs data empty'\n assert self.mode in ['sw', 'hw'\n ], 'Invalid test case specification as mode type not valid'\n icaps, ireq, _ = self.get_requirements_data('decode', self.codec,\n self.mode)\n requires = [ireq]\n if icaps is None:\n slash.skip_test('decode.{codec}.{mode} unsupported'.format(**\n vars(self)))\n maxw, maxh = icaps['maxres']\n if self.width > maxw or self.height > maxh:\n slash.skip_test(\n 'decode.{codec}.{mode}.{width}x{height} unsupported'.format\n (**vars(self)))\n for output in self.outputs:\n codec = output['codec']\n mode = output['mode']\n assert mode in ['sw', 'hw'\n ], 'Invalid test case specification as output mode type not valid'\n ocaps, oreq, _ = self.get_requirements_data('encode', codec, mode)\n requires.append(oreq)\n if ocaps is None:\n slash.skip_test('encode.{codec}.{mode} unsupported'.format(\n codec=codec, mode=mode))\n maxw, maxh = ocaps['maxres']\n w = output.get('width', None)\n h = output.get('height', None)\n if (w or self.width) > maxw or (h or self.height) > maxh:\n slash.skip_test(\n 'encode.{codec}.{mode}.{width}x{height} unsupported'.\n format(codec=codec, mode=mode, width=w or self.width,\n height=h or self.height))\n if w is not None or h is not None:\n ocaps, oreq, _ = self.get_requirements_data('vpp', 'scale',\n mode)\n requires.append(oreq)\n if ocaps is None:\n slash.skip_test('vpp.scale.{mode} unsupported'.format(\n mode=mode))\n unmet = set([m for t, m in requires if not t])\n if len(unmet) != 0:\n slash.skip_test(\n 'Missing one or more required gstreamer elements: {}'.\n format(list(unmet)))\n self.format = vars(self).get('format', 'NV12')\n\n def gen_input_opts(self):\n opts = 'filesrc location={source}'\n opts += ' ! ' + self.get_decoder(self.codec, self.mode)\n opts += ' ! video/x-raw,format={format}'\n return opts.format(**vars(self))\n\n def gen_output_opts(self):\n self.goutputs = dict()\n opts = 'tee name=transcoder'\n for n, output in enumerate(self.outputs):\n codec = output['codec']\n mode = output['mode']\n encoder = self.get_encoder(codec, mode)\n ext = self.get_file_ext(codec)\n vppscale = self.get_vpp_scale(output.get('width', None), output\n .get('height', None), mode)\n for channel in range(output.get('channels', 1)):\n ofile = get_media()._test_artifact('{}_{}_{}.{}'.format(\n self.case, n, channel, ext))\n self.goutputs.setdefault(n, list()).append(ofile)\n opts += (\n ' ! queue max-size-buffers=0 max-size-bytes=0 max-size-time=0'\n )\n if vppscale is not None:\n opts += ' ! {}'.format(vppscale)\n opts += ' ! {}'.format(encoder)\n opts += ' ! filesink location={} transcoder.'.format(ofile)\n self.srcyuv = get_media()._test_artifact('src_{case}.yuv'.format(**\n vars(self)))\n opts += ' ! queue max-size-buffers=0 max-size-bytes=0 max-size-time=0'\n opts += ' ! checksumsink2 file-checksum=false qos=false'\n opts += ' frame-checksum=false plane-checksum=false dump-output=true'\n opts += ' dump-location={srcyuv}'\n return opts.format(**vars(self))\n\n @timefn('gst')\n def call_gst(self, iopts, oopts):\n call('gst-launch-1.0 -vf {iopts} ! {oopts}'.format(iopts=iopts,\n oopts=oopts))\n\n def transcode(self):\n self.validate_caps()\n iopts = self.gen_input_opts()\n oopts = self.gen_output_opts()\n get_media().test_call_timeout = vars(self).get('call_timeout', 0)\n self.call_gst(iopts, oopts)\n for n, output in enumerate(self.outputs):\n get_media()._set_test_details(**{'output.{}'.format(n): output})\n for channel in range(output.get('channels', 1)):\n encoded = self.goutputs[n][channel]\n yuv = get_media()._test_artifact('{}_{}_{}.yuv'.format(self\n .case, n, channel))\n iopts = 'filesrc location={} ! {}'\n oopts = self.get_vpp_scale(self.width, self.height, 'hw')\n oopts += ' ! checksumsink2 file-checksum=false qos=false'\n oopts += (\n ' frame-checksum=false plane-checksum=false dump-output=true'\n )\n oopts += ' dump-location={}'\n self.call_gst(iopts.format(encoded, self.get_decoder(output\n ['codec'], 'hw')), oopts.format(yuv))\n self.check_metrics(yuv, refctx=[(n, channel)])\n get_media()._purge_test_artifact(yuv)\n\n def check_metrics(self, yuv, refctx):\n get_media().baseline.check_psnr(psnr=calculate_psnr(self.srcyuv,\n yuv, self.width, self.height, self.frames, self.format),\n context=self.refctx + refctx)\n", "<import token>\n\n\[email protected](have_gst)\[email protected](*have_gst_element('msdk'))\[email protected](*have_gst_element('checksumsink2'))\[email protected](using_compatible_driver)\nclass TranscoderTest(slash.Test):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def before(self):\n self.refctx = []\n\n def get_requirements_data(self, ttype, codec, mode):\n return self.requirements[ttype].get(codec, {}).get(mode, (None, (\n False, '{}:{}:{}'.format(ttype, codec, mode)), None))\n\n def get_decoder(self, codec, mode):\n _, _, decoder = self.get_requirements_data('decode', codec, mode)\n assert decoder is not None, 'failed to find a suitable decoder: {}:{}'.format(\n codec, mode)\n return decoder.format(**vars(self))\n\n def get_encoder(self, codec, mode):\n _, _, encoder = self.get_requirements_data('encode', codec, mode)\n assert encoder is not None, 'failed to find a suitable encoder: {}:{}'.format(\n codec, mode)\n return encoder.format(**vars(self))\n\n def get_vpp_scale(self, width, height, mode):\n if width is None and height is None:\n return None\n _, _, scale = self.get_requirements_data('vpp', 'scale', mode)\n assert scale is not None, 'failed to find a suitable vpp scaler: {}'.format(\n mode)\n return scale.format(width=width or self.width, height=height or\n self.height, format=self.format)\n <function token>\n\n def validate_caps(self):\n assert len(self.outputs\n ), 'Invalid test case specification, outputs data empty'\n assert self.mode in ['sw', 'hw'\n ], 'Invalid test case specification as mode type not valid'\n icaps, ireq, _ = self.get_requirements_data('decode', self.codec,\n self.mode)\n requires = [ireq]\n if icaps is None:\n slash.skip_test('decode.{codec}.{mode} unsupported'.format(**\n vars(self)))\n maxw, maxh = icaps['maxres']\n if self.width > maxw or self.height > maxh:\n slash.skip_test(\n 'decode.{codec}.{mode}.{width}x{height} unsupported'.format\n (**vars(self)))\n for output in self.outputs:\n codec = output['codec']\n mode = output['mode']\n assert mode in ['sw', 'hw'\n ], 'Invalid test case specification as output mode type not valid'\n ocaps, oreq, _ = self.get_requirements_data('encode', codec, mode)\n requires.append(oreq)\n if ocaps is None:\n slash.skip_test('encode.{codec}.{mode} unsupported'.format(\n codec=codec, mode=mode))\n maxw, maxh = ocaps['maxres']\n w = output.get('width', None)\n h = output.get('height', None)\n if (w or self.width) > maxw or (h or self.height) > maxh:\n slash.skip_test(\n 'encode.{codec}.{mode}.{width}x{height} unsupported'.\n format(codec=codec, mode=mode, width=w or self.width,\n height=h or self.height))\n if w is not None or h is not None:\n ocaps, oreq, _ = self.get_requirements_data('vpp', 'scale',\n mode)\n requires.append(oreq)\n if ocaps is None:\n slash.skip_test('vpp.scale.{mode} unsupported'.format(\n mode=mode))\n unmet = set([m for t, m in requires if not t])\n if len(unmet) != 0:\n slash.skip_test(\n 'Missing one or more required gstreamer elements: {}'.\n format(list(unmet)))\n self.format = vars(self).get('format', 'NV12')\n\n def gen_input_opts(self):\n opts = 'filesrc location={source}'\n opts += ' ! ' + self.get_decoder(self.codec, self.mode)\n opts += ' ! video/x-raw,format={format}'\n return opts.format(**vars(self))\n\n def gen_output_opts(self):\n self.goutputs = dict()\n opts = 'tee name=transcoder'\n for n, output in enumerate(self.outputs):\n codec = output['codec']\n mode = output['mode']\n encoder = self.get_encoder(codec, mode)\n ext = self.get_file_ext(codec)\n vppscale = self.get_vpp_scale(output.get('width', None), output\n .get('height', None), mode)\n for channel in range(output.get('channels', 1)):\n ofile = get_media()._test_artifact('{}_{}_{}.{}'.format(\n self.case, n, channel, ext))\n self.goutputs.setdefault(n, list()).append(ofile)\n opts += (\n ' ! queue max-size-buffers=0 max-size-bytes=0 max-size-time=0'\n )\n if vppscale is not None:\n opts += ' ! {}'.format(vppscale)\n opts += ' ! {}'.format(encoder)\n opts += ' ! filesink location={} transcoder.'.format(ofile)\n self.srcyuv = get_media()._test_artifact('src_{case}.yuv'.format(**\n vars(self)))\n opts += ' ! queue max-size-buffers=0 max-size-bytes=0 max-size-time=0'\n opts += ' ! checksumsink2 file-checksum=false qos=false'\n opts += ' frame-checksum=false plane-checksum=false dump-output=true'\n opts += ' dump-location={srcyuv}'\n return opts.format(**vars(self))\n\n @timefn('gst')\n def call_gst(self, iopts, oopts):\n call('gst-launch-1.0 -vf {iopts} ! {oopts}'.format(iopts=iopts,\n oopts=oopts))\n\n def transcode(self):\n self.validate_caps()\n iopts = self.gen_input_opts()\n oopts = self.gen_output_opts()\n get_media().test_call_timeout = vars(self).get('call_timeout', 0)\n self.call_gst(iopts, oopts)\n for n, output in enumerate(self.outputs):\n get_media()._set_test_details(**{'output.{}'.format(n): output})\n for channel in range(output.get('channels', 1)):\n encoded = self.goutputs[n][channel]\n yuv = get_media()._test_artifact('{}_{}_{}.yuv'.format(self\n .case, n, channel))\n iopts = 'filesrc location={} ! {}'\n oopts = self.get_vpp_scale(self.width, self.height, 'hw')\n oopts += ' ! checksumsink2 file-checksum=false qos=false'\n oopts += (\n ' frame-checksum=false plane-checksum=false dump-output=true'\n )\n oopts += ' dump-location={}'\n self.call_gst(iopts.format(encoded, self.get_decoder(output\n ['codec'], 'hw')), oopts.format(yuv))\n self.check_metrics(yuv, refctx=[(n, channel)])\n get_media()._purge_test_artifact(yuv)\n\n def check_metrics(self, yuv, refctx):\n get_media().baseline.check_psnr(psnr=calculate_psnr(self.srcyuv,\n yuv, self.width, self.height, self.frames, self.format),\n context=self.refctx + refctx)\n", "<import token>\n\n\[email protected](have_gst)\[email protected](*have_gst_element('msdk'))\[email protected](*have_gst_element('checksumsink2'))\[email protected](using_compatible_driver)\nclass TranscoderTest(slash.Test):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def before(self):\n self.refctx = []\n\n def get_requirements_data(self, ttype, codec, mode):\n return self.requirements[ttype].get(codec, {}).get(mode, (None, (\n False, '{}:{}:{}'.format(ttype, codec, mode)), None))\n\n def get_decoder(self, codec, mode):\n _, _, decoder = self.get_requirements_data('decode', codec, mode)\n assert decoder is not None, 'failed to find a suitable decoder: {}:{}'.format(\n codec, mode)\n return decoder.format(**vars(self))\n <function token>\n\n def get_vpp_scale(self, width, height, mode):\n if width is None and height is None:\n return None\n _, _, scale = self.get_requirements_data('vpp', 'scale', mode)\n assert scale is not None, 'failed to find a suitable vpp scaler: {}'.format(\n mode)\n return scale.format(width=width or self.width, height=height or\n self.height, format=self.format)\n <function token>\n\n def validate_caps(self):\n assert len(self.outputs\n ), 'Invalid test case specification, outputs data empty'\n assert self.mode in ['sw', 'hw'\n ], 'Invalid test case specification as mode type not valid'\n icaps, ireq, _ = self.get_requirements_data('decode', self.codec,\n self.mode)\n requires = [ireq]\n if icaps is None:\n slash.skip_test('decode.{codec}.{mode} unsupported'.format(**\n vars(self)))\n maxw, maxh = icaps['maxres']\n if self.width > maxw or self.height > maxh:\n slash.skip_test(\n 'decode.{codec}.{mode}.{width}x{height} unsupported'.format\n (**vars(self)))\n for output in self.outputs:\n codec = output['codec']\n mode = output['mode']\n assert mode in ['sw', 'hw'\n ], 'Invalid test case specification as output mode type not valid'\n ocaps, oreq, _ = self.get_requirements_data('encode', codec, mode)\n requires.append(oreq)\n if ocaps is None:\n slash.skip_test('encode.{codec}.{mode} unsupported'.format(\n codec=codec, mode=mode))\n maxw, maxh = ocaps['maxres']\n w = output.get('width', None)\n h = output.get('height', None)\n if (w or self.width) > maxw or (h or self.height) > maxh:\n slash.skip_test(\n 'encode.{codec}.{mode}.{width}x{height} unsupported'.\n format(codec=codec, mode=mode, width=w or self.width,\n height=h or self.height))\n if w is not None or h is not None:\n ocaps, oreq, _ = self.get_requirements_data('vpp', 'scale',\n mode)\n requires.append(oreq)\n if ocaps is None:\n slash.skip_test('vpp.scale.{mode} unsupported'.format(\n mode=mode))\n unmet = set([m for t, m in requires if not t])\n if len(unmet) != 0:\n slash.skip_test(\n 'Missing one or more required gstreamer elements: {}'.\n format(list(unmet)))\n self.format = vars(self).get('format', 'NV12')\n\n def gen_input_opts(self):\n opts = 'filesrc location={source}'\n opts += ' ! ' + self.get_decoder(self.codec, self.mode)\n opts += ' ! video/x-raw,format={format}'\n return opts.format(**vars(self))\n\n def gen_output_opts(self):\n self.goutputs = dict()\n opts = 'tee name=transcoder'\n for n, output in enumerate(self.outputs):\n codec = output['codec']\n mode = output['mode']\n encoder = self.get_encoder(codec, mode)\n ext = self.get_file_ext(codec)\n vppscale = self.get_vpp_scale(output.get('width', None), output\n .get('height', None), mode)\n for channel in range(output.get('channels', 1)):\n ofile = get_media()._test_artifact('{}_{}_{}.{}'.format(\n self.case, n, channel, ext))\n self.goutputs.setdefault(n, list()).append(ofile)\n opts += (\n ' ! queue max-size-buffers=0 max-size-bytes=0 max-size-time=0'\n )\n if vppscale is not None:\n opts += ' ! {}'.format(vppscale)\n opts += ' ! {}'.format(encoder)\n opts += ' ! filesink location={} transcoder.'.format(ofile)\n self.srcyuv = get_media()._test_artifact('src_{case}.yuv'.format(**\n vars(self)))\n opts += ' ! queue max-size-buffers=0 max-size-bytes=0 max-size-time=0'\n opts += ' ! checksumsink2 file-checksum=false qos=false'\n opts += ' frame-checksum=false plane-checksum=false dump-output=true'\n opts += ' dump-location={srcyuv}'\n return opts.format(**vars(self))\n\n @timefn('gst')\n def call_gst(self, iopts, oopts):\n call('gst-launch-1.0 -vf {iopts} ! {oopts}'.format(iopts=iopts,\n oopts=oopts))\n\n def transcode(self):\n self.validate_caps()\n iopts = self.gen_input_opts()\n oopts = self.gen_output_opts()\n get_media().test_call_timeout = vars(self).get('call_timeout', 0)\n self.call_gst(iopts, oopts)\n for n, output in enumerate(self.outputs):\n get_media()._set_test_details(**{'output.{}'.format(n): output})\n for channel in range(output.get('channels', 1)):\n encoded = self.goutputs[n][channel]\n yuv = get_media()._test_artifact('{}_{}_{}.yuv'.format(self\n .case, n, channel))\n iopts = 'filesrc location={} ! {}'\n oopts = self.get_vpp_scale(self.width, self.height, 'hw')\n oopts += ' ! checksumsink2 file-checksum=false qos=false'\n oopts += (\n ' frame-checksum=false plane-checksum=false dump-output=true'\n )\n oopts += ' dump-location={}'\n self.call_gst(iopts.format(encoded, self.get_decoder(output\n ['codec'], 'hw')), oopts.format(yuv))\n self.check_metrics(yuv, refctx=[(n, channel)])\n get_media()._purge_test_artifact(yuv)\n\n def check_metrics(self, yuv, refctx):\n get_media().baseline.check_psnr(psnr=calculate_psnr(self.srcyuv,\n yuv, self.width, self.height, self.frames, self.format),\n context=self.refctx + refctx)\n", "<import token>\n\n\[email protected](have_gst)\[email protected](*have_gst_element('msdk'))\[email protected](*have_gst_element('checksumsink2'))\[email protected](using_compatible_driver)\nclass TranscoderTest(slash.Test):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def before(self):\n self.refctx = []\n\n def get_requirements_data(self, ttype, codec, mode):\n return self.requirements[ttype].get(codec, {}).get(mode, (None, (\n False, '{}:{}:{}'.format(ttype, codec, mode)), None))\n\n def get_decoder(self, codec, mode):\n _, _, decoder = self.get_requirements_data('decode', codec, mode)\n assert decoder is not None, 'failed to find a suitable decoder: {}:{}'.format(\n codec, mode)\n return decoder.format(**vars(self))\n <function token>\n\n def get_vpp_scale(self, width, height, mode):\n if width is None and height is None:\n return None\n _, _, scale = self.get_requirements_data('vpp', 'scale', mode)\n assert scale is not None, 'failed to find a suitable vpp scaler: {}'.format(\n mode)\n return scale.format(width=width or self.width, height=height or\n self.height, format=self.format)\n <function token>\n\n def validate_caps(self):\n assert len(self.outputs\n ), 'Invalid test case specification, outputs data empty'\n assert self.mode in ['sw', 'hw'\n ], 'Invalid test case specification as mode type not valid'\n icaps, ireq, _ = self.get_requirements_data('decode', self.codec,\n self.mode)\n requires = [ireq]\n if icaps is None:\n slash.skip_test('decode.{codec}.{mode} unsupported'.format(**\n vars(self)))\n maxw, maxh = icaps['maxres']\n if self.width > maxw or self.height > maxh:\n slash.skip_test(\n 'decode.{codec}.{mode}.{width}x{height} unsupported'.format\n (**vars(self)))\n for output in self.outputs:\n codec = output['codec']\n mode = output['mode']\n assert mode in ['sw', 'hw'\n ], 'Invalid test case specification as output mode type not valid'\n ocaps, oreq, _ = self.get_requirements_data('encode', codec, mode)\n requires.append(oreq)\n if ocaps is None:\n slash.skip_test('encode.{codec}.{mode} unsupported'.format(\n codec=codec, mode=mode))\n maxw, maxh = ocaps['maxres']\n w = output.get('width', None)\n h = output.get('height', None)\n if (w or self.width) > maxw or (h or self.height) > maxh:\n slash.skip_test(\n 'encode.{codec}.{mode}.{width}x{height} unsupported'.\n format(codec=codec, mode=mode, width=w or self.width,\n height=h or self.height))\n if w is not None or h is not None:\n ocaps, oreq, _ = self.get_requirements_data('vpp', 'scale',\n mode)\n requires.append(oreq)\n if ocaps is None:\n slash.skip_test('vpp.scale.{mode} unsupported'.format(\n mode=mode))\n unmet = set([m for t, m in requires if not t])\n if len(unmet) != 0:\n slash.skip_test(\n 'Missing one or more required gstreamer elements: {}'.\n format(list(unmet)))\n self.format = vars(self).get('format', 'NV12')\n <function token>\n\n def gen_output_opts(self):\n self.goutputs = dict()\n opts = 'tee name=transcoder'\n for n, output in enumerate(self.outputs):\n codec = output['codec']\n mode = output['mode']\n encoder = self.get_encoder(codec, mode)\n ext = self.get_file_ext(codec)\n vppscale = self.get_vpp_scale(output.get('width', None), output\n .get('height', None), mode)\n for channel in range(output.get('channels', 1)):\n ofile = get_media()._test_artifact('{}_{}_{}.{}'.format(\n self.case, n, channel, ext))\n self.goutputs.setdefault(n, list()).append(ofile)\n opts += (\n ' ! queue max-size-buffers=0 max-size-bytes=0 max-size-time=0'\n )\n if vppscale is not None:\n opts += ' ! {}'.format(vppscale)\n opts += ' ! {}'.format(encoder)\n opts += ' ! filesink location={} transcoder.'.format(ofile)\n self.srcyuv = get_media()._test_artifact('src_{case}.yuv'.format(**\n vars(self)))\n opts += ' ! queue max-size-buffers=0 max-size-bytes=0 max-size-time=0'\n opts += ' ! checksumsink2 file-checksum=false qos=false'\n opts += ' frame-checksum=false plane-checksum=false dump-output=true'\n opts += ' dump-location={srcyuv}'\n return opts.format(**vars(self))\n\n @timefn('gst')\n def call_gst(self, iopts, oopts):\n call('gst-launch-1.0 -vf {iopts} ! {oopts}'.format(iopts=iopts,\n oopts=oopts))\n\n def transcode(self):\n self.validate_caps()\n iopts = self.gen_input_opts()\n oopts = self.gen_output_opts()\n get_media().test_call_timeout = vars(self).get('call_timeout', 0)\n self.call_gst(iopts, oopts)\n for n, output in enumerate(self.outputs):\n get_media()._set_test_details(**{'output.{}'.format(n): output})\n for channel in range(output.get('channels', 1)):\n encoded = self.goutputs[n][channel]\n yuv = get_media()._test_artifact('{}_{}_{}.yuv'.format(self\n .case, n, channel))\n iopts = 'filesrc location={} ! {}'\n oopts = self.get_vpp_scale(self.width, self.height, 'hw')\n oopts += ' ! checksumsink2 file-checksum=false qos=false'\n oopts += (\n ' frame-checksum=false plane-checksum=false dump-output=true'\n )\n oopts += ' dump-location={}'\n self.call_gst(iopts.format(encoded, self.get_decoder(output\n ['codec'], 'hw')), oopts.format(yuv))\n self.check_metrics(yuv, refctx=[(n, channel)])\n get_media()._purge_test_artifact(yuv)\n\n def check_metrics(self, yuv, refctx):\n get_media().baseline.check_psnr(psnr=calculate_psnr(self.srcyuv,\n yuv, self.width, self.height, self.frames, self.format),\n context=self.refctx + refctx)\n", "<import token>\n\n\[email protected](have_gst)\[email protected](*have_gst_element('msdk'))\[email protected](*have_gst_element('checksumsink2'))\[email protected](using_compatible_driver)\nclass TranscoderTest(slash.Test):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def before(self):\n self.refctx = []\n\n def get_requirements_data(self, ttype, codec, mode):\n return self.requirements[ttype].get(codec, {}).get(mode, (None, (\n False, '{}:{}:{}'.format(ttype, codec, mode)), None))\n <function token>\n <function token>\n\n def get_vpp_scale(self, width, height, mode):\n if width is None and height is None:\n return None\n _, _, scale = self.get_requirements_data('vpp', 'scale', mode)\n assert scale is not None, 'failed to find a suitable vpp scaler: {}'.format(\n mode)\n return scale.format(width=width or self.width, height=height or\n self.height, format=self.format)\n <function token>\n\n def validate_caps(self):\n assert len(self.outputs\n ), 'Invalid test case specification, outputs data empty'\n assert self.mode in ['sw', 'hw'\n ], 'Invalid test case specification as mode type not valid'\n icaps, ireq, _ = self.get_requirements_data('decode', self.codec,\n self.mode)\n requires = [ireq]\n if icaps is None:\n slash.skip_test('decode.{codec}.{mode} unsupported'.format(**\n vars(self)))\n maxw, maxh = icaps['maxres']\n if self.width > maxw or self.height > maxh:\n slash.skip_test(\n 'decode.{codec}.{mode}.{width}x{height} unsupported'.format\n (**vars(self)))\n for output in self.outputs:\n codec = output['codec']\n mode = output['mode']\n assert mode in ['sw', 'hw'\n ], 'Invalid test case specification as output mode type not valid'\n ocaps, oreq, _ = self.get_requirements_data('encode', codec, mode)\n requires.append(oreq)\n if ocaps is None:\n slash.skip_test('encode.{codec}.{mode} unsupported'.format(\n codec=codec, mode=mode))\n maxw, maxh = ocaps['maxres']\n w = output.get('width', None)\n h = output.get('height', None)\n if (w or self.width) > maxw or (h or self.height) > maxh:\n slash.skip_test(\n 'encode.{codec}.{mode}.{width}x{height} unsupported'.\n format(codec=codec, mode=mode, width=w or self.width,\n height=h or self.height))\n if w is not None or h is not None:\n ocaps, oreq, _ = self.get_requirements_data('vpp', 'scale',\n mode)\n requires.append(oreq)\n if ocaps is None:\n slash.skip_test('vpp.scale.{mode} unsupported'.format(\n mode=mode))\n unmet = set([m for t, m in requires if not t])\n if len(unmet) != 0:\n slash.skip_test(\n 'Missing one or more required gstreamer elements: {}'.\n format(list(unmet)))\n self.format = vars(self).get('format', 'NV12')\n <function token>\n\n def gen_output_opts(self):\n self.goutputs = dict()\n opts = 'tee name=transcoder'\n for n, output in enumerate(self.outputs):\n codec = output['codec']\n mode = output['mode']\n encoder = self.get_encoder(codec, mode)\n ext = self.get_file_ext(codec)\n vppscale = self.get_vpp_scale(output.get('width', None), output\n .get('height', None), mode)\n for channel in range(output.get('channels', 1)):\n ofile = get_media()._test_artifact('{}_{}_{}.{}'.format(\n self.case, n, channel, ext))\n self.goutputs.setdefault(n, list()).append(ofile)\n opts += (\n ' ! queue max-size-buffers=0 max-size-bytes=0 max-size-time=0'\n )\n if vppscale is not None:\n opts += ' ! {}'.format(vppscale)\n opts += ' ! {}'.format(encoder)\n opts += ' ! filesink location={} transcoder.'.format(ofile)\n self.srcyuv = get_media()._test_artifact('src_{case}.yuv'.format(**\n vars(self)))\n opts += ' ! queue max-size-buffers=0 max-size-bytes=0 max-size-time=0'\n opts += ' ! checksumsink2 file-checksum=false qos=false'\n opts += ' frame-checksum=false plane-checksum=false dump-output=true'\n opts += ' dump-location={srcyuv}'\n return opts.format(**vars(self))\n\n @timefn('gst')\n def call_gst(self, iopts, oopts):\n call('gst-launch-1.0 -vf {iopts} ! {oopts}'.format(iopts=iopts,\n oopts=oopts))\n\n def transcode(self):\n self.validate_caps()\n iopts = self.gen_input_opts()\n oopts = self.gen_output_opts()\n get_media().test_call_timeout = vars(self).get('call_timeout', 0)\n self.call_gst(iopts, oopts)\n for n, output in enumerate(self.outputs):\n get_media()._set_test_details(**{'output.{}'.format(n): output})\n for channel in range(output.get('channels', 1)):\n encoded = self.goutputs[n][channel]\n yuv = get_media()._test_artifact('{}_{}_{}.yuv'.format(self\n .case, n, channel))\n iopts = 'filesrc location={} ! {}'\n oopts = self.get_vpp_scale(self.width, self.height, 'hw')\n oopts += ' ! checksumsink2 file-checksum=false qos=false'\n oopts += (\n ' frame-checksum=false plane-checksum=false dump-output=true'\n )\n oopts += ' dump-location={}'\n self.call_gst(iopts.format(encoded, self.get_decoder(output\n ['codec'], 'hw')), oopts.format(yuv))\n self.check_metrics(yuv, refctx=[(n, channel)])\n get_media()._purge_test_artifact(yuv)\n\n def check_metrics(self, yuv, refctx):\n get_media().baseline.check_psnr(psnr=calculate_psnr(self.srcyuv,\n yuv, self.width, self.height, self.frames, self.format),\n context=self.refctx + refctx)\n", "<import token>\n\n\[email protected](have_gst)\[email protected](*have_gst_element('msdk'))\[email protected](*have_gst_element('checksumsink2'))\[email protected](using_compatible_driver)\nclass TranscoderTest(slash.Test):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def before(self):\n self.refctx = []\n\n def get_requirements_data(self, ttype, codec, mode):\n return self.requirements[ttype].get(codec, {}).get(mode, (None, (\n False, '{}:{}:{}'.format(ttype, codec, mode)), None))\n <function token>\n <function token>\n <function token>\n <function token>\n\n def validate_caps(self):\n assert len(self.outputs\n ), 'Invalid test case specification, outputs data empty'\n assert self.mode in ['sw', 'hw'\n ], 'Invalid test case specification as mode type not valid'\n icaps, ireq, _ = self.get_requirements_data('decode', self.codec,\n self.mode)\n requires = [ireq]\n if icaps is None:\n slash.skip_test('decode.{codec}.{mode} unsupported'.format(**\n vars(self)))\n maxw, maxh = icaps['maxres']\n if self.width > maxw or self.height > maxh:\n slash.skip_test(\n 'decode.{codec}.{mode}.{width}x{height} unsupported'.format\n (**vars(self)))\n for output in self.outputs:\n codec = output['codec']\n mode = output['mode']\n assert mode in ['sw', 'hw'\n ], 'Invalid test case specification as output mode type not valid'\n ocaps, oreq, _ = self.get_requirements_data('encode', codec, mode)\n requires.append(oreq)\n if ocaps is None:\n slash.skip_test('encode.{codec}.{mode} unsupported'.format(\n codec=codec, mode=mode))\n maxw, maxh = ocaps['maxres']\n w = output.get('width', None)\n h = output.get('height', None)\n if (w or self.width) > maxw or (h or self.height) > maxh:\n slash.skip_test(\n 'encode.{codec}.{mode}.{width}x{height} unsupported'.\n format(codec=codec, mode=mode, width=w or self.width,\n height=h or self.height))\n if w is not None or h is not None:\n ocaps, oreq, _ = self.get_requirements_data('vpp', 'scale',\n mode)\n requires.append(oreq)\n if ocaps is None:\n slash.skip_test('vpp.scale.{mode} unsupported'.format(\n mode=mode))\n unmet = set([m for t, m in requires if not t])\n if len(unmet) != 0:\n slash.skip_test(\n 'Missing one or more required gstreamer elements: {}'.\n format(list(unmet)))\n self.format = vars(self).get('format', 'NV12')\n <function token>\n\n def gen_output_opts(self):\n self.goutputs = dict()\n opts = 'tee name=transcoder'\n for n, output in enumerate(self.outputs):\n codec = output['codec']\n mode = output['mode']\n encoder = self.get_encoder(codec, mode)\n ext = self.get_file_ext(codec)\n vppscale = self.get_vpp_scale(output.get('width', None), output\n .get('height', None), mode)\n for channel in range(output.get('channels', 1)):\n ofile = get_media()._test_artifact('{}_{}_{}.{}'.format(\n self.case, n, channel, ext))\n self.goutputs.setdefault(n, list()).append(ofile)\n opts += (\n ' ! queue max-size-buffers=0 max-size-bytes=0 max-size-time=0'\n )\n if vppscale is not None:\n opts += ' ! {}'.format(vppscale)\n opts += ' ! {}'.format(encoder)\n opts += ' ! filesink location={} transcoder.'.format(ofile)\n self.srcyuv = get_media()._test_artifact('src_{case}.yuv'.format(**\n vars(self)))\n opts += ' ! queue max-size-buffers=0 max-size-bytes=0 max-size-time=0'\n opts += ' ! checksumsink2 file-checksum=false qos=false'\n opts += ' frame-checksum=false plane-checksum=false dump-output=true'\n opts += ' dump-location={srcyuv}'\n return opts.format(**vars(self))\n\n @timefn('gst')\n def call_gst(self, iopts, oopts):\n call('gst-launch-1.0 -vf {iopts} ! {oopts}'.format(iopts=iopts,\n oopts=oopts))\n\n def transcode(self):\n self.validate_caps()\n iopts = self.gen_input_opts()\n oopts = self.gen_output_opts()\n get_media().test_call_timeout = vars(self).get('call_timeout', 0)\n self.call_gst(iopts, oopts)\n for n, output in enumerate(self.outputs):\n get_media()._set_test_details(**{'output.{}'.format(n): output})\n for channel in range(output.get('channels', 1)):\n encoded = self.goutputs[n][channel]\n yuv = get_media()._test_artifact('{}_{}_{}.yuv'.format(self\n .case, n, channel))\n iopts = 'filesrc location={} ! {}'\n oopts = self.get_vpp_scale(self.width, self.height, 'hw')\n oopts += ' ! checksumsink2 file-checksum=false qos=false'\n oopts += (\n ' frame-checksum=false plane-checksum=false dump-output=true'\n )\n oopts += ' dump-location={}'\n self.call_gst(iopts.format(encoded, self.get_decoder(output\n ['codec'], 'hw')), oopts.format(yuv))\n self.check_metrics(yuv, refctx=[(n, channel)])\n get_media()._purge_test_artifact(yuv)\n\n def check_metrics(self, yuv, refctx):\n get_media().baseline.check_psnr(psnr=calculate_psnr(self.srcyuv,\n yuv, self.width, self.height, self.frames, self.format),\n context=self.refctx + refctx)\n", "<import token>\n\n\[email protected](have_gst)\[email protected](*have_gst_element('msdk'))\[email protected](*have_gst_element('checksumsink2'))\[email protected](using_compatible_driver)\nclass TranscoderTest(slash.Test):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def before(self):\n self.refctx = []\n\n def get_requirements_data(self, ttype, codec, mode):\n return self.requirements[ttype].get(codec, {}).get(mode, (None, (\n False, '{}:{}:{}'.format(ttype, codec, mode)), None))\n <function token>\n <function token>\n <function token>\n <function token>\n\n def validate_caps(self):\n assert len(self.outputs\n ), 'Invalid test case specification, outputs data empty'\n assert self.mode in ['sw', 'hw'\n ], 'Invalid test case specification as mode type not valid'\n icaps, ireq, _ = self.get_requirements_data('decode', self.codec,\n self.mode)\n requires = [ireq]\n if icaps is None:\n slash.skip_test('decode.{codec}.{mode} unsupported'.format(**\n vars(self)))\n maxw, maxh = icaps['maxres']\n if self.width > maxw or self.height > maxh:\n slash.skip_test(\n 'decode.{codec}.{mode}.{width}x{height} unsupported'.format\n (**vars(self)))\n for output in self.outputs:\n codec = output['codec']\n mode = output['mode']\n assert mode in ['sw', 'hw'\n ], 'Invalid test case specification as output mode type not valid'\n ocaps, oreq, _ = self.get_requirements_data('encode', codec, mode)\n requires.append(oreq)\n if ocaps is None:\n slash.skip_test('encode.{codec}.{mode} unsupported'.format(\n codec=codec, mode=mode))\n maxw, maxh = ocaps['maxres']\n w = output.get('width', None)\n h = output.get('height', None)\n if (w or self.width) > maxw or (h or self.height) > maxh:\n slash.skip_test(\n 'encode.{codec}.{mode}.{width}x{height} unsupported'.\n format(codec=codec, mode=mode, width=w or self.width,\n height=h or self.height))\n if w is not None or h is not None:\n ocaps, oreq, _ = self.get_requirements_data('vpp', 'scale',\n mode)\n requires.append(oreq)\n if ocaps is None:\n slash.skip_test('vpp.scale.{mode} unsupported'.format(\n mode=mode))\n unmet = set([m for t, m in requires if not t])\n if len(unmet) != 0:\n slash.skip_test(\n 'Missing one or more required gstreamer elements: {}'.\n format(list(unmet)))\n self.format = vars(self).get('format', 'NV12')\n <function token>\n\n def gen_output_opts(self):\n self.goutputs = dict()\n opts = 'tee name=transcoder'\n for n, output in enumerate(self.outputs):\n codec = output['codec']\n mode = output['mode']\n encoder = self.get_encoder(codec, mode)\n ext = self.get_file_ext(codec)\n vppscale = self.get_vpp_scale(output.get('width', None), output\n .get('height', None), mode)\n for channel in range(output.get('channels', 1)):\n ofile = get_media()._test_artifact('{}_{}_{}.{}'.format(\n self.case, n, channel, ext))\n self.goutputs.setdefault(n, list()).append(ofile)\n opts += (\n ' ! queue max-size-buffers=0 max-size-bytes=0 max-size-time=0'\n )\n if vppscale is not None:\n opts += ' ! {}'.format(vppscale)\n opts += ' ! {}'.format(encoder)\n opts += ' ! filesink location={} transcoder.'.format(ofile)\n self.srcyuv = get_media()._test_artifact('src_{case}.yuv'.format(**\n vars(self)))\n opts += ' ! queue max-size-buffers=0 max-size-bytes=0 max-size-time=0'\n opts += ' ! checksumsink2 file-checksum=false qos=false'\n opts += ' frame-checksum=false plane-checksum=false dump-output=true'\n opts += ' dump-location={srcyuv}'\n return opts.format(**vars(self))\n\n @timefn('gst')\n def call_gst(self, iopts, oopts):\n call('gst-launch-1.0 -vf {iopts} ! {oopts}'.format(iopts=iopts,\n oopts=oopts))\n\n def transcode(self):\n self.validate_caps()\n iopts = self.gen_input_opts()\n oopts = self.gen_output_opts()\n get_media().test_call_timeout = vars(self).get('call_timeout', 0)\n self.call_gst(iopts, oopts)\n for n, output in enumerate(self.outputs):\n get_media()._set_test_details(**{'output.{}'.format(n): output})\n for channel in range(output.get('channels', 1)):\n encoded = self.goutputs[n][channel]\n yuv = get_media()._test_artifact('{}_{}_{}.yuv'.format(self\n .case, n, channel))\n iopts = 'filesrc location={} ! {}'\n oopts = self.get_vpp_scale(self.width, self.height, 'hw')\n oopts += ' ! checksumsink2 file-checksum=false qos=false'\n oopts += (\n ' frame-checksum=false plane-checksum=false dump-output=true'\n )\n oopts += ' dump-location={}'\n self.call_gst(iopts.format(encoded, self.get_decoder(output\n ['codec'], 'hw')), oopts.format(yuv))\n self.check_metrics(yuv, refctx=[(n, channel)])\n get_media()._purge_test_artifact(yuv)\n <function token>\n", "<import token>\n\n\[email protected](have_gst)\[email protected](*have_gst_element('msdk'))\[email protected](*have_gst_element('checksumsink2'))\[email protected](using_compatible_driver)\nclass TranscoderTest(slash.Test):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def before(self):\n self.refctx = []\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def validate_caps(self):\n assert len(self.outputs\n ), 'Invalid test case specification, outputs data empty'\n assert self.mode in ['sw', 'hw'\n ], 'Invalid test case specification as mode type not valid'\n icaps, ireq, _ = self.get_requirements_data('decode', self.codec,\n self.mode)\n requires = [ireq]\n if icaps is None:\n slash.skip_test('decode.{codec}.{mode} unsupported'.format(**\n vars(self)))\n maxw, maxh = icaps['maxres']\n if self.width > maxw or self.height > maxh:\n slash.skip_test(\n 'decode.{codec}.{mode}.{width}x{height} unsupported'.format\n (**vars(self)))\n for output in self.outputs:\n codec = output['codec']\n mode = output['mode']\n assert mode in ['sw', 'hw'\n ], 'Invalid test case specification as output mode type not valid'\n ocaps, oreq, _ = self.get_requirements_data('encode', codec, mode)\n requires.append(oreq)\n if ocaps is None:\n slash.skip_test('encode.{codec}.{mode} unsupported'.format(\n codec=codec, mode=mode))\n maxw, maxh = ocaps['maxres']\n w = output.get('width', None)\n h = output.get('height', None)\n if (w or self.width) > maxw or (h or self.height) > maxh:\n slash.skip_test(\n 'encode.{codec}.{mode}.{width}x{height} unsupported'.\n format(codec=codec, mode=mode, width=w or self.width,\n height=h or self.height))\n if w is not None or h is not None:\n ocaps, oreq, _ = self.get_requirements_data('vpp', 'scale',\n mode)\n requires.append(oreq)\n if ocaps is None:\n slash.skip_test('vpp.scale.{mode} unsupported'.format(\n mode=mode))\n unmet = set([m for t, m in requires if not t])\n if len(unmet) != 0:\n slash.skip_test(\n 'Missing one or more required gstreamer elements: {}'.\n format(list(unmet)))\n self.format = vars(self).get('format', 'NV12')\n <function token>\n\n def gen_output_opts(self):\n self.goutputs = dict()\n opts = 'tee name=transcoder'\n for n, output in enumerate(self.outputs):\n codec = output['codec']\n mode = output['mode']\n encoder = self.get_encoder(codec, mode)\n ext = self.get_file_ext(codec)\n vppscale = self.get_vpp_scale(output.get('width', None), output\n .get('height', None), mode)\n for channel in range(output.get('channels', 1)):\n ofile = get_media()._test_artifact('{}_{}_{}.{}'.format(\n self.case, n, channel, ext))\n self.goutputs.setdefault(n, list()).append(ofile)\n opts += (\n ' ! queue max-size-buffers=0 max-size-bytes=0 max-size-time=0'\n )\n if vppscale is not None:\n opts += ' ! {}'.format(vppscale)\n opts += ' ! {}'.format(encoder)\n opts += ' ! filesink location={} transcoder.'.format(ofile)\n self.srcyuv = get_media()._test_artifact('src_{case}.yuv'.format(**\n vars(self)))\n opts += ' ! queue max-size-buffers=0 max-size-bytes=0 max-size-time=0'\n opts += ' ! checksumsink2 file-checksum=false qos=false'\n opts += ' frame-checksum=false plane-checksum=false dump-output=true'\n opts += ' dump-location={srcyuv}'\n return opts.format(**vars(self))\n\n @timefn('gst')\n def call_gst(self, iopts, oopts):\n call('gst-launch-1.0 -vf {iopts} ! {oopts}'.format(iopts=iopts,\n oopts=oopts))\n\n def transcode(self):\n self.validate_caps()\n iopts = self.gen_input_opts()\n oopts = self.gen_output_opts()\n get_media().test_call_timeout = vars(self).get('call_timeout', 0)\n self.call_gst(iopts, oopts)\n for n, output in enumerate(self.outputs):\n get_media()._set_test_details(**{'output.{}'.format(n): output})\n for channel in range(output.get('channels', 1)):\n encoded = self.goutputs[n][channel]\n yuv = get_media()._test_artifact('{}_{}_{}.yuv'.format(self\n .case, n, channel))\n iopts = 'filesrc location={} ! {}'\n oopts = self.get_vpp_scale(self.width, self.height, 'hw')\n oopts += ' ! checksumsink2 file-checksum=false qos=false'\n oopts += (\n ' frame-checksum=false plane-checksum=false dump-output=true'\n )\n oopts += ' dump-location={}'\n self.call_gst(iopts.format(encoded, self.get_decoder(output\n ['codec'], 'hw')), oopts.format(yuv))\n self.check_metrics(yuv, refctx=[(n, channel)])\n get_media()._purge_test_artifact(yuv)\n <function token>\n", "<import token>\n\n\[email protected](have_gst)\[email protected](*have_gst_element('msdk'))\[email protected](*have_gst_element('checksumsink2'))\[email protected](using_compatible_driver)\nclass TranscoderTest(slash.Test):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def before(self):\n self.refctx = []\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def validate_caps(self):\n assert len(self.outputs\n ), 'Invalid test case specification, outputs data empty'\n assert self.mode in ['sw', 'hw'\n ], 'Invalid test case specification as mode type not valid'\n icaps, ireq, _ = self.get_requirements_data('decode', self.codec,\n self.mode)\n requires = [ireq]\n if icaps is None:\n slash.skip_test('decode.{codec}.{mode} unsupported'.format(**\n vars(self)))\n maxw, maxh = icaps['maxres']\n if self.width > maxw or self.height > maxh:\n slash.skip_test(\n 'decode.{codec}.{mode}.{width}x{height} unsupported'.format\n (**vars(self)))\n for output in self.outputs:\n codec = output['codec']\n mode = output['mode']\n assert mode in ['sw', 'hw'\n ], 'Invalid test case specification as output mode type not valid'\n ocaps, oreq, _ = self.get_requirements_data('encode', codec, mode)\n requires.append(oreq)\n if ocaps is None:\n slash.skip_test('encode.{codec}.{mode} unsupported'.format(\n codec=codec, mode=mode))\n maxw, maxh = ocaps['maxres']\n w = output.get('width', None)\n h = output.get('height', None)\n if (w or self.width) > maxw or (h or self.height) > maxh:\n slash.skip_test(\n 'encode.{codec}.{mode}.{width}x{height} unsupported'.\n format(codec=codec, mode=mode, width=w or self.width,\n height=h or self.height))\n if w is not None or h is not None:\n ocaps, oreq, _ = self.get_requirements_data('vpp', 'scale',\n mode)\n requires.append(oreq)\n if ocaps is None:\n slash.skip_test('vpp.scale.{mode} unsupported'.format(\n mode=mode))\n unmet = set([m for t, m in requires if not t])\n if len(unmet) != 0:\n slash.skip_test(\n 'Missing one or more required gstreamer elements: {}'.\n format(list(unmet)))\n self.format = vars(self).get('format', 'NV12')\n <function token>\n <function token>\n\n @timefn('gst')\n def call_gst(self, iopts, oopts):\n call('gst-launch-1.0 -vf {iopts} ! {oopts}'.format(iopts=iopts,\n oopts=oopts))\n\n def transcode(self):\n self.validate_caps()\n iopts = self.gen_input_opts()\n oopts = self.gen_output_opts()\n get_media().test_call_timeout = vars(self).get('call_timeout', 0)\n self.call_gst(iopts, oopts)\n for n, output in enumerate(self.outputs):\n get_media()._set_test_details(**{'output.{}'.format(n): output})\n for channel in range(output.get('channels', 1)):\n encoded = self.goutputs[n][channel]\n yuv = get_media()._test_artifact('{}_{}_{}.yuv'.format(self\n .case, n, channel))\n iopts = 'filesrc location={} ! {}'\n oopts = self.get_vpp_scale(self.width, self.height, 'hw')\n oopts += ' ! checksumsink2 file-checksum=false qos=false'\n oopts += (\n ' frame-checksum=false plane-checksum=false dump-output=true'\n )\n oopts += ' dump-location={}'\n self.call_gst(iopts.format(encoded, self.get_decoder(output\n ['codec'], 'hw')), oopts.format(yuv))\n self.check_metrics(yuv, refctx=[(n, channel)])\n get_media()._purge_test_artifact(yuv)\n <function token>\n", "<import token>\n\n\[email protected](have_gst)\[email protected](*have_gst_element('msdk'))\[email protected](*have_gst_element('checksumsink2'))\[email protected](using_compatible_driver)\nclass TranscoderTest(slash.Test):\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def validate_caps(self):\n assert len(self.outputs\n ), 'Invalid test case specification, outputs data empty'\n assert self.mode in ['sw', 'hw'\n ], 'Invalid test case specification as mode type not valid'\n icaps, ireq, _ = self.get_requirements_data('decode', self.codec,\n self.mode)\n requires = [ireq]\n if icaps is None:\n slash.skip_test('decode.{codec}.{mode} unsupported'.format(**\n vars(self)))\n maxw, maxh = icaps['maxres']\n if self.width > maxw or self.height > maxh:\n slash.skip_test(\n 'decode.{codec}.{mode}.{width}x{height} unsupported'.format\n (**vars(self)))\n for output in self.outputs:\n codec = output['codec']\n mode = output['mode']\n assert mode in ['sw', 'hw'\n ], 'Invalid test case specification as output mode type not valid'\n ocaps, oreq, _ = self.get_requirements_data('encode', codec, mode)\n requires.append(oreq)\n if ocaps is None:\n slash.skip_test('encode.{codec}.{mode} unsupported'.format(\n codec=codec, mode=mode))\n maxw, maxh = ocaps['maxres']\n w = output.get('width', None)\n h = output.get('height', None)\n if (w or self.width) > maxw or (h or self.height) > maxh:\n slash.skip_test(\n 'encode.{codec}.{mode}.{width}x{height} unsupported'.\n format(codec=codec, mode=mode, width=w or self.width,\n height=h or self.height))\n if w is not None or h is not None:\n ocaps, oreq, _ = self.get_requirements_data('vpp', 'scale',\n mode)\n requires.append(oreq)\n if ocaps is None:\n slash.skip_test('vpp.scale.{mode} unsupported'.format(\n mode=mode))\n unmet = set([m for t, m in requires if not t])\n if len(unmet) != 0:\n slash.skip_test(\n 'Missing one or more required gstreamer elements: {}'.\n format(list(unmet)))\n self.format = vars(self).get('format', 'NV12')\n <function token>\n <function token>\n\n @timefn('gst')\n def call_gst(self, iopts, oopts):\n call('gst-launch-1.0 -vf {iopts} ! {oopts}'.format(iopts=iopts,\n oopts=oopts))\n\n def transcode(self):\n self.validate_caps()\n iopts = self.gen_input_opts()\n oopts = self.gen_output_opts()\n get_media().test_call_timeout = vars(self).get('call_timeout', 0)\n self.call_gst(iopts, oopts)\n for n, output in enumerate(self.outputs):\n get_media()._set_test_details(**{'output.{}'.format(n): output})\n for channel in range(output.get('channels', 1)):\n encoded = self.goutputs[n][channel]\n yuv = get_media()._test_artifact('{}_{}_{}.yuv'.format(self\n .case, n, channel))\n iopts = 'filesrc location={} ! {}'\n oopts = self.get_vpp_scale(self.width, self.height, 'hw')\n oopts += ' ! checksumsink2 file-checksum=false qos=false'\n oopts += (\n ' frame-checksum=false plane-checksum=false dump-output=true'\n )\n oopts += ' dump-location={}'\n self.call_gst(iopts.format(encoded, self.get_decoder(output\n ['codec'], 'hw')), oopts.format(yuv))\n self.check_metrics(yuv, refctx=[(n, channel)])\n get_media()._purge_test_artifact(yuv)\n <function token>\n", "<import token>\n\n\[email protected](have_gst)\[email protected](*have_gst_element('msdk'))\[email protected](*have_gst_element('checksumsink2'))\[email protected](using_compatible_driver)\nclass TranscoderTest(slash.Test):\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def validate_caps(self):\n assert len(self.outputs\n ), 'Invalid test case specification, outputs data empty'\n assert self.mode in ['sw', 'hw'\n ], 'Invalid test case specification as mode type not valid'\n icaps, ireq, _ = self.get_requirements_data('decode', self.codec,\n self.mode)\n requires = [ireq]\n if icaps is None:\n slash.skip_test('decode.{codec}.{mode} unsupported'.format(**\n vars(self)))\n maxw, maxh = icaps['maxres']\n if self.width > maxw or self.height > maxh:\n slash.skip_test(\n 'decode.{codec}.{mode}.{width}x{height} unsupported'.format\n (**vars(self)))\n for output in self.outputs:\n codec = output['codec']\n mode = output['mode']\n assert mode in ['sw', 'hw'\n ], 'Invalid test case specification as output mode type not valid'\n ocaps, oreq, _ = self.get_requirements_data('encode', codec, mode)\n requires.append(oreq)\n if ocaps is None:\n slash.skip_test('encode.{codec}.{mode} unsupported'.format(\n codec=codec, mode=mode))\n maxw, maxh = ocaps['maxres']\n w = output.get('width', None)\n h = output.get('height', None)\n if (w or self.width) > maxw or (h or self.height) > maxh:\n slash.skip_test(\n 'encode.{codec}.{mode}.{width}x{height} unsupported'.\n format(codec=codec, mode=mode, width=w or self.width,\n height=h or self.height))\n if w is not None or h is not None:\n ocaps, oreq, _ = self.get_requirements_data('vpp', 'scale',\n mode)\n requires.append(oreq)\n if ocaps is None:\n slash.skip_test('vpp.scale.{mode} unsupported'.format(\n mode=mode))\n unmet = set([m for t, m in requires if not t])\n if len(unmet) != 0:\n slash.skip_test(\n 'Missing one or more required gstreamer elements: {}'.\n format(list(unmet)))\n self.format = vars(self).get('format', 'NV12')\n <function token>\n <function token>\n <function token>\n\n def transcode(self):\n self.validate_caps()\n iopts = self.gen_input_opts()\n oopts = self.gen_output_opts()\n get_media().test_call_timeout = vars(self).get('call_timeout', 0)\n self.call_gst(iopts, oopts)\n for n, output in enumerate(self.outputs):\n get_media()._set_test_details(**{'output.{}'.format(n): output})\n for channel in range(output.get('channels', 1)):\n encoded = self.goutputs[n][channel]\n yuv = get_media()._test_artifact('{}_{}_{}.yuv'.format(self\n .case, n, channel))\n iopts = 'filesrc location={} ! {}'\n oopts = self.get_vpp_scale(self.width, self.height, 'hw')\n oopts += ' ! checksumsink2 file-checksum=false qos=false'\n oopts += (\n ' frame-checksum=false plane-checksum=false dump-output=true'\n )\n oopts += ' dump-location={}'\n self.call_gst(iopts.format(encoded, self.get_decoder(output\n ['codec'], 'hw')), oopts.format(yuv))\n self.check_metrics(yuv, refctx=[(n, channel)])\n get_media()._purge_test_artifact(yuv)\n <function token>\n", "<import token>\n\n\[email protected](have_gst)\[email protected](*have_gst_element('msdk'))\[email protected](*have_gst_element('checksumsink2'))\[email protected](using_compatible_driver)\nclass TranscoderTest(slash.Test):\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def validate_caps(self):\n assert len(self.outputs\n ), 'Invalid test case specification, outputs data empty'\n assert self.mode in ['sw', 'hw'\n ], 'Invalid test case specification as mode type not valid'\n icaps, ireq, _ = self.get_requirements_data('decode', self.codec,\n self.mode)\n requires = [ireq]\n if icaps is None:\n slash.skip_test('decode.{codec}.{mode} unsupported'.format(**\n vars(self)))\n maxw, maxh = icaps['maxres']\n if self.width > maxw or self.height > maxh:\n slash.skip_test(\n 'decode.{codec}.{mode}.{width}x{height} unsupported'.format\n (**vars(self)))\n for output in self.outputs:\n codec = output['codec']\n mode = output['mode']\n assert mode in ['sw', 'hw'\n ], 'Invalid test case specification as output mode type not valid'\n ocaps, oreq, _ = self.get_requirements_data('encode', codec, mode)\n requires.append(oreq)\n if ocaps is None:\n slash.skip_test('encode.{codec}.{mode} unsupported'.format(\n codec=codec, mode=mode))\n maxw, maxh = ocaps['maxres']\n w = output.get('width', None)\n h = output.get('height', None)\n if (w or self.width) > maxw or (h or self.height) > maxh:\n slash.skip_test(\n 'encode.{codec}.{mode}.{width}x{height} unsupported'.\n format(codec=codec, mode=mode, width=w or self.width,\n height=h or self.height))\n if w is not None or h is not None:\n ocaps, oreq, _ = self.get_requirements_data('vpp', 'scale',\n mode)\n requires.append(oreq)\n if ocaps is None:\n slash.skip_test('vpp.scale.{mode} unsupported'.format(\n mode=mode))\n unmet = set([m for t, m in requires if not t])\n if len(unmet) != 0:\n slash.skip_test(\n 'Missing one or more required gstreamer elements: {}'.\n format(list(unmet)))\n self.format = vars(self).get('format', 'NV12')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<import token>\n\n\[email protected](have_gst)\[email protected](*have_gst_element('msdk'))\[email protected](*have_gst_element('checksumsink2'))\[email protected](using_compatible_driver)\nclass TranscoderTest(slash.Test):\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<import token>\n<class token>\n" ]
false
98,734
5b8fa53379abc7cc38148be203f7c04cfbf27bfa
import init import models models.sync_tables()
[ "import init\nimport models\n\nmodels.sync_tables()", "import init\nimport models\nmodels.sync_tables()\n", "<import token>\nmodels.sync_tables()\n", "<import token>\n<code token>\n" ]
false
98,735
d7d34b5b8ce806bfe68bfdda71f020fdc1587002
valor = int(input("Qual o valor do saque? ")) x = valor // 50 x50 = valor % 50 notas10 = x50 // 10 resto10 = x50 % 10 notas2 = resto10 // 2 print(int(x)) print(int(notas10)) print(int(notas2))
[ "\nvalor = int(input(\"Qual o valor do saque? \"))\nx = valor // 50 \nx50 = valor % 50\nnotas10 = x50 // 10\nresto10 = x50 % 10\nnotas2 = resto10 // 2\n\nprint(int(x))\nprint(int(notas10))\nprint(int(notas2))\n", "valor = int(input('Qual o valor do saque? '))\nx = valor // 50\nx50 = valor % 50\nnotas10 = x50 // 10\nresto10 = x50 % 10\nnotas2 = resto10 // 2\nprint(int(x))\nprint(int(notas10))\nprint(int(notas2))\n", "<assignment token>\nprint(int(x))\nprint(int(notas10))\nprint(int(notas2))\n", "<assignment token>\n<code token>\n" ]
false
98,736
b3f6247e7afa359764b5e35ed48f2ee8d5370cc9
# # PySNMP MIB module SYMM-COMMON-SMI (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/neermitt/Dev/kusanagi/mibs.snmplabs.com/asn1/SYMM-COMMON-SMI # Produced by pysmi-0.3.4 at Tue Jul 30 11:34:07 2019 # On host NEERMITT-M-J0NV platform Darwin version 18.6.0 by user neermitt # Using Python version 3.7.4 (default, Jul 9 2019, 18:13:23) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") enterprises, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, Integer32, IpAddress, MibIdentifier, iso, TimeTicks, Gauge32, Unsigned32, NotificationType, Counter32, ObjectIdentity, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "enterprises", "Counter64", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "Integer32", "IpAddress", "MibIdentifier", "iso", "TimeTicks", "Gauge32", "Unsigned32", "NotificationType", "Counter32", "ObjectIdentity", "ModuleIdentity") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") symmetricom = ModuleIdentity((1, 3, 6, 1, 4, 1, 9070)) symmetricom.setRevisions(('2018-08-23 08:22',)) if mibBuilder.loadTexts: symmetricom.setLastUpdated('201808230822Z') if mibBuilder.loadTexts: symmetricom.setOrganization('Symmetricom, Inc.') class EnableValue(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2)) namedValues = NamedValues(("enable", 1), ("disable", 2)) class TP5000MODULEID(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)) namedValues = NamedValues(("sys", 1), ("imc", 2), ("ioc1", 3), ("ioc2", 4), ("io", 5), ("exp0", 6), ("exp1", 7), ("exp2", 8), ("exp3", 9), ("exp4", 10), ("exp5", 11), ("exp6", 12), ("exp7", 13), ("exp8", 14), ("exp9", 15)) class ONVALUETYPE(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2)) namedValues = NamedValues(("on", 1), ("off", 2)) class ACTIONONLY(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2)) namedValues = NamedValues(("apply", 1), ("nonapply", 2)) class OPMODETYPE(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2)) namedValues = NamedValues(("auto", 1), ("manual", 2)) class ACTIVEVALUETYPE(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2)) namedValues = NamedValues(("active", 1), ("inactive", 2)) class YESVALUETYPE(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2)) namedValues = NamedValues(("yes", 1), ("no", 2)) class OKVALUETYPE(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2)) namedValues = NamedValues(("ok", 1), ("fault", 2)) class VALIDTYPE(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3)) namedValues = NamedValues(("valid", 1), ("invalid", 2), ("nurture", 3)) class GNSSHealthStatus(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2)) namedValues = NamedValues(("healthy", 1), ("unhealthy", 2)) class GNSSReceiverMode(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 4, 5, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 128)) namedValues = NamedValues(("beidou", 1), ("gps", 2), ("priorityBeidou", 4), ("priorityGps", 5), ("gnssGPS", 17), ("gnssGlonass", 18), ("gnssGPSGlonass", 19), ("gnssGalileo", 20), ("gnssGPSGalileo", 21), ("gnssGlonassGalileo", 22), ("gnssGPSGlonassGalileo", 23), ("gnssBeidou", 24), ("gnssBeidouGPS", 25), ("gnssBeidouGlonass", 26), ("gnssBeidouGlonassGPSReserved", 27), ("gnssBeidouGalileo", 28), ("gnssBeidouGalileoGPS", 29), ("gnssBeidouGalileoGlonassReserved", 30), ("gnssBeidouGalileoGlonassGPSReserved", 31), ("notApplicable", 128)) class GNSSPositionMode(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2)) namedValues = NamedValues(("auto", 1), ("manual", 2)) symmNetworkManagement = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1)) if mibBuilder.loadTexts: symmNetworkManagement.setStatus('current') symmCmipManagement = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 1)) if mibBuilder.loadTexts: symmCmipManagement.setStatus('current') symmSnmpManagement = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2)) if mibBuilder.loadTexts: symmSnmpManagement.setStatus('current') symmTimePictra = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 1)) if mibBuilder.loadTexts: symmTimePictra.setStatus('current') symmBroadband = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 2)) if mibBuilder.loadTexts: symmBroadband.setStatus('current') symmTTM = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 3)) if mibBuilder.loadTexts: symmTTM.setStatus('current') symmTSD = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 4)) if mibBuilder.loadTexts: symmTSD.setStatus('current') symmCommonModelV1 = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5)) if mibBuilder.loadTexts: symmCommonModelV1.setStatus('current') symmPacketService = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1)) if mibBuilder.loadTexts: symmPacketService.setStatus('current') symmPhysicalSignal = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 2)) if mibBuilder.loadTexts: symmPhysicalSignal.setStatus('current') symmClock = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 3)) if mibBuilder.loadTexts: symmClock.setStatus('current') symmNetwork = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 4)) if mibBuilder.loadTexts: symmNetwork.setStatus('current') symmEntPhysicalExtension = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 5)) if mibBuilder.loadTexts: symmEntPhysicalExtension.setStatus('current') symmInterfaceExtension = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 6)) if mibBuilder.loadTexts: symmInterfaceExtension.setStatus('current') symmDeviceDependent = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 7)) if mibBuilder.loadTexts: symmDeviceDependent.setStatus('current') mibBuilder.exportSymbols("SYMM-COMMON-SMI", ONVALUETYPE=ONVALUETYPE, EnableValue=EnableValue, GNSSPositionMode=GNSSPositionMode, symmPhysicalSignal=symmPhysicalSignal, symmTTM=symmTTM, ACTIVEVALUETYPE=ACTIVEVALUETYPE, symmetricom=symmetricom, symmCommonModelV1=symmCommonModelV1, YESVALUETYPE=YESVALUETYPE, symmNetworkManagement=symmNetworkManagement, symmInterfaceExtension=symmInterfaceExtension, symmBroadband=symmBroadband, GNSSReceiverMode=GNSSReceiverMode, symmNetwork=symmNetwork, symmCmipManagement=symmCmipManagement, symmEntPhysicalExtension=symmEntPhysicalExtension, symmSnmpManagement=symmSnmpManagement, symmTimePictra=symmTimePictra, symmClock=symmClock, OPMODETYPE=OPMODETYPE, symmDeviceDependent=symmDeviceDependent, symmPacketService=symmPacketService, GNSSHealthStatus=GNSSHealthStatus, OKVALUETYPE=OKVALUETYPE, symmTSD=symmTSD, VALIDTYPE=VALIDTYPE, TP5000MODULEID=TP5000MODULEID, ACTIONONLY=ACTIONONLY, PYSNMP_MODULE_ID=symmetricom)
[ "#\n# PySNMP MIB module SYMM-COMMON-SMI (http://snmplabs.com/pysmi)\n# ASN.1 source file:///Users/neermitt/Dev/kusanagi/mibs.snmplabs.com/asn1/SYMM-COMMON-SMI\n# Produced by pysmi-0.3.4 at Tue Jul 30 11:34:07 2019\n# On host NEERMITT-M-J0NV platform Darwin version 18.6.0 by user neermitt\n# Using Python version 3.7.4 (default, Jul 9 2019, 18:13:23) \n#\nOctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols(\"ASN1\", \"OctetString\", \"ObjectIdentifier\", \"Integer\")\nNamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\")\nValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ValueRangeConstraint\", \"ConstraintsUnion\", \"ConstraintsIntersection\", \"ValueSizeConstraint\", \"SingleValueConstraint\")\nNotificationGroup, ModuleCompliance = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"NotificationGroup\", \"ModuleCompliance\")\nenterprises, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, Integer32, IpAddress, MibIdentifier, iso, TimeTicks, Gauge32, Unsigned32, NotificationType, Counter32, ObjectIdentity, ModuleIdentity = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"enterprises\", \"Counter64\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"Bits\", \"Integer32\", \"IpAddress\", \"MibIdentifier\", \"iso\", \"TimeTicks\", \"Gauge32\", \"Unsigned32\", \"NotificationType\", \"Counter32\", \"ObjectIdentity\", \"ModuleIdentity\")\nTextualConvention, DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\")\nsymmetricom = ModuleIdentity((1, 3, 6, 1, 4, 1, 9070))\nsymmetricom.setRevisions(('2018-08-23 08:22',))\nif mibBuilder.loadTexts: symmetricom.setLastUpdated('201808230822Z')\nif mibBuilder.loadTexts: symmetricom.setOrganization('Symmetricom, Inc.')\nclass EnableValue(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))\n namedValues = NamedValues((\"enable\", 1), (\"disable\", 2))\n\nclass TP5000MODULEID(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15))\n namedValues = NamedValues((\"sys\", 1), (\"imc\", 2), (\"ioc1\", 3), (\"ioc2\", 4), (\"io\", 5), (\"exp0\", 6), (\"exp1\", 7), (\"exp2\", 8), (\"exp3\", 9), (\"exp4\", 10), (\"exp5\", 11), (\"exp6\", 12), (\"exp7\", 13), (\"exp8\", 14), (\"exp9\", 15))\n\nclass ONVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))\n namedValues = NamedValues((\"on\", 1), (\"off\", 2))\n\nclass ACTIONONLY(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))\n namedValues = NamedValues((\"apply\", 1), (\"nonapply\", 2))\n\nclass OPMODETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))\n namedValues = NamedValues((\"auto\", 1), (\"manual\", 2))\n\nclass ACTIVEVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))\n namedValues = NamedValues((\"active\", 1), (\"inactive\", 2))\n\nclass YESVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))\n namedValues = NamedValues((\"yes\", 1), (\"no\", 2))\n\nclass OKVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))\n namedValues = NamedValues((\"ok\", 1), (\"fault\", 2))\n\nclass VALIDTYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3))\n namedValues = NamedValues((\"valid\", 1), (\"invalid\", 2), (\"nurture\", 3))\n\nclass GNSSHealthStatus(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))\n namedValues = NamedValues((\"healthy\", 1), (\"unhealthy\", 2))\n\nclass GNSSReceiverMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 4, 5, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 128))\n namedValues = NamedValues((\"beidou\", 1), (\"gps\", 2), (\"priorityBeidou\", 4), (\"priorityGps\", 5), (\"gnssGPS\", 17), (\"gnssGlonass\", 18), (\"gnssGPSGlonass\", 19), (\"gnssGalileo\", 20), (\"gnssGPSGalileo\", 21), (\"gnssGlonassGalileo\", 22), (\"gnssGPSGlonassGalileo\", 23), (\"gnssBeidou\", 24), (\"gnssBeidouGPS\", 25), (\"gnssBeidouGlonass\", 26), (\"gnssBeidouGlonassGPSReserved\", 27), (\"gnssBeidouGalileo\", 28), (\"gnssBeidouGalileoGPS\", 29), (\"gnssBeidouGalileoGlonassReserved\", 30), (\"gnssBeidouGalileoGlonassGPSReserved\", 31), (\"notApplicable\", 128))\n\nclass GNSSPositionMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))\n namedValues = NamedValues((\"auto\", 1), (\"manual\", 2))\n\nsymmNetworkManagement = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1))\nif mibBuilder.loadTexts: symmNetworkManagement.setStatus('current')\nsymmCmipManagement = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 1))\nif mibBuilder.loadTexts: symmCmipManagement.setStatus('current')\nsymmSnmpManagement = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2))\nif mibBuilder.loadTexts: symmSnmpManagement.setStatus('current')\nsymmTimePictra = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 1))\nif mibBuilder.loadTexts: symmTimePictra.setStatus('current')\nsymmBroadband = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 2))\nif mibBuilder.loadTexts: symmBroadband.setStatus('current')\nsymmTTM = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 3))\nif mibBuilder.loadTexts: symmTTM.setStatus('current')\nsymmTSD = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 4))\nif mibBuilder.loadTexts: symmTSD.setStatus('current')\nsymmCommonModelV1 = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5))\nif mibBuilder.loadTexts: symmCommonModelV1.setStatus('current')\nsymmPacketService = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1))\nif mibBuilder.loadTexts: symmPacketService.setStatus('current')\nsymmPhysicalSignal = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 2))\nif mibBuilder.loadTexts: symmPhysicalSignal.setStatus('current')\nsymmClock = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 3))\nif mibBuilder.loadTexts: symmClock.setStatus('current')\nsymmNetwork = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 4))\nif mibBuilder.loadTexts: symmNetwork.setStatus('current')\nsymmEntPhysicalExtension = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 5))\nif mibBuilder.loadTexts: symmEntPhysicalExtension.setStatus('current')\nsymmInterfaceExtension = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 6))\nif mibBuilder.loadTexts: symmInterfaceExtension.setStatus('current')\nsymmDeviceDependent = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 7))\nif mibBuilder.loadTexts: symmDeviceDependent.setStatus('current')\nmibBuilder.exportSymbols(\"SYMM-COMMON-SMI\", ONVALUETYPE=ONVALUETYPE, EnableValue=EnableValue, GNSSPositionMode=GNSSPositionMode, symmPhysicalSignal=symmPhysicalSignal, symmTTM=symmTTM, ACTIVEVALUETYPE=ACTIVEVALUETYPE, symmetricom=symmetricom, symmCommonModelV1=symmCommonModelV1, YESVALUETYPE=YESVALUETYPE, symmNetworkManagement=symmNetworkManagement, symmInterfaceExtension=symmInterfaceExtension, symmBroadband=symmBroadband, GNSSReceiverMode=GNSSReceiverMode, symmNetwork=symmNetwork, symmCmipManagement=symmCmipManagement, symmEntPhysicalExtension=symmEntPhysicalExtension, symmSnmpManagement=symmSnmpManagement, symmTimePictra=symmTimePictra, symmClock=symmClock, OPMODETYPE=OPMODETYPE, symmDeviceDependent=symmDeviceDependent, symmPacketService=symmPacketService, GNSSHealthStatus=GNSSHealthStatus, OKVALUETYPE=OKVALUETYPE, symmTSD=symmTSD, VALIDTYPE=VALIDTYPE, TP5000MODULEID=TP5000MODULEID, ACTIONONLY=ACTIONONLY, PYSNMP_MODULE_ID=symmetricom)\n", "OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols('ASN1',\n 'OctetString', 'ObjectIdentifier', 'Integer')\nNamedValues, = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')\n(ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection,\n ValueSizeConstraint, SingleValueConstraint) = (mibBuilder.importSymbols\n ('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ConstraintsUnion',\n 'ConstraintsIntersection', 'ValueSizeConstraint', 'SingleValueConstraint'))\nNotificationGroup, ModuleCompliance = mibBuilder.importSymbols('SNMPv2-CONF',\n 'NotificationGroup', 'ModuleCompliance')\n(enterprises, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn,\n Bits, Integer32, IpAddress, MibIdentifier, iso, TimeTicks, Gauge32,\n Unsigned32, NotificationType, Counter32, ObjectIdentity, ModuleIdentity\n ) = (mibBuilder.importSymbols('SNMPv2-SMI', 'enterprises', 'Counter64',\n 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Bits',\n 'Integer32', 'IpAddress', 'MibIdentifier', 'iso', 'TimeTicks',\n 'Gauge32', 'Unsigned32', 'NotificationType', 'Counter32',\n 'ObjectIdentity', 'ModuleIdentity'))\nTextualConvention, DisplayString = mibBuilder.importSymbols('SNMPv2-TC',\n 'TextualConvention', 'DisplayString')\nsymmetricom = ModuleIdentity((1, 3, 6, 1, 4, 1, 9070))\nsymmetricom.setRevisions(('2018-08-23 08:22',))\nif mibBuilder.loadTexts:\n symmetricom.setLastUpdated('201808230822Z')\nif mibBuilder.loadTexts:\n symmetricom.setOrganization('Symmetricom, Inc.')\n\n\nclass EnableValue(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('enable', 1), ('disable', 2))\n\n\nclass TP5000MODULEID(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,\n 15))\n namedValues = NamedValues(('sys', 1), ('imc', 2), ('ioc1', 3), ('ioc2',\n 4), ('io', 5), ('exp0', 6), ('exp1', 7), ('exp2', 8), ('exp3', 9),\n ('exp4', 10), ('exp5', 11), ('exp6', 12), ('exp7', 13), ('exp8', 14\n ), ('exp9', 15))\n\n\nclass ONVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('on', 1), ('off', 2))\n\n\nclass ACTIONONLY(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('apply', 1), ('nonapply', 2))\n\n\nclass OPMODETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\nclass ACTIVEVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('active', 1), ('inactive', 2))\n\n\nclass YESVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('yes', 1), ('no', 2))\n\n\nclass OKVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('ok', 1), ('fault', 2))\n\n\nclass VALIDTYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 3))\n namedValues = NamedValues(('valid', 1), ('invalid', 2), ('nurture', 3))\n\n\nclass GNSSHealthStatus(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('healthy', 1), ('unhealthy', 2))\n\n\nclass GNSSReceiverMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 4, 5, 17, 18, 19, 20, 21, 22, 23, 24, \n 25, 26, 27, 28, 29, 30, 31, 128))\n namedValues = NamedValues(('beidou', 1), ('gps', 2), ('priorityBeidou',\n 4), ('priorityGps', 5), ('gnssGPS', 17), ('gnssGlonass', 18), (\n 'gnssGPSGlonass', 19), ('gnssGalileo', 20), ('gnssGPSGalileo', 21),\n ('gnssGlonassGalileo', 22), ('gnssGPSGlonassGalileo', 23), (\n 'gnssBeidou', 24), ('gnssBeidouGPS', 25), ('gnssBeidouGlonass', 26),\n ('gnssBeidouGlonassGPSReserved', 27), ('gnssBeidouGalileo', 28), (\n 'gnssBeidouGalileoGPS', 29), ('gnssBeidouGalileoGlonassReserved', \n 30), ('gnssBeidouGalileoGlonassGPSReserved', 31), ('notApplicable',\n 128))\n\n\nclass GNSSPositionMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\nsymmNetworkManagement = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1))\nif mibBuilder.loadTexts:\n symmNetworkManagement.setStatus('current')\nsymmCmipManagement = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 1))\nif mibBuilder.loadTexts:\n symmCmipManagement.setStatus('current')\nsymmSnmpManagement = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2))\nif mibBuilder.loadTexts:\n symmSnmpManagement.setStatus('current')\nsymmTimePictra = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 1))\nif mibBuilder.loadTexts:\n symmTimePictra.setStatus('current')\nsymmBroadband = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 2))\nif mibBuilder.loadTexts:\n symmBroadband.setStatus('current')\nsymmTTM = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 3))\nif mibBuilder.loadTexts:\n symmTTM.setStatus('current')\nsymmTSD = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 4))\nif mibBuilder.loadTexts:\n symmTSD.setStatus('current')\nsymmCommonModelV1 = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5))\nif mibBuilder.loadTexts:\n symmCommonModelV1.setStatus('current')\nsymmPacketService = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1))\nif mibBuilder.loadTexts:\n symmPacketService.setStatus('current')\nsymmPhysicalSignal = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 2))\nif mibBuilder.loadTexts:\n symmPhysicalSignal.setStatus('current')\nsymmClock = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 3))\nif mibBuilder.loadTexts:\n symmClock.setStatus('current')\nsymmNetwork = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 4))\nif mibBuilder.loadTexts:\n symmNetwork.setStatus('current')\nsymmEntPhysicalExtension = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 5))\nif mibBuilder.loadTexts:\n symmEntPhysicalExtension.setStatus('current')\nsymmInterfaceExtension = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 6))\nif mibBuilder.loadTexts:\n symmInterfaceExtension.setStatus('current')\nsymmDeviceDependent = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 7))\nif mibBuilder.loadTexts:\n symmDeviceDependent.setStatus('current')\nmibBuilder.exportSymbols('SYMM-COMMON-SMI', ONVALUETYPE=ONVALUETYPE,\n EnableValue=EnableValue, GNSSPositionMode=GNSSPositionMode,\n symmPhysicalSignal=symmPhysicalSignal, symmTTM=symmTTM, ACTIVEVALUETYPE\n =ACTIVEVALUETYPE, symmetricom=symmetricom, symmCommonModelV1=\n symmCommonModelV1, YESVALUETYPE=YESVALUETYPE, symmNetworkManagement=\n symmNetworkManagement, symmInterfaceExtension=symmInterfaceExtension,\n symmBroadband=symmBroadband, GNSSReceiverMode=GNSSReceiverMode,\n symmNetwork=symmNetwork, symmCmipManagement=symmCmipManagement,\n symmEntPhysicalExtension=symmEntPhysicalExtension, symmSnmpManagement=\n symmSnmpManagement, symmTimePictra=symmTimePictra, symmClock=symmClock,\n OPMODETYPE=OPMODETYPE, symmDeviceDependent=symmDeviceDependent,\n symmPacketService=symmPacketService, GNSSHealthStatus=GNSSHealthStatus,\n OKVALUETYPE=OKVALUETYPE, symmTSD=symmTSD, VALIDTYPE=VALIDTYPE,\n TP5000MODULEID=TP5000MODULEID, ACTIONONLY=ACTIONONLY, PYSNMP_MODULE_ID=\n symmetricom)\n", "<assignment token>\nsymmetricom.setRevisions(('2018-08-23 08:22',))\nif mibBuilder.loadTexts:\n symmetricom.setLastUpdated('201808230822Z')\nif mibBuilder.loadTexts:\n symmetricom.setOrganization('Symmetricom, Inc.')\n\n\nclass EnableValue(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('enable', 1), ('disable', 2))\n\n\nclass TP5000MODULEID(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,\n 15))\n namedValues = NamedValues(('sys', 1), ('imc', 2), ('ioc1', 3), ('ioc2',\n 4), ('io', 5), ('exp0', 6), ('exp1', 7), ('exp2', 8), ('exp3', 9),\n ('exp4', 10), ('exp5', 11), ('exp6', 12), ('exp7', 13), ('exp8', 14\n ), ('exp9', 15))\n\n\nclass ONVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('on', 1), ('off', 2))\n\n\nclass ACTIONONLY(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('apply', 1), ('nonapply', 2))\n\n\nclass OPMODETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\nclass ACTIVEVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('active', 1), ('inactive', 2))\n\n\nclass YESVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('yes', 1), ('no', 2))\n\n\nclass OKVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('ok', 1), ('fault', 2))\n\n\nclass VALIDTYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 3))\n namedValues = NamedValues(('valid', 1), ('invalid', 2), ('nurture', 3))\n\n\nclass GNSSHealthStatus(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('healthy', 1), ('unhealthy', 2))\n\n\nclass GNSSReceiverMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 4, 5, 17, 18, 19, 20, 21, 22, 23, 24, \n 25, 26, 27, 28, 29, 30, 31, 128))\n namedValues = NamedValues(('beidou', 1), ('gps', 2), ('priorityBeidou',\n 4), ('priorityGps', 5), ('gnssGPS', 17), ('gnssGlonass', 18), (\n 'gnssGPSGlonass', 19), ('gnssGalileo', 20), ('gnssGPSGalileo', 21),\n ('gnssGlonassGalileo', 22), ('gnssGPSGlonassGalileo', 23), (\n 'gnssBeidou', 24), ('gnssBeidouGPS', 25), ('gnssBeidouGlonass', 26),\n ('gnssBeidouGlonassGPSReserved', 27), ('gnssBeidouGalileo', 28), (\n 'gnssBeidouGalileoGPS', 29), ('gnssBeidouGalileoGlonassReserved', \n 30), ('gnssBeidouGalileoGlonassGPSReserved', 31), ('notApplicable',\n 128))\n\n\nclass GNSSPositionMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\n<assignment token>\nif mibBuilder.loadTexts:\n symmNetworkManagement.setStatus('current')\n<assignment token>\nif mibBuilder.loadTexts:\n symmCmipManagement.setStatus('current')\n<assignment token>\nif mibBuilder.loadTexts:\n symmSnmpManagement.setStatus('current')\n<assignment token>\nif mibBuilder.loadTexts:\n symmTimePictra.setStatus('current')\n<assignment token>\nif mibBuilder.loadTexts:\n symmBroadband.setStatus('current')\n<assignment token>\nif mibBuilder.loadTexts:\n symmTTM.setStatus('current')\n<assignment token>\nif mibBuilder.loadTexts:\n symmTSD.setStatus('current')\n<assignment token>\nif mibBuilder.loadTexts:\n symmCommonModelV1.setStatus('current')\n<assignment token>\nif mibBuilder.loadTexts:\n symmPacketService.setStatus('current')\n<assignment token>\nif mibBuilder.loadTexts:\n symmPhysicalSignal.setStatus('current')\n<assignment token>\nif mibBuilder.loadTexts:\n symmClock.setStatus('current')\n<assignment token>\nif mibBuilder.loadTexts:\n symmNetwork.setStatus('current')\n<assignment token>\nif mibBuilder.loadTexts:\n symmEntPhysicalExtension.setStatus('current')\n<assignment token>\nif mibBuilder.loadTexts:\n symmInterfaceExtension.setStatus('current')\n<assignment token>\nif mibBuilder.loadTexts:\n symmDeviceDependent.setStatus('current')\nmibBuilder.exportSymbols('SYMM-COMMON-SMI', ONVALUETYPE=ONVALUETYPE,\n EnableValue=EnableValue, GNSSPositionMode=GNSSPositionMode,\n symmPhysicalSignal=symmPhysicalSignal, symmTTM=symmTTM, ACTIVEVALUETYPE\n =ACTIVEVALUETYPE, symmetricom=symmetricom, symmCommonModelV1=\n symmCommonModelV1, YESVALUETYPE=YESVALUETYPE, symmNetworkManagement=\n symmNetworkManagement, symmInterfaceExtension=symmInterfaceExtension,\n symmBroadband=symmBroadband, GNSSReceiverMode=GNSSReceiverMode,\n symmNetwork=symmNetwork, symmCmipManagement=symmCmipManagement,\n symmEntPhysicalExtension=symmEntPhysicalExtension, symmSnmpManagement=\n symmSnmpManagement, symmTimePictra=symmTimePictra, symmClock=symmClock,\n OPMODETYPE=OPMODETYPE, symmDeviceDependent=symmDeviceDependent,\n symmPacketService=symmPacketService, GNSSHealthStatus=GNSSHealthStatus,\n OKVALUETYPE=OKVALUETYPE, symmTSD=symmTSD, VALIDTYPE=VALIDTYPE,\n TP5000MODULEID=TP5000MODULEID, ACTIONONLY=ACTIONONLY, PYSNMP_MODULE_ID=\n symmetricom)\n", "<assignment token>\n<code token>\n\n\nclass EnableValue(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('enable', 1), ('disable', 2))\n\n\nclass TP5000MODULEID(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,\n 15))\n namedValues = NamedValues(('sys', 1), ('imc', 2), ('ioc1', 3), ('ioc2',\n 4), ('io', 5), ('exp0', 6), ('exp1', 7), ('exp2', 8), ('exp3', 9),\n ('exp4', 10), ('exp5', 11), ('exp6', 12), ('exp7', 13), ('exp8', 14\n ), ('exp9', 15))\n\n\nclass ONVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('on', 1), ('off', 2))\n\n\nclass ACTIONONLY(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('apply', 1), ('nonapply', 2))\n\n\nclass OPMODETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\nclass ACTIVEVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('active', 1), ('inactive', 2))\n\n\nclass YESVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('yes', 1), ('no', 2))\n\n\nclass OKVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('ok', 1), ('fault', 2))\n\n\nclass VALIDTYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 3))\n namedValues = NamedValues(('valid', 1), ('invalid', 2), ('nurture', 3))\n\n\nclass GNSSHealthStatus(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('healthy', 1), ('unhealthy', 2))\n\n\nclass GNSSReceiverMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 4, 5, 17, 18, 19, 20, 21, 22, 23, 24, \n 25, 26, 27, 28, 29, 30, 31, 128))\n namedValues = NamedValues(('beidou', 1), ('gps', 2), ('priorityBeidou',\n 4), ('priorityGps', 5), ('gnssGPS', 17), ('gnssGlonass', 18), (\n 'gnssGPSGlonass', 19), ('gnssGalileo', 20), ('gnssGPSGalileo', 21),\n ('gnssGlonassGalileo', 22), ('gnssGPSGlonassGalileo', 23), (\n 'gnssBeidou', 24), ('gnssBeidouGPS', 25), ('gnssBeidouGlonass', 26),\n ('gnssBeidouGlonassGPSReserved', 27), ('gnssBeidouGalileo', 28), (\n 'gnssBeidouGalileoGPS', 29), ('gnssBeidouGalileoGlonassReserved', \n 30), ('gnssBeidouGalileoGlonassGPSReserved', 31), ('notApplicable',\n 128))\n\n\nclass GNSSPositionMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<assignment token>\n<code token>\n\n\nclass EnableValue(Integer32):\n <assignment token>\n <assignment token>\n\n\nclass TP5000MODULEID(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,\n 15))\n namedValues = NamedValues(('sys', 1), ('imc', 2), ('ioc1', 3), ('ioc2',\n 4), ('io', 5), ('exp0', 6), ('exp1', 7), ('exp2', 8), ('exp3', 9),\n ('exp4', 10), ('exp5', 11), ('exp6', 12), ('exp7', 13), ('exp8', 14\n ), ('exp9', 15))\n\n\nclass ONVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('on', 1), ('off', 2))\n\n\nclass ACTIONONLY(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('apply', 1), ('nonapply', 2))\n\n\nclass OPMODETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\nclass ACTIVEVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('active', 1), ('inactive', 2))\n\n\nclass YESVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('yes', 1), ('no', 2))\n\n\nclass OKVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('ok', 1), ('fault', 2))\n\n\nclass VALIDTYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 3))\n namedValues = NamedValues(('valid', 1), ('invalid', 2), ('nurture', 3))\n\n\nclass GNSSHealthStatus(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('healthy', 1), ('unhealthy', 2))\n\n\nclass GNSSReceiverMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 4, 5, 17, 18, 19, 20, 21, 22, 23, 24, \n 25, 26, 27, 28, 29, 30, 31, 128))\n namedValues = NamedValues(('beidou', 1), ('gps', 2), ('priorityBeidou',\n 4), ('priorityGps', 5), ('gnssGPS', 17), ('gnssGlonass', 18), (\n 'gnssGPSGlonass', 19), ('gnssGalileo', 20), ('gnssGPSGalileo', 21),\n ('gnssGlonassGalileo', 22), ('gnssGPSGlonassGalileo', 23), (\n 'gnssBeidou', 24), ('gnssBeidouGPS', 25), ('gnssBeidouGlonass', 26),\n ('gnssBeidouGlonassGPSReserved', 27), ('gnssBeidouGalileo', 28), (\n 'gnssBeidouGalileoGPS', 29), ('gnssBeidouGalileoGlonassReserved', \n 30), ('gnssBeidouGalileoGlonassGPSReserved', 31), ('notApplicable',\n 128))\n\n\nclass GNSSPositionMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<assignment token>\n<code token>\n<class token>\n\n\nclass TP5000MODULEID(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,\n 15))\n namedValues = NamedValues(('sys', 1), ('imc', 2), ('ioc1', 3), ('ioc2',\n 4), ('io', 5), ('exp0', 6), ('exp1', 7), ('exp2', 8), ('exp3', 9),\n ('exp4', 10), ('exp5', 11), ('exp6', 12), ('exp7', 13), ('exp8', 14\n ), ('exp9', 15))\n\n\nclass ONVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('on', 1), ('off', 2))\n\n\nclass ACTIONONLY(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('apply', 1), ('nonapply', 2))\n\n\nclass OPMODETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\nclass ACTIVEVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('active', 1), ('inactive', 2))\n\n\nclass YESVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('yes', 1), ('no', 2))\n\n\nclass OKVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('ok', 1), ('fault', 2))\n\n\nclass VALIDTYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 3))\n namedValues = NamedValues(('valid', 1), ('invalid', 2), ('nurture', 3))\n\n\nclass GNSSHealthStatus(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('healthy', 1), ('unhealthy', 2))\n\n\nclass GNSSReceiverMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 4, 5, 17, 18, 19, 20, 21, 22, 23, 24, \n 25, 26, 27, 28, 29, 30, 31, 128))\n namedValues = NamedValues(('beidou', 1), ('gps', 2), ('priorityBeidou',\n 4), ('priorityGps', 5), ('gnssGPS', 17), ('gnssGlonass', 18), (\n 'gnssGPSGlonass', 19), ('gnssGalileo', 20), ('gnssGPSGalileo', 21),\n ('gnssGlonassGalileo', 22), ('gnssGPSGlonassGalileo', 23), (\n 'gnssBeidou', 24), ('gnssBeidouGPS', 25), ('gnssBeidouGlonass', 26),\n ('gnssBeidouGlonassGPSReserved', 27), ('gnssBeidouGalileo', 28), (\n 'gnssBeidouGalileoGPS', 29), ('gnssBeidouGalileoGlonassReserved', \n 30), ('gnssBeidouGalileoGlonassGPSReserved', 31), ('notApplicable',\n 128))\n\n\nclass GNSSPositionMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<assignment token>\n<code token>\n<class token>\n\n\nclass TP5000MODULEID(Integer32):\n <assignment token>\n <assignment token>\n\n\nclass ONVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('on', 1), ('off', 2))\n\n\nclass ACTIONONLY(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('apply', 1), ('nonapply', 2))\n\n\nclass OPMODETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\nclass ACTIVEVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('active', 1), ('inactive', 2))\n\n\nclass YESVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('yes', 1), ('no', 2))\n\n\nclass OKVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('ok', 1), ('fault', 2))\n\n\nclass VALIDTYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 3))\n namedValues = NamedValues(('valid', 1), ('invalid', 2), ('nurture', 3))\n\n\nclass GNSSHealthStatus(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('healthy', 1), ('unhealthy', 2))\n\n\nclass GNSSReceiverMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 4, 5, 17, 18, 19, 20, 21, 22, 23, 24, \n 25, 26, 27, 28, 29, 30, 31, 128))\n namedValues = NamedValues(('beidou', 1), ('gps', 2), ('priorityBeidou',\n 4), ('priorityGps', 5), ('gnssGPS', 17), ('gnssGlonass', 18), (\n 'gnssGPSGlonass', 19), ('gnssGalileo', 20), ('gnssGPSGalileo', 21),\n ('gnssGlonassGalileo', 22), ('gnssGPSGlonassGalileo', 23), (\n 'gnssBeidou', 24), ('gnssBeidouGPS', 25), ('gnssBeidouGlonass', 26),\n ('gnssBeidouGlonassGPSReserved', 27), ('gnssBeidouGalileo', 28), (\n 'gnssBeidouGalileoGPS', 29), ('gnssBeidouGalileoGlonassReserved', \n 30), ('gnssBeidouGalileoGlonassGPSReserved', 31), ('notApplicable',\n 128))\n\n\nclass GNSSPositionMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<assignment token>\n<code token>\n<class token>\n<class token>\n\n\nclass ONVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('on', 1), ('off', 2))\n\n\nclass ACTIONONLY(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('apply', 1), ('nonapply', 2))\n\n\nclass OPMODETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\nclass ACTIVEVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('active', 1), ('inactive', 2))\n\n\nclass YESVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('yes', 1), ('no', 2))\n\n\nclass OKVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('ok', 1), ('fault', 2))\n\n\nclass VALIDTYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 3))\n namedValues = NamedValues(('valid', 1), ('invalid', 2), ('nurture', 3))\n\n\nclass GNSSHealthStatus(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('healthy', 1), ('unhealthy', 2))\n\n\nclass GNSSReceiverMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 4, 5, 17, 18, 19, 20, 21, 22, 23, 24, \n 25, 26, 27, 28, 29, 30, 31, 128))\n namedValues = NamedValues(('beidou', 1), ('gps', 2), ('priorityBeidou',\n 4), ('priorityGps', 5), ('gnssGPS', 17), ('gnssGlonass', 18), (\n 'gnssGPSGlonass', 19), ('gnssGalileo', 20), ('gnssGPSGalileo', 21),\n ('gnssGlonassGalileo', 22), ('gnssGPSGlonassGalileo', 23), (\n 'gnssBeidou', 24), ('gnssBeidouGPS', 25), ('gnssBeidouGlonass', 26),\n ('gnssBeidouGlonassGPSReserved', 27), ('gnssBeidouGalileo', 28), (\n 'gnssBeidouGalileoGPS', 29), ('gnssBeidouGalileoGlonassReserved', \n 30), ('gnssBeidouGalileoGlonassGPSReserved', 31), ('notApplicable',\n 128))\n\n\nclass GNSSPositionMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<assignment token>\n<code token>\n<class token>\n<class token>\n\n\nclass ONVALUETYPE(Integer32):\n <assignment token>\n <assignment token>\n\n\nclass ACTIONONLY(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('apply', 1), ('nonapply', 2))\n\n\nclass OPMODETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\nclass ACTIVEVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('active', 1), ('inactive', 2))\n\n\nclass YESVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('yes', 1), ('no', 2))\n\n\nclass OKVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('ok', 1), ('fault', 2))\n\n\nclass VALIDTYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 3))\n namedValues = NamedValues(('valid', 1), ('invalid', 2), ('nurture', 3))\n\n\nclass GNSSHealthStatus(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('healthy', 1), ('unhealthy', 2))\n\n\nclass GNSSReceiverMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 4, 5, 17, 18, 19, 20, 21, 22, 23, 24, \n 25, 26, 27, 28, 29, 30, 31, 128))\n namedValues = NamedValues(('beidou', 1), ('gps', 2), ('priorityBeidou',\n 4), ('priorityGps', 5), ('gnssGPS', 17), ('gnssGlonass', 18), (\n 'gnssGPSGlonass', 19), ('gnssGalileo', 20), ('gnssGPSGalileo', 21),\n ('gnssGlonassGalileo', 22), ('gnssGPSGlonassGalileo', 23), (\n 'gnssBeidou', 24), ('gnssBeidouGPS', 25), ('gnssBeidouGlonass', 26),\n ('gnssBeidouGlonassGPSReserved', 27), ('gnssBeidouGalileo', 28), (\n 'gnssBeidouGalileoGPS', 29), ('gnssBeidouGalileoGlonassReserved', \n 30), ('gnssBeidouGalileoGlonassGPSReserved', 31), ('notApplicable',\n 128))\n\n\nclass GNSSPositionMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<assignment token>\n<code token>\n<class token>\n<class token>\n<class token>\n\n\nclass ACTIONONLY(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('apply', 1), ('nonapply', 2))\n\n\nclass OPMODETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\nclass ACTIVEVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('active', 1), ('inactive', 2))\n\n\nclass YESVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('yes', 1), ('no', 2))\n\n\nclass OKVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('ok', 1), ('fault', 2))\n\n\nclass VALIDTYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 3))\n namedValues = NamedValues(('valid', 1), ('invalid', 2), ('nurture', 3))\n\n\nclass GNSSHealthStatus(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('healthy', 1), ('unhealthy', 2))\n\n\nclass GNSSReceiverMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 4, 5, 17, 18, 19, 20, 21, 22, 23, 24, \n 25, 26, 27, 28, 29, 30, 31, 128))\n namedValues = NamedValues(('beidou', 1), ('gps', 2), ('priorityBeidou',\n 4), ('priorityGps', 5), ('gnssGPS', 17), ('gnssGlonass', 18), (\n 'gnssGPSGlonass', 19), ('gnssGalileo', 20), ('gnssGPSGalileo', 21),\n ('gnssGlonassGalileo', 22), ('gnssGPSGlonassGalileo', 23), (\n 'gnssBeidou', 24), ('gnssBeidouGPS', 25), ('gnssBeidouGlonass', 26),\n ('gnssBeidouGlonassGPSReserved', 27), ('gnssBeidouGalileo', 28), (\n 'gnssBeidouGalileoGPS', 29), ('gnssBeidouGalileoGlonassReserved', \n 30), ('gnssBeidouGalileoGlonassGPSReserved', 31), ('notApplicable',\n 128))\n\n\nclass GNSSPositionMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<assignment token>\n<code token>\n<class token>\n<class token>\n<class token>\n\n\nclass ACTIONONLY(Integer32):\n <assignment token>\n <assignment token>\n\n\nclass OPMODETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\nclass ACTIVEVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('active', 1), ('inactive', 2))\n\n\nclass YESVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('yes', 1), ('no', 2))\n\n\nclass OKVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('ok', 1), ('fault', 2))\n\n\nclass VALIDTYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 3))\n namedValues = NamedValues(('valid', 1), ('invalid', 2), ('nurture', 3))\n\n\nclass GNSSHealthStatus(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('healthy', 1), ('unhealthy', 2))\n\n\nclass GNSSReceiverMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 4, 5, 17, 18, 19, 20, 21, 22, 23, 24, \n 25, 26, 27, 28, 29, 30, 31, 128))\n namedValues = NamedValues(('beidou', 1), ('gps', 2), ('priorityBeidou',\n 4), ('priorityGps', 5), ('gnssGPS', 17), ('gnssGlonass', 18), (\n 'gnssGPSGlonass', 19), ('gnssGalileo', 20), ('gnssGPSGalileo', 21),\n ('gnssGlonassGalileo', 22), ('gnssGPSGlonassGalileo', 23), (\n 'gnssBeidou', 24), ('gnssBeidouGPS', 25), ('gnssBeidouGlonass', 26),\n ('gnssBeidouGlonassGPSReserved', 27), ('gnssBeidouGalileo', 28), (\n 'gnssBeidouGalileoGPS', 29), ('gnssBeidouGalileoGlonassReserved', \n 30), ('gnssBeidouGalileoGlonassGPSReserved', 31), ('notApplicable',\n 128))\n\n\nclass GNSSPositionMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<assignment token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass OPMODETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\nclass ACTIVEVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('active', 1), ('inactive', 2))\n\n\nclass YESVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('yes', 1), ('no', 2))\n\n\nclass OKVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('ok', 1), ('fault', 2))\n\n\nclass VALIDTYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 3))\n namedValues = NamedValues(('valid', 1), ('invalid', 2), ('nurture', 3))\n\n\nclass GNSSHealthStatus(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('healthy', 1), ('unhealthy', 2))\n\n\nclass GNSSReceiverMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 4, 5, 17, 18, 19, 20, 21, 22, 23, 24, \n 25, 26, 27, 28, 29, 30, 31, 128))\n namedValues = NamedValues(('beidou', 1), ('gps', 2), ('priorityBeidou',\n 4), ('priorityGps', 5), ('gnssGPS', 17), ('gnssGlonass', 18), (\n 'gnssGPSGlonass', 19), ('gnssGalileo', 20), ('gnssGPSGalileo', 21),\n ('gnssGlonassGalileo', 22), ('gnssGPSGlonassGalileo', 23), (\n 'gnssBeidou', 24), ('gnssBeidouGPS', 25), ('gnssBeidouGlonass', 26),\n ('gnssBeidouGlonassGPSReserved', 27), ('gnssBeidouGalileo', 28), (\n 'gnssBeidouGalileoGPS', 29), ('gnssBeidouGalileoGlonassReserved', \n 30), ('gnssBeidouGalileoGlonassGPSReserved', 31), ('notApplicable',\n 128))\n\n\nclass GNSSPositionMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<assignment token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass OPMODETYPE(Integer32):\n <assignment token>\n <assignment token>\n\n\nclass ACTIVEVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('active', 1), ('inactive', 2))\n\n\nclass YESVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('yes', 1), ('no', 2))\n\n\nclass OKVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('ok', 1), ('fault', 2))\n\n\nclass VALIDTYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 3))\n namedValues = NamedValues(('valid', 1), ('invalid', 2), ('nurture', 3))\n\n\nclass GNSSHealthStatus(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('healthy', 1), ('unhealthy', 2))\n\n\nclass GNSSReceiverMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 4, 5, 17, 18, 19, 20, 21, 22, 23, 24, \n 25, 26, 27, 28, 29, 30, 31, 128))\n namedValues = NamedValues(('beidou', 1), ('gps', 2), ('priorityBeidou',\n 4), ('priorityGps', 5), ('gnssGPS', 17), ('gnssGlonass', 18), (\n 'gnssGPSGlonass', 19), ('gnssGalileo', 20), ('gnssGPSGalileo', 21),\n ('gnssGlonassGalileo', 22), ('gnssGPSGlonassGalileo', 23), (\n 'gnssBeidou', 24), ('gnssBeidouGPS', 25), ('gnssBeidouGlonass', 26),\n ('gnssBeidouGlonassGPSReserved', 27), ('gnssBeidouGalileo', 28), (\n 'gnssBeidouGalileoGPS', 29), ('gnssBeidouGalileoGlonassReserved', \n 30), ('gnssBeidouGalileoGlonassGPSReserved', 31), ('notApplicable',\n 128))\n\n\nclass GNSSPositionMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<assignment token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass ACTIVEVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('active', 1), ('inactive', 2))\n\n\nclass YESVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('yes', 1), ('no', 2))\n\n\nclass OKVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('ok', 1), ('fault', 2))\n\n\nclass VALIDTYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 3))\n namedValues = NamedValues(('valid', 1), ('invalid', 2), ('nurture', 3))\n\n\nclass GNSSHealthStatus(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('healthy', 1), ('unhealthy', 2))\n\n\nclass GNSSReceiverMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 4, 5, 17, 18, 19, 20, 21, 22, 23, 24, \n 25, 26, 27, 28, 29, 30, 31, 128))\n namedValues = NamedValues(('beidou', 1), ('gps', 2), ('priorityBeidou',\n 4), ('priorityGps', 5), ('gnssGPS', 17), ('gnssGlonass', 18), (\n 'gnssGPSGlonass', 19), ('gnssGalileo', 20), ('gnssGPSGalileo', 21),\n ('gnssGlonassGalileo', 22), ('gnssGPSGlonassGalileo', 23), (\n 'gnssBeidou', 24), ('gnssBeidouGPS', 25), ('gnssBeidouGlonass', 26),\n ('gnssBeidouGlonassGPSReserved', 27), ('gnssBeidouGalileo', 28), (\n 'gnssBeidouGalileoGPS', 29), ('gnssBeidouGalileoGlonassReserved', \n 30), ('gnssBeidouGalileoGlonassGPSReserved', 31), ('notApplicable',\n 128))\n\n\nclass GNSSPositionMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<assignment token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass ACTIVEVALUETYPE(Integer32):\n <assignment token>\n <assignment token>\n\n\nclass YESVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('yes', 1), ('no', 2))\n\n\nclass OKVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('ok', 1), ('fault', 2))\n\n\nclass VALIDTYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 3))\n namedValues = NamedValues(('valid', 1), ('invalid', 2), ('nurture', 3))\n\n\nclass GNSSHealthStatus(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('healthy', 1), ('unhealthy', 2))\n\n\nclass GNSSReceiverMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 4, 5, 17, 18, 19, 20, 21, 22, 23, 24, \n 25, 26, 27, 28, 29, 30, 31, 128))\n namedValues = NamedValues(('beidou', 1), ('gps', 2), ('priorityBeidou',\n 4), ('priorityGps', 5), ('gnssGPS', 17), ('gnssGlonass', 18), (\n 'gnssGPSGlonass', 19), ('gnssGalileo', 20), ('gnssGPSGalileo', 21),\n ('gnssGlonassGalileo', 22), ('gnssGPSGlonassGalileo', 23), (\n 'gnssBeidou', 24), ('gnssBeidouGPS', 25), ('gnssBeidouGlonass', 26),\n ('gnssBeidouGlonassGPSReserved', 27), ('gnssBeidouGalileo', 28), (\n 'gnssBeidouGalileoGPS', 29), ('gnssBeidouGalileoGlonassReserved', \n 30), ('gnssBeidouGalileoGlonassGPSReserved', 31), ('notApplicable',\n 128))\n\n\nclass GNSSPositionMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<assignment token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass YESVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('yes', 1), ('no', 2))\n\n\nclass OKVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('ok', 1), ('fault', 2))\n\n\nclass VALIDTYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 3))\n namedValues = NamedValues(('valid', 1), ('invalid', 2), ('nurture', 3))\n\n\nclass GNSSHealthStatus(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('healthy', 1), ('unhealthy', 2))\n\n\nclass GNSSReceiverMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 4, 5, 17, 18, 19, 20, 21, 22, 23, 24, \n 25, 26, 27, 28, 29, 30, 31, 128))\n namedValues = NamedValues(('beidou', 1), ('gps', 2), ('priorityBeidou',\n 4), ('priorityGps', 5), ('gnssGPS', 17), ('gnssGlonass', 18), (\n 'gnssGPSGlonass', 19), ('gnssGalileo', 20), ('gnssGPSGalileo', 21),\n ('gnssGlonassGalileo', 22), ('gnssGPSGlonassGalileo', 23), (\n 'gnssBeidou', 24), ('gnssBeidouGPS', 25), ('gnssBeidouGlonass', 26),\n ('gnssBeidouGlonassGPSReserved', 27), ('gnssBeidouGalileo', 28), (\n 'gnssBeidouGalileoGPS', 29), ('gnssBeidouGalileoGlonassReserved', \n 30), ('gnssBeidouGalileoGlonassGPSReserved', 31), ('notApplicable',\n 128))\n\n\nclass GNSSPositionMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<assignment token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass YESVALUETYPE(Integer32):\n <assignment token>\n <assignment token>\n\n\nclass OKVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('ok', 1), ('fault', 2))\n\n\nclass VALIDTYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 3))\n namedValues = NamedValues(('valid', 1), ('invalid', 2), ('nurture', 3))\n\n\nclass GNSSHealthStatus(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('healthy', 1), ('unhealthy', 2))\n\n\nclass GNSSReceiverMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 4, 5, 17, 18, 19, 20, 21, 22, 23, 24, \n 25, 26, 27, 28, 29, 30, 31, 128))\n namedValues = NamedValues(('beidou', 1), ('gps', 2), ('priorityBeidou',\n 4), ('priorityGps', 5), ('gnssGPS', 17), ('gnssGlonass', 18), (\n 'gnssGPSGlonass', 19), ('gnssGalileo', 20), ('gnssGPSGalileo', 21),\n ('gnssGlonassGalileo', 22), ('gnssGPSGlonassGalileo', 23), (\n 'gnssBeidou', 24), ('gnssBeidouGPS', 25), ('gnssBeidouGlonass', 26),\n ('gnssBeidouGlonassGPSReserved', 27), ('gnssBeidouGalileo', 28), (\n 'gnssBeidouGalileoGPS', 29), ('gnssBeidouGalileoGlonassReserved', \n 30), ('gnssBeidouGalileoGlonassGPSReserved', 31), ('notApplicable',\n 128))\n\n\nclass GNSSPositionMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<assignment token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass OKVALUETYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('ok', 1), ('fault', 2))\n\n\nclass VALIDTYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 3))\n namedValues = NamedValues(('valid', 1), ('invalid', 2), ('nurture', 3))\n\n\nclass GNSSHealthStatus(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('healthy', 1), ('unhealthy', 2))\n\n\nclass GNSSReceiverMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 4, 5, 17, 18, 19, 20, 21, 22, 23, 24, \n 25, 26, 27, 28, 29, 30, 31, 128))\n namedValues = NamedValues(('beidou', 1), ('gps', 2), ('priorityBeidou',\n 4), ('priorityGps', 5), ('gnssGPS', 17), ('gnssGlonass', 18), (\n 'gnssGPSGlonass', 19), ('gnssGalileo', 20), ('gnssGPSGalileo', 21),\n ('gnssGlonassGalileo', 22), ('gnssGPSGlonassGalileo', 23), (\n 'gnssBeidou', 24), ('gnssBeidouGPS', 25), ('gnssBeidouGlonass', 26),\n ('gnssBeidouGlonassGPSReserved', 27), ('gnssBeidouGalileo', 28), (\n 'gnssBeidouGalileoGPS', 29), ('gnssBeidouGalileoGlonassReserved', \n 30), ('gnssBeidouGalileoGlonassGPSReserved', 31), ('notApplicable',\n 128))\n\n\nclass GNSSPositionMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<assignment token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass OKVALUETYPE(Integer32):\n <assignment token>\n <assignment token>\n\n\nclass VALIDTYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 3))\n namedValues = NamedValues(('valid', 1), ('invalid', 2), ('nurture', 3))\n\n\nclass GNSSHealthStatus(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('healthy', 1), ('unhealthy', 2))\n\n\nclass GNSSReceiverMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 4, 5, 17, 18, 19, 20, 21, 22, 23, 24, \n 25, 26, 27, 28, 29, 30, 31, 128))\n namedValues = NamedValues(('beidou', 1), ('gps', 2), ('priorityBeidou',\n 4), ('priorityGps', 5), ('gnssGPS', 17), ('gnssGlonass', 18), (\n 'gnssGPSGlonass', 19), ('gnssGalileo', 20), ('gnssGPSGalileo', 21),\n ('gnssGlonassGalileo', 22), ('gnssGPSGlonassGalileo', 23), (\n 'gnssBeidou', 24), ('gnssBeidouGPS', 25), ('gnssBeidouGlonass', 26),\n ('gnssBeidouGlonassGPSReserved', 27), ('gnssBeidouGalileo', 28), (\n 'gnssBeidouGalileoGPS', 29), ('gnssBeidouGalileoGlonassReserved', \n 30), ('gnssBeidouGalileoGlonassGPSReserved', 31), ('notApplicable',\n 128))\n\n\nclass GNSSPositionMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<assignment token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass VALIDTYPE(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 3))\n namedValues = NamedValues(('valid', 1), ('invalid', 2), ('nurture', 3))\n\n\nclass GNSSHealthStatus(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('healthy', 1), ('unhealthy', 2))\n\n\nclass GNSSReceiverMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 4, 5, 17, 18, 19, 20, 21, 22, 23, 24, \n 25, 26, 27, 28, 29, 30, 31, 128))\n namedValues = NamedValues(('beidou', 1), ('gps', 2), ('priorityBeidou',\n 4), ('priorityGps', 5), ('gnssGPS', 17), ('gnssGlonass', 18), (\n 'gnssGPSGlonass', 19), ('gnssGalileo', 20), ('gnssGPSGalileo', 21),\n ('gnssGlonassGalileo', 22), ('gnssGPSGlonassGalileo', 23), (\n 'gnssBeidou', 24), ('gnssBeidouGPS', 25), ('gnssBeidouGlonass', 26),\n ('gnssBeidouGlonassGPSReserved', 27), ('gnssBeidouGalileo', 28), (\n 'gnssBeidouGalileoGPS', 29), ('gnssBeidouGalileoGlonassReserved', \n 30), ('gnssBeidouGalileoGlonassGPSReserved', 31), ('notApplicable',\n 128))\n\n\nclass GNSSPositionMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<assignment token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass VALIDTYPE(Integer32):\n <assignment token>\n <assignment token>\n\n\nclass GNSSHealthStatus(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('healthy', 1), ('unhealthy', 2))\n\n\nclass GNSSReceiverMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 4, 5, 17, 18, 19, 20, 21, 22, 23, 24, \n 25, 26, 27, 28, 29, 30, 31, 128))\n namedValues = NamedValues(('beidou', 1), ('gps', 2), ('priorityBeidou',\n 4), ('priorityGps', 5), ('gnssGPS', 17), ('gnssGlonass', 18), (\n 'gnssGPSGlonass', 19), ('gnssGalileo', 20), ('gnssGPSGalileo', 21),\n ('gnssGlonassGalileo', 22), ('gnssGPSGlonassGalileo', 23), (\n 'gnssBeidou', 24), ('gnssBeidouGPS', 25), ('gnssBeidouGlonass', 26),\n ('gnssBeidouGlonassGPSReserved', 27), ('gnssBeidouGalileo', 28), (\n 'gnssBeidouGalileoGPS', 29), ('gnssBeidouGalileoGlonassReserved', \n 30), ('gnssBeidouGalileoGlonassGPSReserved', 31), ('notApplicable',\n 128))\n\n\nclass GNSSPositionMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<assignment token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass GNSSHealthStatus(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('healthy', 1), ('unhealthy', 2))\n\n\nclass GNSSReceiverMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 4, 5, 17, 18, 19, 20, 21, 22, 23, 24, \n 25, 26, 27, 28, 29, 30, 31, 128))\n namedValues = NamedValues(('beidou', 1), ('gps', 2), ('priorityBeidou',\n 4), ('priorityGps', 5), ('gnssGPS', 17), ('gnssGlonass', 18), (\n 'gnssGPSGlonass', 19), ('gnssGalileo', 20), ('gnssGPSGalileo', 21),\n ('gnssGlonassGalileo', 22), ('gnssGPSGlonassGalileo', 23), (\n 'gnssBeidou', 24), ('gnssBeidouGPS', 25), ('gnssBeidouGlonass', 26),\n ('gnssBeidouGlonassGPSReserved', 27), ('gnssBeidouGalileo', 28), (\n 'gnssBeidouGalileoGPS', 29), ('gnssBeidouGalileoGlonassReserved', \n 30), ('gnssBeidouGalileoGlonassGPSReserved', 31), ('notApplicable',\n 128))\n\n\nclass GNSSPositionMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<assignment token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass GNSSHealthStatus(Integer32):\n <assignment token>\n <assignment token>\n\n\nclass GNSSReceiverMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 4, 5, 17, 18, 19, 20, 21, 22, 23, 24, \n 25, 26, 27, 28, 29, 30, 31, 128))\n namedValues = NamedValues(('beidou', 1), ('gps', 2), ('priorityBeidou',\n 4), ('priorityGps', 5), ('gnssGPS', 17), ('gnssGlonass', 18), (\n 'gnssGPSGlonass', 19), ('gnssGalileo', 20), ('gnssGPSGalileo', 21),\n ('gnssGlonassGalileo', 22), ('gnssGPSGlonassGalileo', 23), (\n 'gnssBeidou', 24), ('gnssBeidouGPS', 25), ('gnssBeidouGlonass', 26),\n ('gnssBeidouGlonassGPSReserved', 27), ('gnssBeidouGalileo', 28), (\n 'gnssBeidouGalileoGPS', 29), ('gnssBeidouGalileoGlonassReserved', \n 30), ('gnssBeidouGalileoGlonassGPSReserved', 31), ('notApplicable',\n 128))\n\n\nclass GNSSPositionMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<assignment token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass GNSSReceiverMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2, 4, 5, 17, 18, 19, 20, 21, 22, 23, 24, \n 25, 26, 27, 28, 29, 30, 31, 128))\n namedValues = NamedValues(('beidou', 1), ('gps', 2), ('priorityBeidou',\n 4), ('priorityGps', 5), ('gnssGPS', 17), ('gnssGlonass', 18), (\n 'gnssGPSGlonass', 19), ('gnssGalileo', 20), ('gnssGPSGalileo', 21),\n ('gnssGlonassGalileo', 22), ('gnssGPSGlonassGalileo', 23), (\n 'gnssBeidou', 24), ('gnssBeidouGPS', 25), ('gnssBeidouGlonass', 26),\n ('gnssBeidouGlonassGPSReserved', 27), ('gnssBeidouGalileo', 28), (\n 'gnssBeidouGalileoGPS', 29), ('gnssBeidouGalileoGlonassReserved', \n 30), ('gnssBeidouGalileoGlonassGPSReserved', 31), ('notApplicable',\n 128))\n\n\nclass GNSSPositionMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<assignment token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass GNSSReceiverMode(Integer32):\n <assignment token>\n <assignment token>\n\n\nclass GNSSPositionMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<assignment token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass GNSSPositionMode(Integer32):\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(1, 2))\n namedValues = NamedValues(('auto', 1), ('manual', 2))\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<assignment token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass GNSSPositionMode(Integer32):\n <assignment token>\n <assignment token>\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<assignment token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
98,737
d2890366d81dd059db1d4686685032b1341b40e9
def maximumToys(prices, k): new_list = [] count = 0 for index in range(0, len(prices)): if k > prices[index] in prices: new_list.append(prices[index]) if sum(new_list) > k: for elements in range(0, len(new_list) - 1): count += 1 print(count) else: count += 1 print(count) if __name__ == '__main__': nk = input().split() n = int(nk[0]) k = int(nk[1]) prices = list(map(int, input().rstrip().split())) result = maximumToys(prices, k)
[ "def maximumToys(prices, k):\n new_list = []\n count = 0\n for index in range(0, len(prices)):\n if k > prices[index] in prices:\n new_list.append(prices[index])\n if sum(new_list) > k:\n for elements in range(0, len(new_list) - 1):\n count += 1\n print(count)\n else:\n count += 1\n print(count)\n\n\nif __name__ == '__main__':\n nk = input().split()\n\n n = int(nk[0])\n\n k = int(nk[1])\n\n prices = list(map(int, input().rstrip().split()))\n\n result = maximumToys(prices, k)\n", "def maximumToys(prices, k):\n new_list = []\n count = 0\n for index in range(0, len(prices)):\n if k > prices[index] in prices:\n new_list.append(prices[index])\n if sum(new_list) > k:\n for elements in range(0, len(new_list) - 1):\n count += 1\n print(count)\n else:\n count += 1\n print(count)\n\n\nif __name__ == '__main__':\n nk = input().split()\n n = int(nk[0])\n k = int(nk[1])\n prices = list(map(int, input().rstrip().split()))\n result = maximumToys(prices, k)\n", "def maximumToys(prices, k):\n new_list = []\n count = 0\n for index in range(0, len(prices)):\n if k > prices[index] in prices:\n new_list.append(prices[index])\n if sum(new_list) > k:\n for elements in range(0, len(new_list) - 1):\n count += 1\n print(count)\n else:\n count += 1\n print(count)\n\n\n<code token>\n", "<function token>\n<code token>\n" ]
false
98,738
0650005a61fb55c495f9411f6547c40b4afbdf99
# -*- coding: utf-8 -*- # Copyright © 2014, German Neuroinformatics Node (G-Node) # # All rights reserved. # # Redistribution and use in section and binary forms, with or without # modification, are permitted under the terms of the BSD License. See # LICENSE file in the root of the Project. import os import unittest import numpy as np import nixio as nix from .tmp import TempDir class TestTags(unittest.TestCase): def setUp(self): self.tmpdir = TempDir("tagtest") self.testfilename = os.path.join(self.tmpdir.path, "tagtest.nix") self.file = nix.File.open(self.testfilename, nix.FileMode.Overwrite) self.block = self.file.create_block("test block", "recordingsession") self.my_array = self.block.create_data_array("my array", "test", nix.DataType.Int16, (1, )) self.my_tag = self.block.create_tag( "my tag", "tag", [0] ) self.my_tag.references.append(self.my_array) self.your_array = self.block.create_data_array( "your array", "test", nix.DataType.Int16, (1, ) ) self.your_tag = self.block.create_tag( "your tag", "tag", [0] ) self.your_tag.references.append(self.your_array) def tearDown(self): del self.file.blocks[self.block.id] self.file.close() self.tmpdir.cleanup() def test_tag_eq(self): assert(self.my_tag == self.my_tag) assert(not self.my_tag == self.your_tag) assert(self.my_tag is not None) def test_tag_id(self): assert(self.my_tag.id is not None) def test_tag_name(self): assert(self.my_tag.name is not None) def test_tag_type(self): def set_none(): self.my_tag.type = None assert(self.my_tag.type is not None) self.assertRaises(Exception, set_none) self.my_tag.type = "foo type" assert(self.my_tag.type == "foo type") def test_tag_definition(self): assert(self.my_tag.definition is None) self.my_tag.definition = "definition" assert(self.my_tag.definition == "definition") self.my_tag.definition = None assert(self.my_tag.definition is None) def test_tag_timestamps(self): created_at = self.my_tag.created_at assert(created_at > 0) updated_at = self.my_tag.updated_at assert(updated_at > 0) self.my_tag.force_created_at(1403530068) assert(self.my_tag.created_at == 1403530068) def test_tag_units(self): assert(self.my_tag.units == ()) self.my_tag.units = ["mV", "ms"] assert(self.my_tag.units == ("mV", "ms")) self.my_tag.units = [] assert(self.my_tag.units == ()) def test_tag_position(self): assert(self.my_tag.position == (0, )) self.my_tag.position = (1.0, 2.0, 3.0) assert(self.my_tag.position == (1.0, 2.0, 3.0)) def test_tag_extent(self): assert(self.my_tag.extent == ()) self.my_tag.extent = (1.0, 2.0, 3.0) assert(self.my_tag.extent == (1.0, 2.0, 3.0)) self.my_tag.extent = [] assert(self.my_tag.extent == ()) def test_tag_references(self): assert(len(self.my_tag.references) == 1) self.assertRaises(TypeError, lambda _: self.my_tag.references.append(100)) reference1 = self.block.create_data_array("reference1", "stimuli", nix.DataType.Int16, (1, )) reference2 = self.block.create_data_array("reference2", "stimuli", nix.DataType.Int16, (1, )) self.my_tag.references.append(reference1) self.my_tag.references.append(reference2) assert(reference1.name in self.my_tag.references) assert(len(self.my_tag.references) == 3) assert(reference1 in self.my_tag.references) assert(reference2 in self.my_tag.references) # id and name access assert(reference1 == self.my_tag.references[reference1.name]) assert(reference1 == self.my_tag.references[reference1.id]) assert(reference2 == self.my_tag.references[reference2.name]) assert(reference2 == self.my_tag.references[reference2.id]) assert(reference1.name in self.my_tag.references) assert(reference2.name in self.my_tag.references) assert(reference1.id in self.my_tag.references) assert(reference2.id in self.my_tag.references) del self.my_tag.references[reference2] assert(self.my_array in self.my_tag.references) assert(reference1 in self.my_tag.references) del self.my_tag.references[reference1] assert(len(self.my_tag.references) == 1) def test_tag_features(self): assert(len(self.my_tag.features) == 0) data_array = self.block.create_data_array("feature", "stimuli", nix.DataType.Int16, (1, )) feature = self.my_tag.create_feature(data_array, nix.LinkType.Untagged) assert(len(self.my_tag.features) == 1) assert(feature in self.my_tag.features) assert(feature.id in self.my_tag.features) assert("notexist" not in self.my_tag.features) assert(feature.id == self.my_tag.features[0].id) assert(feature.id == self.my_tag.features[-1].id) # id and name access assert(feature.id == self.my_tag.features[feature.id].id) assert(feature.id == self.my_tag.features[data_array.id].id) assert(feature.id == self.my_tag.features[data_array.name].id) assert(data_array == self.my_tag.features[data_array.id].data) assert(data_array == self.my_tag.features[data_array.name].data) assert(data_array.id in self.my_tag.features) assert(data_array.name in self.my_tag.features) del self.my_tag.features[0] assert(len(self.my_tag.features) == 0) def test_tag_tagged_data(self): sample_iv = 1.0 ticks = [1.2, 2.3, 3.4, 4.5, 6.7] unit = "ms" pos = [0.0, 2.0, 3.4] ext = [0.0, 6.0, 2.3] units = ["none", "ms", "ms"] data = np.random.random((2, 10, 5)) da = self.block.create_data_array("dimtest", "test", data=data) setdim = da.append_set_dimension() setdim.labels = ["Label A", "Label B"] samdim = da.append_sampled_dimension(sample_iv) samdim.unit = unit randim = da.append_range_dimension(ticks) randim.unit = unit postag = self.block.create_tag("postag", "event", pos) postag.references.append(da) postag.units = units segtag = self.block.create_tag("region", "segment", pos) segtag.references.append(da) segtag.extent = ext segtag.units = units posdata = postag.tagged_data(0) assert(len(posdata.shape) == 3) assert(posdata.shape == (1, 1, 1)) segdata = segtag.tagged_data(0) assert(len(segdata.shape) == 3) assert(segdata.shape == (1, 7, 2)) # retrieve data by id and name posdata = postag.tagged_data(da.name) assert(len(posdata.shape) == 3) assert(posdata.shape == (1, 1, 1)) segdata = segtag.tagged_data(da.name) assert(len(segdata.shape) == 3) assert(segdata.shape == (1, 7, 2)) posdata = postag.tagged_data(da.id) assert(len(posdata.shape) == 3) assert(posdata.shape == (1, 1, 1)) segdata = segtag.tagged_data(da.id) assert(len(segdata.shape) == 3) assert(segdata.shape == (1, 7, 2)) def test_tag_feature_data(self): number_feat = self.block.create_data_array("number feature", "test", data=10.) ramp_data = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] ramp_feat = self.block.create_data_array("ramp feature", "test", data=np.asarray(ramp_data)) ramp_feat.label = "voltage" ramp_feat.unit = "mV" dim = ramp_feat.append_sampled_dimension(1.0) dim.unit = "ms" pos_tag = self.block.create_tag("feature test", "test", [5.0]) pos_tag.units = ["ms"] pos_tag.create_feature(number_feat, nix.LinkType.Untagged) pos_tag.create_feature(ramp_feat, nix.LinkType.Tagged) pos_tag.create_feature(ramp_feat, nix.LinkType.Untagged) assert(len(pos_tag.features) == 3) data1 = pos_tag.feature_data(0) data2 = pos_tag.feature_data(1) data3 = pos_tag.feature_data(2) assert(data1.size == 1) assert(data2.size == 1) assert(data3.size == len(ramp_data)) # make the tag pointing to a slice pos_tag.extent = [2.0] data1 = pos_tag.feature_data(0) data2 = pos_tag.feature_data(1) data3 = pos_tag.feature_data(2) assert(data1.size == 1) assert(data2.size == 3) assert(data3.size == len(ramp_data)) # get by name data1 = pos_tag.feature_data(number_feat.name) data2 = pos_tag.feature_data(ramp_feat.name) assert(data1.size == 1) assert(data2.size == 3)
[ "# -*- coding: utf-8 -*-\n# Copyright © 2014, German Neuroinformatics Node (G-Node)\n#\n# All rights reserved.\n#\n# Redistribution and use in section and binary forms, with or without\n# modification, are permitted under the terms of the BSD License. See\n# LICENSE file in the root of the Project.\nimport os\nimport unittest\nimport numpy as np\nimport nixio as nix\nfrom .tmp import TempDir\n\n\nclass TestTags(unittest.TestCase):\n\n def setUp(self):\n self.tmpdir = TempDir(\"tagtest\")\n self.testfilename = os.path.join(self.tmpdir.path, \"tagtest.nix\")\n self.file = nix.File.open(self.testfilename, nix.FileMode.Overwrite)\n self.block = self.file.create_block(\"test block\", \"recordingsession\")\n\n self.my_array = self.block.create_data_array(\"my array\", \"test\",\n nix.DataType.Int16, (1, ))\n self.my_tag = self.block.create_tag(\n \"my tag\", \"tag\", [0]\n )\n self.my_tag.references.append(self.my_array)\n\n self.your_array = self.block.create_data_array(\n \"your array\", \"test\", nix.DataType.Int16, (1, )\n )\n self.your_tag = self.block.create_tag(\n \"your tag\", \"tag\", [0]\n )\n self.your_tag.references.append(self.your_array)\n\n def tearDown(self):\n del self.file.blocks[self.block.id]\n self.file.close()\n self.tmpdir.cleanup()\n\n def test_tag_eq(self):\n assert(self.my_tag == self.my_tag)\n assert(not self.my_tag == self.your_tag)\n assert(self.my_tag is not None)\n\n def test_tag_id(self):\n assert(self.my_tag.id is not None)\n\n def test_tag_name(self):\n assert(self.my_tag.name is not None)\n\n def test_tag_type(self):\n def set_none():\n self.my_tag.type = None\n\n assert(self.my_tag.type is not None)\n self.assertRaises(Exception, set_none)\n\n self.my_tag.type = \"foo type\"\n assert(self.my_tag.type == \"foo type\")\n\n def test_tag_definition(self):\n assert(self.my_tag.definition is None)\n\n self.my_tag.definition = \"definition\"\n assert(self.my_tag.definition == \"definition\")\n\n self.my_tag.definition = None\n assert(self.my_tag.definition is None)\n\n def test_tag_timestamps(self):\n created_at = self.my_tag.created_at\n assert(created_at > 0)\n\n updated_at = self.my_tag.updated_at\n assert(updated_at > 0)\n\n self.my_tag.force_created_at(1403530068)\n assert(self.my_tag.created_at == 1403530068)\n\n def test_tag_units(self):\n assert(self.my_tag.units == ())\n\n self.my_tag.units = [\"mV\", \"ms\"]\n assert(self.my_tag.units == (\"mV\", \"ms\"))\n\n self.my_tag.units = []\n assert(self.my_tag.units == ())\n\n def test_tag_position(self):\n assert(self.my_tag.position == (0, ))\n\n self.my_tag.position = (1.0, 2.0, 3.0)\n assert(self.my_tag.position == (1.0, 2.0, 3.0))\n\n def test_tag_extent(self):\n assert(self.my_tag.extent == ())\n\n self.my_tag.extent = (1.0, 2.0, 3.0)\n assert(self.my_tag.extent == (1.0, 2.0, 3.0))\n\n self.my_tag.extent = []\n assert(self.my_tag.extent == ())\n\n def test_tag_references(self):\n assert(len(self.my_tag.references) == 1)\n\n self.assertRaises(TypeError,\n lambda _: self.my_tag.references.append(100))\n\n reference1 = self.block.create_data_array(\"reference1\", \"stimuli\",\n nix.DataType.Int16, (1, ))\n reference2 = self.block.create_data_array(\"reference2\", \"stimuli\",\n nix.DataType.Int16, (1, ))\n\n self.my_tag.references.append(reference1)\n self.my_tag.references.append(reference2)\n\n assert(reference1.name in self.my_tag.references)\n\n assert(len(self.my_tag.references) == 3)\n assert(reference1 in self.my_tag.references)\n assert(reference2 in self.my_tag.references)\n\n # id and name access\n assert(reference1 == self.my_tag.references[reference1.name])\n assert(reference1 == self.my_tag.references[reference1.id])\n assert(reference2 == self.my_tag.references[reference2.name])\n assert(reference2 == self.my_tag.references[reference2.id])\n\n assert(reference1.name in self.my_tag.references)\n assert(reference2.name in self.my_tag.references)\n assert(reference1.id in self.my_tag.references)\n assert(reference2.id in self.my_tag.references)\n\n del self.my_tag.references[reference2]\n assert(self.my_array in self.my_tag.references)\n assert(reference1 in self.my_tag.references)\n\n del self.my_tag.references[reference1]\n assert(len(self.my_tag.references) == 1)\n\n def test_tag_features(self):\n assert(len(self.my_tag.features) == 0)\n\n data_array = self.block.create_data_array(\"feature\", \"stimuli\",\n nix.DataType.Int16, (1, ))\n feature = self.my_tag.create_feature(data_array, nix.LinkType.Untagged)\n\n assert(len(self.my_tag.features) == 1)\n\n assert(feature in self.my_tag.features)\n assert(feature.id in self.my_tag.features)\n assert(\"notexist\" not in self.my_tag.features)\n\n assert(feature.id == self.my_tag.features[0].id)\n assert(feature.id == self.my_tag.features[-1].id)\n\n # id and name access\n assert(feature.id == self.my_tag.features[feature.id].id)\n assert(feature.id == self.my_tag.features[data_array.id].id)\n assert(feature.id == self.my_tag.features[data_array.name].id)\n assert(data_array == self.my_tag.features[data_array.id].data)\n assert(data_array == self.my_tag.features[data_array.name].data)\n\n assert(data_array.id in self.my_tag.features)\n assert(data_array.name in self.my_tag.features)\n\n del self.my_tag.features[0]\n\n assert(len(self.my_tag.features) == 0)\n\n def test_tag_tagged_data(self):\n sample_iv = 1.0\n ticks = [1.2, 2.3, 3.4, 4.5, 6.7]\n unit = \"ms\"\n pos = [0.0, 2.0, 3.4]\n ext = [0.0, 6.0, 2.3]\n units = [\"none\", \"ms\", \"ms\"]\n data = np.random.random((2, 10, 5))\n da = self.block.create_data_array(\"dimtest\", \"test\",\n data=data)\n setdim = da.append_set_dimension()\n setdim.labels = [\"Label A\", \"Label B\"]\n samdim = da.append_sampled_dimension(sample_iv)\n samdim.unit = unit\n randim = da.append_range_dimension(ticks)\n randim.unit = unit\n\n postag = self.block.create_tag(\"postag\", \"event\", pos)\n postag.references.append(da)\n postag.units = units\n\n segtag = self.block.create_tag(\"region\", \"segment\", pos)\n segtag.references.append(da)\n segtag.extent = ext\n segtag.units = units\n\n posdata = postag.tagged_data(0)\n assert(len(posdata.shape) == 3)\n assert(posdata.shape == (1, 1, 1))\n\n segdata = segtag.tagged_data(0)\n assert(len(segdata.shape) == 3)\n assert(segdata.shape == (1, 7, 2))\n\n # retrieve data by id and name\n posdata = postag.tagged_data(da.name)\n assert(len(posdata.shape) == 3)\n assert(posdata.shape == (1, 1, 1))\n segdata = segtag.tagged_data(da.name)\n assert(len(segdata.shape) == 3)\n assert(segdata.shape == (1, 7, 2))\n\n posdata = postag.tagged_data(da.id)\n assert(len(posdata.shape) == 3)\n assert(posdata.shape == (1, 1, 1))\n segdata = segtag.tagged_data(da.id)\n assert(len(segdata.shape) == 3)\n assert(segdata.shape == (1, 7, 2))\n\n def test_tag_feature_data(self):\n number_feat = self.block.create_data_array(\"number feature\", \"test\",\n data=10.)\n ramp_data = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n ramp_feat = self.block.create_data_array(\"ramp feature\", \"test\",\n data=np.asarray(ramp_data))\n ramp_feat.label = \"voltage\"\n ramp_feat.unit = \"mV\"\n dim = ramp_feat.append_sampled_dimension(1.0)\n dim.unit = \"ms\"\n\n pos_tag = self.block.create_tag(\"feature test\", \"test\", [5.0])\n pos_tag.units = [\"ms\"]\n\n pos_tag.create_feature(number_feat, nix.LinkType.Untagged)\n pos_tag.create_feature(ramp_feat, nix.LinkType.Tagged)\n pos_tag.create_feature(ramp_feat, nix.LinkType.Untagged)\n assert(len(pos_tag.features) == 3)\n\n data1 = pos_tag.feature_data(0)\n data2 = pos_tag.feature_data(1)\n data3 = pos_tag.feature_data(2)\n\n assert(data1.size == 1)\n assert(data2.size == 1)\n assert(data3.size == len(ramp_data))\n\n # make the tag pointing to a slice\n pos_tag.extent = [2.0]\n data1 = pos_tag.feature_data(0)\n data2 = pos_tag.feature_data(1)\n data3 = pos_tag.feature_data(2)\n\n assert(data1.size == 1)\n assert(data2.size == 3)\n assert(data3.size == len(ramp_data))\n\n # get by name\n data1 = pos_tag.feature_data(number_feat.name)\n data2 = pos_tag.feature_data(ramp_feat.name)\n\n assert(data1.size == 1)\n assert(data2.size == 3)\n", "import os\nimport unittest\nimport numpy as np\nimport nixio as nix\nfrom .tmp import TempDir\n\n\nclass TestTags(unittest.TestCase):\n\n def setUp(self):\n self.tmpdir = TempDir('tagtest')\n self.testfilename = os.path.join(self.tmpdir.path, 'tagtest.nix')\n self.file = nix.File.open(self.testfilename, nix.FileMode.Overwrite)\n self.block = self.file.create_block('test block', 'recordingsession')\n self.my_array = self.block.create_data_array('my array', 'test',\n nix.DataType.Int16, (1,))\n self.my_tag = self.block.create_tag('my tag', 'tag', [0])\n self.my_tag.references.append(self.my_array)\n self.your_array = self.block.create_data_array('your array', 'test',\n nix.DataType.Int16, (1,))\n self.your_tag = self.block.create_tag('your tag', 'tag', [0])\n self.your_tag.references.append(self.your_array)\n\n def tearDown(self):\n del self.file.blocks[self.block.id]\n self.file.close()\n self.tmpdir.cleanup()\n\n def test_tag_eq(self):\n assert self.my_tag == self.my_tag\n assert not self.my_tag == self.your_tag\n assert self.my_tag is not None\n\n def test_tag_id(self):\n assert self.my_tag.id is not None\n\n def test_tag_name(self):\n assert self.my_tag.name is not None\n\n def test_tag_type(self):\n\n def set_none():\n self.my_tag.type = None\n assert self.my_tag.type is not None\n self.assertRaises(Exception, set_none)\n self.my_tag.type = 'foo type'\n assert self.my_tag.type == 'foo type'\n\n def test_tag_definition(self):\n assert self.my_tag.definition is None\n self.my_tag.definition = 'definition'\n assert self.my_tag.definition == 'definition'\n self.my_tag.definition = None\n assert self.my_tag.definition is None\n\n def test_tag_timestamps(self):\n created_at = self.my_tag.created_at\n assert created_at > 0\n updated_at = self.my_tag.updated_at\n assert updated_at > 0\n self.my_tag.force_created_at(1403530068)\n assert self.my_tag.created_at == 1403530068\n\n def test_tag_units(self):\n assert self.my_tag.units == ()\n self.my_tag.units = ['mV', 'ms']\n assert self.my_tag.units == ('mV', 'ms')\n self.my_tag.units = []\n assert self.my_tag.units == ()\n\n def test_tag_position(self):\n assert self.my_tag.position == (0,)\n self.my_tag.position = 1.0, 2.0, 3.0\n assert self.my_tag.position == (1.0, 2.0, 3.0)\n\n def test_tag_extent(self):\n assert self.my_tag.extent == ()\n self.my_tag.extent = 1.0, 2.0, 3.0\n assert self.my_tag.extent == (1.0, 2.0, 3.0)\n self.my_tag.extent = []\n assert self.my_tag.extent == ()\n\n def test_tag_references(self):\n assert len(self.my_tag.references) == 1\n self.assertRaises(TypeError, lambda _: self.my_tag.references.\n append(100))\n reference1 = self.block.create_data_array('reference1', 'stimuli',\n nix.DataType.Int16, (1,))\n reference2 = self.block.create_data_array('reference2', 'stimuli',\n nix.DataType.Int16, (1,))\n self.my_tag.references.append(reference1)\n self.my_tag.references.append(reference2)\n assert reference1.name in self.my_tag.references\n assert len(self.my_tag.references) == 3\n assert reference1 in self.my_tag.references\n assert reference2 in self.my_tag.references\n assert reference1 == self.my_tag.references[reference1.name]\n assert reference1 == self.my_tag.references[reference1.id]\n assert reference2 == self.my_tag.references[reference2.name]\n assert reference2 == self.my_tag.references[reference2.id]\n assert reference1.name in self.my_tag.references\n assert reference2.name in self.my_tag.references\n assert reference1.id in self.my_tag.references\n assert reference2.id in self.my_tag.references\n del self.my_tag.references[reference2]\n assert self.my_array in self.my_tag.references\n assert reference1 in self.my_tag.references\n del self.my_tag.references[reference1]\n assert len(self.my_tag.references) == 1\n\n def test_tag_features(self):\n assert len(self.my_tag.features) == 0\n data_array = self.block.create_data_array('feature', 'stimuli', nix\n .DataType.Int16, (1,))\n feature = self.my_tag.create_feature(data_array, nix.LinkType.Untagged)\n assert len(self.my_tag.features) == 1\n assert feature in self.my_tag.features\n assert feature.id in self.my_tag.features\n assert 'notexist' not in self.my_tag.features\n assert feature.id == self.my_tag.features[0].id\n assert feature.id == self.my_tag.features[-1].id\n assert feature.id == self.my_tag.features[feature.id].id\n assert feature.id == self.my_tag.features[data_array.id].id\n assert feature.id == self.my_tag.features[data_array.name].id\n assert data_array == self.my_tag.features[data_array.id].data\n assert data_array == self.my_tag.features[data_array.name].data\n assert data_array.id in self.my_tag.features\n assert data_array.name in self.my_tag.features\n del self.my_tag.features[0]\n assert len(self.my_tag.features) == 0\n\n def test_tag_tagged_data(self):\n sample_iv = 1.0\n ticks = [1.2, 2.3, 3.4, 4.5, 6.7]\n unit = 'ms'\n pos = [0.0, 2.0, 3.4]\n ext = [0.0, 6.0, 2.3]\n units = ['none', 'ms', 'ms']\n data = np.random.random((2, 10, 5))\n da = self.block.create_data_array('dimtest', 'test', data=data)\n setdim = da.append_set_dimension()\n setdim.labels = ['Label A', 'Label B']\n samdim = da.append_sampled_dimension(sample_iv)\n samdim.unit = unit\n randim = da.append_range_dimension(ticks)\n randim.unit = unit\n postag = self.block.create_tag('postag', 'event', pos)\n postag.references.append(da)\n postag.units = units\n segtag = self.block.create_tag('region', 'segment', pos)\n segtag.references.append(da)\n segtag.extent = ext\n segtag.units = units\n posdata = postag.tagged_data(0)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(0)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n posdata = postag.tagged_data(da.name)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(da.name)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n posdata = postag.tagged_data(da.id)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(da.id)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n\n def test_tag_feature_data(self):\n number_feat = self.block.create_data_array('number feature', 'test',\n data=10.0)\n ramp_data = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n ramp_feat = self.block.create_data_array('ramp feature', 'test',\n data=np.asarray(ramp_data))\n ramp_feat.label = 'voltage'\n ramp_feat.unit = 'mV'\n dim = ramp_feat.append_sampled_dimension(1.0)\n dim.unit = 'ms'\n pos_tag = self.block.create_tag('feature test', 'test', [5.0])\n pos_tag.units = ['ms']\n pos_tag.create_feature(number_feat, nix.LinkType.Untagged)\n pos_tag.create_feature(ramp_feat, nix.LinkType.Tagged)\n pos_tag.create_feature(ramp_feat, nix.LinkType.Untagged)\n assert len(pos_tag.features) == 3\n data1 = pos_tag.feature_data(0)\n data2 = pos_tag.feature_data(1)\n data3 = pos_tag.feature_data(2)\n assert data1.size == 1\n assert data2.size == 1\n assert data3.size == len(ramp_data)\n pos_tag.extent = [2.0]\n data1 = pos_tag.feature_data(0)\n data2 = pos_tag.feature_data(1)\n data3 = pos_tag.feature_data(2)\n assert data1.size == 1\n assert data2.size == 3\n assert data3.size == len(ramp_data)\n data1 = pos_tag.feature_data(number_feat.name)\n data2 = pos_tag.feature_data(ramp_feat.name)\n assert data1.size == 1\n assert data2.size == 3\n", "<import token>\n\n\nclass TestTags(unittest.TestCase):\n\n def setUp(self):\n self.tmpdir = TempDir('tagtest')\n self.testfilename = os.path.join(self.tmpdir.path, 'tagtest.nix')\n self.file = nix.File.open(self.testfilename, nix.FileMode.Overwrite)\n self.block = self.file.create_block('test block', 'recordingsession')\n self.my_array = self.block.create_data_array('my array', 'test',\n nix.DataType.Int16, (1,))\n self.my_tag = self.block.create_tag('my tag', 'tag', [0])\n self.my_tag.references.append(self.my_array)\n self.your_array = self.block.create_data_array('your array', 'test',\n nix.DataType.Int16, (1,))\n self.your_tag = self.block.create_tag('your tag', 'tag', [0])\n self.your_tag.references.append(self.your_array)\n\n def tearDown(self):\n del self.file.blocks[self.block.id]\n self.file.close()\n self.tmpdir.cleanup()\n\n def test_tag_eq(self):\n assert self.my_tag == self.my_tag\n assert not self.my_tag == self.your_tag\n assert self.my_tag is not None\n\n def test_tag_id(self):\n assert self.my_tag.id is not None\n\n def test_tag_name(self):\n assert self.my_tag.name is not None\n\n def test_tag_type(self):\n\n def set_none():\n self.my_tag.type = None\n assert self.my_tag.type is not None\n self.assertRaises(Exception, set_none)\n self.my_tag.type = 'foo type'\n assert self.my_tag.type == 'foo type'\n\n def test_tag_definition(self):\n assert self.my_tag.definition is None\n self.my_tag.definition = 'definition'\n assert self.my_tag.definition == 'definition'\n self.my_tag.definition = None\n assert self.my_tag.definition is None\n\n def test_tag_timestamps(self):\n created_at = self.my_tag.created_at\n assert created_at > 0\n updated_at = self.my_tag.updated_at\n assert updated_at > 0\n self.my_tag.force_created_at(1403530068)\n assert self.my_tag.created_at == 1403530068\n\n def test_tag_units(self):\n assert self.my_tag.units == ()\n self.my_tag.units = ['mV', 'ms']\n assert self.my_tag.units == ('mV', 'ms')\n self.my_tag.units = []\n assert self.my_tag.units == ()\n\n def test_tag_position(self):\n assert self.my_tag.position == (0,)\n self.my_tag.position = 1.0, 2.0, 3.0\n assert self.my_tag.position == (1.0, 2.0, 3.0)\n\n def test_tag_extent(self):\n assert self.my_tag.extent == ()\n self.my_tag.extent = 1.0, 2.0, 3.0\n assert self.my_tag.extent == (1.0, 2.0, 3.0)\n self.my_tag.extent = []\n assert self.my_tag.extent == ()\n\n def test_tag_references(self):\n assert len(self.my_tag.references) == 1\n self.assertRaises(TypeError, lambda _: self.my_tag.references.\n append(100))\n reference1 = self.block.create_data_array('reference1', 'stimuli',\n nix.DataType.Int16, (1,))\n reference2 = self.block.create_data_array('reference2', 'stimuli',\n nix.DataType.Int16, (1,))\n self.my_tag.references.append(reference1)\n self.my_tag.references.append(reference2)\n assert reference1.name in self.my_tag.references\n assert len(self.my_tag.references) == 3\n assert reference1 in self.my_tag.references\n assert reference2 in self.my_tag.references\n assert reference1 == self.my_tag.references[reference1.name]\n assert reference1 == self.my_tag.references[reference1.id]\n assert reference2 == self.my_tag.references[reference2.name]\n assert reference2 == self.my_tag.references[reference2.id]\n assert reference1.name in self.my_tag.references\n assert reference2.name in self.my_tag.references\n assert reference1.id in self.my_tag.references\n assert reference2.id in self.my_tag.references\n del self.my_tag.references[reference2]\n assert self.my_array in self.my_tag.references\n assert reference1 in self.my_tag.references\n del self.my_tag.references[reference1]\n assert len(self.my_tag.references) == 1\n\n def test_tag_features(self):\n assert len(self.my_tag.features) == 0\n data_array = self.block.create_data_array('feature', 'stimuli', nix\n .DataType.Int16, (1,))\n feature = self.my_tag.create_feature(data_array, nix.LinkType.Untagged)\n assert len(self.my_tag.features) == 1\n assert feature in self.my_tag.features\n assert feature.id in self.my_tag.features\n assert 'notexist' not in self.my_tag.features\n assert feature.id == self.my_tag.features[0].id\n assert feature.id == self.my_tag.features[-1].id\n assert feature.id == self.my_tag.features[feature.id].id\n assert feature.id == self.my_tag.features[data_array.id].id\n assert feature.id == self.my_tag.features[data_array.name].id\n assert data_array == self.my_tag.features[data_array.id].data\n assert data_array == self.my_tag.features[data_array.name].data\n assert data_array.id in self.my_tag.features\n assert data_array.name in self.my_tag.features\n del self.my_tag.features[0]\n assert len(self.my_tag.features) == 0\n\n def test_tag_tagged_data(self):\n sample_iv = 1.0\n ticks = [1.2, 2.3, 3.4, 4.5, 6.7]\n unit = 'ms'\n pos = [0.0, 2.0, 3.4]\n ext = [0.0, 6.0, 2.3]\n units = ['none', 'ms', 'ms']\n data = np.random.random((2, 10, 5))\n da = self.block.create_data_array('dimtest', 'test', data=data)\n setdim = da.append_set_dimension()\n setdim.labels = ['Label A', 'Label B']\n samdim = da.append_sampled_dimension(sample_iv)\n samdim.unit = unit\n randim = da.append_range_dimension(ticks)\n randim.unit = unit\n postag = self.block.create_tag('postag', 'event', pos)\n postag.references.append(da)\n postag.units = units\n segtag = self.block.create_tag('region', 'segment', pos)\n segtag.references.append(da)\n segtag.extent = ext\n segtag.units = units\n posdata = postag.tagged_data(0)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(0)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n posdata = postag.tagged_data(da.name)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(da.name)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n posdata = postag.tagged_data(da.id)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(da.id)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n\n def test_tag_feature_data(self):\n number_feat = self.block.create_data_array('number feature', 'test',\n data=10.0)\n ramp_data = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n ramp_feat = self.block.create_data_array('ramp feature', 'test',\n data=np.asarray(ramp_data))\n ramp_feat.label = 'voltage'\n ramp_feat.unit = 'mV'\n dim = ramp_feat.append_sampled_dimension(1.0)\n dim.unit = 'ms'\n pos_tag = self.block.create_tag('feature test', 'test', [5.0])\n pos_tag.units = ['ms']\n pos_tag.create_feature(number_feat, nix.LinkType.Untagged)\n pos_tag.create_feature(ramp_feat, nix.LinkType.Tagged)\n pos_tag.create_feature(ramp_feat, nix.LinkType.Untagged)\n assert len(pos_tag.features) == 3\n data1 = pos_tag.feature_data(0)\n data2 = pos_tag.feature_data(1)\n data3 = pos_tag.feature_data(2)\n assert data1.size == 1\n assert data2.size == 1\n assert data3.size == len(ramp_data)\n pos_tag.extent = [2.0]\n data1 = pos_tag.feature_data(0)\n data2 = pos_tag.feature_data(1)\n data3 = pos_tag.feature_data(2)\n assert data1.size == 1\n assert data2.size == 3\n assert data3.size == len(ramp_data)\n data1 = pos_tag.feature_data(number_feat.name)\n data2 = pos_tag.feature_data(ramp_feat.name)\n assert data1.size == 1\n assert data2.size == 3\n", "<import token>\n\n\nclass TestTags(unittest.TestCase):\n\n def setUp(self):\n self.tmpdir = TempDir('tagtest')\n self.testfilename = os.path.join(self.tmpdir.path, 'tagtest.nix')\n self.file = nix.File.open(self.testfilename, nix.FileMode.Overwrite)\n self.block = self.file.create_block('test block', 'recordingsession')\n self.my_array = self.block.create_data_array('my array', 'test',\n nix.DataType.Int16, (1,))\n self.my_tag = self.block.create_tag('my tag', 'tag', [0])\n self.my_tag.references.append(self.my_array)\n self.your_array = self.block.create_data_array('your array', 'test',\n nix.DataType.Int16, (1,))\n self.your_tag = self.block.create_tag('your tag', 'tag', [0])\n self.your_tag.references.append(self.your_array)\n\n def tearDown(self):\n del self.file.blocks[self.block.id]\n self.file.close()\n self.tmpdir.cleanup()\n\n def test_tag_eq(self):\n assert self.my_tag == self.my_tag\n assert not self.my_tag == self.your_tag\n assert self.my_tag is not None\n\n def test_tag_id(self):\n assert self.my_tag.id is not None\n\n def test_tag_name(self):\n assert self.my_tag.name is not None\n\n def test_tag_type(self):\n\n def set_none():\n self.my_tag.type = None\n assert self.my_tag.type is not None\n self.assertRaises(Exception, set_none)\n self.my_tag.type = 'foo type'\n assert self.my_tag.type == 'foo type'\n\n def test_tag_definition(self):\n assert self.my_tag.definition is None\n self.my_tag.definition = 'definition'\n assert self.my_tag.definition == 'definition'\n self.my_tag.definition = None\n assert self.my_tag.definition is None\n <function token>\n\n def test_tag_units(self):\n assert self.my_tag.units == ()\n self.my_tag.units = ['mV', 'ms']\n assert self.my_tag.units == ('mV', 'ms')\n self.my_tag.units = []\n assert self.my_tag.units == ()\n\n def test_tag_position(self):\n assert self.my_tag.position == (0,)\n self.my_tag.position = 1.0, 2.0, 3.0\n assert self.my_tag.position == (1.0, 2.0, 3.0)\n\n def test_tag_extent(self):\n assert self.my_tag.extent == ()\n self.my_tag.extent = 1.0, 2.0, 3.0\n assert self.my_tag.extent == (1.0, 2.0, 3.0)\n self.my_tag.extent = []\n assert self.my_tag.extent == ()\n\n def test_tag_references(self):\n assert len(self.my_tag.references) == 1\n self.assertRaises(TypeError, lambda _: self.my_tag.references.\n append(100))\n reference1 = self.block.create_data_array('reference1', 'stimuli',\n nix.DataType.Int16, (1,))\n reference2 = self.block.create_data_array('reference2', 'stimuli',\n nix.DataType.Int16, (1,))\n self.my_tag.references.append(reference1)\n self.my_tag.references.append(reference2)\n assert reference1.name in self.my_tag.references\n assert len(self.my_tag.references) == 3\n assert reference1 in self.my_tag.references\n assert reference2 in self.my_tag.references\n assert reference1 == self.my_tag.references[reference1.name]\n assert reference1 == self.my_tag.references[reference1.id]\n assert reference2 == self.my_tag.references[reference2.name]\n assert reference2 == self.my_tag.references[reference2.id]\n assert reference1.name in self.my_tag.references\n assert reference2.name in self.my_tag.references\n assert reference1.id in self.my_tag.references\n assert reference2.id in self.my_tag.references\n del self.my_tag.references[reference2]\n assert self.my_array in self.my_tag.references\n assert reference1 in self.my_tag.references\n del self.my_tag.references[reference1]\n assert len(self.my_tag.references) == 1\n\n def test_tag_features(self):\n assert len(self.my_tag.features) == 0\n data_array = self.block.create_data_array('feature', 'stimuli', nix\n .DataType.Int16, (1,))\n feature = self.my_tag.create_feature(data_array, nix.LinkType.Untagged)\n assert len(self.my_tag.features) == 1\n assert feature in self.my_tag.features\n assert feature.id in self.my_tag.features\n assert 'notexist' not in self.my_tag.features\n assert feature.id == self.my_tag.features[0].id\n assert feature.id == self.my_tag.features[-1].id\n assert feature.id == self.my_tag.features[feature.id].id\n assert feature.id == self.my_tag.features[data_array.id].id\n assert feature.id == self.my_tag.features[data_array.name].id\n assert data_array == self.my_tag.features[data_array.id].data\n assert data_array == self.my_tag.features[data_array.name].data\n assert data_array.id in self.my_tag.features\n assert data_array.name in self.my_tag.features\n del self.my_tag.features[0]\n assert len(self.my_tag.features) == 0\n\n def test_tag_tagged_data(self):\n sample_iv = 1.0\n ticks = [1.2, 2.3, 3.4, 4.5, 6.7]\n unit = 'ms'\n pos = [0.0, 2.0, 3.4]\n ext = [0.0, 6.0, 2.3]\n units = ['none', 'ms', 'ms']\n data = np.random.random((2, 10, 5))\n da = self.block.create_data_array('dimtest', 'test', data=data)\n setdim = da.append_set_dimension()\n setdim.labels = ['Label A', 'Label B']\n samdim = da.append_sampled_dimension(sample_iv)\n samdim.unit = unit\n randim = da.append_range_dimension(ticks)\n randim.unit = unit\n postag = self.block.create_tag('postag', 'event', pos)\n postag.references.append(da)\n postag.units = units\n segtag = self.block.create_tag('region', 'segment', pos)\n segtag.references.append(da)\n segtag.extent = ext\n segtag.units = units\n posdata = postag.tagged_data(0)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(0)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n posdata = postag.tagged_data(da.name)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(da.name)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n posdata = postag.tagged_data(da.id)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(da.id)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n\n def test_tag_feature_data(self):\n number_feat = self.block.create_data_array('number feature', 'test',\n data=10.0)\n ramp_data = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n ramp_feat = self.block.create_data_array('ramp feature', 'test',\n data=np.asarray(ramp_data))\n ramp_feat.label = 'voltage'\n ramp_feat.unit = 'mV'\n dim = ramp_feat.append_sampled_dimension(1.0)\n dim.unit = 'ms'\n pos_tag = self.block.create_tag('feature test', 'test', [5.0])\n pos_tag.units = ['ms']\n pos_tag.create_feature(number_feat, nix.LinkType.Untagged)\n pos_tag.create_feature(ramp_feat, nix.LinkType.Tagged)\n pos_tag.create_feature(ramp_feat, nix.LinkType.Untagged)\n assert len(pos_tag.features) == 3\n data1 = pos_tag.feature_data(0)\n data2 = pos_tag.feature_data(1)\n data3 = pos_tag.feature_data(2)\n assert data1.size == 1\n assert data2.size == 1\n assert data3.size == len(ramp_data)\n pos_tag.extent = [2.0]\n data1 = pos_tag.feature_data(0)\n data2 = pos_tag.feature_data(1)\n data3 = pos_tag.feature_data(2)\n assert data1.size == 1\n assert data2.size == 3\n assert data3.size == len(ramp_data)\n data1 = pos_tag.feature_data(number_feat.name)\n data2 = pos_tag.feature_data(ramp_feat.name)\n assert data1.size == 1\n assert data2.size == 3\n", "<import token>\n\n\nclass TestTags(unittest.TestCase):\n\n def setUp(self):\n self.tmpdir = TempDir('tagtest')\n self.testfilename = os.path.join(self.tmpdir.path, 'tagtest.nix')\n self.file = nix.File.open(self.testfilename, nix.FileMode.Overwrite)\n self.block = self.file.create_block('test block', 'recordingsession')\n self.my_array = self.block.create_data_array('my array', 'test',\n nix.DataType.Int16, (1,))\n self.my_tag = self.block.create_tag('my tag', 'tag', [0])\n self.my_tag.references.append(self.my_array)\n self.your_array = self.block.create_data_array('your array', 'test',\n nix.DataType.Int16, (1,))\n self.your_tag = self.block.create_tag('your tag', 'tag', [0])\n self.your_tag.references.append(self.your_array)\n\n def tearDown(self):\n del self.file.blocks[self.block.id]\n self.file.close()\n self.tmpdir.cleanup()\n\n def test_tag_eq(self):\n assert self.my_tag == self.my_tag\n assert not self.my_tag == self.your_tag\n assert self.my_tag is not None\n\n def test_tag_id(self):\n assert self.my_tag.id is not None\n\n def test_tag_name(self):\n assert self.my_tag.name is not None\n <function token>\n\n def test_tag_definition(self):\n assert self.my_tag.definition is None\n self.my_tag.definition = 'definition'\n assert self.my_tag.definition == 'definition'\n self.my_tag.definition = None\n assert self.my_tag.definition is None\n <function token>\n\n def test_tag_units(self):\n assert self.my_tag.units == ()\n self.my_tag.units = ['mV', 'ms']\n assert self.my_tag.units == ('mV', 'ms')\n self.my_tag.units = []\n assert self.my_tag.units == ()\n\n def test_tag_position(self):\n assert self.my_tag.position == (0,)\n self.my_tag.position = 1.0, 2.0, 3.0\n assert self.my_tag.position == (1.0, 2.0, 3.0)\n\n def test_tag_extent(self):\n assert self.my_tag.extent == ()\n self.my_tag.extent = 1.0, 2.0, 3.0\n assert self.my_tag.extent == (1.0, 2.0, 3.0)\n self.my_tag.extent = []\n assert self.my_tag.extent == ()\n\n def test_tag_references(self):\n assert len(self.my_tag.references) == 1\n self.assertRaises(TypeError, lambda _: self.my_tag.references.\n append(100))\n reference1 = self.block.create_data_array('reference1', 'stimuli',\n nix.DataType.Int16, (1,))\n reference2 = self.block.create_data_array('reference2', 'stimuli',\n nix.DataType.Int16, (1,))\n self.my_tag.references.append(reference1)\n self.my_tag.references.append(reference2)\n assert reference1.name in self.my_tag.references\n assert len(self.my_tag.references) == 3\n assert reference1 in self.my_tag.references\n assert reference2 in self.my_tag.references\n assert reference1 == self.my_tag.references[reference1.name]\n assert reference1 == self.my_tag.references[reference1.id]\n assert reference2 == self.my_tag.references[reference2.name]\n assert reference2 == self.my_tag.references[reference2.id]\n assert reference1.name in self.my_tag.references\n assert reference2.name in self.my_tag.references\n assert reference1.id in self.my_tag.references\n assert reference2.id in self.my_tag.references\n del self.my_tag.references[reference2]\n assert self.my_array in self.my_tag.references\n assert reference1 in self.my_tag.references\n del self.my_tag.references[reference1]\n assert len(self.my_tag.references) == 1\n\n def test_tag_features(self):\n assert len(self.my_tag.features) == 0\n data_array = self.block.create_data_array('feature', 'stimuli', nix\n .DataType.Int16, (1,))\n feature = self.my_tag.create_feature(data_array, nix.LinkType.Untagged)\n assert len(self.my_tag.features) == 1\n assert feature in self.my_tag.features\n assert feature.id in self.my_tag.features\n assert 'notexist' not in self.my_tag.features\n assert feature.id == self.my_tag.features[0].id\n assert feature.id == self.my_tag.features[-1].id\n assert feature.id == self.my_tag.features[feature.id].id\n assert feature.id == self.my_tag.features[data_array.id].id\n assert feature.id == self.my_tag.features[data_array.name].id\n assert data_array == self.my_tag.features[data_array.id].data\n assert data_array == self.my_tag.features[data_array.name].data\n assert data_array.id in self.my_tag.features\n assert data_array.name in self.my_tag.features\n del self.my_tag.features[0]\n assert len(self.my_tag.features) == 0\n\n def test_tag_tagged_data(self):\n sample_iv = 1.0\n ticks = [1.2, 2.3, 3.4, 4.5, 6.7]\n unit = 'ms'\n pos = [0.0, 2.0, 3.4]\n ext = [0.0, 6.0, 2.3]\n units = ['none', 'ms', 'ms']\n data = np.random.random((2, 10, 5))\n da = self.block.create_data_array('dimtest', 'test', data=data)\n setdim = da.append_set_dimension()\n setdim.labels = ['Label A', 'Label B']\n samdim = da.append_sampled_dimension(sample_iv)\n samdim.unit = unit\n randim = da.append_range_dimension(ticks)\n randim.unit = unit\n postag = self.block.create_tag('postag', 'event', pos)\n postag.references.append(da)\n postag.units = units\n segtag = self.block.create_tag('region', 'segment', pos)\n segtag.references.append(da)\n segtag.extent = ext\n segtag.units = units\n posdata = postag.tagged_data(0)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(0)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n posdata = postag.tagged_data(da.name)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(da.name)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n posdata = postag.tagged_data(da.id)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(da.id)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n\n def test_tag_feature_data(self):\n number_feat = self.block.create_data_array('number feature', 'test',\n data=10.0)\n ramp_data = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n ramp_feat = self.block.create_data_array('ramp feature', 'test',\n data=np.asarray(ramp_data))\n ramp_feat.label = 'voltage'\n ramp_feat.unit = 'mV'\n dim = ramp_feat.append_sampled_dimension(1.0)\n dim.unit = 'ms'\n pos_tag = self.block.create_tag('feature test', 'test', [5.0])\n pos_tag.units = ['ms']\n pos_tag.create_feature(number_feat, nix.LinkType.Untagged)\n pos_tag.create_feature(ramp_feat, nix.LinkType.Tagged)\n pos_tag.create_feature(ramp_feat, nix.LinkType.Untagged)\n assert len(pos_tag.features) == 3\n data1 = pos_tag.feature_data(0)\n data2 = pos_tag.feature_data(1)\n data3 = pos_tag.feature_data(2)\n assert data1.size == 1\n assert data2.size == 1\n assert data3.size == len(ramp_data)\n pos_tag.extent = [2.0]\n data1 = pos_tag.feature_data(0)\n data2 = pos_tag.feature_data(1)\n data3 = pos_tag.feature_data(2)\n assert data1.size == 1\n assert data2.size == 3\n assert data3.size == len(ramp_data)\n data1 = pos_tag.feature_data(number_feat.name)\n data2 = pos_tag.feature_data(ramp_feat.name)\n assert data1.size == 1\n assert data2.size == 3\n", "<import token>\n\n\nclass TestTags(unittest.TestCase):\n\n def setUp(self):\n self.tmpdir = TempDir('tagtest')\n self.testfilename = os.path.join(self.tmpdir.path, 'tagtest.nix')\n self.file = nix.File.open(self.testfilename, nix.FileMode.Overwrite)\n self.block = self.file.create_block('test block', 'recordingsession')\n self.my_array = self.block.create_data_array('my array', 'test',\n nix.DataType.Int16, (1,))\n self.my_tag = self.block.create_tag('my tag', 'tag', [0])\n self.my_tag.references.append(self.my_array)\n self.your_array = self.block.create_data_array('your array', 'test',\n nix.DataType.Int16, (1,))\n self.your_tag = self.block.create_tag('your tag', 'tag', [0])\n self.your_tag.references.append(self.your_array)\n\n def tearDown(self):\n del self.file.blocks[self.block.id]\n self.file.close()\n self.tmpdir.cleanup()\n\n def test_tag_eq(self):\n assert self.my_tag == self.my_tag\n assert not self.my_tag == self.your_tag\n assert self.my_tag is not None\n\n def test_tag_id(self):\n assert self.my_tag.id is not None\n\n def test_tag_name(self):\n assert self.my_tag.name is not None\n <function token>\n\n def test_tag_definition(self):\n assert self.my_tag.definition is None\n self.my_tag.definition = 'definition'\n assert self.my_tag.definition == 'definition'\n self.my_tag.definition = None\n assert self.my_tag.definition is None\n <function token>\n\n def test_tag_units(self):\n assert self.my_tag.units == ()\n self.my_tag.units = ['mV', 'ms']\n assert self.my_tag.units == ('mV', 'ms')\n self.my_tag.units = []\n assert self.my_tag.units == ()\n\n def test_tag_position(self):\n assert self.my_tag.position == (0,)\n self.my_tag.position = 1.0, 2.0, 3.0\n assert self.my_tag.position == (1.0, 2.0, 3.0)\n\n def test_tag_extent(self):\n assert self.my_tag.extent == ()\n self.my_tag.extent = 1.0, 2.0, 3.0\n assert self.my_tag.extent == (1.0, 2.0, 3.0)\n self.my_tag.extent = []\n assert self.my_tag.extent == ()\n <function token>\n\n def test_tag_features(self):\n assert len(self.my_tag.features) == 0\n data_array = self.block.create_data_array('feature', 'stimuli', nix\n .DataType.Int16, (1,))\n feature = self.my_tag.create_feature(data_array, nix.LinkType.Untagged)\n assert len(self.my_tag.features) == 1\n assert feature in self.my_tag.features\n assert feature.id in self.my_tag.features\n assert 'notexist' not in self.my_tag.features\n assert feature.id == self.my_tag.features[0].id\n assert feature.id == self.my_tag.features[-1].id\n assert feature.id == self.my_tag.features[feature.id].id\n assert feature.id == self.my_tag.features[data_array.id].id\n assert feature.id == self.my_tag.features[data_array.name].id\n assert data_array == self.my_tag.features[data_array.id].data\n assert data_array == self.my_tag.features[data_array.name].data\n assert data_array.id in self.my_tag.features\n assert data_array.name in self.my_tag.features\n del self.my_tag.features[0]\n assert len(self.my_tag.features) == 0\n\n def test_tag_tagged_data(self):\n sample_iv = 1.0\n ticks = [1.2, 2.3, 3.4, 4.5, 6.7]\n unit = 'ms'\n pos = [0.0, 2.0, 3.4]\n ext = [0.0, 6.0, 2.3]\n units = ['none', 'ms', 'ms']\n data = np.random.random((2, 10, 5))\n da = self.block.create_data_array('dimtest', 'test', data=data)\n setdim = da.append_set_dimension()\n setdim.labels = ['Label A', 'Label B']\n samdim = da.append_sampled_dimension(sample_iv)\n samdim.unit = unit\n randim = da.append_range_dimension(ticks)\n randim.unit = unit\n postag = self.block.create_tag('postag', 'event', pos)\n postag.references.append(da)\n postag.units = units\n segtag = self.block.create_tag('region', 'segment', pos)\n segtag.references.append(da)\n segtag.extent = ext\n segtag.units = units\n posdata = postag.tagged_data(0)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(0)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n posdata = postag.tagged_data(da.name)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(da.name)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n posdata = postag.tagged_data(da.id)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(da.id)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n\n def test_tag_feature_data(self):\n number_feat = self.block.create_data_array('number feature', 'test',\n data=10.0)\n ramp_data = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n ramp_feat = self.block.create_data_array('ramp feature', 'test',\n data=np.asarray(ramp_data))\n ramp_feat.label = 'voltage'\n ramp_feat.unit = 'mV'\n dim = ramp_feat.append_sampled_dimension(1.0)\n dim.unit = 'ms'\n pos_tag = self.block.create_tag('feature test', 'test', [5.0])\n pos_tag.units = ['ms']\n pos_tag.create_feature(number_feat, nix.LinkType.Untagged)\n pos_tag.create_feature(ramp_feat, nix.LinkType.Tagged)\n pos_tag.create_feature(ramp_feat, nix.LinkType.Untagged)\n assert len(pos_tag.features) == 3\n data1 = pos_tag.feature_data(0)\n data2 = pos_tag.feature_data(1)\n data3 = pos_tag.feature_data(2)\n assert data1.size == 1\n assert data2.size == 1\n assert data3.size == len(ramp_data)\n pos_tag.extent = [2.0]\n data1 = pos_tag.feature_data(0)\n data2 = pos_tag.feature_data(1)\n data3 = pos_tag.feature_data(2)\n assert data1.size == 1\n assert data2.size == 3\n assert data3.size == len(ramp_data)\n data1 = pos_tag.feature_data(number_feat.name)\n data2 = pos_tag.feature_data(ramp_feat.name)\n assert data1.size == 1\n assert data2.size == 3\n", "<import token>\n\n\nclass TestTags(unittest.TestCase):\n\n def setUp(self):\n self.tmpdir = TempDir('tagtest')\n self.testfilename = os.path.join(self.tmpdir.path, 'tagtest.nix')\n self.file = nix.File.open(self.testfilename, nix.FileMode.Overwrite)\n self.block = self.file.create_block('test block', 'recordingsession')\n self.my_array = self.block.create_data_array('my array', 'test',\n nix.DataType.Int16, (1,))\n self.my_tag = self.block.create_tag('my tag', 'tag', [0])\n self.my_tag.references.append(self.my_array)\n self.your_array = self.block.create_data_array('your array', 'test',\n nix.DataType.Int16, (1,))\n self.your_tag = self.block.create_tag('your tag', 'tag', [0])\n self.your_tag.references.append(self.your_array)\n\n def tearDown(self):\n del self.file.blocks[self.block.id]\n self.file.close()\n self.tmpdir.cleanup()\n\n def test_tag_eq(self):\n assert self.my_tag == self.my_tag\n assert not self.my_tag == self.your_tag\n assert self.my_tag is not None\n <function token>\n\n def test_tag_name(self):\n assert self.my_tag.name is not None\n <function token>\n\n def test_tag_definition(self):\n assert self.my_tag.definition is None\n self.my_tag.definition = 'definition'\n assert self.my_tag.definition == 'definition'\n self.my_tag.definition = None\n assert self.my_tag.definition is None\n <function token>\n\n def test_tag_units(self):\n assert self.my_tag.units == ()\n self.my_tag.units = ['mV', 'ms']\n assert self.my_tag.units == ('mV', 'ms')\n self.my_tag.units = []\n assert self.my_tag.units == ()\n\n def test_tag_position(self):\n assert self.my_tag.position == (0,)\n self.my_tag.position = 1.0, 2.0, 3.0\n assert self.my_tag.position == (1.0, 2.0, 3.0)\n\n def test_tag_extent(self):\n assert self.my_tag.extent == ()\n self.my_tag.extent = 1.0, 2.0, 3.0\n assert self.my_tag.extent == (1.0, 2.0, 3.0)\n self.my_tag.extent = []\n assert self.my_tag.extent == ()\n <function token>\n\n def test_tag_features(self):\n assert len(self.my_tag.features) == 0\n data_array = self.block.create_data_array('feature', 'stimuli', nix\n .DataType.Int16, (1,))\n feature = self.my_tag.create_feature(data_array, nix.LinkType.Untagged)\n assert len(self.my_tag.features) == 1\n assert feature in self.my_tag.features\n assert feature.id in self.my_tag.features\n assert 'notexist' not in self.my_tag.features\n assert feature.id == self.my_tag.features[0].id\n assert feature.id == self.my_tag.features[-1].id\n assert feature.id == self.my_tag.features[feature.id].id\n assert feature.id == self.my_tag.features[data_array.id].id\n assert feature.id == self.my_tag.features[data_array.name].id\n assert data_array == self.my_tag.features[data_array.id].data\n assert data_array == self.my_tag.features[data_array.name].data\n assert data_array.id in self.my_tag.features\n assert data_array.name in self.my_tag.features\n del self.my_tag.features[0]\n assert len(self.my_tag.features) == 0\n\n def test_tag_tagged_data(self):\n sample_iv = 1.0\n ticks = [1.2, 2.3, 3.4, 4.5, 6.7]\n unit = 'ms'\n pos = [0.0, 2.0, 3.4]\n ext = [0.0, 6.0, 2.3]\n units = ['none', 'ms', 'ms']\n data = np.random.random((2, 10, 5))\n da = self.block.create_data_array('dimtest', 'test', data=data)\n setdim = da.append_set_dimension()\n setdim.labels = ['Label A', 'Label B']\n samdim = da.append_sampled_dimension(sample_iv)\n samdim.unit = unit\n randim = da.append_range_dimension(ticks)\n randim.unit = unit\n postag = self.block.create_tag('postag', 'event', pos)\n postag.references.append(da)\n postag.units = units\n segtag = self.block.create_tag('region', 'segment', pos)\n segtag.references.append(da)\n segtag.extent = ext\n segtag.units = units\n posdata = postag.tagged_data(0)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(0)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n posdata = postag.tagged_data(da.name)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(da.name)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n posdata = postag.tagged_data(da.id)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(da.id)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n\n def test_tag_feature_data(self):\n number_feat = self.block.create_data_array('number feature', 'test',\n data=10.0)\n ramp_data = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n ramp_feat = self.block.create_data_array('ramp feature', 'test',\n data=np.asarray(ramp_data))\n ramp_feat.label = 'voltage'\n ramp_feat.unit = 'mV'\n dim = ramp_feat.append_sampled_dimension(1.0)\n dim.unit = 'ms'\n pos_tag = self.block.create_tag('feature test', 'test', [5.0])\n pos_tag.units = ['ms']\n pos_tag.create_feature(number_feat, nix.LinkType.Untagged)\n pos_tag.create_feature(ramp_feat, nix.LinkType.Tagged)\n pos_tag.create_feature(ramp_feat, nix.LinkType.Untagged)\n assert len(pos_tag.features) == 3\n data1 = pos_tag.feature_data(0)\n data2 = pos_tag.feature_data(1)\n data3 = pos_tag.feature_data(2)\n assert data1.size == 1\n assert data2.size == 1\n assert data3.size == len(ramp_data)\n pos_tag.extent = [2.0]\n data1 = pos_tag.feature_data(0)\n data2 = pos_tag.feature_data(1)\n data3 = pos_tag.feature_data(2)\n assert data1.size == 1\n assert data2.size == 3\n assert data3.size == len(ramp_data)\n data1 = pos_tag.feature_data(number_feat.name)\n data2 = pos_tag.feature_data(ramp_feat.name)\n assert data1.size == 1\n assert data2.size == 3\n", "<import token>\n\n\nclass TestTags(unittest.TestCase):\n <function token>\n\n def tearDown(self):\n del self.file.blocks[self.block.id]\n self.file.close()\n self.tmpdir.cleanup()\n\n def test_tag_eq(self):\n assert self.my_tag == self.my_tag\n assert not self.my_tag == self.your_tag\n assert self.my_tag is not None\n <function token>\n\n def test_tag_name(self):\n assert self.my_tag.name is not None\n <function token>\n\n def test_tag_definition(self):\n assert self.my_tag.definition is None\n self.my_tag.definition = 'definition'\n assert self.my_tag.definition == 'definition'\n self.my_tag.definition = None\n assert self.my_tag.definition is None\n <function token>\n\n def test_tag_units(self):\n assert self.my_tag.units == ()\n self.my_tag.units = ['mV', 'ms']\n assert self.my_tag.units == ('mV', 'ms')\n self.my_tag.units = []\n assert self.my_tag.units == ()\n\n def test_tag_position(self):\n assert self.my_tag.position == (0,)\n self.my_tag.position = 1.0, 2.0, 3.0\n assert self.my_tag.position == (1.0, 2.0, 3.0)\n\n def test_tag_extent(self):\n assert self.my_tag.extent == ()\n self.my_tag.extent = 1.0, 2.0, 3.0\n assert self.my_tag.extent == (1.0, 2.0, 3.0)\n self.my_tag.extent = []\n assert self.my_tag.extent == ()\n <function token>\n\n def test_tag_features(self):\n assert len(self.my_tag.features) == 0\n data_array = self.block.create_data_array('feature', 'stimuli', nix\n .DataType.Int16, (1,))\n feature = self.my_tag.create_feature(data_array, nix.LinkType.Untagged)\n assert len(self.my_tag.features) == 1\n assert feature in self.my_tag.features\n assert feature.id in self.my_tag.features\n assert 'notexist' not in self.my_tag.features\n assert feature.id == self.my_tag.features[0].id\n assert feature.id == self.my_tag.features[-1].id\n assert feature.id == self.my_tag.features[feature.id].id\n assert feature.id == self.my_tag.features[data_array.id].id\n assert feature.id == self.my_tag.features[data_array.name].id\n assert data_array == self.my_tag.features[data_array.id].data\n assert data_array == self.my_tag.features[data_array.name].data\n assert data_array.id in self.my_tag.features\n assert data_array.name in self.my_tag.features\n del self.my_tag.features[0]\n assert len(self.my_tag.features) == 0\n\n def test_tag_tagged_data(self):\n sample_iv = 1.0\n ticks = [1.2, 2.3, 3.4, 4.5, 6.7]\n unit = 'ms'\n pos = [0.0, 2.0, 3.4]\n ext = [0.0, 6.0, 2.3]\n units = ['none', 'ms', 'ms']\n data = np.random.random((2, 10, 5))\n da = self.block.create_data_array('dimtest', 'test', data=data)\n setdim = da.append_set_dimension()\n setdim.labels = ['Label A', 'Label B']\n samdim = da.append_sampled_dimension(sample_iv)\n samdim.unit = unit\n randim = da.append_range_dimension(ticks)\n randim.unit = unit\n postag = self.block.create_tag('postag', 'event', pos)\n postag.references.append(da)\n postag.units = units\n segtag = self.block.create_tag('region', 'segment', pos)\n segtag.references.append(da)\n segtag.extent = ext\n segtag.units = units\n posdata = postag.tagged_data(0)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(0)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n posdata = postag.tagged_data(da.name)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(da.name)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n posdata = postag.tagged_data(da.id)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(da.id)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n\n def test_tag_feature_data(self):\n number_feat = self.block.create_data_array('number feature', 'test',\n data=10.0)\n ramp_data = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n ramp_feat = self.block.create_data_array('ramp feature', 'test',\n data=np.asarray(ramp_data))\n ramp_feat.label = 'voltage'\n ramp_feat.unit = 'mV'\n dim = ramp_feat.append_sampled_dimension(1.0)\n dim.unit = 'ms'\n pos_tag = self.block.create_tag('feature test', 'test', [5.0])\n pos_tag.units = ['ms']\n pos_tag.create_feature(number_feat, nix.LinkType.Untagged)\n pos_tag.create_feature(ramp_feat, nix.LinkType.Tagged)\n pos_tag.create_feature(ramp_feat, nix.LinkType.Untagged)\n assert len(pos_tag.features) == 3\n data1 = pos_tag.feature_data(0)\n data2 = pos_tag.feature_data(1)\n data3 = pos_tag.feature_data(2)\n assert data1.size == 1\n assert data2.size == 1\n assert data3.size == len(ramp_data)\n pos_tag.extent = [2.0]\n data1 = pos_tag.feature_data(0)\n data2 = pos_tag.feature_data(1)\n data3 = pos_tag.feature_data(2)\n assert data1.size == 1\n assert data2.size == 3\n assert data3.size == len(ramp_data)\n data1 = pos_tag.feature_data(number_feat.name)\n data2 = pos_tag.feature_data(ramp_feat.name)\n assert data1.size == 1\n assert data2.size == 3\n", "<import token>\n\n\nclass TestTags(unittest.TestCase):\n <function token>\n\n def tearDown(self):\n del self.file.blocks[self.block.id]\n self.file.close()\n self.tmpdir.cleanup()\n <function token>\n <function token>\n\n def test_tag_name(self):\n assert self.my_tag.name is not None\n <function token>\n\n def test_tag_definition(self):\n assert self.my_tag.definition is None\n self.my_tag.definition = 'definition'\n assert self.my_tag.definition == 'definition'\n self.my_tag.definition = None\n assert self.my_tag.definition is None\n <function token>\n\n def test_tag_units(self):\n assert self.my_tag.units == ()\n self.my_tag.units = ['mV', 'ms']\n assert self.my_tag.units == ('mV', 'ms')\n self.my_tag.units = []\n assert self.my_tag.units == ()\n\n def test_tag_position(self):\n assert self.my_tag.position == (0,)\n self.my_tag.position = 1.0, 2.0, 3.0\n assert self.my_tag.position == (1.0, 2.0, 3.0)\n\n def test_tag_extent(self):\n assert self.my_tag.extent == ()\n self.my_tag.extent = 1.0, 2.0, 3.0\n assert self.my_tag.extent == (1.0, 2.0, 3.0)\n self.my_tag.extent = []\n assert self.my_tag.extent == ()\n <function token>\n\n def test_tag_features(self):\n assert len(self.my_tag.features) == 0\n data_array = self.block.create_data_array('feature', 'stimuli', nix\n .DataType.Int16, (1,))\n feature = self.my_tag.create_feature(data_array, nix.LinkType.Untagged)\n assert len(self.my_tag.features) == 1\n assert feature in self.my_tag.features\n assert feature.id in self.my_tag.features\n assert 'notexist' not in self.my_tag.features\n assert feature.id == self.my_tag.features[0].id\n assert feature.id == self.my_tag.features[-1].id\n assert feature.id == self.my_tag.features[feature.id].id\n assert feature.id == self.my_tag.features[data_array.id].id\n assert feature.id == self.my_tag.features[data_array.name].id\n assert data_array == self.my_tag.features[data_array.id].data\n assert data_array == self.my_tag.features[data_array.name].data\n assert data_array.id in self.my_tag.features\n assert data_array.name in self.my_tag.features\n del self.my_tag.features[0]\n assert len(self.my_tag.features) == 0\n\n def test_tag_tagged_data(self):\n sample_iv = 1.0\n ticks = [1.2, 2.3, 3.4, 4.5, 6.7]\n unit = 'ms'\n pos = [0.0, 2.0, 3.4]\n ext = [0.0, 6.0, 2.3]\n units = ['none', 'ms', 'ms']\n data = np.random.random((2, 10, 5))\n da = self.block.create_data_array('dimtest', 'test', data=data)\n setdim = da.append_set_dimension()\n setdim.labels = ['Label A', 'Label B']\n samdim = da.append_sampled_dimension(sample_iv)\n samdim.unit = unit\n randim = da.append_range_dimension(ticks)\n randim.unit = unit\n postag = self.block.create_tag('postag', 'event', pos)\n postag.references.append(da)\n postag.units = units\n segtag = self.block.create_tag('region', 'segment', pos)\n segtag.references.append(da)\n segtag.extent = ext\n segtag.units = units\n posdata = postag.tagged_data(0)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(0)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n posdata = postag.tagged_data(da.name)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(da.name)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n posdata = postag.tagged_data(da.id)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(da.id)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n\n def test_tag_feature_data(self):\n number_feat = self.block.create_data_array('number feature', 'test',\n data=10.0)\n ramp_data = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n ramp_feat = self.block.create_data_array('ramp feature', 'test',\n data=np.asarray(ramp_data))\n ramp_feat.label = 'voltage'\n ramp_feat.unit = 'mV'\n dim = ramp_feat.append_sampled_dimension(1.0)\n dim.unit = 'ms'\n pos_tag = self.block.create_tag('feature test', 'test', [5.0])\n pos_tag.units = ['ms']\n pos_tag.create_feature(number_feat, nix.LinkType.Untagged)\n pos_tag.create_feature(ramp_feat, nix.LinkType.Tagged)\n pos_tag.create_feature(ramp_feat, nix.LinkType.Untagged)\n assert len(pos_tag.features) == 3\n data1 = pos_tag.feature_data(0)\n data2 = pos_tag.feature_data(1)\n data3 = pos_tag.feature_data(2)\n assert data1.size == 1\n assert data2.size == 1\n assert data3.size == len(ramp_data)\n pos_tag.extent = [2.0]\n data1 = pos_tag.feature_data(0)\n data2 = pos_tag.feature_data(1)\n data3 = pos_tag.feature_data(2)\n assert data1.size == 1\n assert data2.size == 3\n assert data3.size == len(ramp_data)\n data1 = pos_tag.feature_data(number_feat.name)\n data2 = pos_tag.feature_data(ramp_feat.name)\n assert data1.size == 1\n assert data2.size == 3\n", "<import token>\n\n\nclass TestTags(unittest.TestCase):\n <function token>\n\n def tearDown(self):\n del self.file.blocks[self.block.id]\n self.file.close()\n self.tmpdir.cleanup()\n <function token>\n <function token>\n\n def test_tag_name(self):\n assert self.my_tag.name is not None\n <function token>\n\n def test_tag_definition(self):\n assert self.my_tag.definition is None\n self.my_tag.definition = 'definition'\n assert self.my_tag.definition == 'definition'\n self.my_tag.definition = None\n assert self.my_tag.definition is None\n <function token>\n <function token>\n\n def test_tag_position(self):\n assert self.my_tag.position == (0,)\n self.my_tag.position = 1.0, 2.0, 3.0\n assert self.my_tag.position == (1.0, 2.0, 3.0)\n\n def test_tag_extent(self):\n assert self.my_tag.extent == ()\n self.my_tag.extent = 1.0, 2.0, 3.0\n assert self.my_tag.extent == (1.0, 2.0, 3.0)\n self.my_tag.extent = []\n assert self.my_tag.extent == ()\n <function token>\n\n def test_tag_features(self):\n assert len(self.my_tag.features) == 0\n data_array = self.block.create_data_array('feature', 'stimuli', nix\n .DataType.Int16, (1,))\n feature = self.my_tag.create_feature(data_array, nix.LinkType.Untagged)\n assert len(self.my_tag.features) == 1\n assert feature in self.my_tag.features\n assert feature.id in self.my_tag.features\n assert 'notexist' not in self.my_tag.features\n assert feature.id == self.my_tag.features[0].id\n assert feature.id == self.my_tag.features[-1].id\n assert feature.id == self.my_tag.features[feature.id].id\n assert feature.id == self.my_tag.features[data_array.id].id\n assert feature.id == self.my_tag.features[data_array.name].id\n assert data_array == self.my_tag.features[data_array.id].data\n assert data_array == self.my_tag.features[data_array.name].data\n assert data_array.id in self.my_tag.features\n assert data_array.name in self.my_tag.features\n del self.my_tag.features[0]\n assert len(self.my_tag.features) == 0\n\n def test_tag_tagged_data(self):\n sample_iv = 1.0\n ticks = [1.2, 2.3, 3.4, 4.5, 6.7]\n unit = 'ms'\n pos = [0.0, 2.0, 3.4]\n ext = [0.0, 6.0, 2.3]\n units = ['none', 'ms', 'ms']\n data = np.random.random((2, 10, 5))\n da = self.block.create_data_array('dimtest', 'test', data=data)\n setdim = da.append_set_dimension()\n setdim.labels = ['Label A', 'Label B']\n samdim = da.append_sampled_dimension(sample_iv)\n samdim.unit = unit\n randim = da.append_range_dimension(ticks)\n randim.unit = unit\n postag = self.block.create_tag('postag', 'event', pos)\n postag.references.append(da)\n postag.units = units\n segtag = self.block.create_tag('region', 'segment', pos)\n segtag.references.append(da)\n segtag.extent = ext\n segtag.units = units\n posdata = postag.tagged_data(0)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(0)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n posdata = postag.tagged_data(da.name)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(da.name)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n posdata = postag.tagged_data(da.id)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(da.id)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n\n def test_tag_feature_data(self):\n number_feat = self.block.create_data_array('number feature', 'test',\n data=10.0)\n ramp_data = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n ramp_feat = self.block.create_data_array('ramp feature', 'test',\n data=np.asarray(ramp_data))\n ramp_feat.label = 'voltage'\n ramp_feat.unit = 'mV'\n dim = ramp_feat.append_sampled_dimension(1.0)\n dim.unit = 'ms'\n pos_tag = self.block.create_tag('feature test', 'test', [5.0])\n pos_tag.units = ['ms']\n pos_tag.create_feature(number_feat, nix.LinkType.Untagged)\n pos_tag.create_feature(ramp_feat, nix.LinkType.Tagged)\n pos_tag.create_feature(ramp_feat, nix.LinkType.Untagged)\n assert len(pos_tag.features) == 3\n data1 = pos_tag.feature_data(0)\n data2 = pos_tag.feature_data(1)\n data3 = pos_tag.feature_data(2)\n assert data1.size == 1\n assert data2.size == 1\n assert data3.size == len(ramp_data)\n pos_tag.extent = [2.0]\n data1 = pos_tag.feature_data(0)\n data2 = pos_tag.feature_data(1)\n data3 = pos_tag.feature_data(2)\n assert data1.size == 1\n assert data2.size == 3\n assert data3.size == len(ramp_data)\n data1 = pos_tag.feature_data(number_feat.name)\n data2 = pos_tag.feature_data(ramp_feat.name)\n assert data1.size == 1\n assert data2.size == 3\n", "<import token>\n\n\nclass TestTags(unittest.TestCase):\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_tag_name(self):\n assert self.my_tag.name is not None\n <function token>\n\n def test_tag_definition(self):\n assert self.my_tag.definition is None\n self.my_tag.definition = 'definition'\n assert self.my_tag.definition == 'definition'\n self.my_tag.definition = None\n assert self.my_tag.definition is None\n <function token>\n <function token>\n\n def test_tag_position(self):\n assert self.my_tag.position == (0,)\n self.my_tag.position = 1.0, 2.0, 3.0\n assert self.my_tag.position == (1.0, 2.0, 3.0)\n\n def test_tag_extent(self):\n assert self.my_tag.extent == ()\n self.my_tag.extent = 1.0, 2.0, 3.0\n assert self.my_tag.extent == (1.0, 2.0, 3.0)\n self.my_tag.extent = []\n assert self.my_tag.extent == ()\n <function token>\n\n def test_tag_features(self):\n assert len(self.my_tag.features) == 0\n data_array = self.block.create_data_array('feature', 'stimuli', nix\n .DataType.Int16, (1,))\n feature = self.my_tag.create_feature(data_array, nix.LinkType.Untagged)\n assert len(self.my_tag.features) == 1\n assert feature in self.my_tag.features\n assert feature.id in self.my_tag.features\n assert 'notexist' not in self.my_tag.features\n assert feature.id == self.my_tag.features[0].id\n assert feature.id == self.my_tag.features[-1].id\n assert feature.id == self.my_tag.features[feature.id].id\n assert feature.id == self.my_tag.features[data_array.id].id\n assert feature.id == self.my_tag.features[data_array.name].id\n assert data_array == self.my_tag.features[data_array.id].data\n assert data_array == self.my_tag.features[data_array.name].data\n assert data_array.id in self.my_tag.features\n assert data_array.name in self.my_tag.features\n del self.my_tag.features[0]\n assert len(self.my_tag.features) == 0\n\n def test_tag_tagged_data(self):\n sample_iv = 1.0\n ticks = [1.2, 2.3, 3.4, 4.5, 6.7]\n unit = 'ms'\n pos = [0.0, 2.0, 3.4]\n ext = [0.0, 6.0, 2.3]\n units = ['none', 'ms', 'ms']\n data = np.random.random((2, 10, 5))\n da = self.block.create_data_array('dimtest', 'test', data=data)\n setdim = da.append_set_dimension()\n setdim.labels = ['Label A', 'Label B']\n samdim = da.append_sampled_dimension(sample_iv)\n samdim.unit = unit\n randim = da.append_range_dimension(ticks)\n randim.unit = unit\n postag = self.block.create_tag('postag', 'event', pos)\n postag.references.append(da)\n postag.units = units\n segtag = self.block.create_tag('region', 'segment', pos)\n segtag.references.append(da)\n segtag.extent = ext\n segtag.units = units\n posdata = postag.tagged_data(0)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(0)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n posdata = postag.tagged_data(da.name)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(da.name)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n posdata = postag.tagged_data(da.id)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(da.id)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n\n def test_tag_feature_data(self):\n number_feat = self.block.create_data_array('number feature', 'test',\n data=10.0)\n ramp_data = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n ramp_feat = self.block.create_data_array('ramp feature', 'test',\n data=np.asarray(ramp_data))\n ramp_feat.label = 'voltage'\n ramp_feat.unit = 'mV'\n dim = ramp_feat.append_sampled_dimension(1.0)\n dim.unit = 'ms'\n pos_tag = self.block.create_tag('feature test', 'test', [5.0])\n pos_tag.units = ['ms']\n pos_tag.create_feature(number_feat, nix.LinkType.Untagged)\n pos_tag.create_feature(ramp_feat, nix.LinkType.Tagged)\n pos_tag.create_feature(ramp_feat, nix.LinkType.Untagged)\n assert len(pos_tag.features) == 3\n data1 = pos_tag.feature_data(0)\n data2 = pos_tag.feature_data(1)\n data3 = pos_tag.feature_data(2)\n assert data1.size == 1\n assert data2.size == 1\n assert data3.size == len(ramp_data)\n pos_tag.extent = [2.0]\n data1 = pos_tag.feature_data(0)\n data2 = pos_tag.feature_data(1)\n data3 = pos_tag.feature_data(2)\n assert data1.size == 1\n assert data2.size == 3\n assert data3.size == len(ramp_data)\n data1 = pos_tag.feature_data(number_feat.name)\n data2 = pos_tag.feature_data(ramp_feat.name)\n assert data1.size == 1\n assert data2.size == 3\n", "<import token>\n\n\nclass TestTags(unittest.TestCase):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_tag_definition(self):\n assert self.my_tag.definition is None\n self.my_tag.definition = 'definition'\n assert self.my_tag.definition == 'definition'\n self.my_tag.definition = None\n assert self.my_tag.definition is None\n <function token>\n <function token>\n\n def test_tag_position(self):\n assert self.my_tag.position == (0,)\n self.my_tag.position = 1.0, 2.0, 3.0\n assert self.my_tag.position == (1.0, 2.0, 3.0)\n\n def test_tag_extent(self):\n assert self.my_tag.extent == ()\n self.my_tag.extent = 1.0, 2.0, 3.0\n assert self.my_tag.extent == (1.0, 2.0, 3.0)\n self.my_tag.extent = []\n assert self.my_tag.extent == ()\n <function token>\n\n def test_tag_features(self):\n assert len(self.my_tag.features) == 0\n data_array = self.block.create_data_array('feature', 'stimuli', nix\n .DataType.Int16, (1,))\n feature = self.my_tag.create_feature(data_array, nix.LinkType.Untagged)\n assert len(self.my_tag.features) == 1\n assert feature in self.my_tag.features\n assert feature.id in self.my_tag.features\n assert 'notexist' not in self.my_tag.features\n assert feature.id == self.my_tag.features[0].id\n assert feature.id == self.my_tag.features[-1].id\n assert feature.id == self.my_tag.features[feature.id].id\n assert feature.id == self.my_tag.features[data_array.id].id\n assert feature.id == self.my_tag.features[data_array.name].id\n assert data_array == self.my_tag.features[data_array.id].data\n assert data_array == self.my_tag.features[data_array.name].data\n assert data_array.id in self.my_tag.features\n assert data_array.name in self.my_tag.features\n del self.my_tag.features[0]\n assert len(self.my_tag.features) == 0\n\n def test_tag_tagged_data(self):\n sample_iv = 1.0\n ticks = [1.2, 2.3, 3.4, 4.5, 6.7]\n unit = 'ms'\n pos = [0.0, 2.0, 3.4]\n ext = [0.0, 6.0, 2.3]\n units = ['none', 'ms', 'ms']\n data = np.random.random((2, 10, 5))\n da = self.block.create_data_array('dimtest', 'test', data=data)\n setdim = da.append_set_dimension()\n setdim.labels = ['Label A', 'Label B']\n samdim = da.append_sampled_dimension(sample_iv)\n samdim.unit = unit\n randim = da.append_range_dimension(ticks)\n randim.unit = unit\n postag = self.block.create_tag('postag', 'event', pos)\n postag.references.append(da)\n postag.units = units\n segtag = self.block.create_tag('region', 'segment', pos)\n segtag.references.append(da)\n segtag.extent = ext\n segtag.units = units\n posdata = postag.tagged_data(0)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(0)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n posdata = postag.tagged_data(da.name)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(da.name)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n posdata = postag.tagged_data(da.id)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(da.id)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n\n def test_tag_feature_data(self):\n number_feat = self.block.create_data_array('number feature', 'test',\n data=10.0)\n ramp_data = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n ramp_feat = self.block.create_data_array('ramp feature', 'test',\n data=np.asarray(ramp_data))\n ramp_feat.label = 'voltage'\n ramp_feat.unit = 'mV'\n dim = ramp_feat.append_sampled_dimension(1.0)\n dim.unit = 'ms'\n pos_tag = self.block.create_tag('feature test', 'test', [5.0])\n pos_tag.units = ['ms']\n pos_tag.create_feature(number_feat, nix.LinkType.Untagged)\n pos_tag.create_feature(ramp_feat, nix.LinkType.Tagged)\n pos_tag.create_feature(ramp_feat, nix.LinkType.Untagged)\n assert len(pos_tag.features) == 3\n data1 = pos_tag.feature_data(0)\n data2 = pos_tag.feature_data(1)\n data3 = pos_tag.feature_data(2)\n assert data1.size == 1\n assert data2.size == 1\n assert data3.size == len(ramp_data)\n pos_tag.extent = [2.0]\n data1 = pos_tag.feature_data(0)\n data2 = pos_tag.feature_data(1)\n data3 = pos_tag.feature_data(2)\n assert data1.size == 1\n assert data2.size == 3\n assert data3.size == len(ramp_data)\n data1 = pos_tag.feature_data(number_feat.name)\n data2 = pos_tag.feature_data(ramp_feat.name)\n assert data1.size == 1\n assert data2.size == 3\n", "<import token>\n\n\nclass TestTags(unittest.TestCase):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_tag_definition(self):\n assert self.my_tag.definition is None\n self.my_tag.definition = 'definition'\n assert self.my_tag.definition == 'definition'\n self.my_tag.definition = None\n assert self.my_tag.definition is None\n <function token>\n <function token>\n\n def test_tag_position(self):\n assert self.my_tag.position == (0,)\n self.my_tag.position = 1.0, 2.0, 3.0\n assert self.my_tag.position == (1.0, 2.0, 3.0)\n <function token>\n <function token>\n\n def test_tag_features(self):\n assert len(self.my_tag.features) == 0\n data_array = self.block.create_data_array('feature', 'stimuli', nix\n .DataType.Int16, (1,))\n feature = self.my_tag.create_feature(data_array, nix.LinkType.Untagged)\n assert len(self.my_tag.features) == 1\n assert feature in self.my_tag.features\n assert feature.id in self.my_tag.features\n assert 'notexist' not in self.my_tag.features\n assert feature.id == self.my_tag.features[0].id\n assert feature.id == self.my_tag.features[-1].id\n assert feature.id == self.my_tag.features[feature.id].id\n assert feature.id == self.my_tag.features[data_array.id].id\n assert feature.id == self.my_tag.features[data_array.name].id\n assert data_array == self.my_tag.features[data_array.id].data\n assert data_array == self.my_tag.features[data_array.name].data\n assert data_array.id in self.my_tag.features\n assert data_array.name in self.my_tag.features\n del self.my_tag.features[0]\n assert len(self.my_tag.features) == 0\n\n def test_tag_tagged_data(self):\n sample_iv = 1.0\n ticks = [1.2, 2.3, 3.4, 4.5, 6.7]\n unit = 'ms'\n pos = [0.0, 2.0, 3.4]\n ext = [0.0, 6.0, 2.3]\n units = ['none', 'ms', 'ms']\n data = np.random.random((2, 10, 5))\n da = self.block.create_data_array('dimtest', 'test', data=data)\n setdim = da.append_set_dimension()\n setdim.labels = ['Label A', 'Label B']\n samdim = da.append_sampled_dimension(sample_iv)\n samdim.unit = unit\n randim = da.append_range_dimension(ticks)\n randim.unit = unit\n postag = self.block.create_tag('postag', 'event', pos)\n postag.references.append(da)\n postag.units = units\n segtag = self.block.create_tag('region', 'segment', pos)\n segtag.references.append(da)\n segtag.extent = ext\n segtag.units = units\n posdata = postag.tagged_data(0)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(0)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n posdata = postag.tagged_data(da.name)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(da.name)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n posdata = postag.tagged_data(da.id)\n assert len(posdata.shape) == 3\n assert posdata.shape == (1, 1, 1)\n segdata = segtag.tagged_data(da.id)\n assert len(segdata.shape) == 3\n assert segdata.shape == (1, 7, 2)\n\n def test_tag_feature_data(self):\n number_feat = self.block.create_data_array('number feature', 'test',\n data=10.0)\n ramp_data = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n ramp_feat = self.block.create_data_array('ramp feature', 'test',\n data=np.asarray(ramp_data))\n ramp_feat.label = 'voltage'\n ramp_feat.unit = 'mV'\n dim = ramp_feat.append_sampled_dimension(1.0)\n dim.unit = 'ms'\n pos_tag = self.block.create_tag('feature test', 'test', [5.0])\n pos_tag.units = ['ms']\n pos_tag.create_feature(number_feat, nix.LinkType.Untagged)\n pos_tag.create_feature(ramp_feat, nix.LinkType.Tagged)\n pos_tag.create_feature(ramp_feat, nix.LinkType.Untagged)\n assert len(pos_tag.features) == 3\n data1 = pos_tag.feature_data(0)\n data2 = pos_tag.feature_data(1)\n data3 = pos_tag.feature_data(2)\n assert data1.size == 1\n assert data2.size == 1\n assert data3.size == len(ramp_data)\n pos_tag.extent = [2.0]\n data1 = pos_tag.feature_data(0)\n data2 = pos_tag.feature_data(1)\n data3 = pos_tag.feature_data(2)\n assert data1.size == 1\n assert data2.size == 3\n assert data3.size == len(ramp_data)\n data1 = pos_tag.feature_data(number_feat.name)\n data2 = pos_tag.feature_data(ramp_feat.name)\n assert data1.size == 1\n assert data2.size == 3\n", "<import token>\n\n\nclass TestTags(unittest.TestCase):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_tag_definition(self):\n assert self.my_tag.definition is None\n self.my_tag.definition = 'definition'\n assert self.my_tag.definition == 'definition'\n self.my_tag.definition = None\n assert self.my_tag.definition is None\n <function token>\n <function token>\n\n def test_tag_position(self):\n assert self.my_tag.position == (0,)\n self.my_tag.position = 1.0, 2.0, 3.0\n assert self.my_tag.position == (1.0, 2.0, 3.0)\n <function token>\n <function token>\n\n def test_tag_features(self):\n assert len(self.my_tag.features) == 0\n data_array = self.block.create_data_array('feature', 'stimuli', nix\n .DataType.Int16, (1,))\n feature = self.my_tag.create_feature(data_array, nix.LinkType.Untagged)\n assert len(self.my_tag.features) == 1\n assert feature in self.my_tag.features\n assert feature.id in self.my_tag.features\n assert 'notexist' not in self.my_tag.features\n assert feature.id == self.my_tag.features[0].id\n assert feature.id == self.my_tag.features[-1].id\n assert feature.id == self.my_tag.features[feature.id].id\n assert feature.id == self.my_tag.features[data_array.id].id\n assert feature.id == self.my_tag.features[data_array.name].id\n assert data_array == self.my_tag.features[data_array.id].data\n assert data_array == self.my_tag.features[data_array.name].data\n assert data_array.id in self.my_tag.features\n assert data_array.name in self.my_tag.features\n del self.my_tag.features[0]\n assert len(self.my_tag.features) == 0\n <function token>\n\n def test_tag_feature_data(self):\n number_feat = self.block.create_data_array('number feature', 'test',\n data=10.0)\n ramp_data = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n ramp_feat = self.block.create_data_array('ramp feature', 'test',\n data=np.asarray(ramp_data))\n ramp_feat.label = 'voltage'\n ramp_feat.unit = 'mV'\n dim = ramp_feat.append_sampled_dimension(1.0)\n dim.unit = 'ms'\n pos_tag = self.block.create_tag('feature test', 'test', [5.0])\n pos_tag.units = ['ms']\n pos_tag.create_feature(number_feat, nix.LinkType.Untagged)\n pos_tag.create_feature(ramp_feat, nix.LinkType.Tagged)\n pos_tag.create_feature(ramp_feat, nix.LinkType.Untagged)\n assert len(pos_tag.features) == 3\n data1 = pos_tag.feature_data(0)\n data2 = pos_tag.feature_data(1)\n data3 = pos_tag.feature_data(2)\n assert data1.size == 1\n assert data2.size == 1\n assert data3.size == len(ramp_data)\n pos_tag.extent = [2.0]\n data1 = pos_tag.feature_data(0)\n data2 = pos_tag.feature_data(1)\n data3 = pos_tag.feature_data(2)\n assert data1.size == 1\n assert data2.size == 3\n assert data3.size == len(ramp_data)\n data1 = pos_tag.feature_data(number_feat.name)\n data2 = pos_tag.feature_data(ramp_feat.name)\n assert data1.size == 1\n assert data2.size == 3\n", "<import token>\n\n\nclass TestTags(unittest.TestCase):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_tag_definition(self):\n assert self.my_tag.definition is None\n self.my_tag.definition = 'definition'\n assert self.my_tag.definition == 'definition'\n self.my_tag.definition = None\n assert self.my_tag.definition is None\n <function token>\n <function token>\n\n def test_tag_position(self):\n assert self.my_tag.position == (0,)\n self.my_tag.position = 1.0, 2.0, 3.0\n assert self.my_tag.position == (1.0, 2.0, 3.0)\n <function token>\n <function token>\n\n def test_tag_features(self):\n assert len(self.my_tag.features) == 0\n data_array = self.block.create_data_array('feature', 'stimuli', nix\n .DataType.Int16, (1,))\n feature = self.my_tag.create_feature(data_array, nix.LinkType.Untagged)\n assert len(self.my_tag.features) == 1\n assert feature in self.my_tag.features\n assert feature.id in self.my_tag.features\n assert 'notexist' not in self.my_tag.features\n assert feature.id == self.my_tag.features[0].id\n assert feature.id == self.my_tag.features[-1].id\n assert feature.id == self.my_tag.features[feature.id].id\n assert feature.id == self.my_tag.features[data_array.id].id\n assert feature.id == self.my_tag.features[data_array.name].id\n assert data_array == self.my_tag.features[data_array.id].data\n assert data_array == self.my_tag.features[data_array.name].data\n assert data_array.id in self.my_tag.features\n assert data_array.name in self.my_tag.features\n del self.my_tag.features[0]\n assert len(self.my_tag.features) == 0\n <function token>\n <function token>\n", "<import token>\n\n\nclass TestTags(unittest.TestCase):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_tag_definition(self):\n assert self.my_tag.definition is None\n self.my_tag.definition = 'definition'\n assert self.my_tag.definition == 'definition'\n self.my_tag.definition = None\n assert self.my_tag.definition is None\n <function token>\n <function token>\n\n def test_tag_position(self):\n assert self.my_tag.position == (0,)\n self.my_tag.position = 1.0, 2.0, 3.0\n assert self.my_tag.position == (1.0, 2.0, 3.0)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<import token>\n\n\nclass TestTags(unittest.TestCase):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_tag_position(self):\n assert self.my_tag.position == (0,)\n self.my_tag.position = 1.0, 2.0, 3.0\n assert self.my_tag.position == (1.0, 2.0, 3.0)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<import token>\n\n\nclass TestTags(unittest.TestCase):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<import token>\n<class token>\n" ]
false
98,739
3bc0ba1994df3bf8f30abff9b824c33f43f7c88e
# -*- coding: utf-8 -*- # # Copyright (C) 2019 CERN. # # inspirehep is free software; you can redistribute it and/or modify it under # the terms of the MIT License; see LICENSE file for more details. from inspire_dojson.utils import get_recid_from_ref, strip_empty_values from inspire_utils.helpers import force_list from inspire_utils.record import get_value, get_values_for_schema from marshmallow import Schema, fields, missing, post_dump, pre_dump from inspirehep.records.marshmallow.fields import ListWithLimit, NestedField from .author import AuthorSchemaV1 from .collaboration import CollaborationSchemaV1 from .collaboration_with_suffix import CollaborationWithSuffixSchemaV1 from .publication_info_item import PublicationInfoItemSchemaV1 class ReferenceItemSchemaV1(Schema): authors = ListWithLimit( NestedField(AuthorSchemaV1, dump_only=True, default=[]), limit=10 ) collaborations = fields.List( fields.Nested(CollaborationSchemaV1, dump_only=True), attribute="collaborations" ) collaborations_with_suffix = fields.List( fields.Nested(CollaborationWithSuffixSchemaV1, dump_only=True), attribute="collaborations", ) control_number = fields.Raw() label = fields.Raw() urls = fields.Raw() publication_info = fields.List( NestedField(PublicationInfoItemSchemaV1, dump_only=True) ) titles = fields.Method("get_titles") misc = fields.Method("get_misc") arxiv_eprint = fields.Method("get_arxiv_eprints") dois = fields.Method("get_dois") @pre_dump(pass_many=True) def resolve_and_flatten(self, data, many): reference_records = self.get_resolved_references_by_control_number(data) if not many: return self.get_reference_data(data, reference_records) references = [] for reference in data: reference_data = self.get_reference_data(reference, reference_records) references.append(reference_data) return references @pre_dump def force_each_collaboration_to_be_object(self, data): if not data.get("record"): collaborations = get_value(data, "reference.collaborations") if collaborations: data["reference"]["collaborations"] = [ {"value": collaboration} for collaboration in collaborations ] return data def get_reference_data(self, reference, reference_records): reference_record_id = self.get_reference_record_id(reference) reference_record = reference_records.get(reference_record_id) reference_data = self.get_reference_or_linked_reference_data_with_label( reference, reference_record ) return reference_data or {} def get_reference_record_id(self, reference): return get_recid_from_ref(reference.get("record")) def get_resolved_references_by_control_number(self, data): data = force_list(data) from inspirehep.records.api.literature import LiteratureRecord resolved_records = LiteratureRecord.get_es_linked_references(data) return {record["control_number"]: record.dumps() for record in resolved_records} def get_reference_or_linked_reference_data_with_label( self, reference, reference_record ): if reference_record: reference_record.update( {"label": get_value(reference, "reference.label", default=missing)} ) return reference_record return reference.get("reference") def get_titles(self, data): title = data.get("title") titles = data.get("titles") if title: return [title] elif titles: return [titles[0]] return missing def get_dois(self, data): doi = get_value(data, "dois[0].value") or get_value(data, "dois[0]") if doi: return [{"value": doi}] return missing def get_arxiv_eprints(self, data): arxiv_eprint = data.get("arxiv_eprint") arxiv_eprints = data.get("arxiv_eprints") if arxiv_eprint: return [{"value": arxiv_eprint}] elif arxiv_eprints: return [{"value": arxiv_eprints[0].get("value")}] return missing def get_misc(self, data): titles = data.get("titles") title = data.get("title") misc = data.get("misc") if not title and not titles and misc: return misc[0] return missing @post_dump def strip_empty(self, data): return strip_empty_values(data) class ReferenceItemSchemaV2(ReferenceItemSchemaV1): raw_ref = fields.Raw() def get_reference_data(self, reference, reference_records): reference_data = super().get_reference_data(reference, reference_records) raw_refs = get_values_for_schema(reference.get("raw_refs", []), "text") if raw_refs: reference_data["raw_ref"] = raw_refs[0] return reference_data
[ "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2019 CERN.\n#\n# inspirehep is free software; you can redistribute it and/or modify it under\n# the terms of the MIT License; see LICENSE file for more details.\n\nfrom inspire_dojson.utils import get_recid_from_ref, strip_empty_values\nfrom inspire_utils.helpers import force_list\nfrom inspire_utils.record import get_value, get_values_for_schema\nfrom marshmallow import Schema, fields, missing, post_dump, pre_dump\n\nfrom inspirehep.records.marshmallow.fields import ListWithLimit, NestedField\n\nfrom .author import AuthorSchemaV1\nfrom .collaboration import CollaborationSchemaV1\nfrom .collaboration_with_suffix import CollaborationWithSuffixSchemaV1\nfrom .publication_info_item import PublicationInfoItemSchemaV1\n\n\nclass ReferenceItemSchemaV1(Schema):\n authors = ListWithLimit(\n NestedField(AuthorSchemaV1, dump_only=True, default=[]), limit=10\n )\n collaborations = fields.List(\n fields.Nested(CollaborationSchemaV1, dump_only=True), attribute=\"collaborations\"\n )\n collaborations_with_suffix = fields.List(\n fields.Nested(CollaborationWithSuffixSchemaV1, dump_only=True),\n attribute=\"collaborations\",\n )\n control_number = fields.Raw()\n label = fields.Raw()\n urls = fields.Raw()\n publication_info = fields.List(\n NestedField(PublicationInfoItemSchemaV1, dump_only=True)\n )\n titles = fields.Method(\"get_titles\")\n misc = fields.Method(\"get_misc\")\n arxiv_eprint = fields.Method(\"get_arxiv_eprints\")\n dois = fields.Method(\"get_dois\")\n\n @pre_dump(pass_many=True)\n def resolve_and_flatten(self, data, many):\n reference_records = self.get_resolved_references_by_control_number(data)\n\n if not many:\n return self.get_reference_data(data, reference_records)\n\n references = []\n for reference in data:\n reference_data = self.get_reference_data(reference, reference_records)\n references.append(reference_data)\n return references\n\n @pre_dump\n def force_each_collaboration_to_be_object(self, data):\n if not data.get(\"record\"):\n collaborations = get_value(data, \"reference.collaborations\")\n if collaborations:\n data[\"reference\"][\"collaborations\"] = [\n {\"value\": collaboration} for collaboration in collaborations\n ]\n return data\n\n def get_reference_data(self, reference, reference_records):\n reference_record_id = self.get_reference_record_id(reference)\n reference_record = reference_records.get(reference_record_id)\n reference_data = self.get_reference_or_linked_reference_data_with_label(\n reference, reference_record\n )\n return reference_data or {}\n\n def get_reference_record_id(self, reference):\n return get_recid_from_ref(reference.get(\"record\"))\n\n def get_resolved_references_by_control_number(self, data):\n data = force_list(data)\n from inspirehep.records.api.literature import LiteratureRecord\n\n resolved_records = LiteratureRecord.get_es_linked_references(data)\n\n return {record[\"control_number\"]: record.dumps() for record in resolved_records}\n\n def get_reference_or_linked_reference_data_with_label(\n self, reference, reference_record\n ):\n if reference_record:\n reference_record.update(\n {\"label\": get_value(reference, \"reference.label\", default=missing)}\n )\n return reference_record\n return reference.get(\"reference\")\n\n def get_titles(self, data):\n title = data.get(\"title\")\n titles = data.get(\"titles\")\n if title:\n return [title]\n elif titles:\n return [titles[0]]\n return missing\n\n def get_dois(self, data):\n doi = get_value(data, \"dois[0].value\") or get_value(data, \"dois[0]\")\n if doi:\n return [{\"value\": doi}]\n return missing\n\n def get_arxiv_eprints(self, data):\n arxiv_eprint = data.get(\"arxiv_eprint\")\n arxiv_eprints = data.get(\"arxiv_eprints\")\n if arxiv_eprint:\n return [{\"value\": arxiv_eprint}]\n elif arxiv_eprints:\n return [{\"value\": arxiv_eprints[0].get(\"value\")}]\n return missing\n\n def get_misc(self, data):\n titles = data.get(\"titles\")\n title = data.get(\"title\")\n misc = data.get(\"misc\")\n if not title and not titles and misc:\n return misc[0]\n return missing\n\n @post_dump\n def strip_empty(self, data):\n return strip_empty_values(data)\n\n\nclass ReferenceItemSchemaV2(ReferenceItemSchemaV1):\n raw_ref = fields.Raw()\n\n def get_reference_data(self, reference, reference_records):\n reference_data = super().get_reference_data(reference, reference_records)\n raw_refs = get_values_for_schema(reference.get(\"raw_refs\", []), \"text\")\n if raw_refs:\n reference_data[\"raw_ref\"] = raw_refs[0]\n return reference_data\n", "from inspire_dojson.utils import get_recid_from_ref, strip_empty_values\nfrom inspire_utils.helpers import force_list\nfrom inspire_utils.record import get_value, get_values_for_schema\nfrom marshmallow import Schema, fields, missing, post_dump, pre_dump\nfrom inspirehep.records.marshmallow.fields import ListWithLimit, NestedField\nfrom .author import AuthorSchemaV1\nfrom .collaboration import CollaborationSchemaV1\nfrom .collaboration_with_suffix import CollaborationWithSuffixSchemaV1\nfrom .publication_info_item import PublicationInfoItemSchemaV1\n\n\nclass ReferenceItemSchemaV1(Schema):\n authors = ListWithLimit(NestedField(AuthorSchemaV1, dump_only=True,\n default=[]), limit=10)\n collaborations = fields.List(fields.Nested(CollaborationSchemaV1,\n dump_only=True), attribute='collaborations')\n collaborations_with_suffix = fields.List(fields.Nested(\n CollaborationWithSuffixSchemaV1, dump_only=True), attribute=\n 'collaborations')\n control_number = fields.Raw()\n label = fields.Raw()\n urls = fields.Raw()\n publication_info = fields.List(NestedField(PublicationInfoItemSchemaV1,\n dump_only=True))\n titles = fields.Method('get_titles')\n misc = fields.Method('get_misc')\n arxiv_eprint = fields.Method('get_arxiv_eprints')\n dois = fields.Method('get_dois')\n\n @pre_dump(pass_many=True)\n def resolve_and_flatten(self, data, many):\n reference_records = self.get_resolved_references_by_control_number(data\n )\n if not many:\n return self.get_reference_data(data, reference_records)\n references = []\n for reference in data:\n reference_data = self.get_reference_data(reference,\n reference_records)\n references.append(reference_data)\n return references\n\n @pre_dump\n def force_each_collaboration_to_be_object(self, data):\n if not data.get('record'):\n collaborations = get_value(data, 'reference.collaborations')\n if collaborations:\n data['reference']['collaborations'] = [{'value':\n collaboration} for collaboration in collaborations]\n return data\n\n def get_reference_data(self, reference, reference_records):\n reference_record_id = self.get_reference_record_id(reference)\n reference_record = reference_records.get(reference_record_id)\n reference_data = (self.\n get_reference_or_linked_reference_data_with_label(reference,\n reference_record))\n return reference_data or {}\n\n def get_reference_record_id(self, reference):\n return get_recid_from_ref(reference.get('record'))\n\n def get_resolved_references_by_control_number(self, data):\n data = force_list(data)\n from inspirehep.records.api.literature import LiteratureRecord\n resolved_records = LiteratureRecord.get_es_linked_references(data)\n return {record['control_number']: record.dumps() for record in\n resolved_records}\n\n def get_reference_or_linked_reference_data_with_label(self, reference,\n reference_record):\n if reference_record:\n reference_record.update({'label': get_value(reference,\n 'reference.label', default=missing)})\n return reference_record\n return reference.get('reference')\n\n def get_titles(self, data):\n title = data.get('title')\n titles = data.get('titles')\n if title:\n return [title]\n elif titles:\n return [titles[0]]\n return missing\n\n def get_dois(self, data):\n doi = get_value(data, 'dois[0].value') or get_value(data, 'dois[0]')\n if doi:\n return [{'value': doi}]\n return missing\n\n def get_arxiv_eprints(self, data):\n arxiv_eprint = data.get('arxiv_eprint')\n arxiv_eprints = data.get('arxiv_eprints')\n if arxiv_eprint:\n return [{'value': arxiv_eprint}]\n elif arxiv_eprints:\n return [{'value': arxiv_eprints[0].get('value')}]\n return missing\n\n def get_misc(self, data):\n titles = data.get('titles')\n title = data.get('title')\n misc = data.get('misc')\n if not title and not titles and misc:\n return misc[0]\n return missing\n\n @post_dump\n def strip_empty(self, data):\n return strip_empty_values(data)\n\n\nclass ReferenceItemSchemaV2(ReferenceItemSchemaV1):\n raw_ref = fields.Raw()\n\n def get_reference_data(self, reference, reference_records):\n reference_data = super().get_reference_data(reference,\n reference_records)\n raw_refs = get_values_for_schema(reference.get('raw_refs', []), 'text')\n if raw_refs:\n reference_data['raw_ref'] = raw_refs[0]\n return reference_data\n", "<import token>\n\n\nclass ReferenceItemSchemaV1(Schema):\n authors = ListWithLimit(NestedField(AuthorSchemaV1, dump_only=True,\n default=[]), limit=10)\n collaborations = fields.List(fields.Nested(CollaborationSchemaV1,\n dump_only=True), attribute='collaborations')\n collaborations_with_suffix = fields.List(fields.Nested(\n CollaborationWithSuffixSchemaV1, dump_only=True), attribute=\n 'collaborations')\n control_number = fields.Raw()\n label = fields.Raw()\n urls = fields.Raw()\n publication_info = fields.List(NestedField(PublicationInfoItemSchemaV1,\n dump_only=True))\n titles = fields.Method('get_titles')\n misc = fields.Method('get_misc')\n arxiv_eprint = fields.Method('get_arxiv_eprints')\n dois = fields.Method('get_dois')\n\n @pre_dump(pass_many=True)\n def resolve_and_flatten(self, data, many):\n reference_records = self.get_resolved_references_by_control_number(data\n )\n if not many:\n return self.get_reference_data(data, reference_records)\n references = []\n for reference in data:\n reference_data = self.get_reference_data(reference,\n reference_records)\n references.append(reference_data)\n return references\n\n @pre_dump\n def force_each_collaboration_to_be_object(self, data):\n if not data.get('record'):\n collaborations = get_value(data, 'reference.collaborations')\n if collaborations:\n data['reference']['collaborations'] = [{'value':\n collaboration} for collaboration in collaborations]\n return data\n\n def get_reference_data(self, reference, reference_records):\n reference_record_id = self.get_reference_record_id(reference)\n reference_record = reference_records.get(reference_record_id)\n reference_data = (self.\n get_reference_or_linked_reference_data_with_label(reference,\n reference_record))\n return reference_data or {}\n\n def get_reference_record_id(self, reference):\n return get_recid_from_ref(reference.get('record'))\n\n def get_resolved_references_by_control_number(self, data):\n data = force_list(data)\n from inspirehep.records.api.literature import LiteratureRecord\n resolved_records = LiteratureRecord.get_es_linked_references(data)\n return {record['control_number']: record.dumps() for record in\n resolved_records}\n\n def get_reference_or_linked_reference_data_with_label(self, reference,\n reference_record):\n if reference_record:\n reference_record.update({'label': get_value(reference,\n 'reference.label', default=missing)})\n return reference_record\n return reference.get('reference')\n\n def get_titles(self, data):\n title = data.get('title')\n titles = data.get('titles')\n if title:\n return [title]\n elif titles:\n return [titles[0]]\n return missing\n\n def get_dois(self, data):\n doi = get_value(data, 'dois[0].value') or get_value(data, 'dois[0]')\n if doi:\n return [{'value': doi}]\n return missing\n\n def get_arxiv_eprints(self, data):\n arxiv_eprint = data.get('arxiv_eprint')\n arxiv_eprints = data.get('arxiv_eprints')\n if arxiv_eprint:\n return [{'value': arxiv_eprint}]\n elif arxiv_eprints:\n return [{'value': arxiv_eprints[0].get('value')}]\n return missing\n\n def get_misc(self, data):\n titles = data.get('titles')\n title = data.get('title')\n misc = data.get('misc')\n if not title and not titles and misc:\n return misc[0]\n return missing\n\n @post_dump\n def strip_empty(self, data):\n return strip_empty_values(data)\n\n\nclass ReferenceItemSchemaV2(ReferenceItemSchemaV1):\n raw_ref = fields.Raw()\n\n def get_reference_data(self, reference, reference_records):\n reference_data = super().get_reference_data(reference,\n reference_records)\n raw_refs = get_values_for_schema(reference.get('raw_refs', []), 'text')\n if raw_refs:\n reference_data['raw_ref'] = raw_refs[0]\n return reference_data\n", "<import token>\n\n\nclass ReferenceItemSchemaV1(Schema):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n @pre_dump(pass_many=True)\n def resolve_and_flatten(self, data, many):\n reference_records = self.get_resolved_references_by_control_number(data\n )\n if not many:\n return self.get_reference_data(data, reference_records)\n references = []\n for reference in data:\n reference_data = self.get_reference_data(reference,\n reference_records)\n references.append(reference_data)\n return references\n\n @pre_dump\n def force_each_collaboration_to_be_object(self, data):\n if not data.get('record'):\n collaborations = get_value(data, 'reference.collaborations')\n if collaborations:\n data['reference']['collaborations'] = [{'value':\n collaboration} for collaboration in collaborations]\n return data\n\n def get_reference_data(self, reference, reference_records):\n reference_record_id = self.get_reference_record_id(reference)\n reference_record = reference_records.get(reference_record_id)\n reference_data = (self.\n get_reference_or_linked_reference_data_with_label(reference,\n reference_record))\n return reference_data or {}\n\n def get_reference_record_id(self, reference):\n return get_recid_from_ref(reference.get('record'))\n\n def get_resolved_references_by_control_number(self, data):\n data = force_list(data)\n from inspirehep.records.api.literature import LiteratureRecord\n resolved_records = LiteratureRecord.get_es_linked_references(data)\n return {record['control_number']: record.dumps() for record in\n resolved_records}\n\n def get_reference_or_linked_reference_data_with_label(self, reference,\n reference_record):\n if reference_record:\n reference_record.update({'label': get_value(reference,\n 'reference.label', default=missing)})\n return reference_record\n return reference.get('reference')\n\n def get_titles(self, data):\n title = data.get('title')\n titles = data.get('titles')\n if title:\n return [title]\n elif titles:\n return [titles[0]]\n return missing\n\n def get_dois(self, data):\n doi = get_value(data, 'dois[0].value') or get_value(data, 'dois[0]')\n if doi:\n return [{'value': doi}]\n return missing\n\n def get_arxiv_eprints(self, data):\n arxiv_eprint = data.get('arxiv_eprint')\n arxiv_eprints = data.get('arxiv_eprints')\n if arxiv_eprint:\n return [{'value': arxiv_eprint}]\n elif arxiv_eprints:\n return [{'value': arxiv_eprints[0].get('value')}]\n return missing\n\n def get_misc(self, data):\n titles = data.get('titles')\n title = data.get('title')\n misc = data.get('misc')\n if not title and not titles and misc:\n return misc[0]\n return missing\n\n @post_dump\n def strip_empty(self, data):\n return strip_empty_values(data)\n\n\nclass ReferenceItemSchemaV2(ReferenceItemSchemaV1):\n raw_ref = fields.Raw()\n\n def get_reference_data(self, reference, reference_records):\n reference_data = super().get_reference_data(reference,\n reference_records)\n raw_refs = get_values_for_schema(reference.get('raw_refs', []), 'text')\n if raw_refs:\n reference_data['raw_ref'] = raw_refs[0]\n return reference_data\n", "<import token>\n\n\nclass ReferenceItemSchemaV1(Schema):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n @pre_dump(pass_many=True)\n def resolve_and_flatten(self, data, many):\n reference_records = self.get_resolved_references_by_control_number(data\n )\n if not many:\n return self.get_reference_data(data, reference_records)\n references = []\n for reference in data:\n reference_data = self.get_reference_data(reference,\n reference_records)\n references.append(reference_data)\n return references\n\n @pre_dump\n def force_each_collaboration_to_be_object(self, data):\n if not data.get('record'):\n collaborations = get_value(data, 'reference.collaborations')\n if collaborations:\n data['reference']['collaborations'] = [{'value':\n collaboration} for collaboration in collaborations]\n return data\n\n def get_reference_data(self, reference, reference_records):\n reference_record_id = self.get_reference_record_id(reference)\n reference_record = reference_records.get(reference_record_id)\n reference_data = (self.\n get_reference_or_linked_reference_data_with_label(reference,\n reference_record))\n return reference_data or {}\n\n def get_reference_record_id(self, reference):\n return get_recid_from_ref(reference.get('record'))\n\n def get_resolved_references_by_control_number(self, data):\n data = force_list(data)\n from inspirehep.records.api.literature import LiteratureRecord\n resolved_records = LiteratureRecord.get_es_linked_references(data)\n return {record['control_number']: record.dumps() for record in\n resolved_records}\n\n def get_reference_or_linked_reference_data_with_label(self, reference,\n reference_record):\n if reference_record:\n reference_record.update({'label': get_value(reference,\n 'reference.label', default=missing)})\n return reference_record\n return reference.get('reference')\n <function token>\n\n def get_dois(self, data):\n doi = get_value(data, 'dois[0].value') or get_value(data, 'dois[0]')\n if doi:\n return [{'value': doi}]\n return missing\n\n def get_arxiv_eprints(self, data):\n arxiv_eprint = data.get('arxiv_eprint')\n arxiv_eprints = data.get('arxiv_eprints')\n if arxiv_eprint:\n return [{'value': arxiv_eprint}]\n elif arxiv_eprints:\n return [{'value': arxiv_eprints[0].get('value')}]\n return missing\n\n def get_misc(self, data):\n titles = data.get('titles')\n title = data.get('title')\n misc = data.get('misc')\n if not title and not titles and misc:\n return misc[0]\n return missing\n\n @post_dump\n def strip_empty(self, data):\n return strip_empty_values(data)\n\n\nclass ReferenceItemSchemaV2(ReferenceItemSchemaV1):\n raw_ref = fields.Raw()\n\n def get_reference_data(self, reference, reference_records):\n reference_data = super().get_reference_data(reference,\n reference_records)\n raw_refs = get_values_for_schema(reference.get('raw_refs', []), 'text')\n if raw_refs:\n reference_data['raw_ref'] = raw_refs[0]\n return reference_data\n", "<import token>\n\n\nclass ReferenceItemSchemaV1(Schema):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n @pre_dump(pass_many=True)\n def resolve_and_flatten(self, data, many):\n reference_records = self.get_resolved_references_by_control_number(data\n )\n if not many:\n return self.get_reference_data(data, reference_records)\n references = []\n for reference in data:\n reference_data = self.get_reference_data(reference,\n reference_records)\n references.append(reference_data)\n return references\n\n @pre_dump\n def force_each_collaboration_to_be_object(self, data):\n if not data.get('record'):\n collaborations = get_value(data, 'reference.collaborations')\n if collaborations:\n data['reference']['collaborations'] = [{'value':\n collaboration} for collaboration in collaborations]\n return data\n\n def get_reference_data(self, reference, reference_records):\n reference_record_id = self.get_reference_record_id(reference)\n reference_record = reference_records.get(reference_record_id)\n reference_data = (self.\n get_reference_or_linked_reference_data_with_label(reference,\n reference_record))\n return reference_data or {}\n <function token>\n\n def get_resolved_references_by_control_number(self, data):\n data = force_list(data)\n from inspirehep.records.api.literature import LiteratureRecord\n resolved_records = LiteratureRecord.get_es_linked_references(data)\n return {record['control_number']: record.dumps() for record in\n resolved_records}\n\n def get_reference_or_linked_reference_data_with_label(self, reference,\n reference_record):\n if reference_record:\n reference_record.update({'label': get_value(reference,\n 'reference.label', default=missing)})\n return reference_record\n return reference.get('reference')\n <function token>\n\n def get_dois(self, data):\n doi = get_value(data, 'dois[0].value') or get_value(data, 'dois[0]')\n if doi:\n return [{'value': doi}]\n return missing\n\n def get_arxiv_eprints(self, data):\n arxiv_eprint = data.get('arxiv_eprint')\n arxiv_eprints = data.get('arxiv_eprints')\n if arxiv_eprint:\n return [{'value': arxiv_eprint}]\n elif arxiv_eprints:\n return [{'value': arxiv_eprints[0].get('value')}]\n return missing\n\n def get_misc(self, data):\n titles = data.get('titles')\n title = data.get('title')\n misc = data.get('misc')\n if not title and not titles and misc:\n return misc[0]\n return missing\n\n @post_dump\n def strip_empty(self, data):\n return strip_empty_values(data)\n\n\nclass ReferenceItemSchemaV2(ReferenceItemSchemaV1):\n raw_ref = fields.Raw()\n\n def get_reference_data(self, reference, reference_records):\n reference_data = super().get_reference_data(reference,\n reference_records)\n raw_refs = get_values_for_schema(reference.get('raw_refs', []), 'text')\n if raw_refs:\n reference_data['raw_ref'] = raw_refs[0]\n return reference_data\n", "<import token>\n\n\nclass ReferenceItemSchemaV1(Schema):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n @pre_dump(pass_many=True)\n def resolve_and_flatten(self, data, many):\n reference_records = self.get_resolved_references_by_control_number(data\n )\n if not many:\n return self.get_reference_data(data, reference_records)\n references = []\n for reference in data:\n reference_data = self.get_reference_data(reference,\n reference_records)\n references.append(reference_data)\n return references\n\n @pre_dump\n def force_each_collaboration_to_be_object(self, data):\n if not data.get('record'):\n collaborations = get_value(data, 'reference.collaborations')\n if collaborations:\n data['reference']['collaborations'] = [{'value':\n collaboration} for collaboration in collaborations]\n return data\n\n def get_reference_data(self, reference, reference_records):\n reference_record_id = self.get_reference_record_id(reference)\n reference_record = reference_records.get(reference_record_id)\n reference_data = (self.\n get_reference_or_linked_reference_data_with_label(reference,\n reference_record))\n return reference_data or {}\n <function token>\n\n def get_resolved_references_by_control_number(self, data):\n data = force_list(data)\n from inspirehep.records.api.literature import LiteratureRecord\n resolved_records = LiteratureRecord.get_es_linked_references(data)\n return {record['control_number']: record.dumps() for record in\n resolved_records}\n\n def get_reference_or_linked_reference_data_with_label(self, reference,\n reference_record):\n if reference_record:\n reference_record.update({'label': get_value(reference,\n 'reference.label', default=missing)})\n return reference_record\n return reference.get('reference')\n <function token>\n\n def get_dois(self, data):\n doi = get_value(data, 'dois[0].value') or get_value(data, 'dois[0]')\n if doi:\n return [{'value': doi}]\n return missing\n\n def get_arxiv_eprints(self, data):\n arxiv_eprint = data.get('arxiv_eprint')\n arxiv_eprints = data.get('arxiv_eprints')\n if arxiv_eprint:\n return [{'value': arxiv_eprint}]\n elif arxiv_eprints:\n return [{'value': arxiv_eprints[0].get('value')}]\n return missing\n\n def get_misc(self, data):\n titles = data.get('titles')\n title = data.get('title')\n misc = data.get('misc')\n if not title and not titles and misc:\n return misc[0]\n return missing\n <function token>\n\n\nclass ReferenceItemSchemaV2(ReferenceItemSchemaV1):\n raw_ref = fields.Raw()\n\n def get_reference_data(self, reference, reference_records):\n reference_data = super().get_reference_data(reference,\n reference_records)\n raw_refs = get_values_for_schema(reference.get('raw_refs', []), 'text')\n if raw_refs:\n reference_data['raw_ref'] = raw_refs[0]\n return reference_data\n", "<import token>\n\n\nclass ReferenceItemSchemaV1(Schema):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n @pre_dump(pass_many=True)\n def resolve_and_flatten(self, data, many):\n reference_records = self.get_resolved_references_by_control_number(data\n )\n if not many:\n return self.get_reference_data(data, reference_records)\n references = []\n for reference in data:\n reference_data = self.get_reference_data(reference,\n reference_records)\n references.append(reference_data)\n return references\n\n @pre_dump\n def force_each_collaboration_to_be_object(self, data):\n if not data.get('record'):\n collaborations = get_value(data, 'reference.collaborations')\n if collaborations:\n data['reference']['collaborations'] = [{'value':\n collaboration} for collaboration in collaborations]\n return data\n\n def get_reference_data(self, reference, reference_records):\n reference_record_id = self.get_reference_record_id(reference)\n reference_record = reference_records.get(reference_record_id)\n reference_data = (self.\n get_reference_or_linked_reference_data_with_label(reference,\n reference_record))\n return reference_data or {}\n <function token>\n\n def get_resolved_references_by_control_number(self, data):\n data = force_list(data)\n from inspirehep.records.api.literature import LiteratureRecord\n resolved_records = LiteratureRecord.get_es_linked_references(data)\n return {record['control_number']: record.dumps() for record in\n resolved_records}\n <function token>\n <function token>\n\n def get_dois(self, data):\n doi = get_value(data, 'dois[0].value') or get_value(data, 'dois[0]')\n if doi:\n return [{'value': doi}]\n return missing\n\n def get_arxiv_eprints(self, data):\n arxiv_eprint = data.get('arxiv_eprint')\n arxiv_eprints = data.get('arxiv_eprints')\n if arxiv_eprint:\n return [{'value': arxiv_eprint}]\n elif arxiv_eprints:\n return [{'value': arxiv_eprints[0].get('value')}]\n return missing\n\n def get_misc(self, data):\n titles = data.get('titles')\n title = data.get('title')\n misc = data.get('misc')\n if not title and not titles and misc:\n return misc[0]\n return missing\n <function token>\n\n\nclass ReferenceItemSchemaV2(ReferenceItemSchemaV1):\n raw_ref = fields.Raw()\n\n def get_reference_data(self, reference, reference_records):\n reference_data = super().get_reference_data(reference,\n reference_records)\n raw_refs = get_values_for_schema(reference.get('raw_refs', []), 'text')\n if raw_refs:\n reference_data['raw_ref'] = raw_refs[0]\n return reference_data\n", "<import token>\n\n\nclass ReferenceItemSchemaV1(Schema):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n @pre_dump(pass_many=True)\n def resolve_and_flatten(self, data, many):\n reference_records = self.get_resolved_references_by_control_number(data\n )\n if not many:\n return self.get_reference_data(data, reference_records)\n references = []\n for reference in data:\n reference_data = self.get_reference_data(reference,\n reference_records)\n references.append(reference_data)\n return references\n\n @pre_dump\n def force_each_collaboration_to_be_object(self, data):\n if not data.get('record'):\n collaborations = get_value(data, 'reference.collaborations')\n if collaborations:\n data['reference']['collaborations'] = [{'value':\n collaboration} for collaboration in collaborations]\n return data\n\n def get_reference_data(self, reference, reference_records):\n reference_record_id = self.get_reference_record_id(reference)\n reference_record = reference_records.get(reference_record_id)\n reference_data = (self.\n get_reference_or_linked_reference_data_with_label(reference,\n reference_record))\n return reference_data or {}\n <function token>\n\n def get_resolved_references_by_control_number(self, data):\n data = force_list(data)\n from inspirehep.records.api.literature import LiteratureRecord\n resolved_records = LiteratureRecord.get_es_linked_references(data)\n return {record['control_number']: record.dumps() for record in\n resolved_records}\n <function token>\n <function token>\n\n def get_dois(self, data):\n doi = get_value(data, 'dois[0].value') or get_value(data, 'dois[0]')\n if doi:\n return [{'value': doi}]\n return missing\n <function token>\n\n def get_misc(self, data):\n titles = data.get('titles')\n title = data.get('title')\n misc = data.get('misc')\n if not title and not titles and misc:\n return misc[0]\n return missing\n <function token>\n\n\nclass ReferenceItemSchemaV2(ReferenceItemSchemaV1):\n raw_ref = fields.Raw()\n\n def get_reference_data(self, reference, reference_records):\n reference_data = super().get_reference_data(reference,\n reference_records)\n raw_refs = get_values_for_schema(reference.get('raw_refs', []), 'text')\n if raw_refs:\n reference_data['raw_ref'] = raw_refs[0]\n return reference_data\n", "<import token>\n\n\nclass ReferenceItemSchemaV1(Schema):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n @pre_dump(pass_many=True)\n def resolve_and_flatten(self, data, many):\n reference_records = self.get_resolved_references_by_control_number(data\n )\n if not many:\n return self.get_reference_data(data, reference_records)\n references = []\n for reference in data:\n reference_data = self.get_reference_data(reference,\n reference_records)\n references.append(reference_data)\n return references\n\n @pre_dump\n def force_each_collaboration_to_be_object(self, data):\n if not data.get('record'):\n collaborations = get_value(data, 'reference.collaborations')\n if collaborations:\n data['reference']['collaborations'] = [{'value':\n collaboration} for collaboration in collaborations]\n return data\n <function token>\n <function token>\n\n def get_resolved_references_by_control_number(self, data):\n data = force_list(data)\n from inspirehep.records.api.literature import LiteratureRecord\n resolved_records = LiteratureRecord.get_es_linked_references(data)\n return {record['control_number']: record.dumps() for record in\n resolved_records}\n <function token>\n <function token>\n\n def get_dois(self, data):\n doi = get_value(data, 'dois[0].value') or get_value(data, 'dois[0]')\n if doi:\n return [{'value': doi}]\n return missing\n <function token>\n\n def get_misc(self, data):\n titles = data.get('titles')\n title = data.get('title')\n misc = data.get('misc')\n if not title and not titles and misc:\n return misc[0]\n return missing\n <function token>\n\n\nclass ReferenceItemSchemaV2(ReferenceItemSchemaV1):\n raw_ref = fields.Raw()\n\n def get_reference_data(self, reference, reference_records):\n reference_data = super().get_reference_data(reference,\n reference_records)\n raw_refs = get_values_for_schema(reference.get('raw_refs', []), 'text')\n if raw_refs:\n reference_data['raw_ref'] = raw_refs[0]\n return reference_data\n", "<import token>\n\n\nclass ReferenceItemSchemaV1(Schema):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n\n @pre_dump\n def force_each_collaboration_to_be_object(self, data):\n if not data.get('record'):\n collaborations = get_value(data, 'reference.collaborations')\n if collaborations:\n data['reference']['collaborations'] = [{'value':\n collaboration} for collaboration in collaborations]\n return data\n <function token>\n <function token>\n\n def get_resolved_references_by_control_number(self, data):\n data = force_list(data)\n from inspirehep.records.api.literature import LiteratureRecord\n resolved_records = LiteratureRecord.get_es_linked_references(data)\n return {record['control_number']: record.dumps() for record in\n resolved_records}\n <function token>\n <function token>\n\n def get_dois(self, data):\n doi = get_value(data, 'dois[0].value') or get_value(data, 'dois[0]')\n if doi:\n return [{'value': doi}]\n return missing\n <function token>\n\n def get_misc(self, data):\n titles = data.get('titles')\n title = data.get('title')\n misc = data.get('misc')\n if not title and not titles and misc:\n return misc[0]\n return missing\n <function token>\n\n\nclass ReferenceItemSchemaV2(ReferenceItemSchemaV1):\n raw_ref = fields.Raw()\n\n def get_reference_data(self, reference, reference_records):\n reference_data = super().get_reference_data(reference,\n reference_records)\n raw_refs = get_values_for_schema(reference.get('raw_refs', []), 'text')\n if raw_refs:\n reference_data['raw_ref'] = raw_refs[0]\n return reference_data\n", "<import token>\n\n\nclass ReferenceItemSchemaV1(Schema):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def get_resolved_references_by_control_number(self, data):\n data = force_list(data)\n from inspirehep.records.api.literature import LiteratureRecord\n resolved_records = LiteratureRecord.get_es_linked_references(data)\n return {record['control_number']: record.dumps() for record in\n resolved_records}\n <function token>\n <function token>\n\n def get_dois(self, data):\n doi = get_value(data, 'dois[0].value') or get_value(data, 'dois[0]')\n if doi:\n return [{'value': doi}]\n return missing\n <function token>\n\n def get_misc(self, data):\n titles = data.get('titles')\n title = data.get('title')\n misc = data.get('misc')\n if not title and not titles and misc:\n return misc[0]\n return missing\n <function token>\n\n\nclass ReferenceItemSchemaV2(ReferenceItemSchemaV1):\n raw_ref = fields.Raw()\n\n def get_reference_data(self, reference, reference_records):\n reference_data = super().get_reference_data(reference,\n reference_records)\n raw_refs = get_values_for_schema(reference.get('raw_refs', []), 'text')\n if raw_refs:\n reference_data['raw_ref'] = raw_refs[0]\n return reference_data\n", "<import token>\n\n\nclass ReferenceItemSchemaV1(Schema):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def get_resolved_references_by_control_number(self, data):\n data = force_list(data)\n from inspirehep.records.api.literature import LiteratureRecord\n resolved_records = LiteratureRecord.get_es_linked_references(data)\n return {record['control_number']: record.dumps() for record in\n resolved_records}\n <function token>\n <function token>\n\n def get_dois(self, data):\n doi = get_value(data, 'dois[0].value') or get_value(data, 'dois[0]')\n if doi:\n return [{'value': doi}]\n return missing\n <function token>\n <function token>\n <function token>\n\n\nclass ReferenceItemSchemaV2(ReferenceItemSchemaV1):\n raw_ref = fields.Raw()\n\n def get_reference_data(self, reference, reference_records):\n reference_data = super().get_reference_data(reference,\n reference_records)\n raw_refs = get_values_for_schema(reference.get('raw_refs', []), 'text')\n if raw_refs:\n reference_data['raw_ref'] = raw_refs[0]\n return reference_data\n", "<import token>\n\n\nclass ReferenceItemSchemaV1(Schema):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def get_dois(self, data):\n doi = get_value(data, 'dois[0].value') or get_value(data, 'dois[0]')\n if doi:\n return [{'value': doi}]\n return missing\n <function token>\n <function token>\n <function token>\n\n\nclass ReferenceItemSchemaV2(ReferenceItemSchemaV1):\n raw_ref = fields.Raw()\n\n def get_reference_data(self, reference, reference_records):\n reference_data = super().get_reference_data(reference,\n reference_records)\n raw_refs = get_values_for_schema(reference.get('raw_refs', []), 'text')\n if raw_refs:\n reference_data['raw_ref'] = raw_refs[0]\n return reference_data\n", "<import token>\n\n\nclass ReferenceItemSchemaV1(Schema):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass ReferenceItemSchemaV2(ReferenceItemSchemaV1):\n raw_ref = fields.Raw()\n\n def get_reference_data(self, reference, reference_records):\n reference_data = super().get_reference_data(reference,\n reference_records)\n raw_refs = get_values_for_schema(reference.get('raw_refs', []), 'text')\n if raw_refs:\n reference_data['raw_ref'] = raw_refs[0]\n return reference_data\n", "<import token>\n<class token>\n\n\nclass ReferenceItemSchemaV2(ReferenceItemSchemaV1):\n raw_ref = fields.Raw()\n\n def get_reference_data(self, reference, reference_records):\n reference_data = super().get_reference_data(reference,\n reference_records)\n raw_refs = get_values_for_schema(reference.get('raw_refs', []), 'text')\n if raw_refs:\n reference_data['raw_ref'] = raw_refs[0]\n return reference_data\n", "<import token>\n<class token>\n\n\nclass ReferenceItemSchemaV2(ReferenceItemSchemaV1):\n <assignment token>\n\n def get_reference_data(self, reference, reference_records):\n reference_data = super().get_reference_data(reference,\n reference_records)\n raw_refs = get_values_for_schema(reference.get('raw_refs', []), 'text')\n if raw_refs:\n reference_data['raw_ref'] = raw_refs[0]\n return reference_data\n", "<import token>\n<class token>\n\n\nclass ReferenceItemSchemaV2(ReferenceItemSchemaV1):\n <assignment token>\n <function token>\n", "<import token>\n<class token>\n<class token>\n" ]
false
98,740
5da84186119d634ceaf79f1fc66183fd37f9d89c
import cv2 import numpy as np class LaneDetector(): ''' Lane Detector - performs three key functions: 1a) detects lanes in given image using sliding window algorithm 1b) detects lanes around previously found lanes 2) calculates lane curvature 3) displays lane information Uses code from Udacity lessons ''' def __init__(self): self.left_fit = None self.right_fit = None self.leftx = None self.rightx = None self.car_position = None print('(init: LaneDetector)') def window_fit(self, img): ''' Apply polynomial fit to the given image, returning fit for left/right lanes Called when one frame of image has previously found left_fit/right_fit. This method attempts to find lane fits in the vicinity of previous fits :param img -- input image with lane lines :return left_fit, right_fit ''' if self.left_fit is None or self.right_fit is None: return self.sliding_window_fit(img) # from the next frame of video (also called "binary_warped") # It's now much easier to find line pixels! nonzero = img.nonzero() nonzeroy = np.array(nonzero[0]) nonzerox = np.array(nonzero[1]) margin = 100 left_lane_inds = ((nonzerox > (self.left_fit[0]*(nonzeroy**2) + self.left_fit[1]*nonzeroy + self.left_fit[2] - margin)) & (nonzerox < (self.left_fit[0]*(nonzeroy**2) + self.left_fit[1]*nonzeroy + self.left_fit[2] + margin))) right_lane_inds = ((nonzerox > (self.right_fit[0]*(nonzeroy**2) + self.right_fit[1]*nonzeroy + self.right_fit[2] - margin)) & (nonzerox < (self.right_fit[0]*(nonzeroy**2) + self.right_fit[1]*nonzeroy + self.right_fit[2] + margin))) # Again, extract left and right line pixel positions self.leftx = nonzerox[left_lane_inds] lefty = nonzeroy[left_lane_inds] self.rightx = nonzerox[right_lane_inds] righty = nonzeroy[right_lane_inds] # Fit a second order polynomial to each self.left_fit = np.polyfit(lefty, self.leftx, 2) self.right_fit = np.polyfit(righty, self.rightx, 2) return self.left_fit, self.right_fit def sliding_window_fit(self, img): ''' Apply sliding windows search to the given image to find polynomial to find lane lines Code based largely on Udacity lessons :param img - given image :return left_fit, right_fit - polynomials fitting the left/right lane lines ''' y_half = int(img.shape[0]/2) # take histogram of bottom half of img histogram = np.sum(img[y_half:, :], axis=0) # Create an output image to draw on and visualize the result out_img = np.dstack((img, img, img))*255 # Find the peak of the left and right halves of the histogram # These will be the starting point for the left and right lines midpoint = np.int(histogram.shape[0]/2) leftx_base = np.argmax(histogram[:midpoint]) rightx_base = np.argmax(histogram[midpoint:]) + midpoint # Choose the number of sliding windows nwindows = 9 # Set height of windows window_height = np.int(img.shape[0]/nwindows) # Identify the x and y positions of all nonzero pixels in the image nonzero = img.nonzero() nonzeroy = np.array(nonzero[0]) nonzerox = np.array(nonzero[1]) # Current positions to be updated for each window leftx_current = leftx_base rightx_current = rightx_base # Set the width of the windows +/- margin margin = 100 # Set minimum number of pixels found to recenter window minpix = 50 # Create empty lists to receive left and right lane pixel indices left_lane_inds = [] right_lane_inds = [] for window in range(nwindows): # Identify window boundaries in x and y (and right and left) win_y_low = img.shape[0] - (window+1) * window_height win_y_high = img.shape[0] - window * window_height win_xleft_low = leftx_current - margin win_xleft_high = leftx_current + margin win_xright_low = rightx_current - margin win_xright_high = rightx_current + margin # Draw the windows on the visualization image cv2.rectangle(out_img,(win_xleft_low,win_y_low), (win_xleft_high,win_y_high), (0,255,0), 2) cv2.rectangle(out_img,(win_xright_low,win_y_low),(win_xright_high,win_y_high),(0,255,0), 2) # Identify the nonzero pixels in x and y within the window good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_xleft_low) & (nonzerox < win_xleft_high)).nonzero()[0] good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_xright_low) & (nonzerox < win_xright_high)).nonzero()[0] # Append these indices to the lists left_lane_inds.append(good_left_inds) right_lane_inds.append(good_right_inds) # If you found > minpix pixels, recenter next window on their mean position if len(good_left_inds) > minpix: leftx_current = np.int( np.mean(nonzerox[good_left_inds]) ) if len(good_right_inds) > minpix: rightx_current = np.int( np.mean(nonzerox[good_right_inds]) ) # Concatenate the arrays of indices left_lane_inds = np.concatenate(left_lane_inds) right_lane_inds = np.concatenate(right_lane_inds) # Extract left and right line pixel positions self.leftx = nonzerox[left_lane_inds] lefty = nonzeroy[left_lane_inds] righty = nonzeroy[right_lane_inds] self.rightx = nonzerox[right_lane_inds] # Fit a second order polynomial to each self.left_fit = np.polyfit(lefty, self.leftx, 2) self.right_fit = np.polyfit(righty,self.rightx, 2) return self.left_fit, self.right_fit def find_lane_curvature(self, img): ''' Find lane curvature for the given img :param img - the input image :return lane curvature ''' # Generate some fake data to represent lane-line pixels ploty = np.linspace(0, 719, num=720) # to cover same y-range as image quadratic_coeff = 3e-4 # arbitrary quadratic coefficient # For each y position generate random x position within +/-50 pix # of the line base position in each case (x=200 for left, and x=900 for right) leftx = np.array([200 + (y**2)*quadratic_coeff + np.random.randint(-50, high=51) for y in ploty]) rightx = np.array([900 + (y**2)*quadratic_coeff + np.random.randint(-50, high=51) for y in ploty]) leftx = leftx[::-1] # Reverse to match top-to-bottom in y rightx = rightx[::-1] # Reverse to match top-to-bottom in y # Fit a second order polynomial to pixel positions in each fake lane line # left_fit = np.polyfit(ploty, leftx, 2) # left_fitx = left_fit[0]*ploty**2 + left_fit[1]*ploty + left_fit[2] # right_fit = np.polyfit(ploty, rightx, 2) # right_fitx = right_fit[0]*ploty**2 + right_fit[1]*ploty + right_fit[2] # Define y-value where we want radius of curvature # I'll choose the maximum y-value, corresponding to the bottom of the image y_eval = np.max(ploty) # left_curverad = ((1 + (2*left_fit[0]*y_eval + left_fit[1])**2)**1.5) / np.absolute(2*left_fit[0]) # right_curverad = ((1 + (2*right_fit[0]*y_eval + right_fit[1])**2)**1.5) / np.absolute(2*right_fit[0]) # print(left_curverad, right_curverad) # Example values: 1926.74 1908.48 # Define conversions in x and y from pixels space to meters ym_per_pix = 30/720 # meters per pixel in y dimension xm_per_pix = 3.7/700 # meters per pixel in x dimension # Fit new polynomials to x,y in world space left_fit_cr = np.polyfit(ploty * ym_per_pix, leftx * xm_per_pix, 2) right_fit_cr = np.polyfit(ploty * ym_per_pix, rightx * xm_per_pix, 2) # Calculate the new radii of curvature left_curverad = ((1 + (2 * left_fit_cr[0] * y_eval*ym_per_pix + \ left_fit_cr[1]) ** 2) ** 1.5) / np.absolute(2 * left_fit_cr[0]) right_curverad = ((1 + (2 * right_fit_cr[0] * y_eval * ym_per_pix + \ right_fit_cr[1]) ** 2) ** 1.5) / np.absolute(2 * right_fit_cr[0]) # Now our radius of curvature is in meters # print(left_curverad, 'm', right_curverad, 'm') # Example values: 632.1 m 626.2 m lx = self.left_fit[0] * (img.shape[0] - 1)**2 + \ self.left_fit[1] * (img.shape[0] - 1) + \ self.left_fit[2] rx = self.right_fit[0] * (img.shape[0] - 1)**2 + \ self.right_fit[1] * (img.shape[0] - 1) + \ self.right_fit[2] # calc car's position in the lane w.r.to center position = ((img.shape[1] / 2) - ((lx + rx)/2)) * xm_per_pix # calc mean curvature mean_curverad = (left_curverad + right_curverad) / 2 # save the car's position self.car_position = position.round(2) return mean_curverad def draw_polygon(self, img, left_fit, right_fit, M_inverse): ''' Draw shaded polygon on the lane between left_fit and right_fit :param img - undistorted image, on which to draw the lane polygon :param left_fit - left lane values (x) :param right_fit - right lane values (x) :param M_inverse - matrix for inverse transform warping :return - img - the modified image with polygon ''' fity = np.linspace(0, img.shape[0] - 1, img.shape[0]) left_fitx = left_fit[0] * fity ** 2 + left_fit[1] * fity + left_fit[2] right_fitx = right_fit[0] * fity ** 2 + right_fit[1] * fity + right_fit[2] color_warp = np.zeros_like(img).astype(np.uint8) # Recast the x and y points into usable format for cv2.fillPoly() pts_left = np.array( [np.transpose(np.vstack([left_fitx, fity]))] ) pts_right = np.array( [np.flipud(np.transpose(np.vstack([right_fitx, fity])))] ) pts = np.hstack((pts_left, pts_right)) pts = np.array(pts, dtype=np.int32) # Draw the lane onto the warped blank image cv2.fillPoly(color_warp, np.int_([pts]), (0,255, 0)) # Warp the blank back to original image space using inverse perspective matrix (Minv) newwarp = cv2.warpPerspective(color_warp, M_inverse, (img.shape[1], img.shape[0])) # Combine the result with the original image result = cv2.addWeighted(img, 1, newwarp, 0.3, 0) return result def display_dashboard(self, img, lane_curve): ''' Display a dashboard on the image, with info on Lane curve (avg) :param img - image with lane lines :param lane_curve - the avg lane curvature :param position :return modified img ''' COLOR_LIGHTBLUE = (172,227,239) COLOR_GOLD = (255, 215, 0) if self.car_position > 0: msg = '{}m right of center'.format(self.car_position) else: msg = '{}m left of center'.format(np.abs(self.car_position)) cv2.putText(img, 'Lane curve radius: {}m'.format(lane_curve.round()), (10,50), cv2.FONT_HERSHEY_SIMPLEX, 1, color=COLOR_GOLD, thickness=2) cv2.putText(img, 'Car is {}'.format(msg), (10,80), cv2.FONT_HERSHEY_SIMPLEX, 1, color=COLOR_GOLD, thickness=2) cv2.rectangle(img, (5, 10), (480, 100), color=COLOR_GOLD, thickness=2) return img
[ "import cv2\nimport numpy as np\n\nclass LaneDetector():\n ''' Lane Detector - performs three key functions:\n 1a) detects lanes in given image using sliding window algorithm\n 1b) detects lanes around previously found lanes\n 2) calculates lane curvature\n 3) displays lane information\n\n Uses code from Udacity lessons\n '''\n def __init__(self):\n self.left_fit = None\n self.right_fit = None\n self.leftx = None \n self.rightx = None\n self.car_position = None\n print('(init: LaneDetector)')\n\n def window_fit(self, img):\n ''' Apply polynomial fit to the given image, returning fit for left/right lanes\n Called when one frame of image has previously found left_fit/right_fit. \n This method attempts to find lane fits in the vicinity of previous fits\n :param img -- input image with lane lines\n :return left_fit, right_fit\n '''\n\n if self.left_fit is None or self.right_fit is None:\n return self.sliding_window_fit(img)\n \n # from the next frame of video (also called \"binary_warped\")\n # It's now much easier to find line pixels!\n nonzero = img.nonzero()\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n margin = 100\n left_lane_inds = ((nonzerox > (self.left_fit[0]*(nonzeroy**2) + self.left_fit[1]*nonzeroy + self.left_fit[2] - margin)) & \n (nonzerox < (self.left_fit[0]*(nonzeroy**2) + self.left_fit[1]*nonzeroy + self.left_fit[2] + margin))) \n right_lane_inds = ((nonzerox > (self.right_fit[0]*(nonzeroy**2) + self.right_fit[1]*nonzeroy + self.right_fit[2] - margin)) & \n (nonzerox < (self.right_fit[0]*(nonzeroy**2) + self.right_fit[1]*nonzeroy + self.right_fit[2] + margin))) \n\n # Again, extract left and right line pixel positions\n self.leftx = nonzerox[left_lane_inds]\n lefty = nonzeroy[left_lane_inds] \n self.rightx = nonzerox[right_lane_inds]\n righty = nonzeroy[right_lane_inds]\n # Fit a second order polynomial to each\n self.left_fit = np.polyfit(lefty, self.leftx, 2)\n self.right_fit = np.polyfit(righty, self.rightx, 2)\n\n return self.left_fit, self.right_fit\n\n def sliding_window_fit(self, img):\n ''' Apply sliding windows search to the given image to find polynomial to find lane lines\n Code based largely on Udacity lessons\n :param img - given image\n :return left_fit, right_fit - polynomials fitting the left/right lane lines\n '''\n y_half = int(img.shape[0]/2)\n # take histogram of bottom half of img\n histogram = np.sum(img[y_half:, :], axis=0)\n # Create an output image to draw on and visualize the result\n out_img = np.dstack((img, img, img))*255\n # Find the peak of the left and right halves of the histogram\n # These will be the starting point for the left and right lines\n midpoint = np.int(histogram.shape[0]/2)\n leftx_base = np.argmax(histogram[:midpoint])\n rightx_base = np.argmax(histogram[midpoint:]) + midpoint\n\n # Choose the number of sliding windows\n nwindows = 9\n # Set height of windows\n window_height = np.int(img.shape[0]/nwindows)\n # Identify the x and y positions of all nonzero pixels in the image\n nonzero = img.nonzero()\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n # Current positions to be updated for each window\n leftx_current = leftx_base\n rightx_current = rightx_base\n\n # Set the width of the windows +/- margin\n margin = 100\n # Set minimum number of pixels found to recenter window\n minpix = 50\n # Create empty lists to receive left and right lane pixel indices\n left_lane_inds = []\n right_lane_inds = []\n\n for window in range(nwindows):\n # Identify window boundaries in x and y (and right and left)\n win_y_low = img.shape[0] - (window+1) * window_height\n win_y_high = img.shape[0] - window * window_height\n win_xleft_low = leftx_current - margin\n win_xleft_high = leftx_current + margin\n win_xright_low = rightx_current - margin\n win_xright_high = rightx_current + margin\n # Draw the windows on the visualization image\n cv2.rectangle(out_img,(win_xleft_low,win_y_low), (win_xleft_high,win_y_high), (0,255,0), 2) \n cv2.rectangle(out_img,(win_xright_low,win_y_low),(win_xright_high,win_y_high),(0,255,0), 2) \n # Identify the nonzero pixels in x and y within the window\n good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & \n (nonzerox >= win_xleft_low) & (nonzerox < win_xleft_high)).nonzero()[0]\n good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & \n (nonzerox >= win_xright_low) & (nonzerox < win_xright_high)).nonzero()[0]\n # Append these indices to the lists\n left_lane_inds.append(good_left_inds)\n right_lane_inds.append(good_right_inds)\n # If you found > minpix pixels, recenter next window on their mean position\n if len(good_left_inds) > minpix:\n leftx_current = np.int( np.mean(nonzerox[good_left_inds]) )\n if len(good_right_inds) > minpix: \n rightx_current = np.int( np.mean(nonzerox[good_right_inds]) )\n\n \n # Concatenate the arrays of indices\n left_lane_inds = np.concatenate(left_lane_inds)\n right_lane_inds = np.concatenate(right_lane_inds)\n\n # Extract left and right line pixel positions\n self.leftx = nonzerox[left_lane_inds]\n lefty = nonzeroy[left_lane_inds] \n \n righty = nonzeroy[right_lane_inds]\n self.rightx = nonzerox[right_lane_inds]\n\n # Fit a second order polynomial to each\n self.left_fit = np.polyfit(lefty, self.leftx, 2)\n self.right_fit = np.polyfit(righty,self.rightx, 2)\n\n return self.left_fit, self.right_fit\n\n def find_lane_curvature(self, img):\n ''' Find lane curvature for the given img\n :param img - the input image\n :return lane curvature\n '''\n # Generate some fake data to represent lane-line pixels\n ploty = np.linspace(0, 719, num=720) # to cover same y-range as image\n quadratic_coeff = 3e-4 # arbitrary quadratic coefficient\n # For each y position generate random x position within +/-50 pix\n # of the line base position in each case (x=200 for left, and x=900 for right)\n leftx = np.array([200 + (y**2)*quadratic_coeff + np.random.randint(-50, high=51) \n for y in ploty])\n rightx = np.array([900 + (y**2)*quadratic_coeff + np.random.randint(-50, high=51) \n for y in ploty])\n\n leftx = leftx[::-1] # Reverse to match top-to-bottom in y\n rightx = rightx[::-1] # Reverse to match top-to-bottom in y\n\n\n # Fit a second order polynomial to pixel positions in each fake lane line\n # left_fit = np.polyfit(ploty, leftx, 2)\n # left_fitx = left_fit[0]*ploty**2 + left_fit[1]*ploty + left_fit[2]\n # right_fit = np.polyfit(ploty, rightx, 2)\n # right_fitx = right_fit[0]*ploty**2 + right_fit[1]*ploty + right_fit[2]\n\n # Define y-value where we want radius of curvature\n # I'll choose the maximum y-value, corresponding to the bottom of the image\n y_eval = np.max(ploty)\n # left_curverad = ((1 + (2*left_fit[0]*y_eval + left_fit[1])**2)**1.5) / np.absolute(2*left_fit[0])\n # right_curverad = ((1 + (2*right_fit[0]*y_eval + right_fit[1])**2)**1.5) / np.absolute(2*right_fit[0])\n # print(left_curverad, right_curverad)\n # Example values: 1926.74 1908.48\n\n # Define conversions in x and y from pixels space to meters\n ym_per_pix = 30/720 # meters per pixel in y dimension\n xm_per_pix = 3.7/700 # meters per pixel in x dimension\n\n # Fit new polynomials to x,y in world space\n left_fit_cr = np.polyfit(ploty * ym_per_pix, leftx * xm_per_pix, 2)\n right_fit_cr = np.polyfit(ploty * ym_per_pix, rightx * xm_per_pix, 2)\n # Calculate the new radii of curvature\n left_curverad = ((1 + (2 * left_fit_cr[0] * y_eval*ym_per_pix + \\\n left_fit_cr[1]) ** 2) ** 1.5) / np.absolute(2 * left_fit_cr[0])\n right_curverad = ((1 + (2 * right_fit_cr[0] * y_eval * ym_per_pix + \\\n right_fit_cr[1]) ** 2) ** 1.5) / np.absolute(2 * right_fit_cr[0])\n # Now our radius of curvature is in meters\n # print(left_curverad, 'm', right_curverad, 'm')\n # Example values: 632.1 m 626.2 m\n\n lx = self.left_fit[0] * (img.shape[0] - 1)**2 + \\\n self.left_fit[1] * (img.shape[0] - 1) + \\\n self.left_fit[2]\n rx = self.right_fit[0] * (img.shape[0] - 1)**2 + \\\n self.right_fit[1] * (img.shape[0] - 1) + \\\n self.right_fit[2]\n # calc car's position in the lane w.r.to center\n position = ((img.shape[1] / 2) - ((lx + rx)/2)) * xm_per_pix\n\n # calc mean curvature\n mean_curverad = (left_curverad + right_curverad) / 2\n # save the car's position\n self.car_position = position.round(2)\n return mean_curverad\n\n def draw_polygon(self, img, left_fit, right_fit, M_inverse):\n ''' Draw shaded polygon on the lane between left_fit and right_fit\n :param img - undistorted image, on which to draw the lane polygon\n :param left_fit - left lane values (x)\n :param right_fit - right lane values (x)\n :param M_inverse - matrix for inverse transform warping\n :return - img - the modified image with polygon\n ''' \n fity = np.linspace(0, img.shape[0] - 1, img.shape[0])\n left_fitx = left_fit[0] * fity ** 2 + left_fit[1] * fity + left_fit[2]\n right_fitx = right_fit[0] * fity ** 2 + right_fit[1] * fity + right_fit[2]\n\n color_warp = np.zeros_like(img).astype(np.uint8)\n\n # Recast the x and y points into usable format for cv2.fillPoly()\n pts_left = np.array( [np.transpose(np.vstack([left_fitx, fity]))] )\n pts_right = np.array( [np.flipud(np.transpose(np.vstack([right_fitx, fity])))] )\n pts = np.hstack((pts_left, pts_right))\n pts = np.array(pts, dtype=np.int32)\n\n # Draw the lane onto the warped blank image\n cv2.fillPoly(color_warp, np.int_([pts]), (0,255, 0))\n\n # Warp the blank back to original image space using inverse perspective matrix (Minv)\n newwarp = cv2.warpPerspective(color_warp, M_inverse, (img.shape[1], img.shape[0])) \n # Combine the result with the original image\n result = cv2.addWeighted(img, 1, newwarp, 0.3, 0)\n\n return result\n\n def display_dashboard(self, img, lane_curve):\n ''' Display a dashboard on the image, with info on\n Lane curve (avg)\n :param img - image with lane lines\n :param lane_curve - the avg lane curvature\n :param position\n :return modified img\n '''\n COLOR_LIGHTBLUE = (172,227,239) \n COLOR_GOLD = (255, 215, 0)\n\n if self.car_position > 0:\n msg = '{}m right of center'.format(self.car_position)\n else:\n msg = '{}m left of center'.format(np.abs(self.car_position))\n\n cv2.putText(img, 'Lane curve radius: {}m'.format(lane_curve.round()), \n (10,50), cv2.FONT_HERSHEY_SIMPLEX, 1, \n color=COLOR_GOLD, thickness=2)\n cv2.putText(img, 'Car is {}'.format(msg), \n (10,80), cv2.FONT_HERSHEY_SIMPLEX, 1,\n color=COLOR_GOLD, thickness=2)\n cv2.rectangle(img, (5, 10), (480, 100), color=COLOR_GOLD, thickness=2)\n return img\n\n\n\n", "import cv2\nimport numpy as np\n\n\nclass LaneDetector:\n \"\"\" Lane Detector - performs three key functions:\n 1a) detects lanes in given image using sliding window algorithm\n 1b) detects lanes around previously found lanes\n 2) calculates lane curvature\n 3) displays lane information\n\n Uses code from Udacity lessons\n \"\"\"\n\n def __init__(self):\n self.left_fit = None\n self.right_fit = None\n self.leftx = None\n self.rightx = None\n self.car_position = None\n print('(init: LaneDetector)')\n\n def window_fit(self, img):\n \"\"\" Apply polynomial fit to the given image, returning fit for left/right lanes\n Called when one frame of image has previously found left_fit/right_fit. \n This method attempts to find lane fits in the vicinity of previous fits\n :param img -- input image with lane lines\n :return left_fit, right_fit\n \"\"\"\n if self.left_fit is None or self.right_fit is None:\n return self.sliding_window_fit(img)\n nonzero = img.nonzero()\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n margin = 100\n left_lane_inds = (nonzerox > self.left_fit[0] * nonzeroy ** 2 + \n self.left_fit[1] * nonzeroy + self.left_fit[2] - margin) & (\n nonzerox < self.left_fit[0] * nonzeroy ** 2 + self.left_fit[1] *\n nonzeroy + self.left_fit[2] + margin)\n right_lane_inds = (nonzerox > self.right_fit[0] * nonzeroy ** 2 + \n self.right_fit[1] * nonzeroy + self.right_fit[2] - margin) & (\n nonzerox < self.right_fit[0] * nonzeroy ** 2 + self.right_fit[1\n ] * nonzeroy + self.right_fit[2] + margin)\n self.leftx = nonzerox[left_lane_inds]\n lefty = nonzeroy[left_lane_inds]\n self.rightx = nonzerox[right_lane_inds]\n righty = nonzeroy[right_lane_inds]\n self.left_fit = np.polyfit(lefty, self.leftx, 2)\n self.right_fit = np.polyfit(righty, self.rightx, 2)\n return self.left_fit, self.right_fit\n\n def sliding_window_fit(self, img):\n \"\"\" Apply sliding windows search to the given image to find polynomial to find lane lines\n Code based largely on Udacity lessons\n :param img - given image\n :return left_fit, right_fit - polynomials fitting the left/right lane lines\n \"\"\"\n y_half = int(img.shape[0] / 2)\n histogram = np.sum(img[y_half:, :], axis=0)\n out_img = np.dstack((img, img, img)) * 255\n midpoint = np.int(histogram.shape[0] / 2)\n leftx_base = np.argmax(histogram[:midpoint])\n rightx_base = np.argmax(histogram[midpoint:]) + midpoint\n nwindows = 9\n window_height = np.int(img.shape[0] / nwindows)\n nonzero = img.nonzero()\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n leftx_current = leftx_base\n rightx_current = rightx_base\n margin = 100\n minpix = 50\n left_lane_inds = []\n right_lane_inds = []\n for window in range(nwindows):\n win_y_low = img.shape[0] - (window + 1) * window_height\n win_y_high = img.shape[0] - window * window_height\n win_xleft_low = leftx_current - margin\n win_xleft_high = leftx_current + margin\n win_xright_low = rightx_current - margin\n win_xright_high = rightx_current + margin\n cv2.rectangle(out_img, (win_xleft_low, win_y_low), (\n win_xleft_high, win_y_high), (0, 255, 0), 2)\n cv2.rectangle(out_img, (win_xright_low, win_y_low), (\n win_xright_high, win_y_high), (0, 255, 0), 2)\n good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy <\n win_y_high) & (nonzerox >= win_xleft_low) & (nonzerox <\n win_xleft_high)).nonzero()[0]\n good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy <\n win_y_high) & (nonzerox >= win_xright_low) & (nonzerox <\n win_xright_high)).nonzero()[0]\n left_lane_inds.append(good_left_inds)\n right_lane_inds.append(good_right_inds)\n if len(good_left_inds) > minpix:\n leftx_current = np.int(np.mean(nonzerox[good_left_inds]))\n if len(good_right_inds) > minpix:\n rightx_current = np.int(np.mean(nonzerox[good_right_inds]))\n left_lane_inds = np.concatenate(left_lane_inds)\n right_lane_inds = np.concatenate(right_lane_inds)\n self.leftx = nonzerox[left_lane_inds]\n lefty = nonzeroy[left_lane_inds]\n righty = nonzeroy[right_lane_inds]\n self.rightx = nonzerox[right_lane_inds]\n self.left_fit = np.polyfit(lefty, self.leftx, 2)\n self.right_fit = np.polyfit(righty, self.rightx, 2)\n return self.left_fit, self.right_fit\n\n def find_lane_curvature(self, img):\n \"\"\" Find lane curvature for the given img\n :param img - the input image\n :return lane curvature\n \"\"\"\n ploty = np.linspace(0, 719, num=720)\n quadratic_coeff = 0.0003\n leftx = np.array([(200 + y ** 2 * quadratic_coeff + np.random.\n randint(-50, high=51)) for y in ploty])\n rightx = np.array([(900 + y ** 2 * quadratic_coeff + np.random.\n randint(-50, high=51)) for y in ploty])\n leftx = leftx[::-1]\n rightx = rightx[::-1]\n y_eval = np.max(ploty)\n ym_per_pix = 30 / 720\n xm_per_pix = 3.7 / 700\n left_fit_cr = np.polyfit(ploty * ym_per_pix, leftx * xm_per_pix, 2)\n right_fit_cr = np.polyfit(ploty * ym_per_pix, rightx * xm_per_pix, 2)\n left_curverad = (1 + (2 * left_fit_cr[0] * y_eval * ym_per_pix +\n left_fit_cr[1]) ** 2) ** 1.5 / np.absolute(2 * left_fit_cr[0])\n right_curverad = (1 + (2 * right_fit_cr[0] * y_eval * ym_per_pix +\n right_fit_cr[1]) ** 2) ** 1.5 / np.absolute(2 * right_fit_cr[0])\n lx = self.left_fit[0] * (img.shape[0] - 1) ** 2 + self.left_fit[1] * (\n img.shape[0] - 1) + self.left_fit[2]\n rx = self.right_fit[0] * (img.shape[0] - 1) ** 2 + self.right_fit[1\n ] * (img.shape[0] - 1) + self.right_fit[2]\n position = (img.shape[1] / 2 - (lx + rx) / 2) * xm_per_pix\n mean_curverad = (left_curverad + right_curverad) / 2\n self.car_position = position.round(2)\n return mean_curverad\n\n def draw_polygon(self, img, left_fit, right_fit, M_inverse):\n \"\"\" Draw shaded polygon on the lane between left_fit and right_fit\n :param img - undistorted image, on which to draw the lane polygon\n :param left_fit - left lane values (x)\n :param right_fit - right lane values (x)\n :param M_inverse - matrix for inverse transform warping\n :return - img - the modified image with polygon\n \"\"\"\n fity = np.linspace(0, img.shape[0] - 1, img.shape[0])\n left_fitx = left_fit[0] * fity ** 2 + left_fit[1] * fity + left_fit[2]\n right_fitx = right_fit[0] * fity ** 2 + right_fit[1\n ] * fity + right_fit[2]\n color_warp = np.zeros_like(img).astype(np.uint8)\n pts_left = np.array([np.transpose(np.vstack([left_fitx, fity]))])\n pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx,\n fity])))])\n pts = np.hstack((pts_left, pts_right))\n pts = np.array(pts, dtype=np.int32)\n cv2.fillPoly(color_warp, np.int_([pts]), (0, 255, 0))\n newwarp = cv2.warpPerspective(color_warp, M_inverse, (img.shape[1],\n img.shape[0]))\n result = cv2.addWeighted(img, 1, newwarp, 0.3, 0)\n return result\n\n def display_dashboard(self, img, lane_curve):\n \"\"\" Display a dashboard on the image, with info on\n Lane curve (avg)\n :param img - image with lane lines\n :param lane_curve - the avg lane curvature\n :param position\n :return modified img\n \"\"\"\n COLOR_LIGHTBLUE = 172, 227, 239\n COLOR_GOLD = 255, 215, 0\n if self.car_position > 0:\n msg = '{}m right of center'.format(self.car_position)\n else:\n msg = '{}m left of center'.format(np.abs(self.car_position))\n cv2.putText(img, 'Lane curve radius: {}m'.format(lane_curve.round()\n ), (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, color=COLOR_GOLD,\n thickness=2)\n cv2.putText(img, 'Car is {}'.format(msg), (10, 80), cv2.\n FONT_HERSHEY_SIMPLEX, 1, color=COLOR_GOLD, thickness=2)\n cv2.rectangle(img, (5, 10), (480, 100), color=COLOR_GOLD, thickness=2)\n return img\n", "<import token>\n\n\nclass LaneDetector:\n \"\"\" Lane Detector - performs three key functions:\n 1a) detects lanes in given image using sliding window algorithm\n 1b) detects lanes around previously found lanes\n 2) calculates lane curvature\n 3) displays lane information\n\n Uses code from Udacity lessons\n \"\"\"\n\n def __init__(self):\n self.left_fit = None\n self.right_fit = None\n self.leftx = None\n self.rightx = None\n self.car_position = None\n print('(init: LaneDetector)')\n\n def window_fit(self, img):\n \"\"\" Apply polynomial fit to the given image, returning fit for left/right lanes\n Called when one frame of image has previously found left_fit/right_fit. \n This method attempts to find lane fits in the vicinity of previous fits\n :param img -- input image with lane lines\n :return left_fit, right_fit\n \"\"\"\n if self.left_fit is None or self.right_fit is None:\n return self.sliding_window_fit(img)\n nonzero = img.nonzero()\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n margin = 100\n left_lane_inds = (nonzerox > self.left_fit[0] * nonzeroy ** 2 + \n self.left_fit[1] * nonzeroy + self.left_fit[2] - margin) & (\n nonzerox < self.left_fit[0] * nonzeroy ** 2 + self.left_fit[1] *\n nonzeroy + self.left_fit[2] + margin)\n right_lane_inds = (nonzerox > self.right_fit[0] * nonzeroy ** 2 + \n self.right_fit[1] * nonzeroy + self.right_fit[2] - margin) & (\n nonzerox < self.right_fit[0] * nonzeroy ** 2 + self.right_fit[1\n ] * nonzeroy + self.right_fit[2] + margin)\n self.leftx = nonzerox[left_lane_inds]\n lefty = nonzeroy[left_lane_inds]\n self.rightx = nonzerox[right_lane_inds]\n righty = nonzeroy[right_lane_inds]\n self.left_fit = np.polyfit(lefty, self.leftx, 2)\n self.right_fit = np.polyfit(righty, self.rightx, 2)\n return self.left_fit, self.right_fit\n\n def sliding_window_fit(self, img):\n \"\"\" Apply sliding windows search to the given image to find polynomial to find lane lines\n Code based largely on Udacity lessons\n :param img - given image\n :return left_fit, right_fit - polynomials fitting the left/right lane lines\n \"\"\"\n y_half = int(img.shape[0] / 2)\n histogram = np.sum(img[y_half:, :], axis=0)\n out_img = np.dstack((img, img, img)) * 255\n midpoint = np.int(histogram.shape[0] / 2)\n leftx_base = np.argmax(histogram[:midpoint])\n rightx_base = np.argmax(histogram[midpoint:]) + midpoint\n nwindows = 9\n window_height = np.int(img.shape[0] / nwindows)\n nonzero = img.nonzero()\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n leftx_current = leftx_base\n rightx_current = rightx_base\n margin = 100\n minpix = 50\n left_lane_inds = []\n right_lane_inds = []\n for window in range(nwindows):\n win_y_low = img.shape[0] - (window + 1) * window_height\n win_y_high = img.shape[0] - window * window_height\n win_xleft_low = leftx_current - margin\n win_xleft_high = leftx_current + margin\n win_xright_low = rightx_current - margin\n win_xright_high = rightx_current + margin\n cv2.rectangle(out_img, (win_xleft_low, win_y_low), (\n win_xleft_high, win_y_high), (0, 255, 0), 2)\n cv2.rectangle(out_img, (win_xright_low, win_y_low), (\n win_xright_high, win_y_high), (0, 255, 0), 2)\n good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy <\n win_y_high) & (nonzerox >= win_xleft_low) & (nonzerox <\n win_xleft_high)).nonzero()[0]\n good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy <\n win_y_high) & (nonzerox >= win_xright_low) & (nonzerox <\n win_xright_high)).nonzero()[0]\n left_lane_inds.append(good_left_inds)\n right_lane_inds.append(good_right_inds)\n if len(good_left_inds) > minpix:\n leftx_current = np.int(np.mean(nonzerox[good_left_inds]))\n if len(good_right_inds) > minpix:\n rightx_current = np.int(np.mean(nonzerox[good_right_inds]))\n left_lane_inds = np.concatenate(left_lane_inds)\n right_lane_inds = np.concatenate(right_lane_inds)\n self.leftx = nonzerox[left_lane_inds]\n lefty = nonzeroy[left_lane_inds]\n righty = nonzeroy[right_lane_inds]\n self.rightx = nonzerox[right_lane_inds]\n self.left_fit = np.polyfit(lefty, self.leftx, 2)\n self.right_fit = np.polyfit(righty, self.rightx, 2)\n return self.left_fit, self.right_fit\n\n def find_lane_curvature(self, img):\n \"\"\" Find lane curvature for the given img\n :param img - the input image\n :return lane curvature\n \"\"\"\n ploty = np.linspace(0, 719, num=720)\n quadratic_coeff = 0.0003\n leftx = np.array([(200 + y ** 2 * quadratic_coeff + np.random.\n randint(-50, high=51)) for y in ploty])\n rightx = np.array([(900 + y ** 2 * quadratic_coeff + np.random.\n randint(-50, high=51)) for y in ploty])\n leftx = leftx[::-1]\n rightx = rightx[::-1]\n y_eval = np.max(ploty)\n ym_per_pix = 30 / 720\n xm_per_pix = 3.7 / 700\n left_fit_cr = np.polyfit(ploty * ym_per_pix, leftx * xm_per_pix, 2)\n right_fit_cr = np.polyfit(ploty * ym_per_pix, rightx * xm_per_pix, 2)\n left_curverad = (1 + (2 * left_fit_cr[0] * y_eval * ym_per_pix +\n left_fit_cr[1]) ** 2) ** 1.5 / np.absolute(2 * left_fit_cr[0])\n right_curverad = (1 + (2 * right_fit_cr[0] * y_eval * ym_per_pix +\n right_fit_cr[1]) ** 2) ** 1.5 / np.absolute(2 * right_fit_cr[0])\n lx = self.left_fit[0] * (img.shape[0] - 1) ** 2 + self.left_fit[1] * (\n img.shape[0] - 1) + self.left_fit[2]\n rx = self.right_fit[0] * (img.shape[0] - 1) ** 2 + self.right_fit[1\n ] * (img.shape[0] - 1) + self.right_fit[2]\n position = (img.shape[1] / 2 - (lx + rx) / 2) * xm_per_pix\n mean_curverad = (left_curverad + right_curverad) / 2\n self.car_position = position.round(2)\n return mean_curverad\n\n def draw_polygon(self, img, left_fit, right_fit, M_inverse):\n \"\"\" Draw shaded polygon on the lane between left_fit and right_fit\n :param img - undistorted image, on which to draw the lane polygon\n :param left_fit - left lane values (x)\n :param right_fit - right lane values (x)\n :param M_inverse - matrix for inverse transform warping\n :return - img - the modified image with polygon\n \"\"\"\n fity = np.linspace(0, img.shape[0] - 1, img.shape[0])\n left_fitx = left_fit[0] * fity ** 2 + left_fit[1] * fity + left_fit[2]\n right_fitx = right_fit[0] * fity ** 2 + right_fit[1\n ] * fity + right_fit[2]\n color_warp = np.zeros_like(img).astype(np.uint8)\n pts_left = np.array([np.transpose(np.vstack([left_fitx, fity]))])\n pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx,\n fity])))])\n pts = np.hstack((pts_left, pts_right))\n pts = np.array(pts, dtype=np.int32)\n cv2.fillPoly(color_warp, np.int_([pts]), (0, 255, 0))\n newwarp = cv2.warpPerspective(color_warp, M_inverse, (img.shape[1],\n img.shape[0]))\n result = cv2.addWeighted(img, 1, newwarp, 0.3, 0)\n return result\n\n def display_dashboard(self, img, lane_curve):\n \"\"\" Display a dashboard on the image, with info on\n Lane curve (avg)\n :param img - image with lane lines\n :param lane_curve - the avg lane curvature\n :param position\n :return modified img\n \"\"\"\n COLOR_LIGHTBLUE = 172, 227, 239\n COLOR_GOLD = 255, 215, 0\n if self.car_position > 0:\n msg = '{}m right of center'.format(self.car_position)\n else:\n msg = '{}m left of center'.format(np.abs(self.car_position))\n cv2.putText(img, 'Lane curve radius: {}m'.format(lane_curve.round()\n ), (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, color=COLOR_GOLD,\n thickness=2)\n cv2.putText(img, 'Car is {}'.format(msg), (10, 80), cv2.\n FONT_HERSHEY_SIMPLEX, 1, color=COLOR_GOLD, thickness=2)\n cv2.rectangle(img, (5, 10), (480, 100), color=COLOR_GOLD, thickness=2)\n return img\n", "<import token>\n\n\nclass LaneDetector:\n <docstring token>\n\n def __init__(self):\n self.left_fit = None\n self.right_fit = None\n self.leftx = None\n self.rightx = None\n self.car_position = None\n print('(init: LaneDetector)')\n\n def window_fit(self, img):\n \"\"\" Apply polynomial fit to the given image, returning fit for left/right lanes\n Called when one frame of image has previously found left_fit/right_fit. \n This method attempts to find lane fits in the vicinity of previous fits\n :param img -- input image with lane lines\n :return left_fit, right_fit\n \"\"\"\n if self.left_fit is None or self.right_fit is None:\n return self.sliding_window_fit(img)\n nonzero = img.nonzero()\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n margin = 100\n left_lane_inds = (nonzerox > self.left_fit[0] * nonzeroy ** 2 + \n self.left_fit[1] * nonzeroy + self.left_fit[2] - margin) & (\n nonzerox < self.left_fit[0] * nonzeroy ** 2 + self.left_fit[1] *\n nonzeroy + self.left_fit[2] + margin)\n right_lane_inds = (nonzerox > self.right_fit[0] * nonzeroy ** 2 + \n self.right_fit[1] * nonzeroy + self.right_fit[2] - margin) & (\n nonzerox < self.right_fit[0] * nonzeroy ** 2 + self.right_fit[1\n ] * nonzeroy + self.right_fit[2] + margin)\n self.leftx = nonzerox[left_lane_inds]\n lefty = nonzeroy[left_lane_inds]\n self.rightx = nonzerox[right_lane_inds]\n righty = nonzeroy[right_lane_inds]\n self.left_fit = np.polyfit(lefty, self.leftx, 2)\n self.right_fit = np.polyfit(righty, self.rightx, 2)\n return self.left_fit, self.right_fit\n\n def sliding_window_fit(self, img):\n \"\"\" Apply sliding windows search to the given image to find polynomial to find lane lines\n Code based largely on Udacity lessons\n :param img - given image\n :return left_fit, right_fit - polynomials fitting the left/right lane lines\n \"\"\"\n y_half = int(img.shape[0] / 2)\n histogram = np.sum(img[y_half:, :], axis=0)\n out_img = np.dstack((img, img, img)) * 255\n midpoint = np.int(histogram.shape[0] / 2)\n leftx_base = np.argmax(histogram[:midpoint])\n rightx_base = np.argmax(histogram[midpoint:]) + midpoint\n nwindows = 9\n window_height = np.int(img.shape[0] / nwindows)\n nonzero = img.nonzero()\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n leftx_current = leftx_base\n rightx_current = rightx_base\n margin = 100\n minpix = 50\n left_lane_inds = []\n right_lane_inds = []\n for window in range(nwindows):\n win_y_low = img.shape[0] - (window + 1) * window_height\n win_y_high = img.shape[0] - window * window_height\n win_xleft_low = leftx_current - margin\n win_xleft_high = leftx_current + margin\n win_xright_low = rightx_current - margin\n win_xright_high = rightx_current + margin\n cv2.rectangle(out_img, (win_xleft_low, win_y_low), (\n win_xleft_high, win_y_high), (0, 255, 0), 2)\n cv2.rectangle(out_img, (win_xright_low, win_y_low), (\n win_xright_high, win_y_high), (0, 255, 0), 2)\n good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy <\n win_y_high) & (nonzerox >= win_xleft_low) & (nonzerox <\n win_xleft_high)).nonzero()[0]\n good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy <\n win_y_high) & (nonzerox >= win_xright_low) & (nonzerox <\n win_xright_high)).nonzero()[0]\n left_lane_inds.append(good_left_inds)\n right_lane_inds.append(good_right_inds)\n if len(good_left_inds) > minpix:\n leftx_current = np.int(np.mean(nonzerox[good_left_inds]))\n if len(good_right_inds) > minpix:\n rightx_current = np.int(np.mean(nonzerox[good_right_inds]))\n left_lane_inds = np.concatenate(left_lane_inds)\n right_lane_inds = np.concatenate(right_lane_inds)\n self.leftx = nonzerox[left_lane_inds]\n lefty = nonzeroy[left_lane_inds]\n righty = nonzeroy[right_lane_inds]\n self.rightx = nonzerox[right_lane_inds]\n self.left_fit = np.polyfit(lefty, self.leftx, 2)\n self.right_fit = np.polyfit(righty, self.rightx, 2)\n return self.left_fit, self.right_fit\n\n def find_lane_curvature(self, img):\n \"\"\" Find lane curvature for the given img\n :param img - the input image\n :return lane curvature\n \"\"\"\n ploty = np.linspace(0, 719, num=720)\n quadratic_coeff = 0.0003\n leftx = np.array([(200 + y ** 2 * quadratic_coeff + np.random.\n randint(-50, high=51)) for y in ploty])\n rightx = np.array([(900 + y ** 2 * quadratic_coeff + np.random.\n randint(-50, high=51)) for y in ploty])\n leftx = leftx[::-1]\n rightx = rightx[::-1]\n y_eval = np.max(ploty)\n ym_per_pix = 30 / 720\n xm_per_pix = 3.7 / 700\n left_fit_cr = np.polyfit(ploty * ym_per_pix, leftx * xm_per_pix, 2)\n right_fit_cr = np.polyfit(ploty * ym_per_pix, rightx * xm_per_pix, 2)\n left_curverad = (1 + (2 * left_fit_cr[0] * y_eval * ym_per_pix +\n left_fit_cr[1]) ** 2) ** 1.5 / np.absolute(2 * left_fit_cr[0])\n right_curverad = (1 + (2 * right_fit_cr[0] * y_eval * ym_per_pix +\n right_fit_cr[1]) ** 2) ** 1.5 / np.absolute(2 * right_fit_cr[0])\n lx = self.left_fit[0] * (img.shape[0] - 1) ** 2 + self.left_fit[1] * (\n img.shape[0] - 1) + self.left_fit[2]\n rx = self.right_fit[0] * (img.shape[0] - 1) ** 2 + self.right_fit[1\n ] * (img.shape[0] - 1) + self.right_fit[2]\n position = (img.shape[1] / 2 - (lx + rx) / 2) * xm_per_pix\n mean_curverad = (left_curverad + right_curverad) / 2\n self.car_position = position.round(2)\n return mean_curverad\n\n def draw_polygon(self, img, left_fit, right_fit, M_inverse):\n \"\"\" Draw shaded polygon on the lane between left_fit and right_fit\n :param img - undistorted image, on which to draw the lane polygon\n :param left_fit - left lane values (x)\n :param right_fit - right lane values (x)\n :param M_inverse - matrix for inverse transform warping\n :return - img - the modified image with polygon\n \"\"\"\n fity = np.linspace(0, img.shape[0] - 1, img.shape[0])\n left_fitx = left_fit[0] * fity ** 2 + left_fit[1] * fity + left_fit[2]\n right_fitx = right_fit[0] * fity ** 2 + right_fit[1\n ] * fity + right_fit[2]\n color_warp = np.zeros_like(img).astype(np.uint8)\n pts_left = np.array([np.transpose(np.vstack([left_fitx, fity]))])\n pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx,\n fity])))])\n pts = np.hstack((pts_left, pts_right))\n pts = np.array(pts, dtype=np.int32)\n cv2.fillPoly(color_warp, np.int_([pts]), (0, 255, 0))\n newwarp = cv2.warpPerspective(color_warp, M_inverse, (img.shape[1],\n img.shape[0]))\n result = cv2.addWeighted(img, 1, newwarp, 0.3, 0)\n return result\n\n def display_dashboard(self, img, lane_curve):\n \"\"\" Display a dashboard on the image, with info on\n Lane curve (avg)\n :param img - image with lane lines\n :param lane_curve - the avg lane curvature\n :param position\n :return modified img\n \"\"\"\n COLOR_LIGHTBLUE = 172, 227, 239\n COLOR_GOLD = 255, 215, 0\n if self.car_position > 0:\n msg = '{}m right of center'.format(self.car_position)\n else:\n msg = '{}m left of center'.format(np.abs(self.car_position))\n cv2.putText(img, 'Lane curve radius: {}m'.format(lane_curve.round()\n ), (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, color=COLOR_GOLD,\n thickness=2)\n cv2.putText(img, 'Car is {}'.format(msg), (10, 80), cv2.\n FONT_HERSHEY_SIMPLEX, 1, color=COLOR_GOLD, thickness=2)\n cv2.rectangle(img, (5, 10), (480, 100), color=COLOR_GOLD, thickness=2)\n return img\n", "<import token>\n\n\nclass LaneDetector:\n <docstring token>\n\n def __init__(self):\n self.left_fit = None\n self.right_fit = None\n self.leftx = None\n self.rightx = None\n self.car_position = None\n print('(init: LaneDetector)')\n\n def window_fit(self, img):\n \"\"\" Apply polynomial fit to the given image, returning fit for left/right lanes\n Called when one frame of image has previously found left_fit/right_fit. \n This method attempts to find lane fits in the vicinity of previous fits\n :param img -- input image with lane lines\n :return left_fit, right_fit\n \"\"\"\n if self.left_fit is None or self.right_fit is None:\n return self.sliding_window_fit(img)\n nonzero = img.nonzero()\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n margin = 100\n left_lane_inds = (nonzerox > self.left_fit[0] * nonzeroy ** 2 + \n self.left_fit[1] * nonzeroy + self.left_fit[2] - margin) & (\n nonzerox < self.left_fit[0] * nonzeroy ** 2 + self.left_fit[1] *\n nonzeroy + self.left_fit[2] + margin)\n right_lane_inds = (nonzerox > self.right_fit[0] * nonzeroy ** 2 + \n self.right_fit[1] * nonzeroy + self.right_fit[2] - margin) & (\n nonzerox < self.right_fit[0] * nonzeroy ** 2 + self.right_fit[1\n ] * nonzeroy + self.right_fit[2] + margin)\n self.leftx = nonzerox[left_lane_inds]\n lefty = nonzeroy[left_lane_inds]\n self.rightx = nonzerox[right_lane_inds]\n righty = nonzeroy[right_lane_inds]\n self.left_fit = np.polyfit(lefty, self.leftx, 2)\n self.right_fit = np.polyfit(righty, self.rightx, 2)\n return self.left_fit, self.right_fit\n <function token>\n\n def find_lane_curvature(self, img):\n \"\"\" Find lane curvature for the given img\n :param img - the input image\n :return lane curvature\n \"\"\"\n ploty = np.linspace(0, 719, num=720)\n quadratic_coeff = 0.0003\n leftx = np.array([(200 + y ** 2 * quadratic_coeff + np.random.\n randint(-50, high=51)) for y in ploty])\n rightx = np.array([(900 + y ** 2 * quadratic_coeff + np.random.\n randint(-50, high=51)) for y in ploty])\n leftx = leftx[::-1]\n rightx = rightx[::-1]\n y_eval = np.max(ploty)\n ym_per_pix = 30 / 720\n xm_per_pix = 3.7 / 700\n left_fit_cr = np.polyfit(ploty * ym_per_pix, leftx * xm_per_pix, 2)\n right_fit_cr = np.polyfit(ploty * ym_per_pix, rightx * xm_per_pix, 2)\n left_curverad = (1 + (2 * left_fit_cr[0] * y_eval * ym_per_pix +\n left_fit_cr[1]) ** 2) ** 1.5 / np.absolute(2 * left_fit_cr[0])\n right_curverad = (1 + (2 * right_fit_cr[0] * y_eval * ym_per_pix +\n right_fit_cr[1]) ** 2) ** 1.5 / np.absolute(2 * right_fit_cr[0])\n lx = self.left_fit[0] * (img.shape[0] - 1) ** 2 + self.left_fit[1] * (\n img.shape[0] - 1) + self.left_fit[2]\n rx = self.right_fit[0] * (img.shape[0] - 1) ** 2 + self.right_fit[1\n ] * (img.shape[0] - 1) + self.right_fit[2]\n position = (img.shape[1] / 2 - (lx + rx) / 2) * xm_per_pix\n mean_curverad = (left_curverad + right_curverad) / 2\n self.car_position = position.round(2)\n return mean_curverad\n\n def draw_polygon(self, img, left_fit, right_fit, M_inverse):\n \"\"\" Draw shaded polygon on the lane between left_fit and right_fit\n :param img - undistorted image, on which to draw the lane polygon\n :param left_fit - left lane values (x)\n :param right_fit - right lane values (x)\n :param M_inverse - matrix for inverse transform warping\n :return - img - the modified image with polygon\n \"\"\"\n fity = np.linspace(0, img.shape[0] - 1, img.shape[0])\n left_fitx = left_fit[0] * fity ** 2 + left_fit[1] * fity + left_fit[2]\n right_fitx = right_fit[0] * fity ** 2 + right_fit[1\n ] * fity + right_fit[2]\n color_warp = np.zeros_like(img).astype(np.uint8)\n pts_left = np.array([np.transpose(np.vstack([left_fitx, fity]))])\n pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx,\n fity])))])\n pts = np.hstack((pts_left, pts_right))\n pts = np.array(pts, dtype=np.int32)\n cv2.fillPoly(color_warp, np.int_([pts]), (0, 255, 0))\n newwarp = cv2.warpPerspective(color_warp, M_inverse, (img.shape[1],\n img.shape[0]))\n result = cv2.addWeighted(img, 1, newwarp, 0.3, 0)\n return result\n\n def display_dashboard(self, img, lane_curve):\n \"\"\" Display a dashboard on the image, with info on\n Lane curve (avg)\n :param img - image with lane lines\n :param lane_curve - the avg lane curvature\n :param position\n :return modified img\n \"\"\"\n COLOR_LIGHTBLUE = 172, 227, 239\n COLOR_GOLD = 255, 215, 0\n if self.car_position > 0:\n msg = '{}m right of center'.format(self.car_position)\n else:\n msg = '{}m left of center'.format(np.abs(self.car_position))\n cv2.putText(img, 'Lane curve radius: {}m'.format(lane_curve.round()\n ), (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, color=COLOR_GOLD,\n thickness=2)\n cv2.putText(img, 'Car is {}'.format(msg), (10, 80), cv2.\n FONT_HERSHEY_SIMPLEX, 1, color=COLOR_GOLD, thickness=2)\n cv2.rectangle(img, (5, 10), (480, 100), color=COLOR_GOLD, thickness=2)\n return img\n", "<import token>\n\n\nclass LaneDetector:\n <docstring token>\n\n def __init__(self):\n self.left_fit = None\n self.right_fit = None\n self.leftx = None\n self.rightx = None\n self.car_position = None\n print('(init: LaneDetector)')\n <function token>\n <function token>\n\n def find_lane_curvature(self, img):\n \"\"\" Find lane curvature for the given img\n :param img - the input image\n :return lane curvature\n \"\"\"\n ploty = np.linspace(0, 719, num=720)\n quadratic_coeff = 0.0003\n leftx = np.array([(200 + y ** 2 * quadratic_coeff + np.random.\n randint(-50, high=51)) for y in ploty])\n rightx = np.array([(900 + y ** 2 * quadratic_coeff + np.random.\n randint(-50, high=51)) for y in ploty])\n leftx = leftx[::-1]\n rightx = rightx[::-1]\n y_eval = np.max(ploty)\n ym_per_pix = 30 / 720\n xm_per_pix = 3.7 / 700\n left_fit_cr = np.polyfit(ploty * ym_per_pix, leftx * xm_per_pix, 2)\n right_fit_cr = np.polyfit(ploty * ym_per_pix, rightx * xm_per_pix, 2)\n left_curverad = (1 + (2 * left_fit_cr[0] * y_eval * ym_per_pix +\n left_fit_cr[1]) ** 2) ** 1.5 / np.absolute(2 * left_fit_cr[0])\n right_curverad = (1 + (2 * right_fit_cr[0] * y_eval * ym_per_pix +\n right_fit_cr[1]) ** 2) ** 1.5 / np.absolute(2 * right_fit_cr[0])\n lx = self.left_fit[0] * (img.shape[0] - 1) ** 2 + self.left_fit[1] * (\n img.shape[0] - 1) + self.left_fit[2]\n rx = self.right_fit[0] * (img.shape[0] - 1) ** 2 + self.right_fit[1\n ] * (img.shape[0] - 1) + self.right_fit[2]\n position = (img.shape[1] / 2 - (lx + rx) / 2) * xm_per_pix\n mean_curverad = (left_curverad + right_curverad) / 2\n self.car_position = position.round(2)\n return mean_curverad\n\n def draw_polygon(self, img, left_fit, right_fit, M_inverse):\n \"\"\" Draw shaded polygon on the lane between left_fit and right_fit\n :param img - undistorted image, on which to draw the lane polygon\n :param left_fit - left lane values (x)\n :param right_fit - right lane values (x)\n :param M_inverse - matrix for inverse transform warping\n :return - img - the modified image with polygon\n \"\"\"\n fity = np.linspace(0, img.shape[0] - 1, img.shape[0])\n left_fitx = left_fit[0] * fity ** 2 + left_fit[1] * fity + left_fit[2]\n right_fitx = right_fit[0] * fity ** 2 + right_fit[1\n ] * fity + right_fit[2]\n color_warp = np.zeros_like(img).astype(np.uint8)\n pts_left = np.array([np.transpose(np.vstack([left_fitx, fity]))])\n pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx,\n fity])))])\n pts = np.hstack((pts_left, pts_right))\n pts = np.array(pts, dtype=np.int32)\n cv2.fillPoly(color_warp, np.int_([pts]), (0, 255, 0))\n newwarp = cv2.warpPerspective(color_warp, M_inverse, (img.shape[1],\n img.shape[0]))\n result = cv2.addWeighted(img, 1, newwarp, 0.3, 0)\n return result\n\n def display_dashboard(self, img, lane_curve):\n \"\"\" Display a dashboard on the image, with info on\n Lane curve (avg)\n :param img - image with lane lines\n :param lane_curve - the avg lane curvature\n :param position\n :return modified img\n \"\"\"\n COLOR_LIGHTBLUE = 172, 227, 239\n COLOR_GOLD = 255, 215, 0\n if self.car_position > 0:\n msg = '{}m right of center'.format(self.car_position)\n else:\n msg = '{}m left of center'.format(np.abs(self.car_position))\n cv2.putText(img, 'Lane curve radius: {}m'.format(lane_curve.round()\n ), (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, color=COLOR_GOLD,\n thickness=2)\n cv2.putText(img, 'Car is {}'.format(msg), (10, 80), cv2.\n FONT_HERSHEY_SIMPLEX, 1, color=COLOR_GOLD, thickness=2)\n cv2.rectangle(img, (5, 10), (480, 100), color=COLOR_GOLD, thickness=2)\n return img\n", "<import token>\n\n\nclass LaneDetector:\n <docstring token>\n\n def __init__(self):\n self.left_fit = None\n self.right_fit = None\n self.leftx = None\n self.rightx = None\n self.car_position = None\n print('(init: LaneDetector)')\n <function token>\n <function token>\n\n def find_lane_curvature(self, img):\n \"\"\" Find lane curvature for the given img\n :param img - the input image\n :return lane curvature\n \"\"\"\n ploty = np.linspace(0, 719, num=720)\n quadratic_coeff = 0.0003\n leftx = np.array([(200 + y ** 2 * quadratic_coeff + np.random.\n randint(-50, high=51)) for y in ploty])\n rightx = np.array([(900 + y ** 2 * quadratic_coeff + np.random.\n randint(-50, high=51)) for y in ploty])\n leftx = leftx[::-1]\n rightx = rightx[::-1]\n y_eval = np.max(ploty)\n ym_per_pix = 30 / 720\n xm_per_pix = 3.7 / 700\n left_fit_cr = np.polyfit(ploty * ym_per_pix, leftx * xm_per_pix, 2)\n right_fit_cr = np.polyfit(ploty * ym_per_pix, rightx * xm_per_pix, 2)\n left_curverad = (1 + (2 * left_fit_cr[0] * y_eval * ym_per_pix +\n left_fit_cr[1]) ** 2) ** 1.5 / np.absolute(2 * left_fit_cr[0])\n right_curverad = (1 + (2 * right_fit_cr[0] * y_eval * ym_per_pix +\n right_fit_cr[1]) ** 2) ** 1.5 / np.absolute(2 * right_fit_cr[0])\n lx = self.left_fit[0] * (img.shape[0] - 1) ** 2 + self.left_fit[1] * (\n img.shape[0] - 1) + self.left_fit[2]\n rx = self.right_fit[0] * (img.shape[0] - 1) ** 2 + self.right_fit[1\n ] * (img.shape[0] - 1) + self.right_fit[2]\n position = (img.shape[1] / 2 - (lx + rx) / 2) * xm_per_pix\n mean_curverad = (left_curverad + right_curverad) / 2\n self.car_position = position.round(2)\n return mean_curverad\n\n def draw_polygon(self, img, left_fit, right_fit, M_inverse):\n \"\"\" Draw shaded polygon on the lane between left_fit and right_fit\n :param img - undistorted image, on which to draw the lane polygon\n :param left_fit - left lane values (x)\n :param right_fit - right lane values (x)\n :param M_inverse - matrix for inverse transform warping\n :return - img - the modified image with polygon\n \"\"\"\n fity = np.linspace(0, img.shape[0] - 1, img.shape[0])\n left_fitx = left_fit[0] * fity ** 2 + left_fit[1] * fity + left_fit[2]\n right_fitx = right_fit[0] * fity ** 2 + right_fit[1\n ] * fity + right_fit[2]\n color_warp = np.zeros_like(img).astype(np.uint8)\n pts_left = np.array([np.transpose(np.vstack([left_fitx, fity]))])\n pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx,\n fity])))])\n pts = np.hstack((pts_left, pts_right))\n pts = np.array(pts, dtype=np.int32)\n cv2.fillPoly(color_warp, np.int_([pts]), (0, 255, 0))\n newwarp = cv2.warpPerspective(color_warp, M_inverse, (img.shape[1],\n img.shape[0]))\n result = cv2.addWeighted(img, 1, newwarp, 0.3, 0)\n return result\n <function token>\n", "<import token>\n\n\nclass LaneDetector:\n <docstring token>\n <function token>\n <function token>\n <function token>\n\n def find_lane_curvature(self, img):\n \"\"\" Find lane curvature for the given img\n :param img - the input image\n :return lane curvature\n \"\"\"\n ploty = np.linspace(0, 719, num=720)\n quadratic_coeff = 0.0003\n leftx = np.array([(200 + y ** 2 * quadratic_coeff + np.random.\n randint(-50, high=51)) for y in ploty])\n rightx = np.array([(900 + y ** 2 * quadratic_coeff + np.random.\n randint(-50, high=51)) for y in ploty])\n leftx = leftx[::-1]\n rightx = rightx[::-1]\n y_eval = np.max(ploty)\n ym_per_pix = 30 / 720\n xm_per_pix = 3.7 / 700\n left_fit_cr = np.polyfit(ploty * ym_per_pix, leftx * xm_per_pix, 2)\n right_fit_cr = np.polyfit(ploty * ym_per_pix, rightx * xm_per_pix, 2)\n left_curverad = (1 + (2 * left_fit_cr[0] * y_eval * ym_per_pix +\n left_fit_cr[1]) ** 2) ** 1.5 / np.absolute(2 * left_fit_cr[0])\n right_curverad = (1 + (2 * right_fit_cr[0] * y_eval * ym_per_pix +\n right_fit_cr[1]) ** 2) ** 1.5 / np.absolute(2 * right_fit_cr[0])\n lx = self.left_fit[0] * (img.shape[0] - 1) ** 2 + self.left_fit[1] * (\n img.shape[0] - 1) + self.left_fit[2]\n rx = self.right_fit[0] * (img.shape[0] - 1) ** 2 + self.right_fit[1\n ] * (img.shape[0] - 1) + self.right_fit[2]\n position = (img.shape[1] / 2 - (lx + rx) / 2) * xm_per_pix\n mean_curverad = (left_curverad + right_curverad) / 2\n self.car_position = position.round(2)\n return mean_curverad\n\n def draw_polygon(self, img, left_fit, right_fit, M_inverse):\n \"\"\" Draw shaded polygon on the lane between left_fit and right_fit\n :param img - undistorted image, on which to draw the lane polygon\n :param left_fit - left lane values (x)\n :param right_fit - right lane values (x)\n :param M_inverse - matrix for inverse transform warping\n :return - img - the modified image with polygon\n \"\"\"\n fity = np.linspace(0, img.shape[0] - 1, img.shape[0])\n left_fitx = left_fit[0] * fity ** 2 + left_fit[1] * fity + left_fit[2]\n right_fitx = right_fit[0] * fity ** 2 + right_fit[1\n ] * fity + right_fit[2]\n color_warp = np.zeros_like(img).astype(np.uint8)\n pts_left = np.array([np.transpose(np.vstack([left_fitx, fity]))])\n pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx,\n fity])))])\n pts = np.hstack((pts_left, pts_right))\n pts = np.array(pts, dtype=np.int32)\n cv2.fillPoly(color_warp, np.int_([pts]), (0, 255, 0))\n newwarp = cv2.warpPerspective(color_warp, M_inverse, (img.shape[1],\n img.shape[0]))\n result = cv2.addWeighted(img, 1, newwarp, 0.3, 0)\n return result\n <function token>\n", "<import token>\n\n\nclass LaneDetector:\n <docstring token>\n <function token>\n <function token>\n <function token>\n\n def find_lane_curvature(self, img):\n \"\"\" Find lane curvature for the given img\n :param img - the input image\n :return lane curvature\n \"\"\"\n ploty = np.linspace(0, 719, num=720)\n quadratic_coeff = 0.0003\n leftx = np.array([(200 + y ** 2 * quadratic_coeff + np.random.\n randint(-50, high=51)) for y in ploty])\n rightx = np.array([(900 + y ** 2 * quadratic_coeff + np.random.\n randint(-50, high=51)) for y in ploty])\n leftx = leftx[::-1]\n rightx = rightx[::-1]\n y_eval = np.max(ploty)\n ym_per_pix = 30 / 720\n xm_per_pix = 3.7 / 700\n left_fit_cr = np.polyfit(ploty * ym_per_pix, leftx * xm_per_pix, 2)\n right_fit_cr = np.polyfit(ploty * ym_per_pix, rightx * xm_per_pix, 2)\n left_curverad = (1 + (2 * left_fit_cr[0] * y_eval * ym_per_pix +\n left_fit_cr[1]) ** 2) ** 1.5 / np.absolute(2 * left_fit_cr[0])\n right_curverad = (1 + (2 * right_fit_cr[0] * y_eval * ym_per_pix +\n right_fit_cr[1]) ** 2) ** 1.5 / np.absolute(2 * right_fit_cr[0])\n lx = self.left_fit[0] * (img.shape[0] - 1) ** 2 + self.left_fit[1] * (\n img.shape[0] - 1) + self.left_fit[2]\n rx = self.right_fit[0] * (img.shape[0] - 1) ** 2 + self.right_fit[1\n ] * (img.shape[0] - 1) + self.right_fit[2]\n position = (img.shape[1] / 2 - (lx + rx) / 2) * xm_per_pix\n mean_curverad = (left_curverad + right_curverad) / 2\n self.car_position = position.round(2)\n return mean_curverad\n <function token>\n <function token>\n", "<import token>\n\n\nclass LaneDetector:\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<import token>\n<class token>\n" ]
false
98,741
2001b7805097f10164941e61005ac7a5a8e67fee
from cmath import sqrt import math T = int(input()) test = 1 while test <= T: print("Case #" + str(test) + ": ", end="") test += 1 mnk = input().split() m = int(mnk[0]) n = int(mnk[1]) k = int(mnk[2]) # make m the smaller if m > n: tmp = n n = m m = tmp if m <= 2: print(k) continue if m*n - k <= 4: print((m+n-4)*2 - m*n + k + 4) continue size = math.ceil(sqrt(k+4).real) w = 0 if size > m: w = m else: w = size h = size - 1 while w*h - 4 < k: h += 1 ans = (w+h-4)*2 # make h the smaller one if h > w: tmp = h h = w w = tmp if (w*h - 4) - k >= 2 and m > 3: ans -= 1 if (w-1)*h - 3 >= k: ans = min((w+h-5)*2+1, ans) print(ans)
[ "from cmath import sqrt\nimport math\n\nT = int(input())\ntest = 1\n\nwhile test <= T:\n print(\"Case #\" + str(test) + \": \", end=\"\")\n test += 1\n\n mnk = input().split()\n m = int(mnk[0])\n n = int(mnk[1])\n k = int(mnk[2])\n\n # make m the smaller\n if m > n:\n tmp = n\n n = m\n m = tmp\n\n if m <= 2:\n print(k)\n continue\n\n if m*n - k <= 4:\n print((m+n-4)*2 - m*n + k + 4)\n continue\n\n size = math.ceil(sqrt(k+4).real)\n\n w = 0\n if size > m:\n w = m\n else:\n w = size\n\n h = size - 1\n while w*h - 4 < k:\n h += 1\n\n ans = (w+h-4)*2\n\n # make h the smaller one\n if h > w:\n tmp = h\n h = w\n w = tmp\n\n if (w*h - 4) - k >= 2 and m > 3:\n ans -= 1\n\n if (w-1)*h - 3 >= k:\n ans = min((w+h-5)*2+1, ans)\n\n\n print(ans)", "from cmath import sqrt\nimport math\nT = int(input())\ntest = 1\nwhile test <= T:\n print('Case #' + str(test) + ': ', end='')\n test += 1\n mnk = input().split()\n m = int(mnk[0])\n n = int(mnk[1])\n k = int(mnk[2])\n if m > n:\n tmp = n\n n = m\n m = tmp\n if m <= 2:\n print(k)\n continue\n if m * n - k <= 4:\n print((m + n - 4) * 2 - m * n + k + 4)\n continue\n size = math.ceil(sqrt(k + 4).real)\n w = 0\n if size > m:\n w = m\n else:\n w = size\n h = size - 1\n while w * h - 4 < k:\n h += 1\n ans = (w + h - 4) * 2\n if h > w:\n tmp = h\n h = w\n w = tmp\n if w * h - 4 - k >= 2 and m > 3:\n ans -= 1\n if (w - 1) * h - 3 >= k:\n ans = min((w + h - 5) * 2 + 1, ans)\n print(ans)\n", "<import token>\nT = int(input())\ntest = 1\nwhile test <= T:\n print('Case #' + str(test) + ': ', end='')\n test += 1\n mnk = input().split()\n m = int(mnk[0])\n n = int(mnk[1])\n k = int(mnk[2])\n if m > n:\n tmp = n\n n = m\n m = tmp\n if m <= 2:\n print(k)\n continue\n if m * n - k <= 4:\n print((m + n - 4) * 2 - m * n + k + 4)\n continue\n size = math.ceil(sqrt(k + 4).real)\n w = 0\n if size > m:\n w = m\n else:\n w = size\n h = size - 1\n while w * h - 4 < k:\n h += 1\n ans = (w + h - 4) * 2\n if h > w:\n tmp = h\n h = w\n w = tmp\n if w * h - 4 - k >= 2 and m > 3:\n ans -= 1\n if (w - 1) * h - 3 >= k:\n ans = min((w + h - 5) * 2 + 1, ans)\n print(ans)\n", "<import token>\n<assignment token>\nwhile test <= T:\n print('Case #' + str(test) + ': ', end='')\n test += 1\n mnk = input().split()\n m = int(mnk[0])\n n = int(mnk[1])\n k = int(mnk[2])\n if m > n:\n tmp = n\n n = m\n m = tmp\n if m <= 2:\n print(k)\n continue\n if m * n - k <= 4:\n print((m + n - 4) * 2 - m * n + k + 4)\n continue\n size = math.ceil(sqrt(k + 4).real)\n w = 0\n if size > m:\n w = m\n else:\n w = size\n h = size - 1\n while w * h - 4 < k:\n h += 1\n ans = (w + h - 4) * 2\n if h > w:\n tmp = h\n h = w\n w = tmp\n if w * h - 4 - k >= 2 and m > 3:\n ans -= 1\n if (w - 1) * h - 3 >= k:\n ans = min((w + h - 5) * 2 + 1, ans)\n print(ans)\n", "<import token>\n<assignment token>\n<code token>\n" ]
false
98,742
7350689b881633d12ba2e4beee4c6d77211c60b9
from django.db import models from cms.extensions.models import PageExtension, BaseExtension from cms.extensions.extension_pool import extension_pool from cms.models import CMSPlugin from filer.fields.image import FilerImageField, FilerFileField from categories.models import Discipline, Industry # PAGES class WorkExtension(PageExtension): image = FilerImageField(null=True, related_name="work_display_image") title = models.CharField(max_length=50) description = models.CharField(max_length=50) disciplines = models.ManyToManyField(Discipline) industries = models.ManyToManyField(Industry) allow_access = models.BooleanField(default=True) def copy_relations(self, oldinstance, language): self.disciplines = oldinstance.disciplines.all() self.industries = oldinstance.industries.all() extension_pool.register(WorkExtension) # PLUGINS # Homepage class CarouselPlugin(CMSPlugin): interval = models.IntegerField(default=2000, help_text="interval between slides in milliseconds") class CarouselItemPlugin(CMSPlugin): background = FilerImageField(null=True, related_name="background") # About class LinkVideoPlugin(CMSPlugin): title = models.CharField(max_length=25) jump_to_index = models.CharField(max_length=10) video = FilerFileField(related_name="link_video") def __str__(self): return self.jump_to_index class LinkedSectionPlugin(CMSPlugin): index = models.CharField(max_length=10) def __str__(self): return self.index class MapPlugin(CMSPlugin): latitude = models.FloatField() longitude = models.FloatField() zoom = models.IntegerField() label = models.CharField(max_length=20) direct_link = models.URLField(null=True, help_text="Generate this by going to Google Maps and pressing 'Share'") height = models.CharField(default="500px", max_length=10) def __str__(self): return self.label class AwardPlugin(CMSPlugin): logo = FilerImageField(null=True, related_name="award_logo") text = models.TextField() def __str__(self): return instance.text[:15] # General class RowPlugin(CMSPlugin): title = models.CharField(max_length=30, default="") ymargin = models.IntegerField(help_text="on a scale of 1 to 5, as per Bootstrap, adds margin to top and bottom of row") def __str__(self): if self.title: return self.title return self.css_class() def css_class(self): return 'row my-' + str(self.ymargin) class ColumnPlugin(CMSPlugin): COL_CHOICES = ( ('', 'Extra Small'), ('sm-', 'Small'), ('md-', 'Medium'), ('lg-', 'Large'), ('xl-', 'Extra Large'), ) size = models.CharField(max_length=3, choices=COL_CHOICES, default='md-', help_text="The larger the column, the more likely it will stack as screen size decreases.") width = models.IntegerField(help_text="This creates a Bootstrap Column, full width is 12.") def __str__(self): return self.css_class() def css_class(self): return 'col-' + self.size + str(self.width) class HRPlugin(CMSPlugin): COLOURS = ( ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light', 'Light') ) css_class = models.CharField(max_length=5, choices=COLOURS, default='light') def __str__(self): return dict(self.COLOURS)[self.css_class] class EmailFormPlugin(CMSPlugin): COLOURS = ( ('black', 'Black'), ('white', 'White') ) css_class = models.CharField(max_length=5, choices=COLOURS, default='light') def __str__(self): return dict(self.COLOURS)[self.css_class] # Footer class AddressPlugin(CMSPlugin): address = models.TextField() phone = models.TextField() email = models.CharField(max_length=200) direct_link = models.URLField(null=True, help_text="Generate this by going to Google Maps and pressing 'Share'") class SocialLinkPlugin(CMSPlugin): # icon = FilerImageField(null=True, related_name="social_icon") icon_class = models.CharField(max_length=20, default='fa fa-twitter') text = models.CharField(max_length=30) link = models.URLField() open_new_tab = models.BooleanField(default=True) def __str__(self): return self.text class SocialSharePlugin(CMSPlugin): share_to_pinterest = models.BooleanField(default=True) def __str__(self): return str(self.share_to_pinterest)
[ "from django.db import models\n\nfrom cms.extensions.models import PageExtension, BaseExtension\nfrom cms.extensions.extension_pool import extension_pool\n\nfrom cms.models import CMSPlugin\nfrom filer.fields.image import FilerImageField, FilerFileField\n\nfrom categories.models import Discipline, Industry\n\n# PAGES\n\nclass WorkExtension(PageExtension):\n image = FilerImageField(null=True, related_name=\"work_display_image\")\n title = models.CharField(max_length=50)\n description = models.CharField(max_length=50)\n disciplines = models.ManyToManyField(Discipline)\n industries = models.ManyToManyField(Industry)\n allow_access = models.BooleanField(default=True)\n\n def copy_relations(self, oldinstance, language):\n self.disciplines = oldinstance.disciplines.all()\n self.industries = oldinstance.industries.all()\n\nextension_pool.register(WorkExtension)\n\n# PLUGINS\n# Homepage\n\nclass CarouselPlugin(CMSPlugin):\n interval = models.IntegerField(default=2000, help_text=\"interval between slides in milliseconds\")\n\nclass CarouselItemPlugin(CMSPlugin):\n background = FilerImageField(null=True, related_name=\"background\")\n\n# About\n\nclass LinkVideoPlugin(CMSPlugin):\n title = models.CharField(max_length=25)\n jump_to_index = models.CharField(max_length=10)\n video = FilerFileField(related_name=\"link_video\")\n\n def __str__(self):\n return self.jump_to_index\n\nclass LinkedSectionPlugin(CMSPlugin):\n index = models.CharField(max_length=10)\n\n def __str__(self):\n return self.index\n\nclass MapPlugin(CMSPlugin):\n latitude = models.FloatField()\n longitude = models.FloatField()\n zoom = models.IntegerField()\n label = models.CharField(max_length=20)\n direct_link = models.URLField(null=True, help_text=\"Generate this by going to Google Maps and pressing 'Share'\")\n height = models.CharField(default=\"500px\", max_length=10)\n\n def __str__(self):\n return self.label\n\nclass AwardPlugin(CMSPlugin):\n logo = FilerImageField(null=True, related_name=\"award_logo\")\n text = models.TextField()\n\n def __str__(self):\n return instance.text[:15]\n\n# General\n\nclass RowPlugin(CMSPlugin):\n title = models.CharField(max_length=30, default=\"\")\n ymargin = models.IntegerField(help_text=\"on a scale of 1 to 5, as per Bootstrap, adds margin to top and bottom of row\")\n\n def __str__(self):\n if self.title:\n return self.title\n return self.css_class()\n\n def css_class(self):\n return 'row my-' + str(self.ymargin)\n\nclass ColumnPlugin(CMSPlugin):\n COL_CHOICES = (\n ('', 'Extra Small'),\n ('sm-', 'Small'),\n ('md-', 'Medium'),\n ('lg-', 'Large'),\n ('xl-', 'Extra Large'),\n )\n size = models.CharField(max_length=3, choices=COL_CHOICES, default='md-', help_text=\"The larger the column, the more likely it will stack as screen size decreases.\")\n width = models.IntegerField(help_text=\"This creates a Bootstrap Column, full width is 12.\")\n\n def __str__(self):\n return self.css_class()\n\n def css_class(self):\n return 'col-' + self.size + str(self.width)\n\nclass HRPlugin(CMSPlugin):\n COLOURS = (\n ('thick', 'Dark and thick'),\n ('dark', 'Dark and thin'),\n ('light', 'Light')\n )\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light')\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = (\n ('black', 'Black'),\n ('white', 'White')\n )\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light')\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n# Footer\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\"Generate this by going to Google Maps and pressing 'Share'\")\n\nclass SocialLinkPlugin(CMSPlugin):\n # icon = FilerImageField(null=True, related_name=\"social_icon\")\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)", "from django.db import models\nfrom cms.extensions.models import PageExtension, BaseExtension\nfrom cms.extensions.extension_pool import extension_pool\nfrom cms.models import CMSPlugin\nfrom filer.fields.image import FilerImageField, FilerFileField\nfrom categories.models import Discipline, Industry\n\n\nclass WorkExtension(PageExtension):\n image = FilerImageField(null=True, related_name='work_display_image')\n title = models.CharField(max_length=50)\n description = models.CharField(max_length=50)\n disciplines = models.ManyToManyField(Discipline)\n industries = models.ManyToManyField(Industry)\n allow_access = models.BooleanField(default=True)\n\n def copy_relations(self, oldinstance, language):\n self.disciplines = oldinstance.disciplines.all()\n self.industries = oldinstance.industries.all()\n\n\nextension_pool.register(WorkExtension)\n\n\nclass CarouselPlugin(CMSPlugin):\n interval = models.IntegerField(default=2000, help_text=\n 'interval between slides in milliseconds')\n\n\nclass CarouselItemPlugin(CMSPlugin):\n background = FilerImageField(null=True, related_name='background')\n\n\nclass LinkVideoPlugin(CMSPlugin):\n title = models.CharField(max_length=25)\n jump_to_index = models.CharField(max_length=10)\n video = FilerFileField(related_name='link_video')\n\n def __str__(self):\n return self.jump_to_index\n\n\nclass LinkedSectionPlugin(CMSPlugin):\n index = models.CharField(max_length=10)\n\n def __str__(self):\n return self.index\n\n\nclass MapPlugin(CMSPlugin):\n latitude = models.FloatField()\n longitude = models.FloatField()\n zoom = models.IntegerField()\n label = models.CharField(max_length=20)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n height = models.CharField(default='500px', max_length=10)\n\n def __str__(self):\n return self.label\n\n\nclass AwardPlugin(CMSPlugin):\n logo = FilerImageField(null=True, related_name='award_logo')\n text = models.TextField()\n\n def __str__(self):\n return instance.text[:15]\n\n\nclass RowPlugin(CMSPlugin):\n title = models.CharField(max_length=30, default='')\n ymargin = models.IntegerField(help_text=\n 'on a scale of 1 to 5, as per Bootstrap, adds margin to top and bottom of row'\n )\n\n def __str__(self):\n if self.title:\n return self.title\n return self.css_class()\n\n def css_class(self):\n return 'row my-' + str(self.ymargin)\n\n\nclass ColumnPlugin(CMSPlugin):\n COL_CHOICES = ('', 'Extra Small'), ('sm-', 'Small'), ('md-', 'Medium'), (\n 'lg-', 'Large'), ('xl-', 'Extra Large')\n size = models.CharField(max_length=3, choices=COL_CHOICES, default=\n 'md-', help_text=\n 'The larger the column, the more likely it will stack as screen size decreases.'\n )\n width = models.IntegerField(help_text=\n 'This creates a Bootstrap Column, full width is 12.')\n\n def __str__(self):\n return self.css_class()\n\n def css_class(self):\n return 'col-' + self.size + str(self.width)\n\n\nclass HRPlugin(CMSPlugin):\n COLOURS = ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light',\n 'Light')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n\n\nclass WorkExtension(PageExtension):\n image = FilerImageField(null=True, related_name='work_display_image')\n title = models.CharField(max_length=50)\n description = models.CharField(max_length=50)\n disciplines = models.ManyToManyField(Discipline)\n industries = models.ManyToManyField(Industry)\n allow_access = models.BooleanField(default=True)\n\n def copy_relations(self, oldinstance, language):\n self.disciplines = oldinstance.disciplines.all()\n self.industries = oldinstance.industries.all()\n\n\nextension_pool.register(WorkExtension)\n\n\nclass CarouselPlugin(CMSPlugin):\n interval = models.IntegerField(default=2000, help_text=\n 'interval between slides in milliseconds')\n\n\nclass CarouselItemPlugin(CMSPlugin):\n background = FilerImageField(null=True, related_name='background')\n\n\nclass LinkVideoPlugin(CMSPlugin):\n title = models.CharField(max_length=25)\n jump_to_index = models.CharField(max_length=10)\n video = FilerFileField(related_name='link_video')\n\n def __str__(self):\n return self.jump_to_index\n\n\nclass LinkedSectionPlugin(CMSPlugin):\n index = models.CharField(max_length=10)\n\n def __str__(self):\n return self.index\n\n\nclass MapPlugin(CMSPlugin):\n latitude = models.FloatField()\n longitude = models.FloatField()\n zoom = models.IntegerField()\n label = models.CharField(max_length=20)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n height = models.CharField(default='500px', max_length=10)\n\n def __str__(self):\n return self.label\n\n\nclass AwardPlugin(CMSPlugin):\n logo = FilerImageField(null=True, related_name='award_logo')\n text = models.TextField()\n\n def __str__(self):\n return instance.text[:15]\n\n\nclass RowPlugin(CMSPlugin):\n title = models.CharField(max_length=30, default='')\n ymargin = models.IntegerField(help_text=\n 'on a scale of 1 to 5, as per Bootstrap, adds margin to top and bottom of row'\n )\n\n def __str__(self):\n if self.title:\n return self.title\n return self.css_class()\n\n def css_class(self):\n return 'row my-' + str(self.ymargin)\n\n\nclass ColumnPlugin(CMSPlugin):\n COL_CHOICES = ('', 'Extra Small'), ('sm-', 'Small'), ('md-', 'Medium'), (\n 'lg-', 'Large'), ('xl-', 'Extra Large')\n size = models.CharField(max_length=3, choices=COL_CHOICES, default=\n 'md-', help_text=\n 'The larger the column, the more likely it will stack as screen size decreases.'\n )\n width = models.IntegerField(help_text=\n 'This creates a Bootstrap Column, full width is 12.')\n\n def __str__(self):\n return self.css_class()\n\n def css_class(self):\n return 'col-' + self.size + str(self.width)\n\n\nclass HRPlugin(CMSPlugin):\n COLOURS = ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light',\n 'Light')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n\n\nclass WorkExtension(PageExtension):\n image = FilerImageField(null=True, related_name='work_display_image')\n title = models.CharField(max_length=50)\n description = models.CharField(max_length=50)\n disciplines = models.ManyToManyField(Discipline)\n industries = models.ManyToManyField(Industry)\n allow_access = models.BooleanField(default=True)\n\n def copy_relations(self, oldinstance, language):\n self.disciplines = oldinstance.disciplines.all()\n self.industries = oldinstance.industries.all()\n\n\n<code token>\n\n\nclass CarouselPlugin(CMSPlugin):\n interval = models.IntegerField(default=2000, help_text=\n 'interval between slides in milliseconds')\n\n\nclass CarouselItemPlugin(CMSPlugin):\n background = FilerImageField(null=True, related_name='background')\n\n\nclass LinkVideoPlugin(CMSPlugin):\n title = models.CharField(max_length=25)\n jump_to_index = models.CharField(max_length=10)\n video = FilerFileField(related_name='link_video')\n\n def __str__(self):\n return self.jump_to_index\n\n\nclass LinkedSectionPlugin(CMSPlugin):\n index = models.CharField(max_length=10)\n\n def __str__(self):\n return self.index\n\n\nclass MapPlugin(CMSPlugin):\n latitude = models.FloatField()\n longitude = models.FloatField()\n zoom = models.IntegerField()\n label = models.CharField(max_length=20)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n height = models.CharField(default='500px', max_length=10)\n\n def __str__(self):\n return self.label\n\n\nclass AwardPlugin(CMSPlugin):\n logo = FilerImageField(null=True, related_name='award_logo')\n text = models.TextField()\n\n def __str__(self):\n return instance.text[:15]\n\n\nclass RowPlugin(CMSPlugin):\n title = models.CharField(max_length=30, default='')\n ymargin = models.IntegerField(help_text=\n 'on a scale of 1 to 5, as per Bootstrap, adds margin to top and bottom of row'\n )\n\n def __str__(self):\n if self.title:\n return self.title\n return self.css_class()\n\n def css_class(self):\n return 'row my-' + str(self.ymargin)\n\n\nclass ColumnPlugin(CMSPlugin):\n COL_CHOICES = ('', 'Extra Small'), ('sm-', 'Small'), ('md-', 'Medium'), (\n 'lg-', 'Large'), ('xl-', 'Extra Large')\n size = models.CharField(max_length=3, choices=COL_CHOICES, default=\n 'md-', help_text=\n 'The larger the column, the more likely it will stack as screen size decreases.'\n )\n width = models.IntegerField(help_text=\n 'This creates a Bootstrap Column, full width is 12.')\n\n def __str__(self):\n return self.css_class()\n\n def css_class(self):\n return 'col-' + self.size + str(self.width)\n\n\nclass HRPlugin(CMSPlugin):\n COLOURS = ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light',\n 'Light')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n\n\nclass WorkExtension(PageExtension):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def copy_relations(self, oldinstance, language):\n self.disciplines = oldinstance.disciplines.all()\n self.industries = oldinstance.industries.all()\n\n\n<code token>\n\n\nclass CarouselPlugin(CMSPlugin):\n interval = models.IntegerField(default=2000, help_text=\n 'interval between slides in milliseconds')\n\n\nclass CarouselItemPlugin(CMSPlugin):\n background = FilerImageField(null=True, related_name='background')\n\n\nclass LinkVideoPlugin(CMSPlugin):\n title = models.CharField(max_length=25)\n jump_to_index = models.CharField(max_length=10)\n video = FilerFileField(related_name='link_video')\n\n def __str__(self):\n return self.jump_to_index\n\n\nclass LinkedSectionPlugin(CMSPlugin):\n index = models.CharField(max_length=10)\n\n def __str__(self):\n return self.index\n\n\nclass MapPlugin(CMSPlugin):\n latitude = models.FloatField()\n longitude = models.FloatField()\n zoom = models.IntegerField()\n label = models.CharField(max_length=20)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n height = models.CharField(default='500px', max_length=10)\n\n def __str__(self):\n return self.label\n\n\nclass AwardPlugin(CMSPlugin):\n logo = FilerImageField(null=True, related_name='award_logo')\n text = models.TextField()\n\n def __str__(self):\n return instance.text[:15]\n\n\nclass RowPlugin(CMSPlugin):\n title = models.CharField(max_length=30, default='')\n ymargin = models.IntegerField(help_text=\n 'on a scale of 1 to 5, as per Bootstrap, adds margin to top and bottom of row'\n )\n\n def __str__(self):\n if self.title:\n return self.title\n return self.css_class()\n\n def css_class(self):\n return 'row my-' + str(self.ymargin)\n\n\nclass ColumnPlugin(CMSPlugin):\n COL_CHOICES = ('', 'Extra Small'), ('sm-', 'Small'), ('md-', 'Medium'), (\n 'lg-', 'Large'), ('xl-', 'Extra Large')\n size = models.CharField(max_length=3, choices=COL_CHOICES, default=\n 'md-', help_text=\n 'The larger the column, the more likely it will stack as screen size decreases.'\n )\n width = models.IntegerField(help_text=\n 'This creates a Bootstrap Column, full width is 12.')\n\n def __str__(self):\n return self.css_class()\n\n def css_class(self):\n return 'col-' + self.size + str(self.width)\n\n\nclass HRPlugin(CMSPlugin):\n COLOURS = ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light',\n 'Light')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n\n\nclass WorkExtension(PageExtension):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n\n\n<code token>\n\n\nclass CarouselPlugin(CMSPlugin):\n interval = models.IntegerField(default=2000, help_text=\n 'interval between slides in milliseconds')\n\n\nclass CarouselItemPlugin(CMSPlugin):\n background = FilerImageField(null=True, related_name='background')\n\n\nclass LinkVideoPlugin(CMSPlugin):\n title = models.CharField(max_length=25)\n jump_to_index = models.CharField(max_length=10)\n video = FilerFileField(related_name='link_video')\n\n def __str__(self):\n return self.jump_to_index\n\n\nclass LinkedSectionPlugin(CMSPlugin):\n index = models.CharField(max_length=10)\n\n def __str__(self):\n return self.index\n\n\nclass MapPlugin(CMSPlugin):\n latitude = models.FloatField()\n longitude = models.FloatField()\n zoom = models.IntegerField()\n label = models.CharField(max_length=20)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n height = models.CharField(default='500px', max_length=10)\n\n def __str__(self):\n return self.label\n\n\nclass AwardPlugin(CMSPlugin):\n logo = FilerImageField(null=True, related_name='award_logo')\n text = models.TextField()\n\n def __str__(self):\n return instance.text[:15]\n\n\nclass RowPlugin(CMSPlugin):\n title = models.CharField(max_length=30, default='')\n ymargin = models.IntegerField(help_text=\n 'on a scale of 1 to 5, as per Bootstrap, adds margin to top and bottom of row'\n )\n\n def __str__(self):\n if self.title:\n return self.title\n return self.css_class()\n\n def css_class(self):\n return 'row my-' + str(self.ymargin)\n\n\nclass ColumnPlugin(CMSPlugin):\n COL_CHOICES = ('', 'Extra Small'), ('sm-', 'Small'), ('md-', 'Medium'), (\n 'lg-', 'Large'), ('xl-', 'Extra Large')\n size = models.CharField(max_length=3, choices=COL_CHOICES, default=\n 'md-', help_text=\n 'The larger the column, the more likely it will stack as screen size decreases.'\n )\n width = models.IntegerField(help_text=\n 'This creates a Bootstrap Column, full width is 12.')\n\n def __str__(self):\n return self.css_class()\n\n def css_class(self):\n return 'col-' + self.size + str(self.width)\n\n\nclass HRPlugin(CMSPlugin):\n COLOURS = ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light',\n 'Light')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n\n\nclass CarouselPlugin(CMSPlugin):\n interval = models.IntegerField(default=2000, help_text=\n 'interval between slides in milliseconds')\n\n\nclass CarouselItemPlugin(CMSPlugin):\n background = FilerImageField(null=True, related_name='background')\n\n\nclass LinkVideoPlugin(CMSPlugin):\n title = models.CharField(max_length=25)\n jump_to_index = models.CharField(max_length=10)\n video = FilerFileField(related_name='link_video')\n\n def __str__(self):\n return self.jump_to_index\n\n\nclass LinkedSectionPlugin(CMSPlugin):\n index = models.CharField(max_length=10)\n\n def __str__(self):\n return self.index\n\n\nclass MapPlugin(CMSPlugin):\n latitude = models.FloatField()\n longitude = models.FloatField()\n zoom = models.IntegerField()\n label = models.CharField(max_length=20)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n height = models.CharField(default='500px', max_length=10)\n\n def __str__(self):\n return self.label\n\n\nclass AwardPlugin(CMSPlugin):\n logo = FilerImageField(null=True, related_name='award_logo')\n text = models.TextField()\n\n def __str__(self):\n return instance.text[:15]\n\n\nclass RowPlugin(CMSPlugin):\n title = models.CharField(max_length=30, default='')\n ymargin = models.IntegerField(help_text=\n 'on a scale of 1 to 5, as per Bootstrap, adds margin to top and bottom of row'\n )\n\n def __str__(self):\n if self.title:\n return self.title\n return self.css_class()\n\n def css_class(self):\n return 'row my-' + str(self.ymargin)\n\n\nclass ColumnPlugin(CMSPlugin):\n COL_CHOICES = ('', 'Extra Small'), ('sm-', 'Small'), ('md-', 'Medium'), (\n 'lg-', 'Large'), ('xl-', 'Extra Large')\n size = models.CharField(max_length=3, choices=COL_CHOICES, default=\n 'md-', help_text=\n 'The larger the column, the more likely it will stack as screen size decreases.'\n )\n width = models.IntegerField(help_text=\n 'This creates a Bootstrap Column, full width is 12.')\n\n def __str__(self):\n return self.css_class()\n\n def css_class(self):\n return 'col-' + self.size + str(self.width)\n\n\nclass HRPlugin(CMSPlugin):\n COLOURS = ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light',\n 'Light')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n\n\nclass CarouselPlugin(CMSPlugin):\n <assignment token>\n\n\nclass CarouselItemPlugin(CMSPlugin):\n background = FilerImageField(null=True, related_name='background')\n\n\nclass LinkVideoPlugin(CMSPlugin):\n title = models.CharField(max_length=25)\n jump_to_index = models.CharField(max_length=10)\n video = FilerFileField(related_name='link_video')\n\n def __str__(self):\n return self.jump_to_index\n\n\nclass LinkedSectionPlugin(CMSPlugin):\n index = models.CharField(max_length=10)\n\n def __str__(self):\n return self.index\n\n\nclass MapPlugin(CMSPlugin):\n latitude = models.FloatField()\n longitude = models.FloatField()\n zoom = models.IntegerField()\n label = models.CharField(max_length=20)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n height = models.CharField(default='500px', max_length=10)\n\n def __str__(self):\n return self.label\n\n\nclass AwardPlugin(CMSPlugin):\n logo = FilerImageField(null=True, related_name='award_logo')\n text = models.TextField()\n\n def __str__(self):\n return instance.text[:15]\n\n\nclass RowPlugin(CMSPlugin):\n title = models.CharField(max_length=30, default='')\n ymargin = models.IntegerField(help_text=\n 'on a scale of 1 to 5, as per Bootstrap, adds margin to top and bottom of row'\n )\n\n def __str__(self):\n if self.title:\n return self.title\n return self.css_class()\n\n def css_class(self):\n return 'row my-' + str(self.ymargin)\n\n\nclass ColumnPlugin(CMSPlugin):\n COL_CHOICES = ('', 'Extra Small'), ('sm-', 'Small'), ('md-', 'Medium'), (\n 'lg-', 'Large'), ('xl-', 'Extra Large')\n size = models.CharField(max_length=3, choices=COL_CHOICES, default=\n 'md-', help_text=\n 'The larger the column, the more likely it will stack as screen size decreases.'\n )\n width = models.IntegerField(help_text=\n 'This creates a Bootstrap Column, full width is 12.')\n\n def __str__(self):\n return self.css_class()\n\n def css_class(self):\n return 'col-' + self.size + str(self.width)\n\n\nclass HRPlugin(CMSPlugin):\n COLOURS = ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light',\n 'Light')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n\n\nclass CarouselItemPlugin(CMSPlugin):\n background = FilerImageField(null=True, related_name='background')\n\n\nclass LinkVideoPlugin(CMSPlugin):\n title = models.CharField(max_length=25)\n jump_to_index = models.CharField(max_length=10)\n video = FilerFileField(related_name='link_video')\n\n def __str__(self):\n return self.jump_to_index\n\n\nclass LinkedSectionPlugin(CMSPlugin):\n index = models.CharField(max_length=10)\n\n def __str__(self):\n return self.index\n\n\nclass MapPlugin(CMSPlugin):\n latitude = models.FloatField()\n longitude = models.FloatField()\n zoom = models.IntegerField()\n label = models.CharField(max_length=20)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n height = models.CharField(default='500px', max_length=10)\n\n def __str__(self):\n return self.label\n\n\nclass AwardPlugin(CMSPlugin):\n logo = FilerImageField(null=True, related_name='award_logo')\n text = models.TextField()\n\n def __str__(self):\n return instance.text[:15]\n\n\nclass RowPlugin(CMSPlugin):\n title = models.CharField(max_length=30, default='')\n ymargin = models.IntegerField(help_text=\n 'on a scale of 1 to 5, as per Bootstrap, adds margin to top and bottom of row'\n )\n\n def __str__(self):\n if self.title:\n return self.title\n return self.css_class()\n\n def css_class(self):\n return 'row my-' + str(self.ymargin)\n\n\nclass ColumnPlugin(CMSPlugin):\n COL_CHOICES = ('', 'Extra Small'), ('sm-', 'Small'), ('md-', 'Medium'), (\n 'lg-', 'Large'), ('xl-', 'Extra Large')\n size = models.CharField(max_length=3, choices=COL_CHOICES, default=\n 'md-', help_text=\n 'The larger the column, the more likely it will stack as screen size decreases.'\n )\n width = models.IntegerField(help_text=\n 'This creates a Bootstrap Column, full width is 12.')\n\n def __str__(self):\n return self.css_class()\n\n def css_class(self):\n return 'col-' + self.size + str(self.width)\n\n\nclass HRPlugin(CMSPlugin):\n COLOURS = ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light',\n 'Light')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n\n\nclass CarouselItemPlugin(CMSPlugin):\n <assignment token>\n\n\nclass LinkVideoPlugin(CMSPlugin):\n title = models.CharField(max_length=25)\n jump_to_index = models.CharField(max_length=10)\n video = FilerFileField(related_name='link_video')\n\n def __str__(self):\n return self.jump_to_index\n\n\nclass LinkedSectionPlugin(CMSPlugin):\n index = models.CharField(max_length=10)\n\n def __str__(self):\n return self.index\n\n\nclass MapPlugin(CMSPlugin):\n latitude = models.FloatField()\n longitude = models.FloatField()\n zoom = models.IntegerField()\n label = models.CharField(max_length=20)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n height = models.CharField(default='500px', max_length=10)\n\n def __str__(self):\n return self.label\n\n\nclass AwardPlugin(CMSPlugin):\n logo = FilerImageField(null=True, related_name='award_logo')\n text = models.TextField()\n\n def __str__(self):\n return instance.text[:15]\n\n\nclass RowPlugin(CMSPlugin):\n title = models.CharField(max_length=30, default='')\n ymargin = models.IntegerField(help_text=\n 'on a scale of 1 to 5, as per Bootstrap, adds margin to top and bottom of row'\n )\n\n def __str__(self):\n if self.title:\n return self.title\n return self.css_class()\n\n def css_class(self):\n return 'row my-' + str(self.ymargin)\n\n\nclass ColumnPlugin(CMSPlugin):\n COL_CHOICES = ('', 'Extra Small'), ('sm-', 'Small'), ('md-', 'Medium'), (\n 'lg-', 'Large'), ('xl-', 'Extra Large')\n size = models.CharField(max_length=3, choices=COL_CHOICES, default=\n 'md-', help_text=\n 'The larger the column, the more likely it will stack as screen size decreases.'\n )\n width = models.IntegerField(help_text=\n 'This creates a Bootstrap Column, full width is 12.')\n\n def __str__(self):\n return self.css_class()\n\n def css_class(self):\n return 'col-' + self.size + str(self.width)\n\n\nclass HRPlugin(CMSPlugin):\n COLOURS = ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light',\n 'Light')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n\n\nclass LinkVideoPlugin(CMSPlugin):\n title = models.CharField(max_length=25)\n jump_to_index = models.CharField(max_length=10)\n video = FilerFileField(related_name='link_video')\n\n def __str__(self):\n return self.jump_to_index\n\n\nclass LinkedSectionPlugin(CMSPlugin):\n index = models.CharField(max_length=10)\n\n def __str__(self):\n return self.index\n\n\nclass MapPlugin(CMSPlugin):\n latitude = models.FloatField()\n longitude = models.FloatField()\n zoom = models.IntegerField()\n label = models.CharField(max_length=20)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n height = models.CharField(default='500px', max_length=10)\n\n def __str__(self):\n return self.label\n\n\nclass AwardPlugin(CMSPlugin):\n logo = FilerImageField(null=True, related_name='award_logo')\n text = models.TextField()\n\n def __str__(self):\n return instance.text[:15]\n\n\nclass RowPlugin(CMSPlugin):\n title = models.CharField(max_length=30, default='')\n ymargin = models.IntegerField(help_text=\n 'on a scale of 1 to 5, as per Bootstrap, adds margin to top and bottom of row'\n )\n\n def __str__(self):\n if self.title:\n return self.title\n return self.css_class()\n\n def css_class(self):\n return 'row my-' + str(self.ymargin)\n\n\nclass ColumnPlugin(CMSPlugin):\n COL_CHOICES = ('', 'Extra Small'), ('sm-', 'Small'), ('md-', 'Medium'), (\n 'lg-', 'Large'), ('xl-', 'Extra Large')\n size = models.CharField(max_length=3, choices=COL_CHOICES, default=\n 'md-', help_text=\n 'The larger the column, the more likely it will stack as screen size decreases.'\n )\n width = models.IntegerField(help_text=\n 'This creates a Bootstrap Column, full width is 12.')\n\n def __str__(self):\n return self.css_class()\n\n def css_class(self):\n return 'col-' + self.size + str(self.width)\n\n\nclass HRPlugin(CMSPlugin):\n COLOURS = ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light',\n 'Light')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n\n\nclass LinkVideoPlugin(CMSPlugin):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __str__(self):\n return self.jump_to_index\n\n\nclass LinkedSectionPlugin(CMSPlugin):\n index = models.CharField(max_length=10)\n\n def __str__(self):\n return self.index\n\n\nclass MapPlugin(CMSPlugin):\n latitude = models.FloatField()\n longitude = models.FloatField()\n zoom = models.IntegerField()\n label = models.CharField(max_length=20)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n height = models.CharField(default='500px', max_length=10)\n\n def __str__(self):\n return self.label\n\n\nclass AwardPlugin(CMSPlugin):\n logo = FilerImageField(null=True, related_name='award_logo')\n text = models.TextField()\n\n def __str__(self):\n return instance.text[:15]\n\n\nclass RowPlugin(CMSPlugin):\n title = models.CharField(max_length=30, default='')\n ymargin = models.IntegerField(help_text=\n 'on a scale of 1 to 5, as per Bootstrap, adds margin to top and bottom of row'\n )\n\n def __str__(self):\n if self.title:\n return self.title\n return self.css_class()\n\n def css_class(self):\n return 'row my-' + str(self.ymargin)\n\n\nclass ColumnPlugin(CMSPlugin):\n COL_CHOICES = ('', 'Extra Small'), ('sm-', 'Small'), ('md-', 'Medium'), (\n 'lg-', 'Large'), ('xl-', 'Extra Large')\n size = models.CharField(max_length=3, choices=COL_CHOICES, default=\n 'md-', help_text=\n 'The larger the column, the more likely it will stack as screen size decreases.'\n )\n width = models.IntegerField(help_text=\n 'This creates a Bootstrap Column, full width is 12.')\n\n def __str__(self):\n return self.css_class()\n\n def css_class(self):\n return 'col-' + self.size + str(self.width)\n\n\nclass HRPlugin(CMSPlugin):\n COLOURS = ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light',\n 'Light')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n\n\nclass LinkVideoPlugin(CMSPlugin):\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n\n\nclass LinkedSectionPlugin(CMSPlugin):\n index = models.CharField(max_length=10)\n\n def __str__(self):\n return self.index\n\n\nclass MapPlugin(CMSPlugin):\n latitude = models.FloatField()\n longitude = models.FloatField()\n zoom = models.IntegerField()\n label = models.CharField(max_length=20)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n height = models.CharField(default='500px', max_length=10)\n\n def __str__(self):\n return self.label\n\n\nclass AwardPlugin(CMSPlugin):\n logo = FilerImageField(null=True, related_name='award_logo')\n text = models.TextField()\n\n def __str__(self):\n return instance.text[:15]\n\n\nclass RowPlugin(CMSPlugin):\n title = models.CharField(max_length=30, default='')\n ymargin = models.IntegerField(help_text=\n 'on a scale of 1 to 5, as per Bootstrap, adds margin to top and bottom of row'\n )\n\n def __str__(self):\n if self.title:\n return self.title\n return self.css_class()\n\n def css_class(self):\n return 'row my-' + str(self.ymargin)\n\n\nclass ColumnPlugin(CMSPlugin):\n COL_CHOICES = ('', 'Extra Small'), ('sm-', 'Small'), ('md-', 'Medium'), (\n 'lg-', 'Large'), ('xl-', 'Extra Large')\n size = models.CharField(max_length=3, choices=COL_CHOICES, default=\n 'md-', help_text=\n 'The larger the column, the more likely it will stack as screen size decreases.'\n )\n width = models.IntegerField(help_text=\n 'This creates a Bootstrap Column, full width is 12.')\n\n def __str__(self):\n return self.css_class()\n\n def css_class(self):\n return 'col-' + self.size + str(self.width)\n\n\nclass HRPlugin(CMSPlugin):\n COLOURS = ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light',\n 'Light')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n\n\nclass LinkedSectionPlugin(CMSPlugin):\n index = models.CharField(max_length=10)\n\n def __str__(self):\n return self.index\n\n\nclass MapPlugin(CMSPlugin):\n latitude = models.FloatField()\n longitude = models.FloatField()\n zoom = models.IntegerField()\n label = models.CharField(max_length=20)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n height = models.CharField(default='500px', max_length=10)\n\n def __str__(self):\n return self.label\n\n\nclass AwardPlugin(CMSPlugin):\n logo = FilerImageField(null=True, related_name='award_logo')\n text = models.TextField()\n\n def __str__(self):\n return instance.text[:15]\n\n\nclass RowPlugin(CMSPlugin):\n title = models.CharField(max_length=30, default='')\n ymargin = models.IntegerField(help_text=\n 'on a scale of 1 to 5, as per Bootstrap, adds margin to top and bottom of row'\n )\n\n def __str__(self):\n if self.title:\n return self.title\n return self.css_class()\n\n def css_class(self):\n return 'row my-' + str(self.ymargin)\n\n\nclass ColumnPlugin(CMSPlugin):\n COL_CHOICES = ('', 'Extra Small'), ('sm-', 'Small'), ('md-', 'Medium'), (\n 'lg-', 'Large'), ('xl-', 'Extra Large')\n size = models.CharField(max_length=3, choices=COL_CHOICES, default=\n 'md-', help_text=\n 'The larger the column, the more likely it will stack as screen size decreases.'\n )\n width = models.IntegerField(help_text=\n 'This creates a Bootstrap Column, full width is 12.')\n\n def __str__(self):\n return self.css_class()\n\n def css_class(self):\n return 'col-' + self.size + str(self.width)\n\n\nclass HRPlugin(CMSPlugin):\n COLOURS = ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light',\n 'Light')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n\n\nclass LinkedSectionPlugin(CMSPlugin):\n <assignment token>\n\n def __str__(self):\n return self.index\n\n\nclass MapPlugin(CMSPlugin):\n latitude = models.FloatField()\n longitude = models.FloatField()\n zoom = models.IntegerField()\n label = models.CharField(max_length=20)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n height = models.CharField(default='500px', max_length=10)\n\n def __str__(self):\n return self.label\n\n\nclass AwardPlugin(CMSPlugin):\n logo = FilerImageField(null=True, related_name='award_logo')\n text = models.TextField()\n\n def __str__(self):\n return instance.text[:15]\n\n\nclass RowPlugin(CMSPlugin):\n title = models.CharField(max_length=30, default='')\n ymargin = models.IntegerField(help_text=\n 'on a scale of 1 to 5, as per Bootstrap, adds margin to top and bottom of row'\n )\n\n def __str__(self):\n if self.title:\n return self.title\n return self.css_class()\n\n def css_class(self):\n return 'row my-' + str(self.ymargin)\n\n\nclass ColumnPlugin(CMSPlugin):\n COL_CHOICES = ('', 'Extra Small'), ('sm-', 'Small'), ('md-', 'Medium'), (\n 'lg-', 'Large'), ('xl-', 'Extra Large')\n size = models.CharField(max_length=3, choices=COL_CHOICES, default=\n 'md-', help_text=\n 'The larger the column, the more likely it will stack as screen size decreases.'\n )\n width = models.IntegerField(help_text=\n 'This creates a Bootstrap Column, full width is 12.')\n\n def __str__(self):\n return self.css_class()\n\n def css_class(self):\n return 'col-' + self.size + str(self.width)\n\n\nclass HRPlugin(CMSPlugin):\n COLOURS = ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light',\n 'Light')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n\n\nclass LinkedSectionPlugin(CMSPlugin):\n <assignment token>\n <function token>\n\n\nclass MapPlugin(CMSPlugin):\n latitude = models.FloatField()\n longitude = models.FloatField()\n zoom = models.IntegerField()\n label = models.CharField(max_length=20)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n height = models.CharField(default='500px', max_length=10)\n\n def __str__(self):\n return self.label\n\n\nclass AwardPlugin(CMSPlugin):\n logo = FilerImageField(null=True, related_name='award_logo')\n text = models.TextField()\n\n def __str__(self):\n return instance.text[:15]\n\n\nclass RowPlugin(CMSPlugin):\n title = models.CharField(max_length=30, default='')\n ymargin = models.IntegerField(help_text=\n 'on a scale of 1 to 5, as per Bootstrap, adds margin to top and bottom of row'\n )\n\n def __str__(self):\n if self.title:\n return self.title\n return self.css_class()\n\n def css_class(self):\n return 'row my-' + str(self.ymargin)\n\n\nclass ColumnPlugin(CMSPlugin):\n COL_CHOICES = ('', 'Extra Small'), ('sm-', 'Small'), ('md-', 'Medium'), (\n 'lg-', 'Large'), ('xl-', 'Extra Large')\n size = models.CharField(max_length=3, choices=COL_CHOICES, default=\n 'md-', help_text=\n 'The larger the column, the more likely it will stack as screen size decreases.'\n )\n width = models.IntegerField(help_text=\n 'This creates a Bootstrap Column, full width is 12.')\n\n def __str__(self):\n return self.css_class()\n\n def css_class(self):\n return 'col-' + self.size + str(self.width)\n\n\nclass HRPlugin(CMSPlugin):\n COLOURS = ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light',\n 'Light')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass MapPlugin(CMSPlugin):\n latitude = models.FloatField()\n longitude = models.FloatField()\n zoom = models.IntegerField()\n label = models.CharField(max_length=20)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n height = models.CharField(default='500px', max_length=10)\n\n def __str__(self):\n return self.label\n\n\nclass AwardPlugin(CMSPlugin):\n logo = FilerImageField(null=True, related_name='award_logo')\n text = models.TextField()\n\n def __str__(self):\n return instance.text[:15]\n\n\nclass RowPlugin(CMSPlugin):\n title = models.CharField(max_length=30, default='')\n ymargin = models.IntegerField(help_text=\n 'on a scale of 1 to 5, as per Bootstrap, adds margin to top and bottom of row'\n )\n\n def __str__(self):\n if self.title:\n return self.title\n return self.css_class()\n\n def css_class(self):\n return 'row my-' + str(self.ymargin)\n\n\nclass ColumnPlugin(CMSPlugin):\n COL_CHOICES = ('', 'Extra Small'), ('sm-', 'Small'), ('md-', 'Medium'), (\n 'lg-', 'Large'), ('xl-', 'Extra Large')\n size = models.CharField(max_length=3, choices=COL_CHOICES, default=\n 'md-', help_text=\n 'The larger the column, the more likely it will stack as screen size decreases.'\n )\n width = models.IntegerField(help_text=\n 'This creates a Bootstrap Column, full width is 12.')\n\n def __str__(self):\n return self.css_class()\n\n def css_class(self):\n return 'col-' + self.size + str(self.width)\n\n\nclass HRPlugin(CMSPlugin):\n COLOURS = ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light',\n 'Light')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass MapPlugin(CMSPlugin):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __str__(self):\n return self.label\n\n\nclass AwardPlugin(CMSPlugin):\n logo = FilerImageField(null=True, related_name='award_logo')\n text = models.TextField()\n\n def __str__(self):\n return instance.text[:15]\n\n\nclass RowPlugin(CMSPlugin):\n title = models.CharField(max_length=30, default='')\n ymargin = models.IntegerField(help_text=\n 'on a scale of 1 to 5, as per Bootstrap, adds margin to top and bottom of row'\n )\n\n def __str__(self):\n if self.title:\n return self.title\n return self.css_class()\n\n def css_class(self):\n return 'row my-' + str(self.ymargin)\n\n\nclass ColumnPlugin(CMSPlugin):\n COL_CHOICES = ('', 'Extra Small'), ('sm-', 'Small'), ('md-', 'Medium'), (\n 'lg-', 'Large'), ('xl-', 'Extra Large')\n size = models.CharField(max_length=3, choices=COL_CHOICES, default=\n 'md-', help_text=\n 'The larger the column, the more likely it will stack as screen size decreases.'\n )\n width = models.IntegerField(help_text=\n 'This creates a Bootstrap Column, full width is 12.')\n\n def __str__(self):\n return self.css_class()\n\n def css_class(self):\n return 'col-' + self.size + str(self.width)\n\n\nclass HRPlugin(CMSPlugin):\n COLOURS = ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light',\n 'Light')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass MapPlugin(CMSPlugin):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n\n\nclass AwardPlugin(CMSPlugin):\n logo = FilerImageField(null=True, related_name='award_logo')\n text = models.TextField()\n\n def __str__(self):\n return instance.text[:15]\n\n\nclass RowPlugin(CMSPlugin):\n title = models.CharField(max_length=30, default='')\n ymargin = models.IntegerField(help_text=\n 'on a scale of 1 to 5, as per Bootstrap, adds margin to top and bottom of row'\n )\n\n def __str__(self):\n if self.title:\n return self.title\n return self.css_class()\n\n def css_class(self):\n return 'row my-' + str(self.ymargin)\n\n\nclass ColumnPlugin(CMSPlugin):\n COL_CHOICES = ('', 'Extra Small'), ('sm-', 'Small'), ('md-', 'Medium'), (\n 'lg-', 'Large'), ('xl-', 'Extra Large')\n size = models.CharField(max_length=3, choices=COL_CHOICES, default=\n 'md-', help_text=\n 'The larger the column, the more likely it will stack as screen size decreases.'\n )\n width = models.IntegerField(help_text=\n 'This creates a Bootstrap Column, full width is 12.')\n\n def __str__(self):\n return self.css_class()\n\n def css_class(self):\n return 'col-' + self.size + str(self.width)\n\n\nclass HRPlugin(CMSPlugin):\n COLOURS = ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light',\n 'Light')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass AwardPlugin(CMSPlugin):\n logo = FilerImageField(null=True, related_name='award_logo')\n text = models.TextField()\n\n def __str__(self):\n return instance.text[:15]\n\n\nclass RowPlugin(CMSPlugin):\n title = models.CharField(max_length=30, default='')\n ymargin = models.IntegerField(help_text=\n 'on a scale of 1 to 5, as per Bootstrap, adds margin to top and bottom of row'\n )\n\n def __str__(self):\n if self.title:\n return self.title\n return self.css_class()\n\n def css_class(self):\n return 'row my-' + str(self.ymargin)\n\n\nclass ColumnPlugin(CMSPlugin):\n COL_CHOICES = ('', 'Extra Small'), ('sm-', 'Small'), ('md-', 'Medium'), (\n 'lg-', 'Large'), ('xl-', 'Extra Large')\n size = models.CharField(max_length=3, choices=COL_CHOICES, default=\n 'md-', help_text=\n 'The larger the column, the more likely it will stack as screen size decreases.'\n )\n width = models.IntegerField(help_text=\n 'This creates a Bootstrap Column, full width is 12.')\n\n def __str__(self):\n return self.css_class()\n\n def css_class(self):\n return 'col-' + self.size + str(self.width)\n\n\nclass HRPlugin(CMSPlugin):\n COLOURS = ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light',\n 'Light')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass AwardPlugin(CMSPlugin):\n <assignment token>\n <assignment token>\n\n def __str__(self):\n return instance.text[:15]\n\n\nclass RowPlugin(CMSPlugin):\n title = models.CharField(max_length=30, default='')\n ymargin = models.IntegerField(help_text=\n 'on a scale of 1 to 5, as per Bootstrap, adds margin to top and bottom of row'\n )\n\n def __str__(self):\n if self.title:\n return self.title\n return self.css_class()\n\n def css_class(self):\n return 'row my-' + str(self.ymargin)\n\n\nclass ColumnPlugin(CMSPlugin):\n COL_CHOICES = ('', 'Extra Small'), ('sm-', 'Small'), ('md-', 'Medium'), (\n 'lg-', 'Large'), ('xl-', 'Extra Large')\n size = models.CharField(max_length=3, choices=COL_CHOICES, default=\n 'md-', help_text=\n 'The larger the column, the more likely it will stack as screen size decreases.'\n )\n width = models.IntegerField(help_text=\n 'This creates a Bootstrap Column, full width is 12.')\n\n def __str__(self):\n return self.css_class()\n\n def css_class(self):\n return 'col-' + self.size + str(self.width)\n\n\nclass HRPlugin(CMSPlugin):\n COLOURS = ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light',\n 'Light')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass AwardPlugin(CMSPlugin):\n <assignment token>\n <assignment token>\n <function token>\n\n\nclass RowPlugin(CMSPlugin):\n title = models.CharField(max_length=30, default='')\n ymargin = models.IntegerField(help_text=\n 'on a scale of 1 to 5, as per Bootstrap, adds margin to top and bottom of row'\n )\n\n def __str__(self):\n if self.title:\n return self.title\n return self.css_class()\n\n def css_class(self):\n return 'row my-' + str(self.ymargin)\n\n\nclass ColumnPlugin(CMSPlugin):\n COL_CHOICES = ('', 'Extra Small'), ('sm-', 'Small'), ('md-', 'Medium'), (\n 'lg-', 'Large'), ('xl-', 'Extra Large')\n size = models.CharField(max_length=3, choices=COL_CHOICES, default=\n 'md-', help_text=\n 'The larger the column, the more likely it will stack as screen size decreases.'\n )\n width = models.IntegerField(help_text=\n 'This creates a Bootstrap Column, full width is 12.')\n\n def __str__(self):\n return self.css_class()\n\n def css_class(self):\n return 'col-' + self.size + str(self.width)\n\n\nclass HRPlugin(CMSPlugin):\n COLOURS = ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light',\n 'Light')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass RowPlugin(CMSPlugin):\n title = models.CharField(max_length=30, default='')\n ymargin = models.IntegerField(help_text=\n 'on a scale of 1 to 5, as per Bootstrap, adds margin to top and bottom of row'\n )\n\n def __str__(self):\n if self.title:\n return self.title\n return self.css_class()\n\n def css_class(self):\n return 'row my-' + str(self.ymargin)\n\n\nclass ColumnPlugin(CMSPlugin):\n COL_CHOICES = ('', 'Extra Small'), ('sm-', 'Small'), ('md-', 'Medium'), (\n 'lg-', 'Large'), ('xl-', 'Extra Large')\n size = models.CharField(max_length=3, choices=COL_CHOICES, default=\n 'md-', help_text=\n 'The larger the column, the more likely it will stack as screen size decreases.'\n )\n width = models.IntegerField(help_text=\n 'This creates a Bootstrap Column, full width is 12.')\n\n def __str__(self):\n return self.css_class()\n\n def css_class(self):\n return 'col-' + self.size + str(self.width)\n\n\nclass HRPlugin(CMSPlugin):\n COLOURS = ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light',\n 'Light')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass RowPlugin(CMSPlugin):\n <assignment token>\n <assignment token>\n\n def __str__(self):\n if self.title:\n return self.title\n return self.css_class()\n\n def css_class(self):\n return 'row my-' + str(self.ymargin)\n\n\nclass ColumnPlugin(CMSPlugin):\n COL_CHOICES = ('', 'Extra Small'), ('sm-', 'Small'), ('md-', 'Medium'), (\n 'lg-', 'Large'), ('xl-', 'Extra Large')\n size = models.CharField(max_length=3, choices=COL_CHOICES, default=\n 'md-', help_text=\n 'The larger the column, the more likely it will stack as screen size decreases.'\n )\n width = models.IntegerField(help_text=\n 'This creates a Bootstrap Column, full width is 12.')\n\n def __str__(self):\n return self.css_class()\n\n def css_class(self):\n return 'col-' + self.size + str(self.width)\n\n\nclass HRPlugin(CMSPlugin):\n COLOURS = ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light',\n 'Light')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass RowPlugin(CMSPlugin):\n <assignment token>\n <assignment token>\n\n def __str__(self):\n if self.title:\n return self.title\n return self.css_class()\n <function token>\n\n\nclass ColumnPlugin(CMSPlugin):\n COL_CHOICES = ('', 'Extra Small'), ('sm-', 'Small'), ('md-', 'Medium'), (\n 'lg-', 'Large'), ('xl-', 'Extra Large')\n size = models.CharField(max_length=3, choices=COL_CHOICES, default=\n 'md-', help_text=\n 'The larger the column, the more likely it will stack as screen size decreases.'\n )\n width = models.IntegerField(help_text=\n 'This creates a Bootstrap Column, full width is 12.')\n\n def __str__(self):\n return self.css_class()\n\n def css_class(self):\n return 'col-' + self.size + str(self.width)\n\n\nclass HRPlugin(CMSPlugin):\n COLOURS = ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light',\n 'Light')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass RowPlugin(CMSPlugin):\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n\n\nclass ColumnPlugin(CMSPlugin):\n COL_CHOICES = ('', 'Extra Small'), ('sm-', 'Small'), ('md-', 'Medium'), (\n 'lg-', 'Large'), ('xl-', 'Extra Large')\n size = models.CharField(max_length=3, choices=COL_CHOICES, default=\n 'md-', help_text=\n 'The larger the column, the more likely it will stack as screen size decreases.'\n )\n width = models.IntegerField(help_text=\n 'This creates a Bootstrap Column, full width is 12.')\n\n def __str__(self):\n return self.css_class()\n\n def css_class(self):\n return 'col-' + self.size + str(self.width)\n\n\nclass HRPlugin(CMSPlugin):\n COLOURS = ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light',\n 'Light')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass ColumnPlugin(CMSPlugin):\n COL_CHOICES = ('', 'Extra Small'), ('sm-', 'Small'), ('md-', 'Medium'), (\n 'lg-', 'Large'), ('xl-', 'Extra Large')\n size = models.CharField(max_length=3, choices=COL_CHOICES, default=\n 'md-', help_text=\n 'The larger the column, the more likely it will stack as screen size decreases.'\n )\n width = models.IntegerField(help_text=\n 'This creates a Bootstrap Column, full width is 12.')\n\n def __str__(self):\n return self.css_class()\n\n def css_class(self):\n return 'col-' + self.size + str(self.width)\n\n\nclass HRPlugin(CMSPlugin):\n COLOURS = ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light',\n 'Light')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass ColumnPlugin(CMSPlugin):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __str__(self):\n return self.css_class()\n\n def css_class(self):\n return 'col-' + self.size + str(self.width)\n\n\nclass HRPlugin(CMSPlugin):\n COLOURS = ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light',\n 'Light')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass ColumnPlugin(CMSPlugin):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __str__(self):\n return self.css_class()\n <function token>\n\n\nclass HRPlugin(CMSPlugin):\n COLOURS = ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light',\n 'Light')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass ColumnPlugin(CMSPlugin):\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n\n\nclass HRPlugin(CMSPlugin):\n COLOURS = ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light',\n 'Light')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass HRPlugin(CMSPlugin):\n COLOURS = ('thick', 'Dark and thick'), ('dark', 'Dark and thin'), ('light',\n 'Light')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass HRPlugin(CMSPlugin):\n <assignment token>\n <assignment token>\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass HRPlugin(CMSPlugin):\n <assignment token>\n <assignment token>\n <function token>\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass EmailFormPlugin(CMSPlugin):\n COLOURS = ('black', 'Black'), ('white', 'White')\n css_class = models.CharField(max_length=5, choices=COLOURS, default='light'\n )\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass EmailFormPlugin(CMSPlugin):\n <assignment token>\n <assignment token>\n\n def __str__(self):\n return dict(self.COLOURS)[self.css_class]\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass EmailFormPlugin(CMSPlugin):\n <assignment token>\n <assignment token>\n <function token>\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass AddressPlugin(CMSPlugin):\n address = models.TextField()\n phone = models.TextField()\n email = models.CharField(max_length=200)\n direct_link = models.URLField(null=True, help_text=\n \"Generate this by going to Google Maps and pressing 'Share'\")\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass AddressPlugin(CMSPlugin):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass SocialLinkPlugin(CMSPlugin):\n icon_class = models.CharField(max_length=20, default='fa fa-twitter')\n text = models.CharField(max_length=30)\n link = models.URLField()\n open_new_tab = models.BooleanField(default=True)\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass SocialLinkPlugin(CMSPlugin):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __str__(self):\n return self.text\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass SocialLinkPlugin(CMSPlugin):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass SocialSharePlugin(CMSPlugin):\n share_to_pinterest = models.BooleanField(default=True)\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass SocialSharePlugin(CMSPlugin):\n <assignment token>\n\n def __str__(self):\n return str(self.share_to_pinterest)\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass SocialSharePlugin(CMSPlugin):\n <assignment token>\n <function token>\n", "<import token>\n<class token>\n<code token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n" ]
false
98,743
612ee3d98673a0c65bd338bb10eb8710d0352d57
import argparse p=argparse.ArgumentParser() p.add_argument('--subtype',required=False,default='mp4') p.add_argument('--url',required=False,default='') args=p.parse_args() subtype=args.subtype url=args.url print(subtype) print(url)
[ "import argparse\n\np=argparse.ArgumentParser()\np.add_argument('--subtype',required=False,default='mp4')\np.add_argument('--url',required=False,default='')\nargs=p.parse_args()\nsubtype=args.subtype\nurl=args.url\n\nprint(subtype)\nprint(url)", "import argparse\np = argparse.ArgumentParser()\np.add_argument('--subtype', required=False, default='mp4')\np.add_argument('--url', required=False, default='')\nargs = p.parse_args()\nsubtype = args.subtype\nurl = args.url\nprint(subtype)\nprint(url)\n", "<import token>\np = argparse.ArgumentParser()\np.add_argument('--subtype', required=False, default='mp4')\np.add_argument('--url', required=False, default='')\nargs = p.parse_args()\nsubtype = args.subtype\nurl = args.url\nprint(subtype)\nprint(url)\n", "<import token>\n<assignment token>\np.add_argument('--subtype', required=False, default='mp4')\np.add_argument('--url', required=False, default='')\n<assignment token>\nprint(subtype)\nprint(url)\n", "<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
98,744
419642a1c517e4fcc10b3f2174cfb38e4d473c76
import numpy as np import pdb import itertools as it import matplotlib import matplotlib.pyplot as plt import matplotlib.dates as dates from sklearn.metrics import f1_score import pandas as pd import os import sys import datetime import glob import re import graphviz import seaborn as sns import numpy as np from scipy.stats import norm from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import precision_recall_curve from sklearn.metrics import f1_score from sklearn.preprocessing import StandardScaler from scipy import stats import warnings warnings.filterwarnings('ignore') import statsmodels.api as sm from patsy import dmatrices from sklearn.metrics import roc_auc_score from sklearn import tree from sklearn.svm import SVC from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier, BaggingClassifier, GradientBoostingClassifier from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn.cross_validation import train_test_split from sklearn import metrics from sklearn.cross_validation import cross_val_score import json from sklearn.model_selection import KFold """ Homework 2: ML Pipeline Looking at data regarding credit distress and trying to predict who will have credit distress in the next two years. Below is a pipeline of various ml tools that can be used to analyze, explore, and clean data. author: Yuliana Zamora Date: April 17, 2018 """ # Reading csv data from file - must be in same directory def load_data(csv_file,nrows=None): return pd.read_csv(csv_file,nrows=nrows) #converts a string that is camelCase into snake_case #https://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-snake-case def camel_case(column_name): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', column_name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() #Give data with specific column def histogram(data_frame): sns.distplot(data_frame) plt.show() #Given specific column or row, returns statistical summary def summary(data_frame): return data_frame.describe() #Creating a correlation heat map from data set where var_name is the #variable which has the most correlation def cor_heat(data_frame,var_name): corrmat = data_frame.corr() k = 12 cols = corrmat.nlargest(k, var_name)[var_name].index cm = np.corrcoef(data_frame[cols].values.T) sns.set(font_scale=1.25) hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f', annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.values) plt.show() #Scatter plots of desired variables in list def plotCorr(dataFrame, list): sns.set() sns.pairplot(dataFrame[list], size = 2.5) return plt.show() #Shows data is missing, we should delete the corresponding variable and pretend it never existed - threshold as parameter def miss_data(data_frame): total = data_frame.isnull().sum().sort_values(ascending=False) percent = (data_frame.isnull().sum()/data_frame.isnull().count()).sort_values(ascending=False) missing_data = pd.concat([total, percent], axis=1, keys=['Total', 'Percent']) #return missing_data.head(20) return missing_data #Dealing with missing data def clean_miss(data_frame): missing_data = miss_data(data_frame) data_frame = data_frame.drop((missing_data[missing_data['Total'] > 1]).index,1) data_frame.isnull().sum().max() #just checking that there's no missing data missing... return data_frame #Univariate analysis - scaling data, prints out low range and high range def scale(data_frame, var_scale): data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,np.newaxis]); low_range = data_scaled[data_scaled[:,0].argsort()][:10] high_range= data_scaled[data_scaled[:,0].argsort()][-10:] print('outer range (low) of the distribution:') print(low_range) print('\nouter range (high) of the distribution:') print(high_range) #Bivariate analysis def bivariate(data_frame, var_1,var_2): varx = var_1 vary = var_2 data = pd.concat([data_frame[varx], data_frame[vary]], axis=1) data.plot.scatter(x=varx, y=vary, ylim=(0,100)); plt.show() #histogram and normal probability plot def norm_plot(data_frame,var_name): sns.distplot(data_frame[var_name], fit=norm); fig = plt.figure() res = stats.probplot((data_frame)[var_name], plot=plt) plt.show() #Fill in empty values def fill_empty(data_frame,var, new_var): return data_frame[var].fillna(new_var) #Discretize continuous variables def descretize(data_frame, var, num): return pd.cut(data_frame[var],num,retbins=True) #Creating dummy variables from categorical variables def dummy_var(data_frame, var): return pd.get_dummies(data_frame[var]) #Creating dictionary with no repeated column items def column_dic(data_frame): dict = {line[:1]:line[1:].split()[0] for line in data_frame} print (dict) #Logistic regression = iv, independent variable, var_list - dependent variables def logReg(data_frame, IV, var_list): #organizing variable list to independent and dependent variables #taking care of hyphen if first word contains it if '-' in var_list[0]: formula = IV + "~"+'Q("'+var_list[0]+'")' else: formula = IV + "~"+var_list[0] #taking care of the rest of the potential hyphens for i in range(1, len(var_list)): if '-' in var_list[i]: formula = formula + "+"+'Q("'+var_list[i]+'")' else: formula = formula + "+"+ var_list[i] y, X = dmatrices(formula,data_frame, return_type="dataframe") y = np.ravel(y) model = LogisticRegression() model = model.fit(X, y) print (pd.DataFrame(list(zip(X.columns, np.transpose(model.coef_))))) return model.score(X,y) #Nearest Neighbors - def knearest(data_frame,train, test): #data_frame = data_frame.reshape(-1,1) X = data_frame[train].reshape(-1,1) Y = data_frame[test].reshape(-1,1) X_train = X[:100] Y_train = Y[:100] X_validate = X[100:] Y_validate = Y[100:] neighbor = KNeighborsClassifier(n_neighbors = 2, weights ='uniform') neighbor.fit(X_train, Y_train) predicted = neighbor.predict(X_validate) print (predicted) def merging_data(dataframe_1,dataframe_2): return pd.merge(dataframe_1,dataframe_2) def merging_data2(dataframe_1,dataframe_2): dataframe_1['fully_funded'] = 1 return dataframe_1 def get_combos(param_grid_dict): all = sorted(param_grid_dict) all_combos=[] combinations = it.product(*(param_grid_dict[Name] for Name in all)) for i in combinations: lil_combo = {} for iter,key in enumerate(all): lil_combo[key] = i[iter] all_combos.append(lil_combo) return (all_combos) #change items into binary columns def to_binary(df,array_col): for i in array_col: print(i) #df[i] = df[i].apply(lambda x: 1 if x == 't' else (0 if x =='f' else np.nan)) df[i] = df[i].apply(lambda x: 1 if x == 't' else 0) return df #analyzing results from classifiers def get_metrics(y_pred, val_Y): metric_results ={} #predicting the majority class ones = np.sum(val_Y)['SeriousDlqin2yrs']/float(len(val_Y)) zeros = 1-ones try: metric_results['baseline'] = max(ones, zeros) except: pdb.set_trace() if ones > zeros: metric_results['precision_base'] = precision_score(val_Y, np.ones(len(val_Y))) metric_results['recall_base'] = recall_score(val_Y,np.ones[len(val_Y)]) else: metric_results['precision_base'] = precision_score(val_Y, np.zeros(len(val_Y))) metric_results['recall_base'] = recall_score(val_Y,np.zeros(len(val_Y))) #loss = f1_score(y_pred,val_Y) perf_metrics = [.01,.02,.05,.10,.20,.30,.50] for i in perf_metrics: #pdb.set_trace() print("Recall AT \n") print(recall_at_k(val_Y, y_pred, i)) #metric_results["precision at" + str([i])] = precision_score(val_Y, y_pred > 1 - i) metric_results["precision at" + str([i])] = precision_at_k(val_Y, y_pred, i) metric_results["recall at" + str([i])] = recall_score(val_Y, y_pred> 1 - i) metric_results["F1 at" + str([i])] = f1_score(val_Y, y_pred > 1 - i) metric_results["ROC"] = roc_auc_score(val_Y, y_pred) prec,rec,thresh = precision_recall_curve(val_Y, y_pred) metric_results["PREC"] = prec.tolist() metric_results["REC"] = rec.tolist() metric_results["THRESH"] = thresh.tolist() #out.write(metric_results) return (metric_results) def recall_at_k(y_true, y_scores, k): #y_scores_sorted, y_true_sorted = zip(*sorted(zip(y_scores, y_true), reverse=True)) y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(y_scores), np.array(y_true)) preds_at_k = generate_binary_at_k(y_scores_sorted, k) #precision, _, _, _ = metrics.precision_recall_fscore_support(y_true, preds_at_k) #precision = precision[1] # only interested in precision for label 1 recall = recall_score(y_true_sorted, preds_at_k) return recall def joint_sort_descending(l1, l2): # l1 and l2 have to be numpy arrays idx = np.argsort(l1)[::-1] return l1[idx], l2[idx] def generate_binary_at_k(y_scores, k): cutoff_index = int(len(y_scores) * (k / 100.0)) predictions_binary = [1 if x < cutoff_index else 0 for x in range(len(y_scores))] return predictions_binary def precision_at_k(y_true, y_scores, k): #y_scores_sorted, y_true_sorted = zip(*sorted(zip(y_scores, y_true), reverse=True)) y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(y_scores), np.array(y_true)) preds_at_k = generate_binary_at_k(y_scores_sorted, k) #precision, _, _, _ = metrics.precision_recall_fscore_support(y_true, preds_at_k) #precision = precision[1] # only interested in precision for label 1 precision = precision_score(y_true_sorted, preds_at_k) return precision #plotting precisison and recal graphs, input one column for y_pred in class_comp method def plot_precision_recall(val_Y,y_pred,model_name,output_type): #pdb.set_trace() prec,rec,thresh = precision_recall_curve(val_Y, y_pred) prec = prec[:-1] recall_curve = rec[:-1] pct_above_per_thresh = [] number_scored = len(y_pred) for value in thresh: num_above_thresh = len(y_pred[y_pred>=value]) pct_above_thresh = num_above_thresh / float(len(y_pred)) if pct_above_thresh <= 1: pct_above_per_thresh.append(pct_above_thresh) else: raise Exception pct_above_per_thresh = np.array(pct_above_per_thresh) plt.clf() fig, ax1 = plt.subplots() ax1.plot(pct_above_per_thresh, prec, 'b') print("PLOTTING STUFF") print(pct_above_per_thresh) print(prec[:-1]) ax1.set_xlabel('percent of population') ax1.set_ylabel('precision', color='b') ax2 = ax1.twinx() ax2.plot(pct_above_per_thresh, recall_curve, 'r') ax2.set_ylabel('recall', color='r') ax1.set_ylim([0,1]) ax2.set_xlim([0,1]) name = model_name plt.title(name) #pdb.set_trace() if (output_type == 'save'): plt.savefig(name) elif (output_type == 'show'): plt.show() pdb.set_trace() else: plt.show() pdb.set_trace() def temp_val(data_frame,target,features): models_params = { RandomForestClassifier:{'n_estimators':[100] , 'criterion':['gini','entropy'], 'max_features':['sqrt','log2'] , 'max_depth':[5,10],'n_jobs':[4], 'min_samples_leaf':[10,50,100]}, LogisticRegression: {'C':[10**-1,10**-2,10**-3],'penalty':['l1','l2']}, KNeighborsClassifier:{'n_neighbors':[5,10,25,100], 'p':[1,2,3],'n_jobs':[2]}, DecisionTreeClassifier:{'max_depth': [5,10,15],'min_samples_leaf':[2,5,10]}, GradientBoostingClassifier:{'learning_rate':[.1,.01],'n_estimators':[100] ,'max_features':['sqrt','log2'] , 'max_depth':[1,2,3]}, BaggingClassifier:{'max_samples':[.1,.25,.65], 'n_jobs':[4]}, #SVC:{'kernel':['linear','rbf'],'gamma':[10,1,.1,.01], 'C':[10,1,.1,.01], 'probability':[True]} } # start time of our data #start_time = '2002-09-13' start_time_date = data_frame['date_posted'].min() #last date of data including labels and outcomes that we have #end_time = '2014-05-12' end_time_date = data_frame['date_posted'].max() #how far out do we want to predict (let's say in months for now) prediction_windows = [1] #how often is this prediction being made? every day? every month? once a year? update_window = 12 from datetime import date, datetime, timedelta from dateutil.relativedelta import relativedelta #start_time_date = datetime.strptime(start_time, '%Y-%m-%d') #end_time_date = datetime.strptime(end_time, '%Y-%m-%d') for prediction_window in prediction_windows: print(start_time_date,end_time_date) test_end_time = end_time_date while (test_end_time >= start_time_date + 2 * relativedelta(months=+prediction_window)): test_start_time = test_end_time - relativedelta(months=+prediction_window) train_end_time = test_start_time - relativedelta(days=+1) # minus 1 day train_start_time = train_end_time - relativedelta(months=+prediction_window) while (train_start_time >= start_time_date ): #pdb.set_trace() print (train_start_time,train_end_time,test_start_time,test_end_time, prediction_window) train_start_time -= relativedelta(months=+prediction_window) # call function to get data train_set, test_set = extract_train_test_sets(train_start_time, train_end_time, test_start_time, test_end_time,data_frame) #pdb.set_trace() class_comp(train_set,test_set,target,features,models_params) # fit on train data # predict on test data test_end_time -= relativedelta(months=+update_window) def kfold_eval(df, target, features): models_params = { RandomForestClassifier:{'n_estimators':[100] , 'criterion':['gini','entropy'], 'max_features':['sqrt','log2'] , 'max_depth':[5,10],'n_jobs':[4], 'min_samples_leaf':[10,50,100]}, LogisticRegression: {'C':[10**-1,10**-2,10**-3],'penalty':['l1','l2']}, KNeighborsClassifier:{'n_neighbors':[5,10,25,100], 'p':[1,2,3],'n_jobs':[2]}, DecisionTreeClassifier:{'max_depth': [5,10,15],'min_samples_leaf':[2,5,10]}, GradientBoostingClassifier:{'learning_rate':[.1,.01],'n_estimators':[100] ,'max_features':['sqrt','log2'] , 'max_depth':[1,2,3]}, BaggingClassifier:{'max_samples':[.1,.25,.65], 'n_jobs':[4]}, #SVC:{'kernel':['linear','rbf'],'gamma':[10,1,.1,.01], 'C':[10,1,.1,.01], 'probability':[True]} } X = df[features] #print(X) y = df[target] print(y) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) """ kf = KFold(n_splits=2) kf.get_n_splits(X) #print(kf) KFold(n_splits=2,random_state=None,shuffle=False) for train_index, test_index in kf.split(X): print("TRAIN:", train_index, "TEST:", test_index) X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] """ #knn = KNeighborsClassifier(n_neighbors=5, metric='minkowski',p=4) """rf = RandomForestClassifier(n_estimators=100,criterion='gini',max_features='sqrt',max_depth=5) rf.fit(X_train, y_train) y_score = rf.predict_proba(X_test) #y_score = rf.decision_function(X_test) y_pred = rf.predict(X_test) print(roc_auc_score(y_test,y_score[:,0])) metrics_1 ={}""" class_comp(X_train, X_test, y_train, y_test,target,features,models_params) #print (y_pred.shape) #print (y_test.shape) #return #for i in range(len(y_test)): print(y_pred) print(accuracy_score(y_test,y_pred)) #print (set(y_pred)) #print (metrics_1) #Splitting the data for training and testing sets def extract_train_test_sets(train_start_time, train_end_time, test_start_time, test_end_time, df): train_set = df[(df['date_posted'] > train_start_time) & (df['date_posted']<train_end_time)] test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted']<test_end_time)] return train_set, test_set def class_comp(X_train, X_test, y_train,y_test,target,features,models_params): out = open("out.txt","a") """X_train = train_set[features] #X y_train = train_set[target] #y #validation X_test = test_set[features] #val_x y_test = test_set[target] #val_y""" metrics = {} for m, m_param in models_params.items(): listofparam = get_combos(m_param) print("start training for {0}".format(m)) out.write("start training for {0}\n".format(m)) for params in listofparam: print (params) out.write(json.dumps(params)) model = m(**params) model.fit(X_train,y_train) #y_pred vector of prob estimates #val_y are true values y_pred = model.predict_proba(X_test) metrics[m] = get_metrics(y_pred[:,1],y_test) print("this is valy") print (y_test) print("this is y_pred") print (y_pred) plot_precision_recall(y_test, y_pred[:,1],model,'show') out.write("----------------------------\n") out.write("Using %s classifier \n" % models_params) out.write(json.dumps(metrics[m]))
[ "\nimport numpy as np\nimport pdb\nimport itertools as it\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as dates\nfrom sklearn.metrics import f1_score\nimport pandas as pd\nimport os\n\nimport sys\nimport datetime\nimport glob\nimport re\nimport graphviz\nimport seaborn as sns\nimport numpy as np\nfrom scipy.stats import norm\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import precision_score\nfrom sklearn.metrics import recall_score\nfrom sklearn.metrics import precision_recall_curve\nfrom sklearn.metrics import f1_score\nfrom sklearn.preprocessing import StandardScaler\nfrom scipy import stats\nimport warnings\nwarnings.filterwarnings('ignore')\nimport statsmodels.api as sm\nfrom patsy import dmatrices\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn import tree\nfrom sklearn.svm import SVC\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier, BaggingClassifier, GradientBoostingClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn import metrics\nfrom sklearn.cross_validation import cross_val_score\nimport json\nfrom sklearn.model_selection import KFold\n\n\"\"\"\n Homework 2: ML Pipeline\n Looking at data regarding credit distress and trying to predict who will\n have credit distress in the next two years. Below is a pipeline of various\n ml tools that can be used to analyze, explore, and clean data.\n \n author: Yuliana Zamora\n Date: April 17, 2018\n \"\"\"\n\n# Reading csv data from file - must be in same directory\ndef load_data(csv_file,nrows=None):\n \n return pd.read_csv(csv_file,nrows=nrows)\n\n#converts a string that is camelCase into snake_case\n#https://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-snake-case\ndef camel_case(column_name):\n s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', column_name)\n return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()\n\n#Give data with specific column\ndef histogram(data_frame):\n sns.distplot(data_frame)\n plt.show()\n\n#Given specific column or row, returns statistical summary\ndef summary(data_frame):\n return data_frame.describe()\n\n#Creating a correlation heat map from data set where var_name is the\n#variable which has the most correlation\ndef cor_heat(data_frame,var_name):\n corrmat = data_frame.corr()\n k = 12\n cols = corrmat.nlargest(k, var_name)[var_name].index\n cm = np.corrcoef(data_frame[cols].values.T)\n sns.set(font_scale=1.25)\n hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f', annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.values)\n plt.show()\n\n#Scatter plots of desired variables in list\ndef plotCorr(dataFrame, list):\n sns.set()\n sns.pairplot(dataFrame[list], size = 2.5)\n return plt.show()\n\n#Shows data is missing, we should delete the corresponding variable and pretend it never existed - threshold as parameter\ndef miss_data(data_frame):\n total = data_frame.isnull().sum().sort_values(ascending=False)\n percent = (data_frame.isnull().sum()/data_frame.isnull().count()).sort_values(ascending=False)\n missing_data = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])\n #return missing_data.head(20)\n return missing_data\n\n\n#Dealing with missing data\ndef clean_miss(data_frame):\n missing_data = miss_data(data_frame)\n data_frame = data_frame.drop((missing_data[missing_data['Total'] > 1]).index,1)\n data_frame.isnull().sum().max() #just checking that there's no missing data missing...\n return data_frame\n\n#Univariate analysis - scaling data, prints out low range and high range\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,np.newaxis]);\n low_range = data_scaled[data_scaled[:,0].argsort()][:10]\n high_range= data_scaled[data_scaled[:,0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n#Bivariate analysis\ndef bivariate(data_frame, var_1,var_2):\n varx = var_1\n vary = var_2\n data = pd.concat([data_frame[varx], data_frame[vary]], axis=1)\n data.plot.scatter(x=varx, y=vary, ylim=(0,100));\n plt.show()\n\n#histogram and normal probability plot\ndef norm_plot(data_frame,var_name):\n sns.distplot(data_frame[var_name], fit=norm);\n fig = plt.figure()\n res = stats.probplot((data_frame)[var_name], plot=plt)\n plt.show()\n\n#Fill in empty values\ndef fill_empty(data_frame,var, new_var):\n return data_frame[var].fillna(new_var)\n\n#Discretize continuous variables\ndef descretize(data_frame, var, num):\n return pd.cut(data_frame[var],num,retbins=True)\n\n#Creating dummy variables from categorical variables\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n#Creating dictionary with no repeated column items\ndef column_dic(data_frame):\n dict = {line[:1]:line[1:].split()[0] for line in data_frame}\n print (dict)\n\n\n\n#Logistic regression = iv, independent variable, var_list - dependent variables\ndef logReg(data_frame, IV, var_list):\n #organizing variable list to independent and dependent variables\n #taking care of hyphen if first word contains it\n if '-' in var_list[0]:\n formula = IV + \"~\"+'Q(\"'+var_list[0]+'\")'\n else:\n formula = IV + \"~\"+var_list[0]\n #taking care of the rest of the potential hyphens\n for i in range(1, len(var_list)):\n if '-' in var_list[i]:\n formula = formula + \"+\"+'Q(\"'+var_list[i]+'\")'\n else:\n formula = formula + \"+\"+ var_list[i]\n y, X = dmatrices(formula,data_frame, return_type=\"dataframe\")\n y = np.ravel(y)\n model = LogisticRegression()\n model = model.fit(X, y)\n print (pd.DataFrame(list(zip(X.columns, np.transpose(model.coef_)))))\n return model.score(X,y)\n\n#Nearest Neighbors -\ndef knearest(data_frame,train, test):\n #data_frame = data_frame.reshape(-1,1)\n X = data_frame[train].reshape(-1,1)\n Y = data_frame[test].reshape(-1,1)\n X_train = X[:100]\n Y_train = Y[:100]\n X_validate = X[100:]\n Y_validate = Y[100:]\n neighbor = KNeighborsClassifier(n_neighbors = 2, weights ='uniform')\n neighbor.fit(X_train, Y_train)\n predicted = neighbor.predict(X_validate)\n print (predicted)\n\ndef merging_data(dataframe_1,dataframe_2):\n return pd.merge(dataframe_1,dataframe_2)\n\ndef merging_data2(dataframe_1,dataframe_2):\n dataframe_1['fully_funded'] = 1\n return dataframe_1\n\ndef get_combos(param_grid_dict):\n\n all = sorted(param_grid_dict)\n all_combos=[]\n combinations = it.product(*(param_grid_dict[Name] for Name in all))\n for i in combinations:\n lil_combo = {}\n for iter,key in enumerate(all):\n lil_combo[key] = i[iter]\n all_combos.append(lil_combo)\n\n return (all_combos)\n#change items into binary columns\n\ndef to_binary(df,array_col):\n for i in array_col:\n print(i)\n #df[i] = df[i].apply(lambda x: 1 if x == 't' else (0 if x =='f' else np.nan))\n df[i] = df[i].apply(lambda x: 1 if x == 't' else 0)\n return df\n\n\n#analyzing results from classifiers\ndef get_metrics(y_pred, val_Y):\n metric_results ={}\n #predicting the majority class\n ones = np.sum(val_Y)['SeriousDlqin2yrs']/float(len(val_Y))\n zeros = 1-ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y,np.ones[len(val_Y)])\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y,np.zeros(len(val_Y)))\n\n #loss = f1_score(y_pred,val_Y)\n perf_metrics = [.01,.02,.05,.10,.20,.30,.50]\n for i in perf_metrics:\n #pdb.set_trace()\n print(\"Recall AT \\n\")\n print(recall_at_k(val_Y, y_pred, i))\n #metric_results[\"precision at\" + str([i])] = precision_score(val_Y, y_pred > 1 - i)\n metric_results[\"precision at\" + str([i])] = precision_at_k(val_Y, y_pred, i)\n metric_results[\"recall at\" + str([i])] = recall_score(val_Y, y_pred> 1 - i)\n metric_results[\"F1 at\" + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n \n metric_results[\"ROC\"] = roc_auc_score(val_Y, y_pred)\n prec,rec,thresh = precision_recall_curve(val_Y, y_pred)\n metric_results[\"PREC\"] = prec.tolist()\n metric_results[\"REC\"] = rec.tolist()\n metric_results[\"THRESH\"] = thresh.tolist()\n #out.write(metric_results)\n return (metric_results)\n\ndef recall_at_k(y_true, y_scores, k):\n #y_scores_sorted, y_true_sorted = zip(*sorted(zip(y_scores, y_true), reverse=True))\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n #precision, _, _, _ = metrics.precision_recall_fscore_support(y_true, preds_at_k)\n #precision = precision[1] # only interested in precision for label 1\n recall = recall_score(y_true_sorted, preds_at_k)\n return recall\n\ndef joint_sort_descending(l1, l2):\n # l1 and l2 have to be numpy arrays\n idx = np.argsort(l1)[::-1]\n return l1[idx], l2[idx]\n\ndef generate_binary_at_k(y_scores, k):\n cutoff_index = int(len(y_scores) * (k / 100.0))\n predictions_binary = [1 if x < cutoff_index else 0 for x in range(len(y_scores))]\n return predictions_binary\n\n\ndef precision_at_k(y_true, y_scores, k):\n #y_scores_sorted, y_true_sorted = zip(*sorted(zip(y_scores, y_true), reverse=True))\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n #precision, _, _, _ = metrics.precision_recall_fscore_support(y_true, preds_at_k)\n #precision = precision[1] # only interested in precision for label 1\n precision = precision_score(y_true_sorted, preds_at_k)\n return precision\n\n#plotting precisison and recal graphs, input one column for y_pred in class_comp method\ndef plot_precision_recall(val_Y,y_pred,model_name,output_type):\n #pdb.set_trace()\n prec,rec,thresh = precision_recall_curve(val_Y, y_pred)\n prec = prec[:-1]\n recall_curve = rec[:-1]\n pct_above_per_thresh = []\n number_scored = len(y_pred)\n for value in thresh:\n num_above_thresh = len(y_pred[y_pred>=value])\n pct_above_thresh = num_above_thresh / float(len(y_pred))\n\n if pct_above_thresh <= 1:\n pct_above_per_thresh.append(pct_above_thresh)\n else:\n raise Exception\n\n \n pct_above_per_thresh = np.array(pct_above_per_thresh)\n plt.clf()\n fig, ax1 = plt.subplots()\n ax1.plot(pct_above_per_thresh, prec, 'b')\n print(\"PLOTTING STUFF\")\n print(pct_above_per_thresh)\n print(prec[:-1])\n ax1.set_xlabel('percent of population')\n ax1.set_ylabel('precision', color='b')\n ax2 = ax1.twinx()\n ax2.plot(pct_above_per_thresh, recall_curve, 'r')\n ax2.set_ylabel('recall', color='r')\n ax1.set_ylim([0,1])\n ax2.set_xlim([0,1])\n \n name = model_name\n plt.title(name)\n #pdb.set_trace()\n if (output_type == 'save'):\n plt.savefig(name)\n elif (output_type == 'show'):\n plt.show()\n pdb.set_trace()\n else:\n \n plt.show()\n pdb.set_trace()\n\n\n\ndef temp_val(data_frame,target,features):\n \n models_params = {\n RandomForestClassifier:{'n_estimators':[100] , 'criterion':['gini','entropy'], 'max_features':['sqrt','log2'] , 'max_depth':[5,10],'n_jobs':[4], 'min_samples_leaf':[10,50,100]},\n LogisticRegression: {'C':[10**-1,10**-2,10**-3],'penalty':['l1','l2']},\n KNeighborsClassifier:{'n_neighbors':[5,10,25,100], 'p':[1,2,3],'n_jobs':[2]},\n DecisionTreeClassifier:{'max_depth': [5,10,15],'min_samples_leaf':[2,5,10]},\n GradientBoostingClassifier:{'learning_rate':[.1,.01],'n_estimators':[100] ,'max_features':['sqrt','log2'] , 'max_depth':[1,2,3]},\n BaggingClassifier:{'max_samples':[.1,.25,.65], 'n_jobs':[4]},\n #SVC:{'kernel':['linear','rbf'],'gamma':[10,1,.1,.01], 'C':[10,1,.1,.01], 'probability':[True]}\n }\n # start time of our data\n #start_time = '2002-09-13'\n start_time_date = data_frame['date_posted'].min()\n\n #last date of data including labels and outcomes that we have\n #end_time = '2014-05-12'\n end_time_date = data_frame['date_posted'].max()\n \n #how far out do we want to predict (let's say in months for now)\n prediction_windows = [1]\n\n #how often is this prediction being made? every day? every month? once a year?\n update_window = 12\n\n from datetime import date, datetime, timedelta\n from dateutil.relativedelta import relativedelta\n\n #start_time_date = datetime.strptime(start_time, '%Y-%m-%d')\n #end_time_date = datetime.strptime(end_time, '%Y-%m-%d')\n\n for prediction_window in prediction_windows:\n print(start_time_date,end_time_date)\n test_end_time = end_time_date\n while (test_end_time >= start_time_date + 2 * relativedelta(months=+prediction_window)):\n test_start_time = test_end_time - relativedelta(months=+prediction_window)\n train_end_time = test_start_time - relativedelta(days=+1) # minus 1 day\n train_start_time = train_end_time - relativedelta(months=+prediction_window)\n while (train_start_time >= start_time_date ):\n #pdb.set_trace()\n print (train_start_time,train_end_time,test_start_time,test_end_time, prediction_window)\n train_start_time -= relativedelta(months=+prediction_window)\n # call function to get data\n train_set, test_set = extract_train_test_sets(train_start_time, train_end_time, test_start_time, test_end_time,data_frame)\n #pdb.set_trace()\n class_comp(train_set,test_set,target,features,models_params)\n # fit on train data\n # predict on test data\n test_end_time -= relativedelta(months=+update_window)\n\ndef kfold_eval(df, target, features):\n models_params = {\n RandomForestClassifier:{'n_estimators':[100] , 'criterion':['gini','entropy'], 'max_features':['sqrt','log2'] , 'max_depth':[5,10],'n_jobs':[4], 'min_samples_leaf':[10,50,100]},\n LogisticRegression: {'C':[10**-1,10**-2,10**-3],'penalty':['l1','l2']},\n KNeighborsClassifier:{'n_neighbors':[5,10,25,100], 'p':[1,2,3],'n_jobs':[2]},\n DecisionTreeClassifier:{'max_depth': [5,10,15],'min_samples_leaf':[2,5,10]},\n GradientBoostingClassifier:{'learning_rate':[.1,.01],'n_estimators':[100] ,'max_features':['sqrt','log2'] , 'max_depth':[1,2,3]},\n BaggingClassifier:{'max_samples':[.1,.25,.65], 'n_jobs':[4]},\n #SVC:{'kernel':['linear','rbf'],'gamma':[10,1,.1,.01], 'C':[10,1,.1,.01], 'probability':[True]}\n }\n X = df[features]\n #print(X)\n y = df[target]\n print(y)\n \n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\n \"\"\"\n kf = KFold(n_splits=2)\n kf.get_n_splits(X)\n #print(kf)\n KFold(n_splits=2,random_state=None,shuffle=False)\n for train_index, test_index in kf.split(X):\n print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n \"\"\"\n #knn = KNeighborsClassifier(n_neighbors=5, metric='minkowski',p=4)\n \"\"\"rf = RandomForestClassifier(n_estimators=100,criterion='gini',max_features='sqrt',max_depth=5)\n rf.fit(X_train, y_train)\n y_score = rf.predict_proba(X_test)\n #y_score = rf.decision_function(X_test)\n y_pred = rf.predict(X_test)\n print(roc_auc_score(y_test,y_score[:,0]))\n metrics_1 ={}\"\"\"\n class_comp(X_train, X_test, y_train, y_test,target,features,models_params)\n #print (y_pred.shape)\n #print (y_test.shape)\n \n #return\n #for i in range(len(y_test)): print(y_pred)\n print(accuracy_score(y_test,y_pred)) #print (set(y_pred))\n #print (metrics_1)\n#Splitting the data for training and testing sets\ndef extract_train_test_sets(train_start_time, train_end_time, test_start_time, test_end_time, df):\n train_set = df[(df['date_posted'] > train_start_time) & (df['date_posted']<train_end_time)]\n test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted']<test_end_time)]\n return train_set, test_set\n\n\ndef class_comp(X_train, X_test, y_train,y_test,target,features,models_params):\n out = open(\"out.txt\",\"a\")\n \"\"\"X_train = train_set[features] #X\n y_train = train_set[target] #y\n \n #validation\n X_test = test_set[features] #val_x\n y_test = test_set[target] #val_y\"\"\"\n metrics = {}\n for m, m_param in models_params.items():\n listofparam = get_combos(m_param)\n print(\"start training for {0}\".format(m))\n out.write(\"start training for {0}\\n\".format(m))\n for params in listofparam:\n print (params)\n out.write(json.dumps(params))\n model = m(**params)\n model.fit(X_train,y_train)\n #y_pred vector of prob estimates\n #val_y are true values\n y_pred = model.predict_proba(X_test)\n metrics[m] = get_metrics(y_pred[:,1],y_test)\n print(\"this is valy\")\n print (y_test)\n print(\"this is y_pred\")\n print (y_pred)\n plot_precision_recall(y_test, y_pred[:,1],model,'show')\n out.write(\"----------------------------\\n\")\n out.write(\"Using %s classifier \\n\" % models_params)\n out.write(json.dumps(metrics[m]))\n\n\n\n\n\n", "import numpy as np\nimport pdb\nimport itertools as it\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as dates\nfrom sklearn.metrics import f1_score\nimport pandas as pd\nimport os\nimport sys\nimport datetime\nimport glob\nimport re\nimport graphviz\nimport seaborn as sns\nimport numpy as np\nfrom scipy.stats import norm\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import precision_score\nfrom sklearn.metrics import recall_score\nfrom sklearn.metrics import precision_recall_curve\nfrom sklearn.metrics import f1_score\nfrom sklearn.preprocessing import StandardScaler\nfrom scipy import stats\nimport warnings\nwarnings.filterwarnings('ignore')\nimport statsmodels.api as sm\nfrom patsy import dmatrices\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn import tree\nfrom sklearn.svm import SVC\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier, BaggingClassifier, GradientBoostingClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn import metrics\nfrom sklearn.cross_validation import cross_val_score\nimport json\nfrom sklearn.model_selection import KFold\n<docstring token>\n\n\ndef load_data(csv_file, nrows=None):\n return pd.read_csv(csv_file, nrows=nrows)\n\n\ndef camel_case(column_name):\n s1 = re.sub('(.)([A-Z][a-z]+)', '\\\\1_\\\\2', column_name)\n return re.sub('([a-z0-9])([A-Z])', '\\\\1_\\\\2', s1).lower()\n\n\ndef histogram(data_frame):\n sns.distplot(data_frame)\n plt.show()\n\n\ndef summary(data_frame):\n return data_frame.describe()\n\n\ndef cor_heat(data_frame, var_name):\n corrmat = data_frame.corr()\n k = 12\n cols = corrmat.nlargest(k, var_name)[var_name].index\n cm = np.corrcoef(data_frame[cols].values.T)\n sns.set(font_scale=1.25)\n hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f',\n annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.\n values)\n plt.show()\n\n\ndef plotCorr(dataFrame, list):\n sns.set()\n sns.pairplot(dataFrame[list], size=2.5)\n return plt.show()\n\n\ndef miss_data(data_frame):\n total = data_frame.isnull().sum().sort_values(ascending=False)\n percent = (data_frame.isnull().sum() / data_frame.isnull().count()\n ).sort_values(ascending=False)\n missing_data = pd.concat([total, percent], axis=1, keys=['Total',\n 'Percent'])\n return missing_data\n\n\ndef clean_miss(data_frame):\n missing_data = miss_data(data_frame)\n data_frame = data_frame.drop(missing_data[missing_data['Total'] > 1].\n index, 1)\n data_frame.isnull().sum().max()\n return data_frame\n\n\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,\n np.newaxis])\n low_range = data_scaled[data_scaled[:, 0].argsort()][:10]\n high_range = data_scaled[data_scaled[:, 0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n\ndef bivariate(data_frame, var_1, var_2):\n varx = var_1\n vary = var_2\n data = pd.concat([data_frame[varx], data_frame[vary]], axis=1)\n data.plot.scatter(x=varx, y=vary, ylim=(0, 100))\n plt.show()\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\ndef fill_empty(data_frame, var, new_var):\n return data_frame[var].fillna(new_var)\n\n\ndef descretize(data_frame, var, num):\n return pd.cut(data_frame[var], num, retbins=True)\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\ndef column_dic(data_frame):\n dict = {line[:1]: line[1:].split()[0] for line in data_frame}\n print(dict)\n\n\ndef logReg(data_frame, IV, var_list):\n if '-' in var_list[0]:\n formula = IV + '~' + 'Q(\"' + var_list[0] + '\")'\n else:\n formula = IV + '~' + var_list[0]\n for i in range(1, len(var_list)):\n if '-' in var_list[i]:\n formula = formula + '+' + 'Q(\"' + var_list[i] + '\")'\n else:\n formula = formula + '+' + var_list[i]\n y, X = dmatrices(formula, data_frame, return_type='dataframe')\n y = np.ravel(y)\n model = LogisticRegression()\n model = model.fit(X, y)\n print(pd.DataFrame(list(zip(X.columns, np.transpose(model.coef_)))))\n return model.score(X, y)\n\n\ndef knearest(data_frame, train, test):\n X = data_frame[train].reshape(-1, 1)\n Y = data_frame[test].reshape(-1, 1)\n X_train = X[:100]\n Y_train = Y[:100]\n X_validate = X[100:]\n Y_validate = Y[100:]\n neighbor = KNeighborsClassifier(n_neighbors=2, weights='uniform')\n neighbor.fit(X_train, Y_train)\n predicted = neighbor.predict(X_validate)\n print(predicted)\n\n\ndef merging_data(dataframe_1, dataframe_2):\n return pd.merge(dataframe_1, dataframe_2)\n\n\ndef merging_data2(dataframe_1, dataframe_2):\n dataframe_1['fully_funded'] = 1\n return dataframe_1\n\n\ndef get_combos(param_grid_dict):\n all = sorted(param_grid_dict)\n all_combos = []\n combinations = it.product(*(param_grid_dict[Name] for Name in all))\n for i in combinations:\n lil_combo = {}\n for iter, key in enumerate(all):\n lil_combo[key] = i[iter]\n all_combos.append(lil_combo)\n return all_combos\n\n\ndef to_binary(df, array_col):\n for i in array_col:\n print(i)\n df[i] = df[i].apply(lambda x: 1 if x == 't' else 0)\n return df\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\ndef recall_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n recall = recall_score(y_true_sorted, preds_at_k)\n return recall\n\n\ndef joint_sort_descending(l1, l2):\n idx = np.argsort(l1)[::-1]\n return l1[idx], l2[idx]\n\n\ndef generate_binary_at_k(y_scores, k):\n cutoff_index = int(len(y_scores) * (k / 100.0))\n predictions_binary = [(1 if x < cutoff_index else 0) for x in range(len\n (y_scores))]\n return predictions_binary\n\n\ndef precision_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n precision = precision_score(y_true_sorted, preds_at_k)\n return precision\n\n\ndef plot_precision_recall(val_Y, y_pred, model_name, output_type):\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n prec = prec[:-1]\n recall_curve = rec[:-1]\n pct_above_per_thresh = []\n number_scored = len(y_pred)\n for value in thresh:\n num_above_thresh = len(y_pred[y_pred >= value])\n pct_above_thresh = num_above_thresh / float(len(y_pred))\n if pct_above_thresh <= 1:\n pct_above_per_thresh.append(pct_above_thresh)\n else:\n raise Exception\n pct_above_per_thresh = np.array(pct_above_per_thresh)\n plt.clf()\n fig, ax1 = plt.subplots()\n ax1.plot(pct_above_per_thresh, prec, 'b')\n print('PLOTTING STUFF')\n print(pct_above_per_thresh)\n print(prec[:-1])\n ax1.set_xlabel('percent of population')\n ax1.set_ylabel('precision', color='b')\n ax2 = ax1.twinx()\n ax2.plot(pct_above_per_thresh, recall_curve, 'r')\n ax2.set_ylabel('recall', color='r')\n ax1.set_ylim([0, 1])\n ax2.set_xlim([0, 1])\n name = model_name\n plt.title(name)\n if output_type == 'save':\n plt.savefig(name)\n elif output_type == 'show':\n plt.show()\n pdb.set_trace()\n else:\n plt.show()\n pdb.set_trace()\n\n\ndef temp_val(data_frame, target, features):\n models_params = {RandomForestClassifier: {'n_estimators': [100],\n 'criterion': ['gini', 'entropy'], 'max_features': ['sqrt', 'log2'],\n 'max_depth': [5, 10], 'n_jobs': [4], 'min_samples_leaf': [10, 50, \n 100]}, LogisticRegression: {'C': [10 ** -1, 10 ** -2, 10 ** -3],\n 'penalty': ['l1', 'l2']}, KNeighborsClassifier: {'n_neighbors': [5,\n 10, 25, 100], 'p': [1, 2, 3], 'n_jobs': [2]},\n DecisionTreeClassifier: {'max_depth': [5, 10, 15],\n 'min_samples_leaf': [2, 5, 10]}, GradientBoostingClassifier: {\n 'learning_rate': [0.1, 0.01], 'n_estimators': [100], 'max_features':\n ['sqrt', 'log2'], 'max_depth': [1, 2, 3]}, BaggingClassifier: {\n 'max_samples': [0.1, 0.25, 0.65], 'n_jobs': [4]}}\n start_time_date = data_frame['date_posted'].min()\n end_time_date = data_frame['date_posted'].max()\n prediction_windows = [1]\n update_window = 12\n from datetime import date, datetime, timedelta\n from dateutil.relativedelta import relativedelta\n for prediction_window in prediction_windows:\n print(start_time_date, end_time_date)\n test_end_time = end_time_date\n while test_end_time >= start_time_date + 2 * relativedelta(months=+\n prediction_window):\n test_start_time = test_end_time - relativedelta(months=+\n prediction_window)\n train_end_time = test_start_time - relativedelta(days=+1)\n train_start_time = train_end_time - relativedelta(months=+\n prediction_window)\n while train_start_time >= start_time_date:\n print(train_start_time, train_end_time, test_start_time,\n test_end_time, prediction_window)\n train_start_time -= relativedelta(months=+prediction_window)\n train_set, test_set = extract_train_test_sets(train_start_time,\n train_end_time, test_start_time, test_end_time, data_frame)\n class_comp(train_set, test_set, target, features, models_params\n )\n test_end_time -= relativedelta(months=+update_window)\n\n\ndef kfold_eval(df, target, features):\n models_params = {RandomForestClassifier: {'n_estimators': [100],\n 'criterion': ['gini', 'entropy'], 'max_features': ['sqrt', 'log2'],\n 'max_depth': [5, 10], 'n_jobs': [4], 'min_samples_leaf': [10, 50, \n 100]}, LogisticRegression: {'C': [10 ** -1, 10 ** -2, 10 ** -3],\n 'penalty': ['l1', 'l2']}, KNeighborsClassifier: {'n_neighbors': [5,\n 10, 25, 100], 'p': [1, 2, 3], 'n_jobs': [2]},\n DecisionTreeClassifier: {'max_depth': [5, 10, 15],\n 'min_samples_leaf': [2, 5, 10]}, GradientBoostingClassifier: {\n 'learning_rate': [0.1, 0.01], 'n_estimators': [100], 'max_features':\n ['sqrt', 'log2'], 'max_depth': [1, 2, 3]}, BaggingClassifier: {\n 'max_samples': [0.1, 0.25, 0.65], 'n_jobs': [4]}}\n X = df[features]\n y = df[target]\n print(y)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,\n random_state=0)\n \"\"\"\n kf = KFold(n_splits=2)\n kf.get_n_splits(X)\n #print(kf)\n KFold(n_splits=2,random_state=None,shuffle=False)\n for train_index, test_index in kf.split(X):\n print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n \"\"\"\n \"\"\"rf = RandomForestClassifier(n_estimators=100,criterion='gini',max_features='sqrt',max_depth=5)\n rf.fit(X_train, y_train)\n y_score = rf.predict_proba(X_test)\n #y_score = rf.decision_function(X_test)\n y_pred = rf.predict(X_test)\n print(roc_auc_score(y_test,y_score[:,0]))\n metrics_1 ={}\"\"\"\n class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params)\n print(accuracy_score(y_test, y_pred))\n\n\ndef extract_train_test_sets(train_start_time, train_end_time,\n test_start_time, test_end_time, df):\n train_set = df[(df['date_posted'] > train_start_time) & (df[\n 'date_posted'] < train_end_time)]\n test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted'\n ] < test_end_time)]\n return train_set, test_set\n\n\ndef class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params):\n out = open('out.txt', 'a')\n \"\"\"X_train = train_set[features] #X\n y_train = train_set[target] #y\n \n #validation\n X_test = test_set[features] #val_x\n y_test = test_set[target] #val_y\"\"\"\n metrics = {}\n for m, m_param in models_params.items():\n listofparam = get_combos(m_param)\n print('start training for {0}'.format(m))\n out.write('start training for {0}\\n'.format(m))\n for params in listofparam:\n print(params)\n out.write(json.dumps(params))\n model = m(**params)\n model.fit(X_train, y_train)\n y_pred = model.predict_proba(X_test)\n metrics[m] = get_metrics(y_pred[:, 1], y_test)\n print('this is valy')\n print(y_test)\n print('this is y_pred')\n print(y_pred)\n plot_precision_recall(y_test, y_pred[:, 1], model, 'show')\n out.write('----------------------------\\n')\n out.write('Using %s classifier \\n' % models_params)\n out.write(json.dumps(metrics[m]))\n", "<import token>\nwarnings.filterwarnings('ignore')\n<import token>\n<docstring token>\n\n\ndef load_data(csv_file, nrows=None):\n return pd.read_csv(csv_file, nrows=nrows)\n\n\ndef camel_case(column_name):\n s1 = re.sub('(.)([A-Z][a-z]+)', '\\\\1_\\\\2', column_name)\n return re.sub('([a-z0-9])([A-Z])', '\\\\1_\\\\2', s1).lower()\n\n\ndef histogram(data_frame):\n sns.distplot(data_frame)\n plt.show()\n\n\ndef summary(data_frame):\n return data_frame.describe()\n\n\ndef cor_heat(data_frame, var_name):\n corrmat = data_frame.corr()\n k = 12\n cols = corrmat.nlargest(k, var_name)[var_name].index\n cm = np.corrcoef(data_frame[cols].values.T)\n sns.set(font_scale=1.25)\n hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f',\n annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.\n values)\n plt.show()\n\n\ndef plotCorr(dataFrame, list):\n sns.set()\n sns.pairplot(dataFrame[list], size=2.5)\n return plt.show()\n\n\ndef miss_data(data_frame):\n total = data_frame.isnull().sum().sort_values(ascending=False)\n percent = (data_frame.isnull().sum() / data_frame.isnull().count()\n ).sort_values(ascending=False)\n missing_data = pd.concat([total, percent], axis=1, keys=['Total',\n 'Percent'])\n return missing_data\n\n\ndef clean_miss(data_frame):\n missing_data = miss_data(data_frame)\n data_frame = data_frame.drop(missing_data[missing_data['Total'] > 1].\n index, 1)\n data_frame.isnull().sum().max()\n return data_frame\n\n\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,\n np.newaxis])\n low_range = data_scaled[data_scaled[:, 0].argsort()][:10]\n high_range = data_scaled[data_scaled[:, 0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n\ndef bivariate(data_frame, var_1, var_2):\n varx = var_1\n vary = var_2\n data = pd.concat([data_frame[varx], data_frame[vary]], axis=1)\n data.plot.scatter(x=varx, y=vary, ylim=(0, 100))\n plt.show()\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\ndef fill_empty(data_frame, var, new_var):\n return data_frame[var].fillna(new_var)\n\n\ndef descretize(data_frame, var, num):\n return pd.cut(data_frame[var], num, retbins=True)\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\ndef column_dic(data_frame):\n dict = {line[:1]: line[1:].split()[0] for line in data_frame}\n print(dict)\n\n\ndef logReg(data_frame, IV, var_list):\n if '-' in var_list[0]:\n formula = IV + '~' + 'Q(\"' + var_list[0] + '\")'\n else:\n formula = IV + '~' + var_list[0]\n for i in range(1, len(var_list)):\n if '-' in var_list[i]:\n formula = formula + '+' + 'Q(\"' + var_list[i] + '\")'\n else:\n formula = formula + '+' + var_list[i]\n y, X = dmatrices(formula, data_frame, return_type='dataframe')\n y = np.ravel(y)\n model = LogisticRegression()\n model = model.fit(X, y)\n print(pd.DataFrame(list(zip(X.columns, np.transpose(model.coef_)))))\n return model.score(X, y)\n\n\ndef knearest(data_frame, train, test):\n X = data_frame[train].reshape(-1, 1)\n Y = data_frame[test].reshape(-1, 1)\n X_train = X[:100]\n Y_train = Y[:100]\n X_validate = X[100:]\n Y_validate = Y[100:]\n neighbor = KNeighborsClassifier(n_neighbors=2, weights='uniform')\n neighbor.fit(X_train, Y_train)\n predicted = neighbor.predict(X_validate)\n print(predicted)\n\n\ndef merging_data(dataframe_1, dataframe_2):\n return pd.merge(dataframe_1, dataframe_2)\n\n\ndef merging_data2(dataframe_1, dataframe_2):\n dataframe_1['fully_funded'] = 1\n return dataframe_1\n\n\ndef get_combos(param_grid_dict):\n all = sorted(param_grid_dict)\n all_combos = []\n combinations = it.product(*(param_grid_dict[Name] for Name in all))\n for i in combinations:\n lil_combo = {}\n for iter, key in enumerate(all):\n lil_combo[key] = i[iter]\n all_combos.append(lil_combo)\n return all_combos\n\n\ndef to_binary(df, array_col):\n for i in array_col:\n print(i)\n df[i] = df[i].apply(lambda x: 1 if x == 't' else 0)\n return df\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\ndef recall_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n recall = recall_score(y_true_sorted, preds_at_k)\n return recall\n\n\ndef joint_sort_descending(l1, l2):\n idx = np.argsort(l1)[::-1]\n return l1[idx], l2[idx]\n\n\ndef generate_binary_at_k(y_scores, k):\n cutoff_index = int(len(y_scores) * (k / 100.0))\n predictions_binary = [(1 if x < cutoff_index else 0) for x in range(len\n (y_scores))]\n return predictions_binary\n\n\ndef precision_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n precision = precision_score(y_true_sorted, preds_at_k)\n return precision\n\n\ndef plot_precision_recall(val_Y, y_pred, model_name, output_type):\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n prec = prec[:-1]\n recall_curve = rec[:-1]\n pct_above_per_thresh = []\n number_scored = len(y_pred)\n for value in thresh:\n num_above_thresh = len(y_pred[y_pred >= value])\n pct_above_thresh = num_above_thresh / float(len(y_pred))\n if pct_above_thresh <= 1:\n pct_above_per_thresh.append(pct_above_thresh)\n else:\n raise Exception\n pct_above_per_thresh = np.array(pct_above_per_thresh)\n plt.clf()\n fig, ax1 = plt.subplots()\n ax1.plot(pct_above_per_thresh, prec, 'b')\n print('PLOTTING STUFF')\n print(pct_above_per_thresh)\n print(prec[:-1])\n ax1.set_xlabel('percent of population')\n ax1.set_ylabel('precision', color='b')\n ax2 = ax1.twinx()\n ax2.plot(pct_above_per_thresh, recall_curve, 'r')\n ax2.set_ylabel('recall', color='r')\n ax1.set_ylim([0, 1])\n ax2.set_xlim([0, 1])\n name = model_name\n plt.title(name)\n if output_type == 'save':\n plt.savefig(name)\n elif output_type == 'show':\n plt.show()\n pdb.set_trace()\n else:\n plt.show()\n pdb.set_trace()\n\n\ndef temp_val(data_frame, target, features):\n models_params = {RandomForestClassifier: {'n_estimators': [100],\n 'criterion': ['gini', 'entropy'], 'max_features': ['sqrt', 'log2'],\n 'max_depth': [5, 10], 'n_jobs': [4], 'min_samples_leaf': [10, 50, \n 100]}, LogisticRegression: {'C': [10 ** -1, 10 ** -2, 10 ** -3],\n 'penalty': ['l1', 'l2']}, KNeighborsClassifier: {'n_neighbors': [5,\n 10, 25, 100], 'p': [1, 2, 3], 'n_jobs': [2]},\n DecisionTreeClassifier: {'max_depth': [5, 10, 15],\n 'min_samples_leaf': [2, 5, 10]}, GradientBoostingClassifier: {\n 'learning_rate': [0.1, 0.01], 'n_estimators': [100], 'max_features':\n ['sqrt', 'log2'], 'max_depth': [1, 2, 3]}, BaggingClassifier: {\n 'max_samples': [0.1, 0.25, 0.65], 'n_jobs': [4]}}\n start_time_date = data_frame['date_posted'].min()\n end_time_date = data_frame['date_posted'].max()\n prediction_windows = [1]\n update_window = 12\n from datetime import date, datetime, timedelta\n from dateutil.relativedelta import relativedelta\n for prediction_window in prediction_windows:\n print(start_time_date, end_time_date)\n test_end_time = end_time_date\n while test_end_time >= start_time_date + 2 * relativedelta(months=+\n prediction_window):\n test_start_time = test_end_time - relativedelta(months=+\n prediction_window)\n train_end_time = test_start_time - relativedelta(days=+1)\n train_start_time = train_end_time - relativedelta(months=+\n prediction_window)\n while train_start_time >= start_time_date:\n print(train_start_time, train_end_time, test_start_time,\n test_end_time, prediction_window)\n train_start_time -= relativedelta(months=+prediction_window)\n train_set, test_set = extract_train_test_sets(train_start_time,\n train_end_time, test_start_time, test_end_time, data_frame)\n class_comp(train_set, test_set, target, features, models_params\n )\n test_end_time -= relativedelta(months=+update_window)\n\n\ndef kfold_eval(df, target, features):\n models_params = {RandomForestClassifier: {'n_estimators': [100],\n 'criterion': ['gini', 'entropy'], 'max_features': ['sqrt', 'log2'],\n 'max_depth': [5, 10], 'n_jobs': [4], 'min_samples_leaf': [10, 50, \n 100]}, LogisticRegression: {'C': [10 ** -1, 10 ** -2, 10 ** -3],\n 'penalty': ['l1', 'l2']}, KNeighborsClassifier: {'n_neighbors': [5,\n 10, 25, 100], 'p': [1, 2, 3], 'n_jobs': [2]},\n DecisionTreeClassifier: {'max_depth': [5, 10, 15],\n 'min_samples_leaf': [2, 5, 10]}, GradientBoostingClassifier: {\n 'learning_rate': [0.1, 0.01], 'n_estimators': [100], 'max_features':\n ['sqrt', 'log2'], 'max_depth': [1, 2, 3]}, BaggingClassifier: {\n 'max_samples': [0.1, 0.25, 0.65], 'n_jobs': [4]}}\n X = df[features]\n y = df[target]\n print(y)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,\n random_state=0)\n \"\"\"\n kf = KFold(n_splits=2)\n kf.get_n_splits(X)\n #print(kf)\n KFold(n_splits=2,random_state=None,shuffle=False)\n for train_index, test_index in kf.split(X):\n print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n \"\"\"\n \"\"\"rf = RandomForestClassifier(n_estimators=100,criterion='gini',max_features='sqrt',max_depth=5)\n rf.fit(X_train, y_train)\n y_score = rf.predict_proba(X_test)\n #y_score = rf.decision_function(X_test)\n y_pred = rf.predict(X_test)\n print(roc_auc_score(y_test,y_score[:,0]))\n metrics_1 ={}\"\"\"\n class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params)\n print(accuracy_score(y_test, y_pred))\n\n\ndef extract_train_test_sets(train_start_time, train_end_time,\n test_start_time, test_end_time, df):\n train_set = df[(df['date_posted'] > train_start_time) & (df[\n 'date_posted'] < train_end_time)]\n test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted'\n ] < test_end_time)]\n return train_set, test_set\n\n\ndef class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params):\n out = open('out.txt', 'a')\n \"\"\"X_train = train_set[features] #X\n y_train = train_set[target] #y\n \n #validation\n X_test = test_set[features] #val_x\n y_test = test_set[target] #val_y\"\"\"\n metrics = {}\n for m, m_param in models_params.items():\n listofparam = get_combos(m_param)\n print('start training for {0}'.format(m))\n out.write('start training for {0}\\n'.format(m))\n for params in listofparam:\n print(params)\n out.write(json.dumps(params))\n model = m(**params)\n model.fit(X_train, y_train)\n y_pred = model.predict_proba(X_test)\n metrics[m] = get_metrics(y_pred[:, 1], y_test)\n print('this is valy')\n print(y_test)\n print('this is y_pred')\n print(y_pred)\n plot_precision_recall(y_test, y_pred[:, 1], model, 'show')\n out.write('----------------------------\\n')\n out.write('Using %s classifier \\n' % models_params)\n out.write(json.dumps(metrics[m]))\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n\n\ndef load_data(csv_file, nrows=None):\n return pd.read_csv(csv_file, nrows=nrows)\n\n\ndef camel_case(column_name):\n s1 = re.sub('(.)([A-Z][a-z]+)', '\\\\1_\\\\2', column_name)\n return re.sub('([a-z0-9])([A-Z])', '\\\\1_\\\\2', s1).lower()\n\n\ndef histogram(data_frame):\n sns.distplot(data_frame)\n plt.show()\n\n\ndef summary(data_frame):\n return data_frame.describe()\n\n\ndef cor_heat(data_frame, var_name):\n corrmat = data_frame.corr()\n k = 12\n cols = corrmat.nlargest(k, var_name)[var_name].index\n cm = np.corrcoef(data_frame[cols].values.T)\n sns.set(font_scale=1.25)\n hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f',\n annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.\n values)\n plt.show()\n\n\ndef plotCorr(dataFrame, list):\n sns.set()\n sns.pairplot(dataFrame[list], size=2.5)\n return plt.show()\n\n\ndef miss_data(data_frame):\n total = data_frame.isnull().sum().sort_values(ascending=False)\n percent = (data_frame.isnull().sum() / data_frame.isnull().count()\n ).sort_values(ascending=False)\n missing_data = pd.concat([total, percent], axis=1, keys=['Total',\n 'Percent'])\n return missing_data\n\n\ndef clean_miss(data_frame):\n missing_data = miss_data(data_frame)\n data_frame = data_frame.drop(missing_data[missing_data['Total'] > 1].\n index, 1)\n data_frame.isnull().sum().max()\n return data_frame\n\n\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,\n np.newaxis])\n low_range = data_scaled[data_scaled[:, 0].argsort()][:10]\n high_range = data_scaled[data_scaled[:, 0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n\ndef bivariate(data_frame, var_1, var_2):\n varx = var_1\n vary = var_2\n data = pd.concat([data_frame[varx], data_frame[vary]], axis=1)\n data.plot.scatter(x=varx, y=vary, ylim=(0, 100))\n plt.show()\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\ndef fill_empty(data_frame, var, new_var):\n return data_frame[var].fillna(new_var)\n\n\ndef descretize(data_frame, var, num):\n return pd.cut(data_frame[var], num, retbins=True)\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\ndef column_dic(data_frame):\n dict = {line[:1]: line[1:].split()[0] for line in data_frame}\n print(dict)\n\n\ndef logReg(data_frame, IV, var_list):\n if '-' in var_list[0]:\n formula = IV + '~' + 'Q(\"' + var_list[0] + '\")'\n else:\n formula = IV + '~' + var_list[0]\n for i in range(1, len(var_list)):\n if '-' in var_list[i]:\n formula = formula + '+' + 'Q(\"' + var_list[i] + '\")'\n else:\n formula = formula + '+' + var_list[i]\n y, X = dmatrices(formula, data_frame, return_type='dataframe')\n y = np.ravel(y)\n model = LogisticRegression()\n model = model.fit(X, y)\n print(pd.DataFrame(list(zip(X.columns, np.transpose(model.coef_)))))\n return model.score(X, y)\n\n\ndef knearest(data_frame, train, test):\n X = data_frame[train].reshape(-1, 1)\n Y = data_frame[test].reshape(-1, 1)\n X_train = X[:100]\n Y_train = Y[:100]\n X_validate = X[100:]\n Y_validate = Y[100:]\n neighbor = KNeighborsClassifier(n_neighbors=2, weights='uniform')\n neighbor.fit(X_train, Y_train)\n predicted = neighbor.predict(X_validate)\n print(predicted)\n\n\ndef merging_data(dataframe_1, dataframe_2):\n return pd.merge(dataframe_1, dataframe_2)\n\n\ndef merging_data2(dataframe_1, dataframe_2):\n dataframe_1['fully_funded'] = 1\n return dataframe_1\n\n\ndef get_combos(param_grid_dict):\n all = sorted(param_grid_dict)\n all_combos = []\n combinations = it.product(*(param_grid_dict[Name] for Name in all))\n for i in combinations:\n lil_combo = {}\n for iter, key in enumerate(all):\n lil_combo[key] = i[iter]\n all_combos.append(lil_combo)\n return all_combos\n\n\ndef to_binary(df, array_col):\n for i in array_col:\n print(i)\n df[i] = df[i].apply(lambda x: 1 if x == 't' else 0)\n return df\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\ndef recall_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n recall = recall_score(y_true_sorted, preds_at_k)\n return recall\n\n\ndef joint_sort_descending(l1, l2):\n idx = np.argsort(l1)[::-1]\n return l1[idx], l2[idx]\n\n\ndef generate_binary_at_k(y_scores, k):\n cutoff_index = int(len(y_scores) * (k / 100.0))\n predictions_binary = [(1 if x < cutoff_index else 0) for x in range(len\n (y_scores))]\n return predictions_binary\n\n\ndef precision_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n precision = precision_score(y_true_sorted, preds_at_k)\n return precision\n\n\ndef plot_precision_recall(val_Y, y_pred, model_name, output_type):\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n prec = prec[:-1]\n recall_curve = rec[:-1]\n pct_above_per_thresh = []\n number_scored = len(y_pred)\n for value in thresh:\n num_above_thresh = len(y_pred[y_pred >= value])\n pct_above_thresh = num_above_thresh / float(len(y_pred))\n if pct_above_thresh <= 1:\n pct_above_per_thresh.append(pct_above_thresh)\n else:\n raise Exception\n pct_above_per_thresh = np.array(pct_above_per_thresh)\n plt.clf()\n fig, ax1 = plt.subplots()\n ax1.plot(pct_above_per_thresh, prec, 'b')\n print('PLOTTING STUFF')\n print(pct_above_per_thresh)\n print(prec[:-1])\n ax1.set_xlabel('percent of population')\n ax1.set_ylabel('precision', color='b')\n ax2 = ax1.twinx()\n ax2.plot(pct_above_per_thresh, recall_curve, 'r')\n ax2.set_ylabel('recall', color='r')\n ax1.set_ylim([0, 1])\n ax2.set_xlim([0, 1])\n name = model_name\n plt.title(name)\n if output_type == 'save':\n plt.savefig(name)\n elif output_type == 'show':\n plt.show()\n pdb.set_trace()\n else:\n plt.show()\n pdb.set_trace()\n\n\ndef temp_val(data_frame, target, features):\n models_params = {RandomForestClassifier: {'n_estimators': [100],\n 'criterion': ['gini', 'entropy'], 'max_features': ['sqrt', 'log2'],\n 'max_depth': [5, 10], 'n_jobs': [4], 'min_samples_leaf': [10, 50, \n 100]}, LogisticRegression: {'C': [10 ** -1, 10 ** -2, 10 ** -3],\n 'penalty': ['l1', 'l2']}, KNeighborsClassifier: {'n_neighbors': [5,\n 10, 25, 100], 'p': [1, 2, 3], 'n_jobs': [2]},\n DecisionTreeClassifier: {'max_depth': [5, 10, 15],\n 'min_samples_leaf': [2, 5, 10]}, GradientBoostingClassifier: {\n 'learning_rate': [0.1, 0.01], 'n_estimators': [100], 'max_features':\n ['sqrt', 'log2'], 'max_depth': [1, 2, 3]}, BaggingClassifier: {\n 'max_samples': [0.1, 0.25, 0.65], 'n_jobs': [4]}}\n start_time_date = data_frame['date_posted'].min()\n end_time_date = data_frame['date_posted'].max()\n prediction_windows = [1]\n update_window = 12\n from datetime import date, datetime, timedelta\n from dateutil.relativedelta import relativedelta\n for prediction_window in prediction_windows:\n print(start_time_date, end_time_date)\n test_end_time = end_time_date\n while test_end_time >= start_time_date + 2 * relativedelta(months=+\n prediction_window):\n test_start_time = test_end_time - relativedelta(months=+\n prediction_window)\n train_end_time = test_start_time - relativedelta(days=+1)\n train_start_time = train_end_time - relativedelta(months=+\n prediction_window)\n while train_start_time >= start_time_date:\n print(train_start_time, train_end_time, test_start_time,\n test_end_time, prediction_window)\n train_start_time -= relativedelta(months=+prediction_window)\n train_set, test_set = extract_train_test_sets(train_start_time,\n train_end_time, test_start_time, test_end_time, data_frame)\n class_comp(train_set, test_set, target, features, models_params\n )\n test_end_time -= relativedelta(months=+update_window)\n\n\ndef kfold_eval(df, target, features):\n models_params = {RandomForestClassifier: {'n_estimators': [100],\n 'criterion': ['gini', 'entropy'], 'max_features': ['sqrt', 'log2'],\n 'max_depth': [5, 10], 'n_jobs': [4], 'min_samples_leaf': [10, 50, \n 100]}, LogisticRegression: {'C': [10 ** -1, 10 ** -2, 10 ** -3],\n 'penalty': ['l1', 'l2']}, KNeighborsClassifier: {'n_neighbors': [5,\n 10, 25, 100], 'p': [1, 2, 3], 'n_jobs': [2]},\n DecisionTreeClassifier: {'max_depth': [5, 10, 15],\n 'min_samples_leaf': [2, 5, 10]}, GradientBoostingClassifier: {\n 'learning_rate': [0.1, 0.01], 'n_estimators': [100], 'max_features':\n ['sqrt', 'log2'], 'max_depth': [1, 2, 3]}, BaggingClassifier: {\n 'max_samples': [0.1, 0.25, 0.65], 'n_jobs': [4]}}\n X = df[features]\n y = df[target]\n print(y)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,\n random_state=0)\n \"\"\"\n kf = KFold(n_splits=2)\n kf.get_n_splits(X)\n #print(kf)\n KFold(n_splits=2,random_state=None,shuffle=False)\n for train_index, test_index in kf.split(X):\n print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n \"\"\"\n \"\"\"rf = RandomForestClassifier(n_estimators=100,criterion='gini',max_features='sqrt',max_depth=5)\n rf.fit(X_train, y_train)\n y_score = rf.predict_proba(X_test)\n #y_score = rf.decision_function(X_test)\n y_pred = rf.predict(X_test)\n print(roc_auc_score(y_test,y_score[:,0]))\n metrics_1 ={}\"\"\"\n class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params)\n print(accuracy_score(y_test, y_pred))\n\n\ndef extract_train_test_sets(train_start_time, train_end_time,\n test_start_time, test_end_time, df):\n train_set = df[(df['date_posted'] > train_start_time) & (df[\n 'date_posted'] < train_end_time)]\n test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted'\n ] < test_end_time)]\n return train_set, test_set\n\n\ndef class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params):\n out = open('out.txt', 'a')\n \"\"\"X_train = train_set[features] #X\n y_train = train_set[target] #y\n \n #validation\n X_test = test_set[features] #val_x\n y_test = test_set[target] #val_y\"\"\"\n metrics = {}\n for m, m_param in models_params.items():\n listofparam = get_combos(m_param)\n print('start training for {0}'.format(m))\n out.write('start training for {0}\\n'.format(m))\n for params in listofparam:\n print(params)\n out.write(json.dumps(params))\n model = m(**params)\n model.fit(X_train, y_train)\n y_pred = model.predict_proba(X_test)\n metrics[m] = get_metrics(y_pred[:, 1], y_test)\n print('this is valy')\n print(y_test)\n print('this is y_pred')\n print(y_pred)\n plot_precision_recall(y_test, y_pred[:, 1], model, 'show')\n out.write('----------------------------\\n')\n out.write('Using %s classifier \\n' % models_params)\n out.write(json.dumps(metrics[m]))\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n\n\ndef load_data(csv_file, nrows=None):\n return pd.read_csv(csv_file, nrows=nrows)\n\n\ndef camel_case(column_name):\n s1 = re.sub('(.)([A-Z][a-z]+)', '\\\\1_\\\\2', column_name)\n return re.sub('([a-z0-9])([A-Z])', '\\\\1_\\\\2', s1).lower()\n\n\ndef histogram(data_frame):\n sns.distplot(data_frame)\n plt.show()\n\n\ndef summary(data_frame):\n return data_frame.describe()\n\n\ndef cor_heat(data_frame, var_name):\n corrmat = data_frame.corr()\n k = 12\n cols = corrmat.nlargest(k, var_name)[var_name].index\n cm = np.corrcoef(data_frame[cols].values.T)\n sns.set(font_scale=1.25)\n hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f',\n annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.\n values)\n plt.show()\n\n\ndef plotCorr(dataFrame, list):\n sns.set()\n sns.pairplot(dataFrame[list], size=2.5)\n return plt.show()\n\n\ndef miss_data(data_frame):\n total = data_frame.isnull().sum().sort_values(ascending=False)\n percent = (data_frame.isnull().sum() / data_frame.isnull().count()\n ).sort_values(ascending=False)\n missing_data = pd.concat([total, percent], axis=1, keys=['Total',\n 'Percent'])\n return missing_data\n\n\ndef clean_miss(data_frame):\n missing_data = miss_data(data_frame)\n data_frame = data_frame.drop(missing_data[missing_data['Total'] > 1].\n index, 1)\n data_frame.isnull().sum().max()\n return data_frame\n\n\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,\n np.newaxis])\n low_range = data_scaled[data_scaled[:, 0].argsort()][:10]\n high_range = data_scaled[data_scaled[:, 0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n\n<function token>\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\ndef fill_empty(data_frame, var, new_var):\n return data_frame[var].fillna(new_var)\n\n\ndef descretize(data_frame, var, num):\n return pd.cut(data_frame[var], num, retbins=True)\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\ndef column_dic(data_frame):\n dict = {line[:1]: line[1:].split()[0] for line in data_frame}\n print(dict)\n\n\ndef logReg(data_frame, IV, var_list):\n if '-' in var_list[0]:\n formula = IV + '~' + 'Q(\"' + var_list[0] + '\")'\n else:\n formula = IV + '~' + var_list[0]\n for i in range(1, len(var_list)):\n if '-' in var_list[i]:\n formula = formula + '+' + 'Q(\"' + var_list[i] + '\")'\n else:\n formula = formula + '+' + var_list[i]\n y, X = dmatrices(formula, data_frame, return_type='dataframe')\n y = np.ravel(y)\n model = LogisticRegression()\n model = model.fit(X, y)\n print(pd.DataFrame(list(zip(X.columns, np.transpose(model.coef_)))))\n return model.score(X, y)\n\n\ndef knearest(data_frame, train, test):\n X = data_frame[train].reshape(-1, 1)\n Y = data_frame[test].reshape(-1, 1)\n X_train = X[:100]\n Y_train = Y[:100]\n X_validate = X[100:]\n Y_validate = Y[100:]\n neighbor = KNeighborsClassifier(n_neighbors=2, weights='uniform')\n neighbor.fit(X_train, Y_train)\n predicted = neighbor.predict(X_validate)\n print(predicted)\n\n\ndef merging_data(dataframe_1, dataframe_2):\n return pd.merge(dataframe_1, dataframe_2)\n\n\ndef merging_data2(dataframe_1, dataframe_2):\n dataframe_1['fully_funded'] = 1\n return dataframe_1\n\n\ndef get_combos(param_grid_dict):\n all = sorted(param_grid_dict)\n all_combos = []\n combinations = it.product(*(param_grid_dict[Name] for Name in all))\n for i in combinations:\n lil_combo = {}\n for iter, key in enumerate(all):\n lil_combo[key] = i[iter]\n all_combos.append(lil_combo)\n return all_combos\n\n\ndef to_binary(df, array_col):\n for i in array_col:\n print(i)\n df[i] = df[i].apply(lambda x: 1 if x == 't' else 0)\n return df\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\ndef recall_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n recall = recall_score(y_true_sorted, preds_at_k)\n return recall\n\n\ndef joint_sort_descending(l1, l2):\n idx = np.argsort(l1)[::-1]\n return l1[idx], l2[idx]\n\n\ndef generate_binary_at_k(y_scores, k):\n cutoff_index = int(len(y_scores) * (k / 100.0))\n predictions_binary = [(1 if x < cutoff_index else 0) for x in range(len\n (y_scores))]\n return predictions_binary\n\n\ndef precision_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n precision = precision_score(y_true_sorted, preds_at_k)\n return precision\n\n\ndef plot_precision_recall(val_Y, y_pred, model_name, output_type):\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n prec = prec[:-1]\n recall_curve = rec[:-1]\n pct_above_per_thresh = []\n number_scored = len(y_pred)\n for value in thresh:\n num_above_thresh = len(y_pred[y_pred >= value])\n pct_above_thresh = num_above_thresh / float(len(y_pred))\n if pct_above_thresh <= 1:\n pct_above_per_thresh.append(pct_above_thresh)\n else:\n raise Exception\n pct_above_per_thresh = np.array(pct_above_per_thresh)\n plt.clf()\n fig, ax1 = plt.subplots()\n ax1.plot(pct_above_per_thresh, prec, 'b')\n print('PLOTTING STUFF')\n print(pct_above_per_thresh)\n print(prec[:-1])\n ax1.set_xlabel('percent of population')\n ax1.set_ylabel('precision', color='b')\n ax2 = ax1.twinx()\n ax2.plot(pct_above_per_thresh, recall_curve, 'r')\n ax2.set_ylabel('recall', color='r')\n ax1.set_ylim([0, 1])\n ax2.set_xlim([0, 1])\n name = model_name\n plt.title(name)\n if output_type == 'save':\n plt.savefig(name)\n elif output_type == 'show':\n plt.show()\n pdb.set_trace()\n else:\n plt.show()\n pdb.set_trace()\n\n\ndef temp_val(data_frame, target, features):\n models_params = {RandomForestClassifier: {'n_estimators': [100],\n 'criterion': ['gini', 'entropy'], 'max_features': ['sqrt', 'log2'],\n 'max_depth': [5, 10], 'n_jobs': [4], 'min_samples_leaf': [10, 50, \n 100]}, LogisticRegression: {'C': [10 ** -1, 10 ** -2, 10 ** -3],\n 'penalty': ['l1', 'l2']}, KNeighborsClassifier: {'n_neighbors': [5,\n 10, 25, 100], 'p': [1, 2, 3], 'n_jobs': [2]},\n DecisionTreeClassifier: {'max_depth': [5, 10, 15],\n 'min_samples_leaf': [2, 5, 10]}, GradientBoostingClassifier: {\n 'learning_rate': [0.1, 0.01], 'n_estimators': [100], 'max_features':\n ['sqrt', 'log2'], 'max_depth': [1, 2, 3]}, BaggingClassifier: {\n 'max_samples': [0.1, 0.25, 0.65], 'n_jobs': [4]}}\n start_time_date = data_frame['date_posted'].min()\n end_time_date = data_frame['date_posted'].max()\n prediction_windows = [1]\n update_window = 12\n from datetime import date, datetime, timedelta\n from dateutil.relativedelta import relativedelta\n for prediction_window in prediction_windows:\n print(start_time_date, end_time_date)\n test_end_time = end_time_date\n while test_end_time >= start_time_date + 2 * relativedelta(months=+\n prediction_window):\n test_start_time = test_end_time - relativedelta(months=+\n prediction_window)\n train_end_time = test_start_time - relativedelta(days=+1)\n train_start_time = train_end_time - relativedelta(months=+\n prediction_window)\n while train_start_time >= start_time_date:\n print(train_start_time, train_end_time, test_start_time,\n test_end_time, prediction_window)\n train_start_time -= relativedelta(months=+prediction_window)\n train_set, test_set = extract_train_test_sets(train_start_time,\n train_end_time, test_start_time, test_end_time, data_frame)\n class_comp(train_set, test_set, target, features, models_params\n )\n test_end_time -= relativedelta(months=+update_window)\n\n\ndef kfold_eval(df, target, features):\n models_params = {RandomForestClassifier: {'n_estimators': [100],\n 'criterion': ['gini', 'entropy'], 'max_features': ['sqrt', 'log2'],\n 'max_depth': [5, 10], 'n_jobs': [4], 'min_samples_leaf': [10, 50, \n 100]}, LogisticRegression: {'C': [10 ** -1, 10 ** -2, 10 ** -3],\n 'penalty': ['l1', 'l2']}, KNeighborsClassifier: {'n_neighbors': [5,\n 10, 25, 100], 'p': [1, 2, 3], 'n_jobs': [2]},\n DecisionTreeClassifier: {'max_depth': [5, 10, 15],\n 'min_samples_leaf': [2, 5, 10]}, GradientBoostingClassifier: {\n 'learning_rate': [0.1, 0.01], 'n_estimators': [100], 'max_features':\n ['sqrt', 'log2'], 'max_depth': [1, 2, 3]}, BaggingClassifier: {\n 'max_samples': [0.1, 0.25, 0.65], 'n_jobs': [4]}}\n X = df[features]\n y = df[target]\n print(y)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,\n random_state=0)\n \"\"\"\n kf = KFold(n_splits=2)\n kf.get_n_splits(X)\n #print(kf)\n KFold(n_splits=2,random_state=None,shuffle=False)\n for train_index, test_index in kf.split(X):\n print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n \"\"\"\n \"\"\"rf = RandomForestClassifier(n_estimators=100,criterion='gini',max_features='sqrt',max_depth=5)\n rf.fit(X_train, y_train)\n y_score = rf.predict_proba(X_test)\n #y_score = rf.decision_function(X_test)\n y_pred = rf.predict(X_test)\n print(roc_auc_score(y_test,y_score[:,0]))\n metrics_1 ={}\"\"\"\n class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params)\n print(accuracy_score(y_test, y_pred))\n\n\ndef extract_train_test_sets(train_start_time, train_end_time,\n test_start_time, test_end_time, df):\n train_set = df[(df['date_posted'] > train_start_time) & (df[\n 'date_posted'] < train_end_time)]\n test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted'\n ] < test_end_time)]\n return train_set, test_set\n\n\ndef class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params):\n out = open('out.txt', 'a')\n \"\"\"X_train = train_set[features] #X\n y_train = train_set[target] #y\n \n #validation\n X_test = test_set[features] #val_x\n y_test = test_set[target] #val_y\"\"\"\n metrics = {}\n for m, m_param in models_params.items():\n listofparam = get_combos(m_param)\n print('start training for {0}'.format(m))\n out.write('start training for {0}\\n'.format(m))\n for params in listofparam:\n print(params)\n out.write(json.dumps(params))\n model = m(**params)\n model.fit(X_train, y_train)\n y_pred = model.predict_proba(X_test)\n metrics[m] = get_metrics(y_pred[:, 1], y_test)\n print('this is valy')\n print(y_test)\n print('this is y_pred')\n print(y_pred)\n plot_precision_recall(y_test, y_pred[:, 1], model, 'show')\n out.write('----------------------------\\n')\n out.write('Using %s classifier \\n' % models_params)\n out.write(json.dumps(metrics[m]))\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n\n\ndef load_data(csv_file, nrows=None):\n return pd.read_csv(csv_file, nrows=nrows)\n\n\ndef camel_case(column_name):\n s1 = re.sub('(.)([A-Z][a-z]+)', '\\\\1_\\\\2', column_name)\n return re.sub('([a-z0-9])([A-Z])', '\\\\1_\\\\2', s1).lower()\n\n\ndef histogram(data_frame):\n sns.distplot(data_frame)\n plt.show()\n\n\ndef summary(data_frame):\n return data_frame.describe()\n\n\ndef cor_heat(data_frame, var_name):\n corrmat = data_frame.corr()\n k = 12\n cols = corrmat.nlargest(k, var_name)[var_name].index\n cm = np.corrcoef(data_frame[cols].values.T)\n sns.set(font_scale=1.25)\n hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f',\n annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.\n values)\n plt.show()\n\n\ndef plotCorr(dataFrame, list):\n sns.set()\n sns.pairplot(dataFrame[list], size=2.5)\n return plt.show()\n\n\ndef miss_data(data_frame):\n total = data_frame.isnull().sum().sort_values(ascending=False)\n percent = (data_frame.isnull().sum() / data_frame.isnull().count()\n ).sort_values(ascending=False)\n missing_data = pd.concat([total, percent], axis=1, keys=['Total',\n 'Percent'])\n return missing_data\n\n\ndef clean_miss(data_frame):\n missing_data = miss_data(data_frame)\n data_frame = data_frame.drop(missing_data[missing_data['Total'] > 1].\n index, 1)\n data_frame.isnull().sum().max()\n return data_frame\n\n\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,\n np.newaxis])\n low_range = data_scaled[data_scaled[:, 0].argsort()][:10]\n high_range = data_scaled[data_scaled[:, 0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n\n<function token>\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\ndef fill_empty(data_frame, var, new_var):\n return data_frame[var].fillna(new_var)\n\n\ndef descretize(data_frame, var, num):\n return pd.cut(data_frame[var], num, retbins=True)\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\ndef column_dic(data_frame):\n dict = {line[:1]: line[1:].split()[0] for line in data_frame}\n print(dict)\n\n\ndef logReg(data_frame, IV, var_list):\n if '-' in var_list[0]:\n formula = IV + '~' + 'Q(\"' + var_list[0] + '\")'\n else:\n formula = IV + '~' + var_list[0]\n for i in range(1, len(var_list)):\n if '-' in var_list[i]:\n formula = formula + '+' + 'Q(\"' + var_list[i] + '\")'\n else:\n formula = formula + '+' + var_list[i]\n y, X = dmatrices(formula, data_frame, return_type='dataframe')\n y = np.ravel(y)\n model = LogisticRegression()\n model = model.fit(X, y)\n print(pd.DataFrame(list(zip(X.columns, np.transpose(model.coef_)))))\n return model.score(X, y)\n\n\ndef knearest(data_frame, train, test):\n X = data_frame[train].reshape(-1, 1)\n Y = data_frame[test].reshape(-1, 1)\n X_train = X[:100]\n Y_train = Y[:100]\n X_validate = X[100:]\n Y_validate = Y[100:]\n neighbor = KNeighborsClassifier(n_neighbors=2, weights='uniform')\n neighbor.fit(X_train, Y_train)\n predicted = neighbor.predict(X_validate)\n print(predicted)\n\n\ndef merging_data(dataframe_1, dataframe_2):\n return pd.merge(dataframe_1, dataframe_2)\n\n\ndef merging_data2(dataframe_1, dataframe_2):\n dataframe_1['fully_funded'] = 1\n return dataframe_1\n\n\ndef get_combos(param_grid_dict):\n all = sorted(param_grid_dict)\n all_combos = []\n combinations = it.product(*(param_grid_dict[Name] for Name in all))\n for i in combinations:\n lil_combo = {}\n for iter, key in enumerate(all):\n lil_combo[key] = i[iter]\n all_combos.append(lil_combo)\n return all_combos\n\n\ndef to_binary(df, array_col):\n for i in array_col:\n print(i)\n df[i] = df[i].apply(lambda x: 1 if x == 't' else 0)\n return df\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\ndef recall_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n recall = recall_score(y_true_sorted, preds_at_k)\n return recall\n\n\ndef joint_sort_descending(l1, l2):\n idx = np.argsort(l1)[::-1]\n return l1[idx], l2[idx]\n\n\ndef generate_binary_at_k(y_scores, k):\n cutoff_index = int(len(y_scores) * (k / 100.0))\n predictions_binary = [(1 if x < cutoff_index else 0) for x in range(len\n (y_scores))]\n return predictions_binary\n\n\ndef precision_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n precision = precision_score(y_true_sorted, preds_at_k)\n return precision\n\n\ndef plot_precision_recall(val_Y, y_pred, model_name, output_type):\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n prec = prec[:-1]\n recall_curve = rec[:-1]\n pct_above_per_thresh = []\n number_scored = len(y_pred)\n for value in thresh:\n num_above_thresh = len(y_pred[y_pred >= value])\n pct_above_thresh = num_above_thresh / float(len(y_pred))\n if pct_above_thresh <= 1:\n pct_above_per_thresh.append(pct_above_thresh)\n else:\n raise Exception\n pct_above_per_thresh = np.array(pct_above_per_thresh)\n plt.clf()\n fig, ax1 = plt.subplots()\n ax1.plot(pct_above_per_thresh, prec, 'b')\n print('PLOTTING STUFF')\n print(pct_above_per_thresh)\n print(prec[:-1])\n ax1.set_xlabel('percent of population')\n ax1.set_ylabel('precision', color='b')\n ax2 = ax1.twinx()\n ax2.plot(pct_above_per_thresh, recall_curve, 'r')\n ax2.set_ylabel('recall', color='r')\n ax1.set_ylim([0, 1])\n ax2.set_xlim([0, 1])\n name = model_name\n plt.title(name)\n if output_type == 'save':\n plt.savefig(name)\n elif output_type == 'show':\n plt.show()\n pdb.set_trace()\n else:\n plt.show()\n pdb.set_trace()\n\n\n<function token>\n\n\ndef kfold_eval(df, target, features):\n models_params = {RandomForestClassifier: {'n_estimators': [100],\n 'criterion': ['gini', 'entropy'], 'max_features': ['sqrt', 'log2'],\n 'max_depth': [5, 10], 'n_jobs': [4], 'min_samples_leaf': [10, 50, \n 100]}, LogisticRegression: {'C': [10 ** -1, 10 ** -2, 10 ** -3],\n 'penalty': ['l1', 'l2']}, KNeighborsClassifier: {'n_neighbors': [5,\n 10, 25, 100], 'p': [1, 2, 3], 'n_jobs': [2]},\n DecisionTreeClassifier: {'max_depth': [5, 10, 15],\n 'min_samples_leaf': [2, 5, 10]}, GradientBoostingClassifier: {\n 'learning_rate': [0.1, 0.01], 'n_estimators': [100], 'max_features':\n ['sqrt', 'log2'], 'max_depth': [1, 2, 3]}, BaggingClassifier: {\n 'max_samples': [0.1, 0.25, 0.65], 'n_jobs': [4]}}\n X = df[features]\n y = df[target]\n print(y)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,\n random_state=0)\n \"\"\"\n kf = KFold(n_splits=2)\n kf.get_n_splits(X)\n #print(kf)\n KFold(n_splits=2,random_state=None,shuffle=False)\n for train_index, test_index in kf.split(X):\n print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n \"\"\"\n \"\"\"rf = RandomForestClassifier(n_estimators=100,criterion='gini',max_features='sqrt',max_depth=5)\n rf.fit(X_train, y_train)\n y_score = rf.predict_proba(X_test)\n #y_score = rf.decision_function(X_test)\n y_pred = rf.predict(X_test)\n print(roc_auc_score(y_test,y_score[:,0]))\n metrics_1 ={}\"\"\"\n class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params)\n print(accuracy_score(y_test, y_pred))\n\n\ndef extract_train_test_sets(train_start_time, train_end_time,\n test_start_time, test_end_time, df):\n train_set = df[(df['date_posted'] > train_start_time) & (df[\n 'date_posted'] < train_end_time)]\n test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted'\n ] < test_end_time)]\n return train_set, test_set\n\n\ndef class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params):\n out = open('out.txt', 'a')\n \"\"\"X_train = train_set[features] #X\n y_train = train_set[target] #y\n \n #validation\n X_test = test_set[features] #val_x\n y_test = test_set[target] #val_y\"\"\"\n metrics = {}\n for m, m_param in models_params.items():\n listofparam = get_combos(m_param)\n print('start training for {0}'.format(m))\n out.write('start training for {0}\\n'.format(m))\n for params in listofparam:\n print(params)\n out.write(json.dumps(params))\n model = m(**params)\n model.fit(X_train, y_train)\n y_pred = model.predict_proba(X_test)\n metrics[m] = get_metrics(y_pred[:, 1], y_test)\n print('this is valy')\n print(y_test)\n print('this is y_pred')\n print(y_pred)\n plot_precision_recall(y_test, y_pred[:, 1], model, 'show')\n out.write('----------------------------\\n')\n out.write('Using %s classifier \\n' % models_params)\n out.write(json.dumps(metrics[m]))\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n\n\ndef load_data(csv_file, nrows=None):\n return pd.read_csv(csv_file, nrows=nrows)\n\n\n<function token>\n\n\ndef histogram(data_frame):\n sns.distplot(data_frame)\n plt.show()\n\n\ndef summary(data_frame):\n return data_frame.describe()\n\n\ndef cor_heat(data_frame, var_name):\n corrmat = data_frame.corr()\n k = 12\n cols = corrmat.nlargest(k, var_name)[var_name].index\n cm = np.corrcoef(data_frame[cols].values.T)\n sns.set(font_scale=1.25)\n hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f',\n annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.\n values)\n plt.show()\n\n\ndef plotCorr(dataFrame, list):\n sns.set()\n sns.pairplot(dataFrame[list], size=2.5)\n return plt.show()\n\n\ndef miss_data(data_frame):\n total = data_frame.isnull().sum().sort_values(ascending=False)\n percent = (data_frame.isnull().sum() / data_frame.isnull().count()\n ).sort_values(ascending=False)\n missing_data = pd.concat([total, percent], axis=1, keys=['Total',\n 'Percent'])\n return missing_data\n\n\ndef clean_miss(data_frame):\n missing_data = miss_data(data_frame)\n data_frame = data_frame.drop(missing_data[missing_data['Total'] > 1].\n index, 1)\n data_frame.isnull().sum().max()\n return data_frame\n\n\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,\n np.newaxis])\n low_range = data_scaled[data_scaled[:, 0].argsort()][:10]\n high_range = data_scaled[data_scaled[:, 0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n\n<function token>\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\ndef fill_empty(data_frame, var, new_var):\n return data_frame[var].fillna(new_var)\n\n\ndef descretize(data_frame, var, num):\n return pd.cut(data_frame[var], num, retbins=True)\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\ndef column_dic(data_frame):\n dict = {line[:1]: line[1:].split()[0] for line in data_frame}\n print(dict)\n\n\ndef logReg(data_frame, IV, var_list):\n if '-' in var_list[0]:\n formula = IV + '~' + 'Q(\"' + var_list[0] + '\")'\n else:\n formula = IV + '~' + var_list[0]\n for i in range(1, len(var_list)):\n if '-' in var_list[i]:\n formula = formula + '+' + 'Q(\"' + var_list[i] + '\")'\n else:\n formula = formula + '+' + var_list[i]\n y, X = dmatrices(formula, data_frame, return_type='dataframe')\n y = np.ravel(y)\n model = LogisticRegression()\n model = model.fit(X, y)\n print(pd.DataFrame(list(zip(X.columns, np.transpose(model.coef_)))))\n return model.score(X, y)\n\n\ndef knearest(data_frame, train, test):\n X = data_frame[train].reshape(-1, 1)\n Y = data_frame[test].reshape(-1, 1)\n X_train = X[:100]\n Y_train = Y[:100]\n X_validate = X[100:]\n Y_validate = Y[100:]\n neighbor = KNeighborsClassifier(n_neighbors=2, weights='uniform')\n neighbor.fit(X_train, Y_train)\n predicted = neighbor.predict(X_validate)\n print(predicted)\n\n\ndef merging_data(dataframe_1, dataframe_2):\n return pd.merge(dataframe_1, dataframe_2)\n\n\ndef merging_data2(dataframe_1, dataframe_2):\n dataframe_1['fully_funded'] = 1\n return dataframe_1\n\n\ndef get_combos(param_grid_dict):\n all = sorted(param_grid_dict)\n all_combos = []\n combinations = it.product(*(param_grid_dict[Name] for Name in all))\n for i in combinations:\n lil_combo = {}\n for iter, key in enumerate(all):\n lil_combo[key] = i[iter]\n all_combos.append(lil_combo)\n return all_combos\n\n\ndef to_binary(df, array_col):\n for i in array_col:\n print(i)\n df[i] = df[i].apply(lambda x: 1 if x == 't' else 0)\n return df\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\ndef recall_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n recall = recall_score(y_true_sorted, preds_at_k)\n return recall\n\n\ndef joint_sort_descending(l1, l2):\n idx = np.argsort(l1)[::-1]\n return l1[idx], l2[idx]\n\n\ndef generate_binary_at_k(y_scores, k):\n cutoff_index = int(len(y_scores) * (k / 100.0))\n predictions_binary = [(1 if x < cutoff_index else 0) for x in range(len\n (y_scores))]\n return predictions_binary\n\n\ndef precision_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n precision = precision_score(y_true_sorted, preds_at_k)\n return precision\n\n\ndef plot_precision_recall(val_Y, y_pred, model_name, output_type):\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n prec = prec[:-1]\n recall_curve = rec[:-1]\n pct_above_per_thresh = []\n number_scored = len(y_pred)\n for value in thresh:\n num_above_thresh = len(y_pred[y_pred >= value])\n pct_above_thresh = num_above_thresh / float(len(y_pred))\n if pct_above_thresh <= 1:\n pct_above_per_thresh.append(pct_above_thresh)\n else:\n raise Exception\n pct_above_per_thresh = np.array(pct_above_per_thresh)\n plt.clf()\n fig, ax1 = plt.subplots()\n ax1.plot(pct_above_per_thresh, prec, 'b')\n print('PLOTTING STUFF')\n print(pct_above_per_thresh)\n print(prec[:-1])\n ax1.set_xlabel('percent of population')\n ax1.set_ylabel('precision', color='b')\n ax2 = ax1.twinx()\n ax2.plot(pct_above_per_thresh, recall_curve, 'r')\n ax2.set_ylabel('recall', color='r')\n ax1.set_ylim([0, 1])\n ax2.set_xlim([0, 1])\n name = model_name\n plt.title(name)\n if output_type == 'save':\n plt.savefig(name)\n elif output_type == 'show':\n plt.show()\n pdb.set_trace()\n else:\n plt.show()\n pdb.set_trace()\n\n\n<function token>\n\n\ndef kfold_eval(df, target, features):\n models_params = {RandomForestClassifier: {'n_estimators': [100],\n 'criterion': ['gini', 'entropy'], 'max_features': ['sqrt', 'log2'],\n 'max_depth': [5, 10], 'n_jobs': [4], 'min_samples_leaf': [10, 50, \n 100]}, LogisticRegression: {'C': [10 ** -1, 10 ** -2, 10 ** -3],\n 'penalty': ['l1', 'l2']}, KNeighborsClassifier: {'n_neighbors': [5,\n 10, 25, 100], 'p': [1, 2, 3], 'n_jobs': [2]},\n DecisionTreeClassifier: {'max_depth': [5, 10, 15],\n 'min_samples_leaf': [2, 5, 10]}, GradientBoostingClassifier: {\n 'learning_rate': [0.1, 0.01], 'n_estimators': [100], 'max_features':\n ['sqrt', 'log2'], 'max_depth': [1, 2, 3]}, BaggingClassifier: {\n 'max_samples': [0.1, 0.25, 0.65], 'n_jobs': [4]}}\n X = df[features]\n y = df[target]\n print(y)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,\n random_state=0)\n \"\"\"\n kf = KFold(n_splits=2)\n kf.get_n_splits(X)\n #print(kf)\n KFold(n_splits=2,random_state=None,shuffle=False)\n for train_index, test_index in kf.split(X):\n print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n \"\"\"\n \"\"\"rf = RandomForestClassifier(n_estimators=100,criterion='gini',max_features='sqrt',max_depth=5)\n rf.fit(X_train, y_train)\n y_score = rf.predict_proba(X_test)\n #y_score = rf.decision_function(X_test)\n y_pred = rf.predict(X_test)\n print(roc_auc_score(y_test,y_score[:,0]))\n metrics_1 ={}\"\"\"\n class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params)\n print(accuracy_score(y_test, y_pred))\n\n\ndef extract_train_test_sets(train_start_time, train_end_time,\n test_start_time, test_end_time, df):\n train_set = df[(df['date_posted'] > train_start_time) & (df[\n 'date_posted'] < train_end_time)]\n test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted'\n ] < test_end_time)]\n return train_set, test_set\n\n\ndef class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params):\n out = open('out.txt', 'a')\n \"\"\"X_train = train_set[features] #X\n y_train = train_set[target] #y\n \n #validation\n X_test = test_set[features] #val_x\n y_test = test_set[target] #val_y\"\"\"\n metrics = {}\n for m, m_param in models_params.items():\n listofparam = get_combos(m_param)\n print('start training for {0}'.format(m))\n out.write('start training for {0}\\n'.format(m))\n for params in listofparam:\n print(params)\n out.write(json.dumps(params))\n model = m(**params)\n model.fit(X_train, y_train)\n y_pred = model.predict_proba(X_test)\n metrics[m] = get_metrics(y_pred[:, 1], y_test)\n print('this is valy')\n print(y_test)\n print('this is y_pred')\n print(y_pred)\n plot_precision_recall(y_test, y_pred[:, 1], model, 'show')\n out.write('----------------------------\\n')\n out.write('Using %s classifier \\n' % models_params)\n out.write(json.dumps(metrics[m]))\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n\n\ndef load_data(csv_file, nrows=None):\n return pd.read_csv(csv_file, nrows=nrows)\n\n\n<function token>\n\n\ndef histogram(data_frame):\n sns.distplot(data_frame)\n plt.show()\n\n\ndef summary(data_frame):\n return data_frame.describe()\n\n\ndef cor_heat(data_frame, var_name):\n corrmat = data_frame.corr()\n k = 12\n cols = corrmat.nlargest(k, var_name)[var_name].index\n cm = np.corrcoef(data_frame[cols].values.T)\n sns.set(font_scale=1.25)\n hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f',\n annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.\n values)\n plt.show()\n\n\ndef plotCorr(dataFrame, list):\n sns.set()\n sns.pairplot(dataFrame[list], size=2.5)\n return plt.show()\n\n\ndef miss_data(data_frame):\n total = data_frame.isnull().sum().sort_values(ascending=False)\n percent = (data_frame.isnull().sum() / data_frame.isnull().count()\n ).sort_values(ascending=False)\n missing_data = pd.concat([total, percent], axis=1, keys=['Total',\n 'Percent'])\n return missing_data\n\n\ndef clean_miss(data_frame):\n missing_data = miss_data(data_frame)\n data_frame = data_frame.drop(missing_data[missing_data['Total'] > 1].\n index, 1)\n data_frame.isnull().sum().max()\n return data_frame\n\n\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,\n np.newaxis])\n low_range = data_scaled[data_scaled[:, 0].argsort()][:10]\n high_range = data_scaled[data_scaled[:, 0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n\n<function token>\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\ndef fill_empty(data_frame, var, new_var):\n return data_frame[var].fillna(new_var)\n\n\ndef descretize(data_frame, var, num):\n return pd.cut(data_frame[var], num, retbins=True)\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\n<function token>\n\n\ndef logReg(data_frame, IV, var_list):\n if '-' in var_list[0]:\n formula = IV + '~' + 'Q(\"' + var_list[0] + '\")'\n else:\n formula = IV + '~' + var_list[0]\n for i in range(1, len(var_list)):\n if '-' in var_list[i]:\n formula = formula + '+' + 'Q(\"' + var_list[i] + '\")'\n else:\n formula = formula + '+' + var_list[i]\n y, X = dmatrices(formula, data_frame, return_type='dataframe')\n y = np.ravel(y)\n model = LogisticRegression()\n model = model.fit(X, y)\n print(pd.DataFrame(list(zip(X.columns, np.transpose(model.coef_)))))\n return model.score(X, y)\n\n\ndef knearest(data_frame, train, test):\n X = data_frame[train].reshape(-1, 1)\n Y = data_frame[test].reshape(-1, 1)\n X_train = X[:100]\n Y_train = Y[:100]\n X_validate = X[100:]\n Y_validate = Y[100:]\n neighbor = KNeighborsClassifier(n_neighbors=2, weights='uniform')\n neighbor.fit(X_train, Y_train)\n predicted = neighbor.predict(X_validate)\n print(predicted)\n\n\ndef merging_data(dataframe_1, dataframe_2):\n return pd.merge(dataframe_1, dataframe_2)\n\n\ndef merging_data2(dataframe_1, dataframe_2):\n dataframe_1['fully_funded'] = 1\n return dataframe_1\n\n\ndef get_combos(param_grid_dict):\n all = sorted(param_grid_dict)\n all_combos = []\n combinations = it.product(*(param_grid_dict[Name] for Name in all))\n for i in combinations:\n lil_combo = {}\n for iter, key in enumerate(all):\n lil_combo[key] = i[iter]\n all_combos.append(lil_combo)\n return all_combos\n\n\ndef to_binary(df, array_col):\n for i in array_col:\n print(i)\n df[i] = df[i].apply(lambda x: 1 if x == 't' else 0)\n return df\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\ndef recall_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n recall = recall_score(y_true_sorted, preds_at_k)\n return recall\n\n\ndef joint_sort_descending(l1, l2):\n idx = np.argsort(l1)[::-1]\n return l1[idx], l2[idx]\n\n\ndef generate_binary_at_k(y_scores, k):\n cutoff_index = int(len(y_scores) * (k / 100.0))\n predictions_binary = [(1 if x < cutoff_index else 0) for x in range(len\n (y_scores))]\n return predictions_binary\n\n\ndef precision_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n precision = precision_score(y_true_sorted, preds_at_k)\n return precision\n\n\ndef plot_precision_recall(val_Y, y_pred, model_name, output_type):\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n prec = prec[:-1]\n recall_curve = rec[:-1]\n pct_above_per_thresh = []\n number_scored = len(y_pred)\n for value in thresh:\n num_above_thresh = len(y_pred[y_pred >= value])\n pct_above_thresh = num_above_thresh / float(len(y_pred))\n if pct_above_thresh <= 1:\n pct_above_per_thresh.append(pct_above_thresh)\n else:\n raise Exception\n pct_above_per_thresh = np.array(pct_above_per_thresh)\n plt.clf()\n fig, ax1 = plt.subplots()\n ax1.plot(pct_above_per_thresh, prec, 'b')\n print('PLOTTING STUFF')\n print(pct_above_per_thresh)\n print(prec[:-1])\n ax1.set_xlabel('percent of population')\n ax1.set_ylabel('precision', color='b')\n ax2 = ax1.twinx()\n ax2.plot(pct_above_per_thresh, recall_curve, 'r')\n ax2.set_ylabel('recall', color='r')\n ax1.set_ylim([0, 1])\n ax2.set_xlim([0, 1])\n name = model_name\n plt.title(name)\n if output_type == 'save':\n plt.savefig(name)\n elif output_type == 'show':\n plt.show()\n pdb.set_trace()\n else:\n plt.show()\n pdb.set_trace()\n\n\n<function token>\n\n\ndef kfold_eval(df, target, features):\n models_params = {RandomForestClassifier: {'n_estimators': [100],\n 'criterion': ['gini', 'entropy'], 'max_features': ['sqrt', 'log2'],\n 'max_depth': [5, 10], 'n_jobs': [4], 'min_samples_leaf': [10, 50, \n 100]}, LogisticRegression: {'C': [10 ** -1, 10 ** -2, 10 ** -3],\n 'penalty': ['l1', 'l2']}, KNeighborsClassifier: {'n_neighbors': [5,\n 10, 25, 100], 'p': [1, 2, 3], 'n_jobs': [2]},\n DecisionTreeClassifier: {'max_depth': [5, 10, 15],\n 'min_samples_leaf': [2, 5, 10]}, GradientBoostingClassifier: {\n 'learning_rate': [0.1, 0.01], 'n_estimators': [100], 'max_features':\n ['sqrt', 'log2'], 'max_depth': [1, 2, 3]}, BaggingClassifier: {\n 'max_samples': [0.1, 0.25, 0.65], 'n_jobs': [4]}}\n X = df[features]\n y = df[target]\n print(y)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,\n random_state=0)\n \"\"\"\n kf = KFold(n_splits=2)\n kf.get_n_splits(X)\n #print(kf)\n KFold(n_splits=2,random_state=None,shuffle=False)\n for train_index, test_index in kf.split(X):\n print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n \"\"\"\n \"\"\"rf = RandomForestClassifier(n_estimators=100,criterion='gini',max_features='sqrt',max_depth=5)\n rf.fit(X_train, y_train)\n y_score = rf.predict_proba(X_test)\n #y_score = rf.decision_function(X_test)\n y_pred = rf.predict(X_test)\n print(roc_auc_score(y_test,y_score[:,0]))\n metrics_1 ={}\"\"\"\n class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params)\n print(accuracy_score(y_test, y_pred))\n\n\ndef extract_train_test_sets(train_start_time, train_end_time,\n test_start_time, test_end_time, df):\n train_set = df[(df['date_posted'] > train_start_time) & (df[\n 'date_posted'] < train_end_time)]\n test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted'\n ] < test_end_time)]\n return train_set, test_set\n\n\ndef class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params):\n out = open('out.txt', 'a')\n \"\"\"X_train = train_set[features] #X\n y_train = train_set[target] #y\n \n #validation\n X_test = test_set[features] #val_x\n y_test = test_set[target] #val_y\"\"\"\n metrics = {}\n for m, m_param in models_params.items():\n listofparam = get_combos(m_param)\n print('start training for {0}'.format(m))\n out.write('start training for {0}\\n'.format(m))\n for params in listofparam:\n print(params)\n out.write(json.dumps(params))\n model = m(**params)\n model.fit(X_train, y_train)\n y_pred = model.predict_proba(X_test)\n metrics[m] = get_metrics(y_pred[:, 1], y_test)\n print('this is valy')\n print(y_test)\n print('this is y_pred')\n print(y_pred)\n plot_precision_recall(y_test, y_pred[:, 1], model, 'show')\n out.write('----------------------------\\n')\n out.write('Using %s classifier \\n' % models_params)\n out.write(json.dumps(metrics[m]))\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n\n\ndef load_data(csv_file, nrows=None):\n return pd.read_csv(csv_file, nrows=nrows)\n\n\n<function token>\n\n\ndef histogram(data_frame):\n sns.distplot(data_frame)\n plt.show()\n\n\ndef summary(data_frame):\n return data_frame.describe()\n\n\ndef cor_heat(data_frame, var_name):\n corrmat = data_frame.corr()\n k = 12\n cols = corrmat.nlargest(k, var_name)[var_name].index\n cm = np.corrcoef(data_frame[cols].values.T)\n sns.set(font_scale=1.25)\n hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f',\n annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.\n values)\n plt.show()\n\n\ndef plotCorr(dataFrame, list):\n sns.set()\n sns.pairplot(dataFrame[list], size=2.5)\n return plt.show()\n\n\ndef miss_data(data_frame):\n total = data_frame.isnull().sum().sort_values(ascending=False)\n percent = (data_frame.isnull().sum() / data_frame.isnull().count()\n ).sort_values(ascending=False)\n missing_data = pd.concat([total, percent], axis=1, keys=['Total',\n 'Percent'])\n return missing_data\n\n\n<function token>\n\n\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,\n np.newaxis])\n low_range = data_scaled[data_scaled[:, 0].argsort()][:10]\n high_range = data_scaled[data_scaled[:, 0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n\n<function token>\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\ndef fill_empty(data_frame, var, new_var):\n return data_frame[var].fillna(new_var)\n\n\ndef descretize(data_frame, var, num):\n return pd.cut(data_frame[var], num, retbins=True)\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\n<function token>\n\n\ndef logReg(data_frame, IV, var_list):\n if '-' in var_list[0]:\n formula = IV + '~' + 'Q(\"' + var_list[0] + '\")'\n else:\n formula = IV + '~' + var_list[0]\n for i in range(1, len(var_list)):\n if '-' in var_list[i]:\n formula = formula + '+' + 'Q(\"' + var_list[i] + '\")'\n else:\n formula = formula + '+' + var_list[i]\n y, X = dmatrices(formula, data_frame, return_type='dataframe')\n y = np.ravel(y)\n model = LogisticRegression()\n model = model.fit(X, y)\n print(pd.DataFrame(list(zip(X.columns, np.transpose(model.coef_)))))\n return model.score(X, y)\n\n\ndef knearest(data_frame, train, test):\n X = data_frame[train].reshape(-1, 1)\n Y = data_frame[test].reshape(-1, 1)\n X_train = X[:100]\n Y_train = Y[:100]\n X_validate = X[100:]\n Y_validate = Y[100:]\n neighbor = KNeighborsClassifier(n_neighbors=2, weights='uniform')\n neighbor.fit(X_train, Y_train)\n predicted = neighbor.predict(X_validate)\n print(predicted)\n\n\ndef merging_data(dataframe_1, dataframe_2):\n return pd.merge(dataframe_1, dataframe_2)\n\n\ndef merging_data2(dataframe_1, dataframe_2):\n dataframe_1['fully_funded'] = 1\n return dataframe_1\n\n\ndef get_combos(param_grid_dict):\n all = sorted(param_grid_dict)\n all_combos = []\n combinations = it.product(*(param_grid_dict[Name] for Name in all))\n for i in combinations:\n lil_combo = {}\n for iter, key in enumerate(all):\n lil_combo[key] = i[iter]\n all_combos.append(lil_combo)\n return all_combos\n\n\ndef to_binary(df, array_col):\n for i in array_col:\n print(i)\n df[i] = df[i].apply(lambda x: 1 if x == 't' else 0)\n return df\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\ndef recall_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n recall = recall_score(y_true_sorted, preds_at_k)\n return recall\n\n\ndef joint_sort_descending(l1, l2):\n idx = np.argsort(l1)[::-1]\n return l1[idx], l2[idx]\n\n\ndef generate_binary_at_k(y_scores, k):\n cutoff_index = int(len(y_scores) * (k / 100.0))\n predictions_binary = [(1 if x < cutoff_index else 0) for x in range(len\n (y_scores))]\n return predictions_binary\n\n\ndef precision_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n precision = precision_score(y_true_sorted, preds_at_k)\n return precision\n\n\ndef plot_precision_recall(val_Y, y_pred, model_name, output_type):\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n prec = prec[:-1]\n recall_curve = rec[:-1]\n pct_above_per_thresh = []\n number_scored = len(y_pred)\n for value in thresh:\n num_above_thresh = len(y_pred[y_pred >= value])\n pct_above_thresh = num_above_thresh / float(len(y_pred))\n if pct_above_thresh <= 1:\n pct_above_per_thresh.append(pct_above_thresh)\n else:\n raise Exception\n pct_above_per_thresh = np.array(pct_above_per_thresh)\n plt.clf()\n fig, ax1 = plt.subplots()\n ax1.plot(pct_above_per_thresh, prec, 'b')\n print('PLOTTING STUFF')\n print(pct_above_per_thresh)\n print(prec[:-1])\n ax1.set_xlabel('percent of population')\n ax1.set_ylabel('precision', color='b')\n ax2 = ax1.twinx()\n ax2.plot(pct_above_per_thresh, recall_curve, 'r')\n ax2.set_ylabel('recall', color='r')\n ax1.set_ylim([0, 1])\n ax2.set_xlim([0, 1])\n name = model_name\n plt.title(name)\n if output_type == 'save':\n plt.savefig(name)\n elif output_type == 'show':\n plt.show()\n pdb.set_trace()\n else:\n plt.show()\n pdb.set_trace()\n\n\n<function token>\n\n\ndef kfold_eval(df, target, features):\n models_params = {RandomForestClassifier: {'n_estimators': [100],\n 'criterion': ['gini', 'entropy'], 'max_features': ['sqrt', 'log2'],\n 'max_depth': [5, 10], 'n_jobs': [4], 'min_samples_leaf': [10, 50, \n 100]}, LogisticRegression: {'C': [10 ** -1, 10 ** -2, 10 ** -3],\n 'penalty': ['l1', 'l2']}, KNeighborsClassifier: {'n_neighbors': [5,\n 10, 25, 100], 'p': [1, 2, 3], 'n_jobs': [2]},\n DecisionTreeClassifier: {'max_depth': [5, 10, 15],\n 'min_samples_leaf': [2, 5, 10]}, GradientBoostingClassifier: {\n 'learning_rate': [0.1, 0.01], 'n_estimators': [100], 'max_features':\n ['sqrt', 'log2'], 'max_depth': [1, 2, 3]}, BaggingClassifier: {\n 'max_samples': [0.1, 0.25, 0.65], 'n_jobs': [4]}}\n X = df[features]\n y = df[target]\n print(y)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,\n random_state=0)\n \"\"\"\n kf = KFold(n_splits=2)\n kf.get_n_splits(X)\n #print(kf)\n KFold(n_splits=2,random_state=None,shuffle=False)\n for train_index, test_index in kf.split(X):\n print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n \"\"\"\n \"\"\"rf = RandomForestClassifier(n_estimators=100,criterion='gini',max_features='sqrt',max_depth=5)\n rf.fit(X_train, y_train)\n y_score = rf.predict_proba(X_test)\n #y_score = rf.decision_function(X_test)\n y_pred = rf.predict(X_test)\n print(roc_auc_score(y_test,y_score[:,0]))\n metrics_1 ={}\"\"\"\n class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params)\n print(accuracy_score(y_test, y_pred))\n\n\ndef extract_train_test_sets(train_start_time, train_end_time,\n test_start_time, test_end_time, df):\n train_set = df[(df['date_posted'] > train_start_time) & (df[\n 'date_posted'] < train_end_time)]\n test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted'\n ] < test_end_time)]\n return train_set, test_set\n\n\ndef class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params):\n out = open('out.txt', 'a')\n \"\"\"X_train = train_set[features] #X\n y_train = train_set[target] #y\n \n #validation\n X_test = test_set[features] #val_x\n y_test = test_set[target] #val_y\"\"\"\n metrics = {}\n for m, m_param in models_params.items():\n listofparam = get_combos(m_param)\n print('start training for {0}'.format(m))\n out.write('start training for {0}\\n'.format(m))\n for params in listofparam:\n print(params)\n out.write(json.dumps(params))\n model = m(**params)\n model.fit(X_train, y_train)\n y_pred = model.predict_proba(X_test)\n metrics[m] = get_metrics(y_pred[:, 1], y_test)\n print('this is valy')\n print(y_test)\n print('this is y_pred')\n print(y_pred)\n plot_precision_recall(y_test, y_pred[:, 1], model, 'show')\n out.write('----------------------------\\n')\n out.write('Using %s classifier \\n' % models_params)\n out.write(json.dumps(metrics[m]))\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n\n\ndef load_data(csv_file, nrows=None):\n return pd.read_csv(csv_file, nrows=nrows)\n\n\n<function token>\n\n\ndef histogram(data_frame):\n sns.distplot(data_frame)\n plt.show()\n\n\n<function token>\n\n\ndef cor_heat(data_frame, var_name):\n corrmat = data_frame.corr()\n k = 12\n cols = corrmat.nlargest(k, var_name)[var_name].index\n cm = np.corrcoef(data_frame[cols].values.T)\n sns.set(font_scale=1.25)\n hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f',\n annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.\n values)\n plt.show()\n\n\ndef plotCorr(dataFrame, list):\n sns.set()\n sns.pairplot(dataFrame[list], size=2.5)\n return plt.show()\n\n\ndef miss_data(data_frame):\n total = data_frame.isnull().sum().sort_values(ascending=False)\n percent = (data_frame.isnull().sum() / data_frame.isnull().count()\n ).sort_values(ascending=False)\n missing_data = pd.concat([total, percent], axis=1, keys=['Total',\n 'Percent'])\n return missing_data\n\n\n<function token>\n\n\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,\n np.newaxis])\n low_range = data_scaled[data_scaled[:, 0].argsort()][:10]\n high_range = data_scaled[data_scaled[:, 0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n\n<function token>\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\ndef fill_empty(data_frame, var, new_var):\n return data_frame[var].fillna(new_var)\n\n\ndef descretize(data_frame, var, num):\n return pd.cut(data_frame[var], num, retbins=True)\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\n<function token>\n\n\ndef logReg(data_frame, IV, var_list):\n if '-' in var_list[0]:\n formula = IV + '~' + 'Q(\"' + var_list[0] + '\")'\n else:\n formula = IV + '~' + var_list[0]\n for i in range(1, len(var_list)):\n if '-' in var_list[i]:\n formula = formula + '+' + 'Q(\"' + var_list[i] + '\")'\n else:\n formula = formula + '+' + var_list[i]\n y, X = dmatrices(formula, data_frame, return_type='dataframe')\n y = np.ravel(y)\n model = LogisticRegression()\n model = model.fit(X, y)\n print(pd.DataFrame(list(zip(X.columns, np.transpose(model.coef_)))))\n return model.score(X, y)\n\n\ndef knearest(data_frame, train, test):\n X = data_frame[train].reshape(-1, 1)\n Y = data_frame[test].reshape(-1, 1)\n X_train = X[:100]\n Y_train = Y[:100]\n X_validate = X[100:]\n Y_validate = Y[100:]\n neighbor = KNeighborsClassifier(n_neighbors=2, weights='uniform')\n neighbor.fit(X_train, Y_train)\n predicted = neighbor.predict(X_validate)\n print(predicted)\n\n\ndef merging_data(dataframe_1, dataframe_2):\n return pd.merge(dataframe_1, dataframe_2)\n\n\ndef merging_data2(dataframe_1, dataframe_2):\n dataframe_1['fully_funded'] = 1\n return dataframe_1\n\n\ndef get_combos(param_grid_dict):\n all = sorted(param_grid_dict)\n all_combos = []\n combinations = it.product(*(param_grid_dict[Name] for Name in all))\n for i in combinations:\n lil_combo = {}\n for iter, key in enumerate(all):\n lil_combo[key] = i[iter]\n all_combos.append(lil_combo)\n return all_combos\n\n\ndef to_binary(df, array_col):\n for i in array_col:\n print(i)\n df[i] = df[i].apply(lambda x: 1 if x == 't' else 0)\n return df\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\ndef recall_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n recall = recall_score(y_true_sorted, preds_at_k)\n return recall\n\n\ndef joint_sort_descending(l1, l2):\n idx = np.argsort(l1)[::-1]\n return l1[idx], l2[idx]\n\n\ndef generate_binary_at_k(y_scores, k):\n cutoff_index = int(len(y_scores) * (k / 100.0))\n predictions_binary = [(1 if x < cutoff_index else 0) for x in range(len\n (y_scores))]\n return predictions_binary\n\n\ndef precision_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n precision = precision_score(y_true_sorted, preds_at_k)\n return precision\n\n\ndef plot_precision_recall(val_Y, y_pred, model_name, output_type):\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n prec = prec[:-1]\n recall_curve = rec[:-1]\n pct_above_per_thresh = []\n number_scored = len(y_pred)\n for value in thresh:\n num_above_thresh = len(y_pred[y_pred >= value])\n pct_above_thresh = num_above_thresh / float(len(y_pred))\n if pct_above_thresh <= 1:\n pct_above_per_thresh.append(pct_above_thresh)\n else:\n raise Exception\n pct_above_per_thresh = np.array(pct_above_per_thresh)\n plt.clf()\n fig, ax1 = plt.subplots()\n ax1.plot(pct_above_per_thresh, prec, 'b')\n print('PLOTTING STUFF')\n print(pct_above_per_thresh)\n print(prec[:-1])\n ax1.set_xlabel('percent of population')\n ax1.set_ylabel('precision', color='b')\n ax2 = ax1.twinx()\n ax2.plot(pct_above_per_thresh, recall_curve, 'r')\n ax2.set_ylabel('recall', color='r')\n ax1.set_ylim([0, 1])\n ax2.set_xlim([0, 1])\n name = model_name\n plt.title(name)\n if output_type == 'save':\n plt.savefig(name)\n elif output_type == 'show':\n plt.show()\n pdb.set_trace()\n else:\n plt.show()\n pdb.set_trace()\n\n\n<function token>\n\n\ndef kfold_eval(df, target, features):\n models_params = {RandomForestClassifier: {'n_estimators': [100],\n 'criterion': ['gini', 'entropy'], 'max_features': ['sqrt', 'log2'],\n 'max_depth': [5, 10], 'n_jobs': [4], 'min_samples_leaf': [10, 50, \n 100]}, LogisticRegression: {'C': [10 ** -1, 10 ** -2, 10 ** -3],\n 'penalty': ['l1', 'l2']}, KNeighborsClassifier: {'n_neighbors': [5,\n 10, 25, 100], 'p': [1, 2, 3], 'n_jobs': [2]},\n DecisionTreeClassifier: {'max_depth': [5, 10, 15],\n 'min_samples_leaf': [2, 5, 10]}, GradientBoostingClassifier: {\n 'learning_rate': [0.1, 0.01], 'n_estimators': [100], 'max_features':\n ['sqrt', 'log2'], 'max_depth': [1, 2, 3]}, BaggingClassifier: {\n 'max_samples': [0.1, 0.25, 0.65], 'n_jobs': [4]}}\n X = df[features]\n y = df[target]\n print(y)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,\n random_state=0)\n \"\"\"\n kf = KFold(n_splits=2)\n kf.get_n_splits(X)\n #print(kf)\n KFold(n_splits=2,random_state=None,shuffle=False)\n for train_index, test_index in kf.split(X):\n print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n \"\"\"\n \"\"\"rf = RandomForestClassifier(n_estimators=100,criterion='gini',max_features='sqrt',max_depth=5)\n rf.fit(X_train, y_train)\n y_score = rf.predict_proba(X_test)\n #y_score = rf.decision_function(X_test)\n y_pred = rf.predict(X_test)\n print(roc_auc_score(y_test,y_score[:,0]))\n metrics_1 ={}\"\"\"\n class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params)\n print(accuracy_score(y_test, y_pred))\n\n\ndef extract_train_test_sets(train_start_time, train_end_time,\n test_start_time, test_end_time, df):\n train_set = df[(df['date_posted'] > train_start_time) & (df[\n 'date_posted'] < train_end_time)]\n test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted'\n ] < test_end_time)]\n return train_set, test_set\n\n\ndef class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params):\n out = open('out.txt', 'a')\n \"\"\"X_train = train_set[features] #X\n y_train = train_set[target] #y\n \n #validation\n X_test = test_set[features] #val_x\n y_test = test_set[target] #val_y\"\"\"\n metrics = {}\n for m, m_param in models_params.items():\n listofparam = get_combos(m_param)\n print('start training for {0}'.format(m))\n out.write('start training for {0}\\n'.format(m))\n for params in listofparam:\n print(params)\n out.write(json.dumps(params))\n model = m(**params)\n model.fit(X_train, y_train)\n y_pred = model.predict_proba(X_test)\n metrics[m] = get_metrics(y_pred[:, 1], y_test)\n print('this is valy')\n print(y_test)\n print('this is y_pred')\n print(y_pred)\n plot_precision_recall(y_test, y_pred[:, 1], model, 'show')\n out.write('----------------------------\\n')\n out.write('Using %s classifier \\n' % models_params)\n out.write(json.dumps(metrics[m]))\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n\n\ndef load_data(csv_file, nrows=None):\n return pd.read_csv(csv_file, nrows=nrows)\n\n\n<function token>\n\n\ndef histogram(data_frame):\n sns.distplot(data_frame)\n plt.show()\n\n\n<function token>\n\n\ndef cor_heat(data_frame, var_name):\n corrmat = data_frame.corr()\n k = 12\n cols = corrmat.nlargest(k, var_name)[var_name].index\n cm = np.corrcoef(data_frame[cols].values.T)\n sns.set(font_scale=1.25)\n hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f',\n annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.\n values)\n plt.show()\n\n\ndef plotCorr(dataFrame, list):\n sns.set()\n sns.pairplot(dataFrame[list], size=2.5)\n return plt.show()\n\n\ndef miss_data(data_frame):\n total = data_frame.isnull().sum().sort_values(ascending=False)\n percent = (data_frame.isnull().sum() / data_frame.isnull().count()\n ).sort_values(ascending=False)\n missing_data = pd.concat([total, percent], axis=1, keys=['Total',\n 'Percent'])\n return missing_data\n\n\n<function token>\n\n\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,\n np.newaxis])\n low_range = data_scaled[data_scaled[:, 0].argsort()][:10]\n high_range = data_scaled[data_scaled[:, 0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n\n<function token>\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\ndef fill_empty(data_frame, var, new_var):\n return data_frame[var].fillna(new_var)\n\n\ndef descretize(data_frame, var, num):\n return pd.cut(data_frame[var], num, retbins=True)\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\n<function token>\n\n\ndef logReg(data_frame, IV, var_list):\n if '-' in var_list[0]:\n formula = IV + '~' + 'Q(\"' + var_list[0] + '\")'\n else:\n formula = IV + '~' + var_list[0]\n for i in range(1, len(var_list)):\n if '-' in var_list[i]:\n formula = formula + '+' + 'Q(\"' + var_list[i] + '\")'\n else:\n formula = formula + '+' + var_list[i]\n y, X = dmatrices(formula, data_frame, return_type='dataframe')\n y = np.ravel(y)\n model = LogisticRegression()\n model = model.fit(X, y)\n print(pd.DataFrame(list(zip(X.columns, np.transpose(model.coef_)))))\n return model.score(X, y)\n\n\ndef knearest(data_frame, train, test):\n X = data_frame[train].reshape(-1, 1)\n Y = data_frame[test].reshape(-1, 1)\n X_train = X[:100]\n Y_train = Y[:100]\n X_validate = X[100:]\n Y_validate = Y[100:]\n neighbor = KNeighborsClassifier(n_neighbors=2, weights='uniform')\n neighbor.fit(X_train, Y_train)\n predicted = neighbor.predict(X_validate)\n print(predicted)\n\n\ndef merging_data(dataframe_1, dataframe_2):\n return pd.merge(dataframe_1, dataframe_2)\n\n\ndef merging_data2(dataframe_1, dataframe_2):\n dataframe_1['fully_funded'] = 1\n return dataframe_1\n\n\n<function token>\n\n\ndef to_binary(df, array_col):\n for i in array_col:\n print(i)\n df[i] = df[i].apply(lambda x: 1 if x == 't' else 0)\n return df\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\ndef recall_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n recall = recall_score(y_true_sorted, preds_at_k)\n return recall\n\n\ndef joint_sort_descending(l1, l2):\n idx = np.argsort(l1)[::-1]\n return l1[idx], l2[idx]\n\n\ndef generate_binary_at_k(y_scores, k):\n cutoff_index = int(len(y_scores) * (k / 100.0))\n predictions_binary = [(1 if x < cutoff_index else 0) for x in range(len\n (y_scores))]\n return predictions_binary\n\n\ndef precision_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n precision = precision_score(y_true_sorted, preds_at_k)\n return precision\n\n\ndef plot_precision_recall(val_Y, y_pred, model_name, output_type):\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n prec = prec[:-1]\n recall_curve = rec[:-1]\n pct_above_per_thresh = []\n number_scored = len(y_pred)\n for value in thresh:\n num_above_thresh = len(y_pred[y_pred >= value])\n pct_above_thresh = num_above_thresh / float(len(y_pred))\n if pct_above_thresh <= 1:\n pct_above_per_thresh.append(pct_above_thresh)\n else:\n raise Exception\n pct_above_per_thresh = np.array(pct_above_per_thresh)\n plt.clf()\n fig, ax1 = plt.subplots()\n ax1.plot(pct_above_per_thresh, prec, 'b')\n print('PLOTTING STUFF')\n print(pct_above_per_thresh)\n print(prec[:-1])\n ax1.set_xlabel('percent of population')\n ax1.set_ylabel('precision', color='b')\n ax2 = ax1.twinx()\n ax2.plot(pct_above_per_thresh, recall_curve, 'r')\n ax2.set_ylabel('recall', color='r')\n ax1.set_ylim([0, 1])\n ax2.set_xlim([0, 1])\n name = model_name\n plt.title(name)\n if output_type == 'save':\n plt.savefig(name)\n elif output_type == 'show':\n plt.show()\n pdb.set_trace()\n else:\n plt.show()\n pdb.set_trace()\n\n\n<function token>\n\n\ndef kfold_eval(df, target, features):\n models_params = {RandomForestClassifier: {'n_estimators': [100],\n 'criterion': ['gini', 'entropy'], 'max_features': ['sqrt', 'log2'],\n 'max_depth': [5, 10], 'n_jobs': [4], 'min_samples_leaf': [10, 50, \n 100]}, LogisticRegression: {'C': [10 ** -1, 10 ** -2, 10 ** -3],\n 'penalty': ['l1', 'l2']}, KNeighborsClassifier: {'n_neighbors': [5,\n 10, 25, 100], 'p': [1, 2, 3], 'n_jobs': [2]},\n DecisionTreeClassifier: {'max_depth': [5, 10, 15],\n 'min_samples_leaf': [2, 5, 10]}, GradientBoostingClassifier: {\n 'learning_rate': [0.1, 0.01], 'n_estimators': [100], 'max_features':\n ['sqrt', 'log2'], 'max_depth': [1, 2, 3]}, BaggingClassifier: {\n 'max_samples': [0.1, 0.25, 0.65], 'n_jobs': [4]}}\n X = df[features]\n y = df[target]\n print(y)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,\n random_state=0)\n \"\"\"\n kf = KFold(n_splits=2)\n kf.get_n_splits(X)\n #print(kf)\n KFold(n_splits=2,random_state=None,shuffle=False)\n for train_index, test_index in kf.split(X):\n print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n \"\"\"\n \"\"\"rf = RandomForestClassifier(n_estimators=100,criterion='gini',max_features='sqrt',max_depth=5)\n rf.fit(X_train, y_train)\n y_score = rf.predict_proba(X_test)\n #y_score = rf.decision_function(X_test)\n y_pred = rf.predict(X_test)\n print(roc_auc_score(y_test,y_score[:,0]))\n metrics_1 ={}\"\"\"\n class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params)\n print(accuracy_score(y_test, y_pred))\n\n\ndef extract_train_test_sets(train_start_time, train_end_time,\n test_start_time, test_end_time, df):\n train_set = df[(df['date_posted'] > train_start_time) & (df[\n 'date_posted'] < train_end_time)]\n test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted'\n ] < test_end_time)]\n return train_set, test_set\n\n\ndef class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params):\n out = open('out.txt', 'a')\n \"\"\"X_train = train_set[features] #X\n y_train = train_set[target] #y\n \n #validation\n X_test = test_set[features] #val_x\n y_test = test_set[target] #val_y\"\"\"\n metrics = {}\n for m, m_param in models_params.items():\n listofparam = get_combos(m_param)\n print('start training for {0}'.format(m))\n out.write('start training for {0}\\n'.format(m))\n for params in listofparam:\n print(params)\n out.write(json.dumps(params))\n model = m(**params)\n model.fit(X_train, y_train)\n y_pred = model.predict_proba(X_test)\n metrics[m] = get_metrics(y_pred[:, 1], y_test)\n print('this is valy')\n print(y_test)\n print('this is y_pred')\n print(y_pred)\n plot_precision_recall(y_test, y_pred[:, 1], model, 'show')\n out.write('----------------------------\\n')\n out.write('Using %s classifier \\n' % models_params)\n out.write(json.dumps(metrics[m]))\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n\n\ndef load_data(csv_file, nrows=None):\n return pd.read_csv(csv_file, nrows=nrows)\n\n\n<function token>\n\n\ndef histogram(data_frame):\n sns.distplot(data_frame)\n plt.show()\n\n\n<function token>\n\n\ndef cor_heat(data_frame, var_name):\n corrmat = data_frame.corr()\n k = 12\n cols = corrmat.nlargest(k, var_name)[var_name].index\n cm = np.corrcoef(data_frame[cols].values.T)\n sns.set(font_scale=1.25)\n hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f',\n annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.\n values)\n plt.show()\n\n\ndef plotCorr(dataFrame, list):\n sns.set()\n sns.pairplot(dataFrame[list], size=2.5)\n return plt.show()\n\n\ndef miss_data(data_frame):\n total = data_frame.isnull().sum().sort_values(ascending=False)\n percent = (data_frame.isnull().sum() / data_frame.isnull().count()\n ).sort_values(ascending=False)\n missing_data = pd.concat([total, percent], axis=1, keys=['Total',\n 'Percent'])\n return missing_data\n\n\n<function token>\n\n\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,\n np.newaxis])\n low_range = data_scaled[data_scaled[:, 0].argsort()][:10]\n high_range = data_scaled[data_scaled[:, 0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n\n<function token>\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\ndef fill_empty(data_frame, var, new_var):\n return data_frame[var].fillna(new_var)\n\n\ndef descretize(data_frame, var, num):\n return pd.cut(data_frame[var], num, retbins=True)\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\n<function token>\n\n\ndef logReg(data_frame, IV, var_list):\n if '-' in var_list[0]:\n formula = IV + '~' + 'Q(\"' + var_list[0] + '\")'\n else:\n formula = IV + '~' + var_list[0]\n for i in range(1, len(var_list)):\n if '-' in var_list[i]:\n formula = formula + '+' + 'Q(\"' + var_list[i] + '\")'\n else:\n formula = formula + '+' + var_list[i]\n y, X = dmatrices(formula, data_frame, return_type='dataframe')\n y = np.ravel(y)\n model = LogisticRegression()\n model = model.fit(X, y)\n print(pd.DataFrame(list(zip(X.columns, np.transpose(model.coef_)))))\n return model.score(X, y)\n\n\ndef knearest(data_frame, train, test):\n X = data_frame[train].reshape(-1, 1)\n Y = data_frame[test].reshape(-1, 1)\n X_train = X[:100]\n Y_train = Y[:100]\n X_validate = X[100:]\n Y_validate = Y[100:]\n neighbor = KNeighborsClassifier(n_neighbors=2, weights='uniform')\n neighbor.fit(X_train, Y_train)\n predicted = neighbor.predict(X_validate)\n print(predicted)\n\n\ndef merging_data(dataframe_1, dataframe_2):\n return pd.merge(dataframe_1, dataframe_2)\n\n\n<function token>\n<function token>\n\n\ndef to_binary(df, array_col):\n for i in array_col:\n print(i)\n df[i] = df[i].apply(lambda x: 1 if x == 't' else 0)\n return df\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\ndef recall_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n recall = recall_score(y_true_sorted, preds_at_k)\n return recall\n\n\ndef joint_sort_descending(l1, l2):\n idx = np.argsort(l1)[::-1]\n return l1[idx], l2[idx]\n\n\ndef generate_binary_at_k(y_scores, k):\n cutoff_index = int(len(y_scores) * (k / 100.0))\n predictions_binary = [(1 if x < cutoff_index else 0) for x in range(len\n (y_scores))]\n return predictions_binary\n\n\ndef precision_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n precision = precision_score(y_true_sorted, preds_at_k)\n return precision\n\n\ndef plot_precision_recall(val_Y, y_pred, model_name, output_type):\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n prec = prec[:-1]\n recall_curve = rec[:-1]\n pct_above_per_thresh = []\n number_scored = len(y_pred)\n for value in thresh:\n num_above_thresh = len(y_pred[y_pred >= value])\n pct_above_thresh = num_above_thresh / float(len(y_pred))\n if pct_above_thresh <= 1:\n pct_above_per_thresh.append(pct_above_thresh)\n else:\n raise Exception\n pct_above_per_thresh = np.array(pct_above_per_thresh)\n plt.clf()\n fig, ax1 = plt.subplots()\n ax1.plot(pct_above_per_thresh, prec, 'b')\n print('PLOTTING STUFF')\n print(pct_above_per_thresh)\n print(prec[:-1])\n ax1.set_xlabel('percent of population')\n ax1.set_ylabel('precision', color='b')\n ax2 = ax1.twinx()\n ax2.plot(pct_above_per_thresh, recall_curve, 'r')\n ax2.set_ylabel('recall', color='r')\n ax1.set_ylim([0, 1])\n ax2.set_xlim([0, 1])\n name = model_name\n plt.title(name)\n if output_type == 'save':\n plt.savefig(name)\n elif output_type == 'show':\n plt.show()\n pdb.set_trace()\n else:\n plt.show()\n pdb.set_trace()\n\n\n<function token>\n\n\ndef kfold_eval(df, target, features):\n models_params = {RandomForestClassifier: {'n_estimators': [100],\n 'criterion': ['gini', 'entropy'], 'max_features': ['sqrt', 'log2'],\n 'max_depth': [5, 10], 'n_jobs': [4], 'min_samples_leaf': [10, 50, \n 100]}, LogisticRegression: {'C': [10 ** -1, 10 ** -2, 10 ** -3],\n 'penalty': ['l1', 'l2']}, KNeighborsClassifier: {'n_neighbors': [5,\n 10, 25, 100], 'p': [1, 2, 3], 'n_jobs': [2]},\n DecisionTreeClassifier: {'max_depth': [5, 10, 15],\n 'min_samples_leaf': [2, 5, 10]}, GradientBoostingClassifier: {\n 'learning_rate': [0.1, 0.01], 'n_estimators': [100], 'max_features':\n ['sqrt', 'log2'], 'max_depth': [1, 2, 3]}, BaggingClassifier: {\n 'max_samples': [0.1, 0.25, 0.65], 'n_jobs': [4]}}\n X = df[features]\n y = df[target]\n print(y)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,\n random_state=0)\n \"\"\"\n kf = KFold(n_splits=2)\n kf.get_n_splits(X)\n #print(kf)\n KFold(n_splits=2,random_state=None,shuffle=False)\n for train_index, test_index in kf.split(X):\n print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n \"\"\"\n \"\"\"rf = RandomForestClassifier(n_estimators=100,criterion='gini',max_features='sqrt',max_depth=5)\n rf.fit(X_train, y_train)\n y_score = rf.predict_proba(X_test)\n #y_score = rf.decision_function(X_test)\n y_pred = rf.predict(X_test)\n print(roc_auc_score(y_test,y_score[:,0]))\n metrics_1 ={}\"\"\"\n class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params)\n print(accuracy_score(y_test, y_pred))\n\n\ndef extract_train_test_sets(train_start_time, train_end_time,\n test_start_time, test_end_time, df):\n train_set = df[(df['date_posted'] > train_start_time) & (df[\n 'date_posted'] < train_end_time)]\n test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted'\n ] < test_end_time)]\n return train_set, test_set\n\n\ndef class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params):\n out = open('out.txt', 'a')\n \"\"\"X_train = train_set[features] #X\n y_train = train_set[target] #y\n \n #validation\n X_test = test_set[features] #val_x\n y_test = test_set[target] #val_y\"\"\"\n metrics = {}\n for m, m_param in models_params.items():\n listofparam = get_combos(m_param)\n print('start training for {0}'.format(m))\n out.write('start training for {0}\\n'.format(m))\n for params in listofparam:\n print(params)\n out.write(json.dumps(params))\n model = m(**params)\n model.fit(X_train, y_train)\n y_pred = model.predict_proba(X_test)\n metrics[m] = get_metrics(y_pred[:, 1], y_test)\n print('this is valy')\n print(y_test)\n print('this is y_pred')\n print(y_pred)\n plot_precision_recall(y_test, y_pred[:, 1], model, 'show')\n out.write('----------------------------\\n')\n out.write('Using %s classifier \\n' % models_params)\n out.write(json.dumps(metrics[m]))\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n\n\ndef load_data(csv_file, nrows=None):\n return pd.read_csv(csv_file, nrows=nrows)\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef cor_heat(data_frame, var_name):\n corrmat = data_frame.corr()\n k = 12\n cols = corrmat.nlargest(k, var_name)[var_name].index\n cm = np.corrcoef(data_frame[cols].values.T)\n sns.set(font_scale=1.25)\n hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f',\n annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.\n values)\n plt.show()\n\n\ndef plotCorr(dataFrame, list):\n sns.set()\n sns.pairplot(dataFrame[list], size=2.5)\n return plt.show()\n\n\ndef miss_data(data_frame):\n total = data_frame.isnull().sum().sort_values(ascending=False)\n percent = (data_frame.isnull().sum() / data_frame.isnull().count()\n ).sort_values(ascending=False)\n missing_data = pd.concat([total, percent], axis=1, keys=['Total',\n 'Percent'])\n return missing_data\n\n\n<function token>\n\n\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,\n np.newaxis])\n low_range = data_scaled[data_scaled[:, 0].argsort()][:10]\n high_range = data_scaled[data_scaled[:, 0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n\n<function token>\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\ndef fill_empty(data_frame, var, new_var):\n return data_frame[var].fillna(new_var)\n\n\ndef descretize(data_frame, var, num):\n return pd.cut(data_frame[var], num, retbins=True)\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\n<function token>\n\n\ndef logReg(data_frame, IV, var_list):\n if '-' in var_list[0]:\n formula = IV + '~' + 'Q(\"' + var_list[0] + '\")'\n else:\n formula = IV + '~' + var_list[0]\n for i in range(1, len(var_list)):\n if '-' in var_list[i]:\n formula = formula + '+' + 'Q(\"' + var_list[i] + '\")'\n else:\n formula = formula + '+' + var_list[i]\n y, X = dmatrices(formula, data_frame, return_type='dataframe')\n y = np.ravel(y)\n model = LogisticRegression()\n model = model.fit(X, y)\n print(pd.DataFrame(list(zip(X.columns, np.transpose(model.coef_)))))\n return model.score(X, y)\n\n\ndef knearest(data_frame, train, test):\n X = data_frame[train].reshape(-1, 1)\n Y = data_frame[test].reshape(-1, 1)\n X_train = X[:100]\n Y_train = Y[:100]\n X_validate = X[100:]\n Y_validate = Y[100:]\n neighbor = KNeighborsClassifier(n_neighbors=2, weights='uniform')\n neighbor.fit(X_train, Y_train)\n predicted = neighbor.predict(X_validate)\n print(predicted)\n\n\ndef merging_data(dataframe_1, dataframe_2):\n return pd.merge(dataframe_1, dataframe_2)\n\n\n<function token>\n<function token>\n\n\ndef to_binary(df, array_col):\n for i in array_col:\n print(i)\n df[i] = df[i].apply(lambda x: 1 if x == 't' else 0)\n return df\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\ndef recall_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n recall = recall_score(y_true_sorted, preds_at_k)\n return recall\n\n\ndef joint_sort_descending(l1, l2):\n idx = np.argsort(l1)[::-1]\n return l1[idx], l2[idx]\n\n\ndef generate_binary_at_k(y_scores, k):\n cutoff_index = int(len(y_scores) * (k / 100.0))\n predictions_binary = [(1 if x < cutoff_index else 0) for x in range(len\n (y_scores))]\n return predictions_binary\n\n\ndef precision_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n precision = precision_score(y_true_sorted, preds_at_k)\n return precision\n\n\ndef plot_precision_recall(val_Y, y_pred, model_name, output_type):\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n prec = prec[:-1]\n recall_curve = rec[:-1]\n pct_above_per_thresh = []\n number_scored = len(y_pred)\n for value in thresh:\n num_above_thresh = len(y_pred[y_pred >= value])\n pct_above_thresh = num_above_thresh / float(len(y_pred))\n if pct_above_thresh <= 1:\n pct_above_per_thresh.append(pct_above_thresh)\n else:\n raise Exception\n pct_above_per_thresh = np.array(pct_above_per_thresh)\n plt.clf()\n fig, ax1 = plt.subplots()\n ax1.plot(pct_above_per_thresh, prec, 'b')\n print('PLOTTING STUFF')\n print(pct_above_per_thresh)\n print(prec[:-1])\n ax1.set_xlabel('percent of population')\n ax1.set_ylabel('precision', color='b')\n ax2 = ax1.twinx()\n ax2.plot(pct_above_per_thresh, recall_curve, 'r')\n ax2.set_ylabel('recall', color='r')\n ax1.set_ylim([0, 1])\n ax2.set_xlim([0, 1])\n name = model_name\n plt.title(name)\n if output_type == 'save':\n plt.savefig(name)\n elif output_type == 'show':\n plt.show()\n pdb.set_trace()\n else:\n plt.show()\n pdb.set_trace()\n\n\n<function token>\n\n\ndef kfold_eval(df, target, features):\n models_params = {RandomForestClassifier: {'n_estimators': [100],\n 'criterion': ['gini', 'entropy'], 'max_features': ['sqrt', 'log2'],\n 'max_depth': [5, 10], 'n_jobs': [4], 'min_samples_leaf': [10, 50, \n 100]}, LogisticRegression: {'C': [10 ** -1, 10 ** -2, 10 ** -3],\n 'penalty': ['l1', 'l2']}, KNeighborsClassifier: {'n_neighbors': [5,\n 10, 25, 100], 'p': [1, 2, 3], 'n_jobs': [2]},\n DecisionTreeClassifier: {'max_depth': [5, 10, 15],\n 'min_samples_leaf': [2, 5, 10]}, GradientBoostingClassifier: {\n 'learning_rate': [0.1, 0.01], 'n_estimators': [100], 'max_features':\n ['sqrt', 'log2'], 'max_depth': [1, 2, 3]}, BaggingClassifier: {\n 'max_samples': [0.1, 0.25, 0.65], 'n_jobs': [4]}}\n X = df[features]\n y = df[target]\n print(y)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,\n random_state=0)\n \"\"\"\n kf = KFold(n_splits=2)\n kf.get_n_splits(X)\n #print(kf)\n KFold(n_splits=2,random_state=None,shuffle=False)\n for train_index, test_index in kf.split(X):\n print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n \"\"\"\n \"\"\"rf = RandomForestClassifier(n_estimators=100,criterion='gini',max_features='sqrt',max_depth=5)\n rf.fit(X_train, y_train)\n y_score = rf.predict_proba(X_test)\n #y_score = rf.decision_function(X_test)\n y_pred = rf.predict(X_test)\n print(roc_auc_score(y_test,y_score[:,0]))\n metrics_1 ={}\"\"\"\n class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params)\n print(accuracy_score(y_test, y_pred))\n\n\ndef extract_train_test_sets(train_start_time, train_end_time,\n test_start_time, test_end_time, df):\n train_set = df[(df['date_posted'] > train_start_time) & (df[\n 'date_posted'] < train_end_time)]\n test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted'\n ] < test_end_time)]\n return train_set, test_set\n\n\ndef class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params):\n out = open('out.txt', 'a')\n \"\"\"X_train = train_set[features] #X\n y_train = train_set[target] #y\n \n #validation\n X_test = test_set[features] #val_x\n y_test = test_set[target] #val_y\"\"\"\n metrics = {}\n for m, m_param in models_params.items():\n listofparam = get_combos(m_param)\n print('start training for {0}'.format(m))\n out.write('start training for {0}\\n'.format(m))\n for params in listofparam:\n print(params)\n out.write(json.dumps(params))\n model = m(**params)\n model.fit(X_train, y_train)\n y_pred = model.predict_proba(X_test)\n metrics[m] = get_metrics(y_pred[:, 1], y_test)\n print('this is valy')\n print(y_test)\n print('this is y_pred')\n print(y_pred)\n plot_precision_recall(y_test, y_pred[:, 1], model, 'show')\n out.write('----------------------------\\n')\n out.write('Using %s classifier \\n' % models_params)\n out.write(json.dumps(metrics[m]))\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n\n\ndef load_data(csv_file, nrows=None):\n return pd.read_csv(csv_file, nrows=nrows)\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef cor_heat(data_frame, var_name):\n corrmat = data_frame.corr()\n k = 12\n cols = corrmat.nlargest(k, var_name)[var_name].index\n cm = np.corrcoef(data_frame[cols].values.T)\n sns.set(font_scale=1.25)\n hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f',\n annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.\n values)\n plt.show()\n\n\ndef plotCorr(dataFrame, list):\n sns.set()\n sns.pairplot(dataFrame[list], size=2.5)\n return plt.show()\n\n\n<function token>\n<function token>\n\n\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,\n np.newaxis])\n low_range = data_scaled[data_scaled[:, 0].argsort()][:10]\n high_range = data_scaled[data_scaled[:, 0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n\n<function token>\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\ndef fill_empty(data_frame, var, new_var):\n return data_frame[var].fillna(new_var)\n\n\ndef descretize(data_frame, var, num):\n return pd.cut(data_frame[var], num, retbins=True)\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\n<function token>\n\n\ndef logReg(data_frame, IV, var_list):\n if '-' in var_list[0]:\n formula = IV + '~' + 'Q(\"' + var_list[0] + '\")'\n else:\n formula = IV + '~' + var_list[0]\n for i in range(1, len(var_list)):\n if '-' in var_list[i]:\n formula = formula + '+' + 'Q(\"' + var_list[i] + '\")'\n else:\n formula = formula + '+' + var_list[i]\n y, X = dmatrices(formula, data_frame, return_type='dataframe')\n y = np.ravel(y)\n model = LogisticRegression()\n model = model.fit(X, y)\n print(pd.DataFrame(list(zip(X.columns, np.transpose(model.coef_)))))\n return model.score(X, y)\n\n\ndef knearest(data_frame, train, test):\n X = data_frame[train].reshape(-1, 1)\n Y = data_frame[test].reshape(-1, 1)\n X_train = X[:100]\n Y_train = Y[:100]\n X_validate = X[100:]\n Y_validate = Y[100:]\n neighbor = KNeighborsClassifier(n_neighbors=2, weights='uniform')\n neighbor.fit(X_train, Y_train)\n predicted = neighbor.predict(X_validate)\n print(predicted)\n\n\ndef merging_data(dataframe_1, dataframe_2):\n return pd.merge(dataframe_1, dataframe_2)\n\n\n<function token>\n<function token>\n\n\ndef to_binary(df, array_col):\n for i in array_col:\n print(i)\n df[i] = df[i].apply(lambda x: 1 if x == 't' else 0)\n return df\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\ndef recall_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n recall = recall_score(y_true_sorted, preds_at_k)\n return recall\n\n\ndef joint_sort_descending(l1, l2):\n idx = np.argsort(l1)[::-1]\n return l1[idx], l2[idx]\n\n\ndef generate_binary_at_k(y_scores, k):\n cutoff_index = int(len(y_scores) * (k / 100.0))\n predictions_binary = [(1 if x < cutoff_index else 0) for x in range(len\n (y_scores))]\n return predictions_binary\n\n\ndef precision_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n precision = precision_score(y_true_sorted, preds_at_k)\n return precision\n\n\ndef plot_precision_recall(val_Y, y_pred, model_name, output_type):\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n prec = prec[:-1]\n recall_curve = rec[:-1]\n pct_above_per_thresh = []\n number_scored = len(y_pred)\n for value in thresh:\n num_above_thresh = len(y_pred[y_pred >= value])\n pct_above_thresh = num_above_thresh / float(len(y_pred))\n if pct_above_thresh <= 1:\n pct_above_per_thresh.append(pct_above_thresh)\n else:\n raise Exception\n pct_above_per_thresh = np.array(pct_above_per_thresh)\n plt.clf()\n fig, ax1 = plt.subplots()\n ax1.plot(pct_above_per_thresh, prec, 'b')\n print('PLOTTING STUFF')\n print(pct_above_per_thresh)\n print(prec[:-1])\n ax1.set_xlabel('percent of population')\n ax1.set_ylabel('precision', color='b')\n ax2 = ax1.twinx()\n ax2.plot(pct_above_per_thresh, recall_curve, 'r')\n ax2.set_ylabel('recall', color='r')\n ax1.set_ylim([0, 1])\n ax2.set_xlim([0, 1])\n name = model_name\n plt.title(name)\n if output_type == 'save':\n plt.savefig(name)\n elif output_type == 'show':\n plt.show()\n pdb.set_trace()\n else:\n plt.show()\n pdb.set_trace()\n\n\n<function token>\n\n\ndef kfold_eval(df, target, features):\n models_params = {RandomForestClassifier: {'n_estimators': [100],\n 'criterion': ['gini', 'entropy'], 'max_features': ['sqrt', 'log2'],\n 'max_depth': [5, 10], 'n_jobs': [4], 'min_samples_leaf': [10, 50, \n 100]}, LogisticRegression: {'C': [10 ** -1, 10 ** -2, 10 ** -3],\n 'penalty': ['l1', 'l2']}, KNeighborsClassifier: {'n_neighbors': [5,\n 10, 25, 100], 'p': [1, 2, 3], 'n_jobs': [2]},\n DecisionTreeClassifier: {'max_depth': [5, 10, 15],\n 'min_samples_leaf': [2, 5, 10]}, GradientBoostingClassifier: {\n 'learning_rate': [0.1, 0.01], 'n_estimators': [100], 'max_features':\n ['sqrt', 'log2'], 'max_depth': [1, 2, 3]}, BaggingClassifier: {\n 'max_samples': [0.1, 0.25, 0.65], 'n_jobs': [4]}}\n X = df[features]\n y = df[target]\n print(y)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,\n random_state=0)\n \"\"\"\n kf = KFold(n_splits=2)\n kf.get_n_splits(X)\n #print(kf)\n KFold(n_splits=2,random_state=None,shuffle=False)\n for train_index, test_index in kf.split(X):\n print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n \"\"\"\n \"\"\"rf = RandomForestClassifier(n_estimators=100,criterion='gini',max_features='sqrt',max_depth=5)\n rf.fit(X_train, y_train)\n y_score = rf.predict_proba(X_test)\n #y_score = rf.decision_function(X_test)\n y_pred = rf.predict(X_test)\n print(roc_auc_score(y_test,y_score[:,0]))\n metrics_1 ={}\"\"\"\n class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params)\n print(accuracy_score(y_test, y_pred))\n\n\ndef extract_train_test_sets(train_start_time, train_end_time,\n test_start_time, test_end_time, df):\n train_set = df[(df['date_posted'] > train_start_time) & (df[\n 'date_posted'] < train_end_time)]\n test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted'\n ] < test_end_time)]\n return train_set, test_set\n\n\ndef class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params):\n out = open('out.txt', 'a')\n \"\"\"X_train = train_set[features] #X\n y_train = train_set[target] #y\n \n #validation\n X_test = test_set[features] #val_x\n y_test = test_set[target] #val_y\"\"\"\n metrics = {}\n for m, m_param in models_params.items():\n listofparam = get_combos(m_param)\n print('start training for {0}'.format(m))\n out.write('start training for {0}\\n'.format(m))\n for params in listofparam:\n print(params)\n out.write(json.dumps(params))\n model = m(**params)\n model.fit(X_train, y_train)\n y_pred = model.predict_proba(X_test)\n metrics[m] = get_metrics(y_pred[:, 1], y_test)\n print('this is valy')\n print(y_test)\n print('this is y_pred')\n print(y_pred)\n plot_precision_recall(y_test, y_pred[:, 1], model, 'show')\n out.write('----------------------------\\n')\n out.write('Using %s classifier \\n' % models_params)\n out.write(json.dumps(metrics[m]))\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n\n\ndef load_data(csv_file, nrows=None):\n return pd.read_csv(csv_file, nrows=nrows)\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef cor_heat(data_frame, var_name):\n corrmat = data_frame.corr()\n k = 12\n cols = corrmat.nlargest(k, var_name)[var_name].index\n cm = np.corrcoef(data_frame[cols].values.T)\n sns.set(font_scale=1.25)\n hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f',\n annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.\n values)\n plt.show()\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,\n np.newaxis])\n low_range = data_scaled[data_scaled[:, 0].argsort()][:10]\n high_range = data_scaled[data_scaled[:, 0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n\n<function token>\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\ndef fill_empty(data_frame, var, new_var):\n return data_frame[var].fillna(new_var)\n\n\ndef descretize(data_frame, var, num):\n return pd.cut(data_frame[var], num, retbins=True)\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\n<function token>\n\n\ndef logReg(data_frame, IV, var_list):\n if '-' in var_list[0]:\n formula = IV + '~' + 'Q(\"' + var_list[0] + '\")'\n else:\n formula = IV + '~' + var_list[0]\n for i in range(1, len(var_list)):\n if '-' in var_list[i]:\n formula = formula + '+' + 'Q(\"' + var_list[i] + '\")'\n else:\n formula = formula + '+' + var_list[i]\n y, X = dmatrices(formula, data_frame, return_type='dataframe')\n y = np.ravel(y)\n model = LogisticRegression()\n model = model.fit(X, y)\n print(pd.DataFrame(list(zip(X.columns, np.transpose(model.coef_)))))\n return model.score(X, y)\n\n\ndef knearest(data_frame, train, test):\n X = data_frame[train].reshape(-1, 1)\n Y = data_frame[test].reshape(-1, 1)\n X_train = X[:100]\n Y_train = Y[:100]\n X_validate = X[100:]\n Y_validate = Y[100:]\n neighbor = KNeighborsClassifier(n_neighbors=2, weights='uniform')\n neighbor.fit(X_train, Y_train)\n predicted = neighbor.predict(X_validate)\n print(predicted)\n\n\ndef merging_data(dataframe_1, dataframe_2):\n return pd.merge(dataframe_1, dataframe_2)\n\n\n<function token>\n<function token>\n\n\ndef to_binary(df, array_col):\n for i in array_col:\n print(i)\n df[i] = df[i].apply(lambda x: 1 if x == 't' else 0)\n return df\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\ndef recall_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n recall = recall_score(y_true_sorted, preds_at_k)\n return recall\n\n\ndef joint_sort_descending(l1, l2):\n idx = np.argsort(l1)[::-1]\n return l1[idx], l2[idx]\n\n\ndef generate_binary_at_k(y_scores, k):\n cutoff_index = int(len(y_scores) * (k / 100.0))\n predictions_binary = [(1 if x < cutoff_index else 0) for x in range(len\n (y_scores))]\n return predictions_binary\n\n\ndef precision_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n precision = precision_score(y_true_sorted, preds_at_k)\n return precision\n\n\ndef plot_precision_recall(val_Y, y_pred, model_name, output_type):\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n prec = prec[:-1]\n recall_curve = rec[:-1]\n pct_above_per_thresh = []\n number_scored = len(y_pred)\n for value in thresh:\n num_above_thresh = len(y_pred[y_pred >= value])\n pct_above_thresh = num_above_thresh / float(len(y_pred))\n if pct_above_thresh <= 1:\n pct_above_per_thresh.append(pct_above_thresh)\n else:\n raise Exception\n pct_above_per_thresh = np.array(pct_above_per_thresh)\n plt.clf()\n fig, ax1 = plt.subplots()\n ax1.plot(pct_above_per_thresh, prec, 'b')\n print('PLOTTING STUFF')\n print(pct_above_per_thresh)\n print(prec[:-1])\n ax1.set_xlabel('percent of population')\n ax1.set_ylabel('precision', color='b')\n ax2 = ax1.twinx()\n ax2.plot(pct_above_per_thresh, recall_curve, 'r')\n ax2.set_ylabel('recall', color='r')\n ax1.set_ylim([0, 1])\n ax2.set_xlim([0, 1])\n name = model_name\n plt.title(name)\n if output_type == 'save':\n plt.savefig(name)\n elif output_type == 'show':\n plt.show()\n pdb.set_trace()\n else:\n plt.show()\n pdb.set_trace()\n\n\n<function token>\n\n\ndef kfold_eval(df, target, features):\n models_params = {RandomForestClassifier: {'n_estimators': [100],\n 'criterion': ['gini', 'entropy'], 'max_features': ['sqrt', 'log2'],\n 'max_depth': [5, 10], 'n_jobs': [4], 'min_samples_leaf': [10, 50, \n 100]}, LogisticRegression: {'C': [10 ** -1, 10 ** -2, 10 ** -3],\n 'penalty': ['l1', 'l2']}, KNeighborsClassifier: {'n_neighbors': [5,\n 10, 25, 100], 'p': [1, 2, 3], 'n_jobs': [2]},\n DecisionTreeClassifier: {'max_depth': [5, 10, 15],\n 'min_samples_leaf': [2, 5, 10]}, GradientBoostingClassifier: {\n 'learning_rate': [0.1, 0.01], 'n_estimators': [100], 'max_features':\n ['sqrt', 'log2'], 'max_depth': [1, 2, 3]}, BaggingClassifier: {\n 'max_samples': [0.1, 0.25, 0.65], 'n_jobs': [4]}}\n X = df[features]\n y = df[target]\n print(y)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,\n random_state=0)\n \"\"\"\n kf = KFold(n_splits=2)\n kf.get_n_splits(X)\n #print(kf)\n KFold(n_splits=2,random_state=None,shuffle=False)\n for train_index, test_index in kf.split(X):\n print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n \"\"\"\n \"\"\"rf = RandomForestClassifier(n_estimators=100,criterion='gini',max_features='sqrt',max_depth=5)\n rf.fit(X_train, y_train)\n y_score = rf.predict_proba(X_test)\n #y_score = rf.decision_function(X_test)\n y_pred = rf.predict(X_test)\n print(roc_auc_score(y_test,y_score[:,0]))\n metrics_1 ={}\"\"\"\n class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params)\n print(accuracy_score(y_test, y_pred))\n\n\ndef extract_train_test_sets(train_start_time, train_end_time,\n test_start_time, test_end_time, df):\n train_set = df[(df['date_posted'] > train_start_time) & (df[\n 'date_posted'] < train_end_time)]\n test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted'\n ] < test_end_time)]\n return train_set, test_set\n\n\ndef class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params):\n out = open('out.txt', 'a')\n \"\"\"X_train = train_set[features] #X\n y_train = train_set[target] #y\n \n #validation\n X_test = test_set[features] #val_x\n y_test = test_set[target] #val_y\"\"\"\n metrics = {}\n for m, m_param in models_params.items():\n listofparam = get_combos(m_param)\n print('start training for {0}'.format(m))\n out.write('start training for {0}\\n'.format(m))\n for params in listofparam:\n print(params)\n out.write(json.dumps(params))\n model = m(**params)\n model.fit(X_train, y_train)\n y_pred = model.predict_proba(X_test)\n metrics[m] = get_metrics(y_pred[:, 1], y_test)\n print('this is valy')\n print(y_test)\n print('this is y_pred')\n print(y_pred)\n plot_precision_recall(y_test, y_pred[:, 1], model, 'show')\n out.write('----------------------------\\n')\n out.write('Using %s classifier \\n' % models_params)\n out.write(json.dumps(metrics[m]))\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n\n\ndef load_data(csv_file, nrows=None):\n return pd.read_csv(csv_file, nrows=nrows)\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef cor_heat(data_frame, var_name):\n corrmat = data_frame.corr()\n k = 12\n cols = corrmat.nlargest(k, var_name)[var_name].index\n cm = np.corrcoef(data_frame[cols].values.T)\n sns.set(font_scale=1.25)\n hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f',\n annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.\n values)\n plt.show()\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,\n np.newaxis])\n low_range = data_scaled[data_scaled[:, 0].argsort()][:10]\n high_range = data_scaled[data_scaled[:, 0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n\n<function token>\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\ndef fill_empty(data_frame, var, new_var):\n return data_frame[var].fillna(new_var)\n\n\ndef descretize(data_frame, var, num):\n return pd.cut(data_frame[var], num, retbins=True)\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\n<function token>\n\n\ndef logReg(data_frame, IV, var_list):\n if '-' in var_list[0]:\n formula = IV + '~' + 'Q(\"' + var_list[0] + '\")'\n else:\n formula = IV + '~' + var_list[0]\n for i in range(1, len(var_list)):\n if '-' in var_list[i]:\n formula = formula + '+' + 'Q(\"' + var_list[i] + '\")'\n else:\n formula = formula + '+' + var_list[i]\n y, X = dmatrices(formula, data_frame, return_type='dataframe')\n y = np.ravel(y)\n model = LogisticRegression()\n model = model.fit(X, y)\n print(pd.DataFrame(list(zip(X.columns, np.transpose(model.coef_)))))\n return model.score(X, y)\n\n\ndef knearest(data_frame, train, test):\n X = data_frame[train].reshape(-1, 1)\n Y = data_frame[test].reshape(-1, 1)\n X_train = X[:100]\n Y_train = Y[:100]\n X_validate = X[100:]\n Y_validate = Y[100:]\n neighbor = KNeighborsClassifier(n_neighbors=2, weights='uniform')\n neighbor.fit(X_train, Y_train)\n predicted = neighbor.predict(X_validate)\n print(predicted)\n\n\ndef merging_data(dataframe_1, dataframe_2):\n return pd.merge(dataframe_1, dataframe_2)\n\n\n<function token>\n<function token>\n\n\ndef to_binary(df, array_col):\n for i in array_col:\n print(i)\n df[i] = df[i].apply(lambda x: 1 if x == 't' else 0)\n return df\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\ndef recall_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n recall = recall_score(y_true_sorted, preds_at_k)\n return recall\n\n\ndef joint_sort_descending(l1, l2):\n idx = np.argsort(l1)[::-1]\n return l1[idx], l2[idx]\n\n\ndef generate_binary_at_k(y_scores, k):\n cutoff_index = int(len(y_scores) * (k / 100.0))\n predictions_binary = [(1 if x < cutoff_index else 0) for x in range(len\n (y_scores))]\n return predictions_binary\n\n\n<function token>\n\n\ndef plot_precision_recall(val_Y, y_pred, model_name, output_type):\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n prec = prec[:-1]\n recall_curve = rec[:-1]\n pct_above_per_thresh = []\n number_scored = len(y_pred)\n for value in thresh:\n num_above_thresh = len(y_pred[y_pred >= value])\n pct_above_thresh = num_above_thresh / float(len(y_pred))\n if pct_above_thresh <= 1:\n pct_above_per_thresh.append(pct_above_thresh)\n else:\n raise Exception\n pct_above_per_thresh = np.array(pct_above_per_thresh)\n plt.clf()\n fig, ax1 = plt.subplots()\n ax1.plot(pct_above_per_thresh, prec, 'b')\n print('PLOTTING STUFF')\n print(pct_above_per_thresh)\n print(prec[:-1])\n ax1.set_xlabel('percent of population')\n ax1.set_ylabel('precision', color='b')\n ax2 = ax1.twinx()\n ax2.plot(pct_above_per_thresh, recall_curve, 'r')\n ax2.set_ylabel('recall', color='r')\n ax1.set_ylim([0, 1])\n ax2.set_xlim([0, 1])\n name = model_name\n plt.title(name)\n if output_type == 'save':\n plt.savefig(name)\n elif output_type == 'show':\n plt.show()\n pdb.set_trace()\n else:\n plt.show()\n pdb.set_trace()\n\n\n<function token>\n\n\ndef kfold_eval(df, target, features):\n models_params = {RandomForestClassifier: {'n_estimators': [100],\n 'criterion': ['gini', 'entropy'], 'max_features': ['sqrt', 'log2'],\n 'max_depth': [5, 10], 'n_jobs': [4], 'min_samples_leaf': [10, 50, \n 100]}, LogisticRegression: {'C': [10 ** -1, 10 ** -2, 10 ** -3],\n 'penalty': ['l1', 'l2']}, KNeighborsClassifier: {'n_neighbors': [5,\n 10, 25, 100], 'p': [1, 2, 3], 'n_jobs': [2]},\n DecisionTreeClassifier: {'max_depth': [5, 10, 15],\n 'min_samples_leaf': [2, 5, 10]}, GradientBoostingClassifier: {\n 'learning_rate': [0.1, 0.01], 'n_estimators': [100], 'max_features':\n ['sqrt', 'log2'], 'max_depth': [1, 2, 3]}, BaggingClassifier: {\n 'max_samples': [0.1, 0.25, 0.65], 'n_jobs': [4]}}\n X = df[features]\n y = df[target]\n print(y)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,\n random_state=0)\n \"\"\"\n kf = KFold(n_splits=2)\n kf.get_n_splits(X)\n #print(kf)\n KFold(n_splits=2,random_state=None,shuffle=False)\n for train_index, test_index in kf.split(X):\n print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n \"\"\"\n \"\"\"rf = RandomForestClassifier(n_estimators=100,criterion='gini',max_features='sqrt',max_depth=5)\n rf.fit(X_train, y_train)\n y_score = rf.predict_proba(X_test)\n #y_score = rf.decision_function(X_test)\n y_pred = rf.predict(X_test)\n print(roc_auc_score(y_test,y_score[:,0]))\n metrics_1 ={}\"\"\"\n class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params)\n print(accuracy_score(y_test, y_pred))\n\n\ndef extract_train_test_sets(train_start_time, train_end_time,\n test_start_time, test_end_time, df):\n train_set = df[(df['date_posted'] > train_start_time) & (df[\n 'date_posted'] < train_end_time)]\n test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted'\n ] < test_end_time)]\n return train_set, test_set\n\n\ndef class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params):\n out = open('out.txt', 'a')\n \"\"\"X_train = train_set[features] #X\n y_train = train_set[target] #y\n \n #validation\n X_test = test_set[features] #val_x\n y_test = test_set[target] #val_y\"\"\"\n metrics = {}\n for m, m_param in models_params.items():\n listofparam = get_combos(m_param)\n print('start training for {0}'.format(m))\n out.write('start training for {0}\\n'.format(m))\n for params in listofparam:\n print(params)\n out.write(json.dumps(params))\n model = m(**params)\n model.fit(X_train, y_train)\n y_pred = model.predict_proba(X_test)\n metrics[m] = get_metrics(y_pred[:, 1], y_test)\n print('this is valy')\n print(y_test)\n print('this is y_pred')\n print(y_pred)\n plot_precision_recall(y_test, y_pred[:, 1], model, 'show')\n out.write('----------------------------\\n')\n out.write('Using %s classifier \\n' % models_params)\n out.write(json.dumps(metrics[m]))\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n\n\ndef load_data(csv_file, nrows=None):\n return pd.read_csv(csv_file, nrows=nrows)\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef cor_heat(data_frame, var_name):\n corrmat = data_frame.corr()\n k = 12\n cols = corrmat.nlargest(k, var_name)[var_name].index\n cm = np.corrcoef(data_frame[cols].values.T)\n sns.set(font_scale=1.25)\n hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f',\n annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.\n values)\n plt.show()\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,\n np.newaxis])\n low_range = data_scaled[data_scaled[:, 0].argsort()][:10]\n high_range = data_scaled[data_scaled[:, 0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n\n<function token>\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\ndef fill_empty(data_frame, var, new_var):\n return data_frame[var].fillna(new_var)\n\n\ndef descretize(data_frame, var, num):\n return pd.cut(data_frame[var], num, retbins=True)\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\n<function token>\n\n\ndef logReg(data_frame, IV, var_list):\n if '-' in var_list[0]:\n formula = IV + '~' + 'Q(\"' + var_list[0] + '\")'\n else:\n formula = IV + '~' + var_list[0]\n for i in range(1, len(var_list)):\n if '-' in var_list[i]:\n formula = formula + '+' + 'Q(\"' + var_list[i] + '\")'\n else:\n formula = formula + '+' + var_list[i]\n y, X = dmatrices(formula, data_frame, return_type='dataframe')\n y = np.ravel(y)\n model = LogisticRegression()\n model = model.fit(X, y)\n print(pd.DataFrame(list(zip(X.columns, np.transpose(model.coef_)))))\n return model.score(X, y)\n\n\ndef knearest(data_frame, train, test):\n X = data_frame[train].reshape(-1, 1)\n Y = data_frame[test].reshape(-1, 1)\n X_train = X[:100]\n Y_train = Y[:100]\n X_validate = X[100:]\n Y_validate = Y[100:]\n neighbor = KNeighborsClassifier(n_neighbors=2, weights='uniform')\n neighbor.fit(X_train, Y_train)\n predicted = neighbor.predict(X_validate)\n print(predicted)\n\n\ndef merging_data(dataframe_1, dataframe_2):\n return pd.merge(dataframe_1, dataframe_2)\n\n\n<function token>\n<function token>\n\n\ndef to_binary(df, array_col):\n for i in array_col:\n print(i)\n df[i] = df[i].apply(lambda x: 1 if x == 't' else 0)\n return df\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\ndef recall_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n recall = recall_score(y_true_sorted, preds_at_k)\n return recall\n\n\n<function token>\n\n\ndef generate_binary_at_k(y_scores, k):\n cutoff_index = int(len(y_scores) * (k / 100.0))\n predictions_binary = [(1 if x < cutoff_index else 0) for x in range(len\n (y_scores))]\n return predictions_binary\n\n\n<function token>\n\n\ndef plot_precision_recall(val_Y, y_pred, model_name, output_type):\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n prec = prec[:-1]\n recall_curve = rec[:-1]\n pct_above_per_thresh = []\n number_scored = len(y_pred)\n for value in thresh:\n num_above_thresh = len(y_pred[y_pred >= value])\n pct_above_thresh = num_above_thresh / float(len(y_pred))\n if pct_above_thresh <= 1:\n pct_above_per_thresh.append(pct_above_thresh)\n else:\n raise Exception\n pct_above_per_thresh = np.array(pct_above_per_thresh)\n plt.clf()\n fig, ax1 = plt.subplots()\n ax1.plot(pct_above_per_thresh, prec, 'b')\n print('PLOTTING STUFF')\n print(pct_above_per_thresh)\n print(prec[:-1])\n ax1.set_xlabel('percent of population')\n ax1.set_ylabel('precision', color='b')\n ax2 = ax1.twinx()\n ax2.plot(pct_above_per_thresh, recall_curve, 'r')\n ax2.set_ylabel('recall', color='r')\n ax1.set_ylim([0, 1])\n ax2.set_xlim([0, 1])\n name = model_name\n plt.title(name)\n if output_type == 'save':\n plt.savefig(name)\n elif output_type == 'show':\n plt.show()\n pdb.set_trace()\n else:\n plt.show()\n pdb.set_trace()\n\n\n<function token>\n\n\ndef kfold_eval(df, target, features):\n models_params = {RandomForestClassifier: {'n_estimators': [100],\n 'criterion': ['gini', 'entropy'], 'max_features': ['sqrt', 'log2'],\n 'max_depth': [5, 10], 'n_jobs': [4], 'min_samples_leaf': [10, 50, \n 100]}, LogisticRegression: {'C': [10 ** -1, 10 ** -2, 10 ** -3],\n 'penalty': ['l1', 'l2']}, KNeighborsClassifier: {'n_neighbors': [5,\n 10, 25, 100], 'p': [1, 2, 3], 'n_jobs': [2]},\n DecisionTreeClassifier: {'max_depth': [5, 10, 15],\n 'min_samples_leaf': [2, 5, 10]}, GradientBoostingClassifier: {\n 'learning_rate': [0.1, 0.01], 'n_estimators': [100], 'max_features':\n ['sqrt', 'log2'], 'max_depth': [1, 2, 3]}, BaggingClassifier: {\n 'max_samples': [0.1, 0.25, 0.65], 'n_jobs': [4]}}\n X = df[features]\n y = df[target]\n print(y)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,\n random_state=0)\n \"\"\"\n kf = KFold(n_splits=2)\n kf.get_n_splits(X)\n #print(kf)\n KFold(n_splits=2,random_state=None,shuffle=False)\n for train_index, test_index in kf.split(X):\n print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n \"\"\"\n \"\"\"rf = RandomForestClassifier(n_estimators=100,criterion='gini',max_features='sqrt',max_depth=5)\n rf.fit(X_train, y_train)\n y_score = rf.predict_proba(X_test)\n #y_score = rf.decision_function(X_test)\n y_pred = rf.predict(X_test)\n print(roc_auc_score(y_test,y_score[:,0]))\n metrics_1 ={}\"\"\"\n class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params)\n print(accuracy_score(y_test, y_pred))\n\n\ndef extract_train_test_sets(train_start_time, train_end_time,\n test_start_time, test_end_time, df):\n train_set = df[(df['date_posted'] > train_start_time) & (df[\n 'date_posted'] < train_end_time)]\n test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted'\n ] < test_end_time)]\n return train_set, test_set\n\n\ndef class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params):\n out = open('out.txt', 'a')\n \"\"\"X_train = train_set[features] #X\n y_train = train_set[target] #y\n \n #validation\n X_test = test_set[features] #val_x\n y_test = test_set[target] #val_y\"\"\"\n metrics = {}\n for m, m_param in models_params.items():\n listofparam = get_combos(m_param)\n print('start training for {0}'.format(m))\n out.write('start training for {0}\\n'.format(m))\n for params in listofparam:\n print(params)\n out.write(json.dumps(params))\n model = m(**params)\n model.fit(X_train, y_train)\n y_pred = model.predict_proba(X_test)\n metrics[m] = get_metrics(y_pred[:, 1], y_test)\n print('this is valy')\n print(y_test)\n print('this is y_pred')\n print(y_pred)\n plot_precision_recall(y_test, y_pred[:, 1], model, 'show')\n out.write('----------------------------\\n')\n out.write('Using %s classifier \\n' % models_params)\n out.write(json.dumps(metrics[m]))\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n\n\ndef load_data(csv_file, nrows=None):\n return pd.read_csv(csv_file, nrows=nrows)\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef cor_heat(data_frame, var_name):\n corrmat = data_frame.corr()\n k = 12\n cols = corrmat.nlargest(k, var_name)[var_name].index\n cm = np.corrcoef(data_frame[cols].values.T)\n sns.set(font_scale=1.25)\n hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f',\n annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.\n values)\n plt.show()\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,\n np.newaxis])\n low_range = data_scaled[data_scaled[:, 0].argsort()][:10]\n high_range = data_scaled[data_scaled[:, 0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n\n<function token>\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\ndef fill_empty(data_frame, var, new_var):\n return data_frame[var].fillna(new_var)\n\n\ndef descretize(data_frame, var, num):\n return pd.cut(data_frame[var], num, retbins=True)\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\n<function token>\n\n\ndef logReg(data_frame, IV, var_list):\n if '-' in var_list[0]:\n formula = IV + '~' + 'Q(\"' + var_list[0] + '\")'\n else:\n formula = IV + '~' + var_list[0]\n for i in range(1, len(var_list)):\n if '-' in var_list[i]:\n formula = formula + '+' + 'Q(\"' + var_list[i] + '\")'\n else:\n formula = formula + '+' + var_list[i]\n y, X = dmatrices(formula, data_frame, return_type='dataframe')\n y = np.ravel(y)\n model = LogisticRegression()\n model = model.fit(X, y)\n print(pd.DataFrame(list(zip(X.columns, np.transpose(model.coef_)))))\n return model.score(X, y)\n\n\ndef knearest(data_frame, train, test):\n X = data_frame[train].reshape(-1, 1)\n Y = data_frame[test].reshape(-1, 1)\n X_train = X[:100]\n Y_train = Y[:100]\n X_validate = X[100:]\n Y_validate = Y[100:]\n neighbor = KNeighborsClassifier(n_neighbors=2, weights='uniform')\n neighbor.fit(X_train, Y_train)\n predicted = neighbor.predict(X_validate)\n print(predicted)\n\n\ndef merging_data(dataframe_1, dataframe_2):\n return pd.merge(dataframe_1, dataframe_2)\n\n\n<function token>\n<function token>\n\n\ndef to_binary(df, array_col):\n for i in array_col:\n print(i)\n df[i] = df[i].apply(lambda x: 1 if x == 't' else 0)\n return df\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\ndef recall_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n recall = recall_score(y_true_sorted, preds_at_k)\n return recall\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef plot_precision_recall(val_Y, y_pred, model_name, output_type):\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n prec = prec[:-1]\n recall_curve = rec[:-1]\n pct_above_per_thresh = []\n number_scored = len(y_pred)\n for value in thresh:\n num_above_thresh = len(y_pred[y_pred >= value])\n pct_above_thresh = num_above_thresh / float(len(y_pred))\n if pct_above_thresh <= 1:\n pct_above_per_thresh.append(pct_above_thresh)\n else:\n raise Exception\n pct_above_per_thresh = np.array(pct_above_per_thresh)\n plt.clf()\n fig, ax1 = plt.subplots()\n ax1.plot(pct_above_per_thresh, prec, 'b')\n print('PLOTTING STUFF')\n print(pct_above_per_thresh)\n print(prec[:-1])\n ax1.set_xlabel('percent of population')\n ax1.set_ylabel('precision', color='b')\n ax2 = ax1.twinx()\n ax2.plot(pct_above_per_thresh, recall_curve, 'r')\n ax2.set_ylabel('recall', color='r')\n ax1.set_ylim([0, 1])\n ax2.set_xlim([0, 1])\n name = model_name\n plt.title(name)\n if output_type == 'save':\n plt.savefig(name)\n elif output_type == 'show':\n plt.show()\n pdb.set_trace()\n else:\n plt.show()\n pdb.set_trace()\n\n\n<function token>\n\n\ndef kfold_eval(df, target, features):\n models_params = {RandomForestClassifier: {'n_estimators': [100],\n 'criterion': ['gini', 'entropy'], 'max_features': ['sqrt', 'log2'],\n 'max_depth': [5, 10], 'n_jobs': [4], 'min_samples_leaf': [10, 50, \n 100]}, LogisticRegression: {'C': [10 ** -1, 10 ** -2, 10 ** -3],\n 'penalty': ['l1', 'l2']}, KNeighborsClassifier: {'n_neighbors': [5,\n 10, 25, 100], 'p': [1, 2, 3], 'n_jobs': [2]},\n DecisionTreeClassifier: {'max_depth': [5, 10, 15],\n 'min_samples_leaf': [2, 5, 10]}, GradientBoostingClassifier: {\n 'learning_rate': [0.1, 0.01], 'n_estimators': [100], 'max_features':\n ['sqrt', 'log2'], 'max_depth': [1, 2, 3]}, BaggingClassifier: {\n 'max_samples': [0.1, 0.25, 0.65], 'n_jobs': [4]}}\n X = df[features]\n y = df[target]\n print(y)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,\n random_state=0)\n \"\"\"\n kf = KFold(n_splits=2)\n kf.get_n_splits(X)\n #print(kf)\n KFold(n_splits=2,random_state=None,shuffle=False)\n for train_index, test_index in kf.split(X):\n print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n \"\"\"\n \"\"\"rf = RandomForestClassifier(n_estimators=100,criterion='gini',max_features='sqrt',max_depth=5)\n rf.fit(X_train, y_train)\n y_score = rf.predict_proba(X_test)\n #y_score = rf.decision_function(X_test)\n y_pred = rf.predict(X_test)\n print(roc_auc_score(y_test,y_score[:,0]))\n metrics_1 ={}\"\"\"\n class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params)\n print(accuracy_score(y_test, y_pred))\n\n\ndef extract_train_test_sets(train_start_time, train_end_time,\n test_start_time, test_end_time, df):\n train_set = df[(df['date_posted'] > train_start_time) & (df[\n 'date_posted'] < train_end_time)]\n test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted'\n ] < test_end_time)]\n return train_set, test_set\n\n\ndef class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params):\n out = open('out.txt', 'a')\n \"\"\"X_train = train_set[features] #X\n y_train = train_set[target] #y\n \n #validation\n X_test = test_set[features] #val_x\n y_test = test_set[target] #val_y\"\"\"\n metrics = {}\n for m, m_param in models_params.items():\n listofparam = get_combos(m_param)\n print('start training for {0}'.format(m))\n out.write('start training for {0}\\n'.format(m))\n for params in listofparam:\n print(params)\n out.write(json.dumps(params))\n model = m(**params)\n model.fit(X_train, y_train)\n y_pred = model.predict_proba(X_test)\n metrics[m] = get_metrics(y_pred[:, 1], y_test)\n print('this is valy')\n print(y_test)\n print('this is y_pred')\n print(y_pred)\n plot_precision_recall(y_test, y_pred[:, 1], model, 'show')\n out.write('----------------------------\\n')\n out.write('Using %s classifier \\n' % models_params)\n out.write(json.dumps(metrics[m]))\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n\n\ndef load_data(csv_file, nrows=None):\n return pd.read_csv(csv_file, nrows=nrows)\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef cor_heat(data_frame, var_name):\n corrmat = data_frame.corr()\n k = 12\n cols = corrmat.nlargest(k, var_name)[var_name].index\n cm = np.corrcoef(data_frame[cols].values.T)\n sns.set(font_scale=1.25)\n hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f',\n annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.\n values)\n plt.show()\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,\n np.newaxis])\n low_range = data_scaled[data_scaled[:, 0].argsort()][:10]\n high_range = data_scaled[data_scaled[:, 0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n\n<function token>\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\ndef fill_empty(data_frame, var, new_var):\n return data_frame[var].fillna(new_var)\n\n\ndef descretize(data_frame, var, num):\n return pd.cut(data_frame[var], num, retbins=True)\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\n<function token>\n\n\ndef logReg(data_frame, IV, var_list):\n if '-' in var_list[0]:\n formula = IV + '~' + 'Q(\"' + var_list[0] + '\")'\n else:\n formula = IV + '~' + var_list[0]\n for i in range(1, len(var_list)):\n if '-' in var_list[i]:\n formula = formula + '+' + 'Q(\"' + var_list[i] + '\")'\n else:\n formula = formula + '+' + var_list[i]\n y, X = dmatrices(formula, data_frame, return_type='dataframe')\n y = np.ravel(y)\n model = LogisticRegression()\n model = model.fit(X, y)\n print(pd.DataFrame(list(zip(X.columns, np.transpose(model.coef_)))))\n return model.score(X, y)\n\n\ndef knearest(data_frame, train, test):\n X = data_frame[train].reshape(-1, 1)\n Y = data_frame[test].reshape(-1, 1)\n X_train = X[:100]\n Y_train = Y[:100]\n X_validate = X[100:]\n Y_validate = Y[100:]\n neighbor = KNeighborsClassifier(n_neighbors=2, weights='uniform')\n neighbor.fit(X_train, Y_train)\n predicted = neighbor.predict(X_validate)\n print(predicted)\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef to_binary(df, array_col):\n for i in array_col:\n print(i)\n df[i] = df[i].apply(lambda x: 1 if x == 't' else 0)\n return df\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\ndef recall_at_k(y_true, y_scores, k):\n y_scores_sorted, y_true_sorted = joint_sort_descending(np.array(\n y_scores), np.array(y_true))\n preds_at_k = generate_binary_at_k(y_scores_sorted, k)\n recall = recall_score(y_true_sorted, preds_at_k)\n return recall\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef plot_precision_recall(val_Y, y_pred, model_name, output_type):\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n prec = prec[:-1]\n recall_curve = rec[:-1]\n pct_above_per_thresh = []\n number_scored = len(y_pred)\n for value in thresh:\n num_above_thresh = len(y_pred[y_pred >= value])\n pct_above_thresh = num_above_thresh / float(len(y_pred))\n if pct_above_thresh <= 1:\n pct_above_per_thresh.append(pct_above_thresh)\n else:\n raise Exception\n pct_above_per_thresh = np.array(pct_above_per_thresh)\n plt.clf()\n fig, ax1 = plt.subplots()\n ax1.plot(pct_above_per_thresh, prec, 'b')\n print('PLOTTING STUFF')\n print(pct_above_per_thresh)\n print(prec[:-1])\n ax1.set_xlabel('percent of population')\n ax1.set_ylabel('precision', color='b')\n ax2 = ax1.twinx()\n ax2.plot(pct_above_per_thresh, recall_curve, 'r')\n ax2.set_ylabel('recall', color='r')\n ax1.set_ylim([0, 1])\n ax2.set_xlim([0, 1])\n name = model_name\n plt.title(name)\n if output_type == 'save':\n plt.savefig(name)\n elif output_type == 'show':\n plt.show()\n pdb.set_trace()\n else:\n plt.show()\n pdb.set_trace()\n\n\n<function token>\n\n\ndef kfold_eval(df, target, features):\n models_params = {RandomForestClassifier: {'n_estimators': [100],\n 'criterion': ['gini', 'entropy'], 'max_features': ['sqrt', 'log2'],\n 'max_depth': [5, 10], 'n_jobs': [4], 'min_samples_leaf': [10, 50, \n 100]}, LogisticRegression: {'C': [10 ** -1, 10 ** -2, 10 ** -3],\n 'penalty': ['l1', 'l2']}, KNeighborsClassifier: {'n_neighbors': [5,\n 10, 25, 100], 'p': [1, 2, 3], 'n_jobs': [2]},\n DecisionTreeClassifier: {'max_depth': [5, 10, 15],\n 'min_samples_leaf': [2, 5, 10]}, GradientBoostingClassifier: {\n 'learning_rate': [0.1, 0.01], 'n_estimators': [100], 'max_features':\n ['sqrt', 'log2'], 'max_depth': [1, 2, 3]}, BaggingClassifier: {\n 'max_samples': [0.1, 0.25, 0.65], 'n_jobs': [4]}}\n X = df[features]\n y = df[target]\n print(y)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,\n random_state=0)\n \"\"\"\n kf = KFold(n_splits=2)\n kf.get_n_splits(X)\n #print(kf)\n KFold(n_splits=2,random_state=None,shuffle=False)\n for train_index, test_index in kf.split(X):\n print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n \"\"\"\n \"\"\"rf = RandomForestClassifier(n_estimators=100,criterion='gini',max_features='sqrt',max_depth=5)\n rf.fit(X_train, y_train)\n y_score = rf.predict_proba(X_test)\n #y_score = rf.decision_function(X_test)\n y_pred = rf.predict(X_test)\n print(roc_auc_score(y_test,y_score[:,0]))\n metrics_1 ={}\"\"\"\n class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params)\n print(accuracy_score(y_test, y_pred))\n\n\ndef extract_train_test_sets(train_start_time, train_end_time,\n test_start_time, test_end_time, df):\n train_set = df[(df['date_posted'] > train_start_time) & (df[\n 'date_posted'] < train_end_time)]\n test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted'\n ] < test_end_time)]\n return train_set, test_set\n\n\ndef class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params):\n out = open('out.txt', 'a')\n \"\"\"X_train = train_set[features] #X\n y_train = train_set[target] #y\n \n #validation\n X_test = test_set[features] #val_x\n y_test = test_set[target] #val_y\"\"\"\n metrics = {}\n for m, m_param in models_params.items():\n listofparam = get_combos(m_param)\n print('start training for {0}'.format(m))\n out.write('start training for {0}\\n'.format(m))\n for params in listofparam:\n print(params)\n out.write(json.dumps(params))\n model = m(**params)\n model.fit(X_train, y_train)\n y_pred = model.predict_proba(X_test)\n metrics[m] = get_metrics(y_pred[:, 1], y_test)\n print('this is valy')\n print(y_test)\n print('this is y_pred')\n print(y_pred)\n plot_precision_recall(y_test, y_pred[:, 1], model, 'show')\n out.write('----------------------------\\n')\n out.write('Using %s classifier \\n' % models_params)\n out.write(json.dumps(metrics[m]))\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n\n\ndef load_data(csv_file, nrows=None):\n return pd.read_csv(csv_file, nrows=nrows)\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef cor_heat(data_frame, var_name):\n corrmat = data_frame.corr()\n k = 12\n cols = corrmat.nlargest(k, var_name)[var_name].index\n cm = np.corrcoef(data_frame[cols].values.T)\n sns.set(font_scale=1.25)\n hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f',\n annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.\n values)\n plt.show()\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,\n np.newaxis])\n low_range = data_scaled[data_scaled[:, 0].argsort()][:10]\n high_range = data_scaled[data_scaled[:, 0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n\n<function token>\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\ndef fill_empty(data_frame, var, new_var):\n return data_frame[var].fillna(new_var)\n\n\ndef descretize(data_frame, var, num):\n return pd.cut(data_frame[var], num, retbins=True)\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\n<function token>\n\n\ndef logReg(data_frame, IV, var_list):\n if '-' in var_list[0]:\n formula = IV + '~' + 'Q(\"' + var_list[0] + '\")'\n else:\n formula = IV + '~' + var_list[0]\n for i in range(1, len(var_list)):\n if '-' in var_list[i]:\n formula = formula + '+' + 'Q(\"' + var_list[i] + '\")'\n else:\n formula = formula + '+' + var_list[i]\n y, X = dmatrices(formula, data_frame, return_type='dataframe')\n y = np.ravel(y)\n model = LogisticRegression()\n model = model.fit(X, y)\n print(pd.DataFrame(list(zip(X.columns, np.transpose(model.coef_)))))\n return model.score(X, y)\n\n\ndef knearest(data_frame, train, test):\n X = data_frame[train].reshape(-1, 1)\n Y = data_frame[test].reshape(-1, 1)\n X_train = X[:100]\n Y_train = Y[:100]\n X_validate = X[100:]\n Y_validate = Y[100:]\n neighbor = KNeighborsClassifier(n_neighbors=2, weights='uniform')\n neighbor.fit(X_train, Y_train)\n predicted = neighbor.predict(X_validate)\n print(predicted)\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef to_binary(df, array_col):\n for i in array_col:\n print(i)\n df[i] = df[i].apply(lambda x: 1 if x == 't' else 0)\n return df\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef plot_precision_recall(val_Y, y_pred, model_name, output_type):\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n prec = prec[:-1]\n recall_curve = rec[:-1]\n pct_above_per_thresh = []\n number_scored = len(y_pred)\n for value in thresh:\n num_above_thresh = len(y_pred[y_pred >= value])\n pct_above_thresh = num_above_thresh / float(len(y_pred))\n if pct_above_thresh <= 1:\n pct_above_per_thresh.append(pct_above_thresh)\n else:\n raise Exception\n pct_above_per_thresh = np.array(pct_above_per_thresh)\n plt.clf()\n fig, ax1 = plt.subplots()\n ax1.plot(pct_above_per_thresh, prec, 'b')\n print('PLOTTING STUFF')\n print(pct_above_per_thresh)\n print(prec[:-1])\n ax1.set_xlabel('percent of population')\n ax1.set_ylabel('precision', color='b')\n ax2 = ax1.twinx()\n ax2.plot(pct_above_per_thresh, recall_curve, 'r')\n ax2.set_ylabel('recall', color='r')\n ax1.set_ylim([0, 1])\n ax2.set_xlim([0, 1])\n name = model_name\n plt.title(name)\n if output_type == 'save':\n plt.savefig(name)\n elif output_type == 'show':\n plt.show()\n pdb.set_trace()\n else:\n plt.show()\n pdb.set_trace()\n\n\n<function token>\n\n\ndef kfold_eval(df, target, features):\n models_params = {RandomForestClassifier: {'n_estimators': [100],\n 'criterion': ['gini', 'entropy'], 'max_features': ['sqrt', 'log2'],\n 'max_depth': [5, 10], 'n_jobs': [4], 'min_samples_leaf': [10, 50, \n 100]}, LogisticRegression: {'C': [10 ** -1, 10 ** -2, 10 ** -3],\n 'penalty': ['l1', 'l2']}, KNeighborsClassifier: {'n_neighbors': [5,\n 10, 25, 100], 'p': [1, 2, 3], 'n_jobs': [2]},\n DecisionTreeClassifier: {'max_depth': [5, 10, 15],\n 'min_samples_leaf': [2, 5, 10]}, GradientBoostingClassifier: {\n 'learning_rate': [0.1, 0.01], 'n_estimators': [100], 'max_features':\n ['sqrt', 'log2'], 'max_depth': [1, 2, 3]}, BaggingClassifier: {\n 'max_samples': [0.1, 0.25, 0.65], 'n_jobs': [4]}}\n X = df[features]\n y = df[target]\n print(y)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,\n random_state=0)\n \"\"\"\n kf = KFold(n_splits=2)\n kf.get_n_splits(X)\n #print(kf)\n KFold(n_splits=2,random_state=None,shuffle=False)\n for train_index, test_index in kf.split(X):\n print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n \"\"\"\n \"\"\"rf = RandomForestClassifier(n_estimators=100,criterion='gini',max_features='sqrt',max_depth=5)\n rf.fit(X_train, y_train)\n y_score = rf.predict_proba(X_test)\n #y_score = rf.decision_function(X_test)\n y_pred = rf.predict(X_test)\n print(roc_auc_score(y_test,y_score[:,0]))\n metrics_1 ={}\"\"\"\n class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params)\n print(accuracy_score(y_test, y_pred))\n\n\ndef extract_train_test_sets(train_start_time, train_end_time,\n test_start_time, test_end_time, df):\n train_set = df[(df['date_posted'] > train_start_time) & (df[\n 'date_posted'] < train_end_time)]\n test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted'\n ] < test_end_time)]\n return train_set, test_set\n\n\ndef class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params):\n out = open('out.txt', 'a')\n \"\"\"X_train = train_set[features] #X\n y_train = train_set[target] #y\n \n #validation\n X_test = test_set[features] #val_x\n y_test = test_set[target] #val_y\"\"\"\n metrics = {}\n for m, m_param in models_params.items():\n listofparam = get_combos(m_param)\n print('start training for {0}'.format(m))\n out.write('start training for {0}\\n'.format(m))\n for params in listofparam:\n print(params)\n out.write(json.dumps(params))\n model = m(**params)\n model.fit(X_train, y_train)\n y_pred = model.predict_proba(X_test)\n metrics[m] = get_metrics(y_pred[:, 1], y_test)\n print('this is valy')\n print(y_test)\n print('this is y_pred')\n print(y_pred)\n plot_precision_recall(y_test, y_pred[:, 1], model, 'show')\n out.write('----------------------------\\n')\n out.write('Using %s classifier \\n' % models_params)\n out.write(json.dumps(metrics[m]))\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n\n\ndef load_data(csv_file, nrows=None):\n return pd.read_csv(csv_file, nrows=nrows)\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef cor_heat(data_frame, var_name):\n corrmat = data_frame.corr()\n k = 12\n cols = corrmat.nlargest(k, var_name)[var_name].index\n cm = np.corrcoef(data_frame[cols].values.T)\n sns.set(font_scale=1.25)\n hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f',\n annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.\n values)\n plt.show()\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,\n np.newaxis])\n low_range = data_scaled[data_scaled[:, 0].argsort()][:10]\n high_range = data_scaled[data_scaled[:, 0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n\n<function token>\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\ndef fill_empty(data_frame, var, new_var):\n return data_frame[var].fillna(new_var)\n\n\ndef descretize(data_frame, var, num):\n return pd.cut(data_frame[var], num, retbins=True)\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\n<function token>\n\n\ndef logReg(data_frame, IV, var_list):\n if '-' in var_list[0]:\n formula = IV + '~' + 'Q(\"' + var_list[0] + '\")'\n else:\n formula = IV + '~' + var_list[0]\n for i in range(1, len(var_list)):\n if '-' in var_list[i]:\n formula = formula + '+' + 'Q(\"' + var_list[i] + '\")'\n else:\n formula = formula + '+' + var_list[i]\n y, X = dmatrices(formula, data_frame, return_type='dataframe')\n y = np.ravel(y)\n model = LogisticRegression()\n model = model.fit(X, y)\n print(pd.DataFrame(list(zip(X.columns, np.transpose(model.coef_)))))\n return model.score(X, y)\n\n\ndef knearest(data_frame, train, test):\n X = data_frame[train].reshape(-1, 1)\n Y = data_frame[test].reshape(-1, 1)\n X_train = X[:100]\n Y_train = Y[:100]\n X_validate = X[100:]\n Y_validate = Y[100:]\n neighbor = KNeighborsClassifier(n_neighbors=2, weights='uniform')\n neighbor.fit(X_train, Y_train)\n predicted = neighbor.predict(X_validate)\n print(predicted)\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef plot_precision_recall(val_Y, y_pred, model_name, output_type):\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n prec = prec[:-1]\n recall_curve = rec[:-1]\n pct_above_per_thresh = []\n number_scored = len(y_pred)\n for value in thresh:\n num_above_thresh = len(y_pred[y_pred >= value])\n pct_above_thresh = num_above_thresh / float(len(y_pred))\n if pct_above_thresh <= 1:\n pct_above_per_thresh.append(pct_above_thresh)\n else:\n raise Exception\n pct_above_per_thresh = np.array(pct_above_per_thresh)\n plt.clf()\n fig, ax1 = plt.subplots()\n ax1.plot(pct_above_per_thresh, prec, 'b')\n print('PLOTTING STUFF')\n print(pct_above_per_thresh)\n print(prec[:-1])\n ax1.set_xlabel('percent of population')\n ax1.set_ylabel('precision', color='b')\n ax2 = ax1.twinx()\n ax2.plot(pct_above_per_thresh, recall_curve, 'r')\n ax2.set_ylabel('recall', color='r')\n ax1.set_ylim([0, 1])\n ax2.set_xlim([0, 1])\n name = model_name\n plt.title(name)\n if output_type == 'save':\n plt.savefig(name)\n elif output_type == 'show':\n plt.show()\n pdb.set_trace()\n else:\n plt.show()\n pdb.set_trace()\n\n\n<function token>\n\n\ndef kfold_eval(df, target, features):\n models_params = {RandomForestClassifier: {'n_estimators': [100],\n 'criterion': ['gini', 'entropy'], 'max_features': ['sqrt', 'log2'],\n 'max_depth': [5, 10], 'n_jobs': [4], 'min_samples_leaf': [10, 50, \n 100]}, LogisticRegression: {'C': [10 ** -1, 10 ** -2, 10 ** -3],\n 'penalty': ['l1', 'l2']}, KNeighborsClassifier: {'n_neighbors': [5,\n 10, 25, 100], 'p': [1, 2, 3], 'n_jobs': [2]},\n DecisionTreeClassifier: {'max_depth': [5, 10, 15],\n 'min_samples_leaf': [2, 5, 10]}, GradientBoostingClassifier: {\n 'learning_rate': [0.1, 0.01], 'n_estimators': [100], 'max_features':\n ['sqrt', 'log2'], 'max_depth': [1, 2, 3]}, BaggingClassifier: {\n 'max_samples': [0.1, 0.25, 0.65], 'n_jobs': [4]}}\n X = df[features]\n y = df[target]\n print(y)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,\n random_state=0)\n \"\"\"\n kf = KFold(n_splits=2)\n kf.get_n_splits(X)\n #print(kf)\n KFold(n_splits=2,random_state=None,shuffle=False)\n for train_index, test_index in kf.split(X):\n print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n \"\"\"\n \"\"\"rf = RandomForestClassifier(n_estimators=100,criterion='gini',max_features='sqrt',max_depth=5)\n rf.fit(X_train, y_train)\n y_score = rf.predict_proba(X_test)\n #y_score = rf.decision_function(X_test)\n y_pred = rf.predict(X_test)\n print(roc_auc_score(y_test,y_score[:,0]))\n metrics_1 ={}\"\"\"\n class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params)\n print(accuracy_score(y_test, y_pred))\n\n\ndef extract_train_test_sets(train_start_time, train_end_time,\n test_start_time, test_end_time, df):\n train_set = df[(df['date_posted'] > train_start_time) & (df[\n 'date_posted'] < train_end_time)]\n test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted'\n ] < test_end_time)]\n return train_set, test_set\n\n\ndef class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params):\n out = open('out.txt', 'a')\n \"\"\"X_train = train_set[features] #X\n y_train = train_set[target] #y\n \n #validation\n X_test = test_set[features] #val_x\n y_test = test_set[target] #val_y\"\"\"\n metrics = {}\n for m, m_param in models_params.items():\n listofparam = get_combos(m_param)\n print('start training for {0}'.format(m))\n out.write('start training for {0}\\n'.format(m))\n for params in listofparam:\n print(params)\n out.write(json.dumps(params))\n model = m(**params)\n model.fit(X_train, y_train)\n y_pred = model.predict_proba(X_test)\n metrics[m] = get_metrics(y_pred[:, 1], y_test)\n print('this is valy')\n print(y_test)\n print('this is y_pred')\n print(y_pred)\n plot_precision_recall(y_test, y_pred[:, 1], model, 'show')\n out.write('----------------------------\\n')\n out.write('Using %s classifier \\n' % models_params)\n out.write(json.dumps(metrics[m]))\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n\n\ndef load_data(csv_file, nrows=None):\n return pd.read_csv(csv_file, nrows=nrows)\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef cor_heat(data_frame, var_name):\n corrmat = data_frame.corr()\n k = 12\n cols = corrmat.nlargest(k, var_name)[var_name].index\n cm = np.corrcoef(data_frame[cols].values.T)\n sns.set(font_scale=1.25)\n hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f',\n annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.\n values)\n plt.show()\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,\n np.newaxis])\n low_range = data_scaled[data_scaled[:, 0].argsort()][:10]\n high_range = data_scaled[data_scaled[:, 0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n\n<function token>\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\ndef fill_empty(data_frame, var, new_var):\n return data_frame[var].fillna(new_var)\n\n\ndef descretize(data_frame, var, num):\n return pd.cut(data_frame[var], num, retbins=True)\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\n<function token>\n\n\ndef logReg(data_frame, IV, var_list):\n if '-' in var_list[0]:\n formula = IV + '~' + 'Q(\"' + var_list[0] + '\")'\n else:\n formula = IV + '~' + var_list[0]\n for i in range(1, len(var_list)):\n if '-' in var_list[i]:\n formula = formula + '+' + 'Q(\"' + var_list[i] + '\")'\n else:\n formula = formula + '+' + var_list[i]\n y, X = dmatrices(formula, data_frame, return_type='dataframe')\n y = np.ravel(y)\n model = LogisticRegression()\n model = model.fit(X, y)\n print(pd.DataFrame(list(zip(X.columns, np.transpose(model.coef_)))))\n return model.score(X, y)\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef plot_precision_recall(val_Y, y_pred, model_name, output_type):\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n prec = prec[:-1]\n recall_curve = rec[:-1]\n pct_above_per_thresh = []\n number_scored = len(y_pred)\n for value in thresh:\n num_above_thresh = len(y_pred[y_pred >= value])\n pct_above_thresh = num_above_thresh / float(len(y_pred))\n if pct_above_thresh <= 1:\n pct_above_per_thresh.append(pct_above_thresh)\n else:\n raise Exception\n pct_above_per_thresh = np.array(pct_above_per_thresh)\n plt.clf()\n fig, ax1 = plt.subplots()\n ax1.plot(pct_above_per_thresh, prec, 'b')\n print('PLOTTING STUFF')\n print(pct_above_per_thresh)\n print(prec[:-1])\n ax1.set_xlabel('percent of population')\n ax1.set_ylabel('precision', color='b')\n ax2 = ax1.twinx()\n ax2.plot(pct_above_per_thresh, recall_curve, 'r')\n ax2.set_ylabel('recall', color='r')\n ax1.set_ylim([0, 1])\n ax2.set_xlim([0, 1])\n name = model_name\n plt.title(name)\n if output_type == 'save':\n plt.savefig(name)\n elif output_type == 'show':\n plt.show()\n pdb.set_trace()\n else:\n plt.show()\n pdb.set_trace()\n\n\n<function token>\n\n\ndef kfold_eval(df, target, features):\n models_params = {RandomForestClassifier: {'n_estimators': [100],\n 'criterion': ['gini', 'entropy'], 'max_features': ['sqrt', 'log2'],\n 'max_depth': [5, 10], 'n_jobs': [4], 'min_samples_leaf': [10, 50, \n 100]}, LogisticRegression: {'C': [10 ** -1, 10 ** -2, 10 ** -3],\n 'penalty': ['l1', 'l2']}, KNeighborsClassifier: {'n_neighbors': [5,\n 10, 25, 100], 'p': [1, 2, 3], 'n_jobs': [2]},\n DecisionTreeClassifier: {'max_depth': [5, 10, 15],\n 'min_samples_leaf': [2, 5, 10]}, GradientBoostingClassifier: {\n 'learning_rate': [0.1, 0.01], 'n_estimators': [100], 'max_features':\n ['sqrt', 'log2'], 'max_depth': [1, 2, 3]}, BaggingClassifier: {\n 'max_samples': [0.1, 0.25, 0.65], 'n_jobs': [4]}}\n X = df[features]\n y = df[target]\n print(y)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,\n random_state=0)\n \"\"\"\n kf = KFold(n_splits=2)\n kf.get_n_splits(X)\n #print(kf)\n KFold(n_splits=2,random_state=None,shuffle=False)\n for train_index, test_index in kf.split(X):\n print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n \"\"\"\n \"\"\"rf = RandomForestClassifier(n_estimators=100,criterion='gini',max_features='sqrt',max_depth=5)\n rf.fit(X_train, y_train)\n y_score = rf.predict_proba(X_test)\n #y_score = rf.decision_function(X_test)\n y_pred = rf.predict(X_test)\n print(roc_auc_score(y_test,y_score[:,0]))\n metrics_1 ={}\"\"\"\n class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params)\n print(accuracy_score(y_test, y_pred))\n\n\ndef extract_train_test_sets(train_start_time, train_end_time,\n test_start_time, test_end_time, df):\n train_set = df[(df['date_posted'] > train_start_time) & (df[\n 'date_posted'] < train_end_time)]\n test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted'\n ] < test_end_time)]\n return train_set, test_set\n\n\ndef class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params):\n out = open('out.txt', 'a')\n \"\"\"X_train = train_set[features] #X\n y_train = train_set[target] #y\n \n #validation\n X_test = test_set[features] #val_x\n y_test = test_set[target] #val_y\"\"\"\n metrics = {}\n for m, m_param in models_params.items():\n listofparam = get_combos(m_param)\n print('start training for {0}'.format(m))\n out.write('start training for {0}\\n'.format(m))\n for params in listofparam:\n print(params)\n out.write(json.dumps(params))\n model = m(**params)\n model.fit(X_train, y_train)\n y_pred = model.predict_proba(X_test)\n metrics[m] = get_metrics(y_pred[:, 1], y_test)\n print('this is valy')\n print(y_test)\n print('this is y_pred')\n print(y_pred)\n plot_precision_recall(y_test, y_pred[:, 1], model, 'show')\n out.write('----------------------------\\n')\n out.write('Using %s classifier \\n' % models_params)\n out.write(json.dumps(metrics[m]))\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n\n\ndef load_data(csv_file, nrows=None):\n return pd.read_csv(csv_file, nrows=nrows)\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef cor_heat(data_frame, var_name):\n corrmat = data_frame.corr()\n k = 12\n cols = corrmat.nlargest(k, var_name)[var_name].index\n cm = np.corrcoef(data_frame[cols].values.T)\n sns.set(font_scale=1.25)\n hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f',\n annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.\n values)\n plt.show()\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,\n np.newaxis])\n low_range = data_scaled[data_scaled[:, 0].argsort()][:10]\n high_range = data_scaled[data_scaled[:, 0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n\n<function token>\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\ndef fill_empty(data_frame, var, new_var):\n return data_frame[var].fillna(new_var)\n\n\ndef descretize(data_frame, var, num):\n return pd.cut(data_frame[var], num, retbins=True)\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef plot_precision_recall(val_Y, y_pred, model_name, output_type):\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n prec = prec[:-1]\n recall_curve = rec[:-1]\n pct_above_per_thresh = []\n number_scored = len(y_pred)\n for value in thresh:\n num_above_thresh = len(y_pred[y_pred >= value])\n pct_above_thresh = num_above_thresh / float(len(y_pred))\n if pct_above_thresh <= 1:\n pct_above_per_thresh.append(pct_above_thresh)\n else:\n raise Exception\n pct_above_per_thresh = np.array(pct_above_per_thresh)\n plt.clf()\n fig, ax1 = plt.subplots()\n ax1.plot(pct_above_per_thresh, prec, 'b')\n print('PLOTTING STUFF')\n print(pct_above_per_thresh)\n print(prec[:-1])\n ax1.set_xlabel('percent of population')\n ax1.set_ylabel('precision', color='b')\n ax2 = ax1.twinx()\n ax2.plot(pct_above_per_thresh, recall_curve, 'r')\n ax2.set_ylabel('recall', color='r')\n ax1.set_ylim([0, 1])\n ax2.set_xlim([0, 1])\n name = model_name\n plt.title(name)\n if output_type == 'save':\n plt.savefig(name)\n elif output_type == 'show':\n plt.show()\n pdb.set_trace()\n else:\n plt.show()\n pdb.set_trace()\n\n\n<function token>\n\n\ndef kfold_eval(df, target, features):\n models_params = {RandomForestClassifier: {'n_estimators': [100],\n 'criterion': ['gini', 'entropy'], 'max_features': ['sqrt', 'log2'],\n 'max_depth': [5, 10], 'n_jobs': [4], 'min_samples_leaf': [10, 50, \n 100]}, LogisticRegression: {'C': [10 ** -1, 10 ** -2, 10 ** -3],\n 'penalty': ['l1', 'l2']}, KNeighborsClassifier: {'n_neighbors': [5,\n 10, 25, 100], 'p': [1, 2, 3], 'n_jobs': [2]},\n DecisionTreeClassifier: {'max_depth': [5, 10, 15],\n 'min_samples_leaf': [2, 5, 10]}, GradientBoostingClassifier: {\n 'learning_rate': [0.1, 0.01], 'n_estimators': [100], 'max_features':\n ['sqrt', 'log2'], 'max_depth': [1, 2, 3]}, BaggingClassifier: {\n 'max_samples': [0.1, 0.25, 0.65], 'n_jobs': [4]}}\n X = df[features]\n y = df[target]\n print(y)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,\n random_state=0)\n \"\"\"\n kf = KFold(n_splits=2)\n kf.get_n_splits(X)\n #print(kf)\n KFold(n_splits=2,random_state=None,shuffle=False)\n for train_index, test_index in kf.split(X):\n print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n \"\"\"\n \"\"\"rf = RandomForestClassifier(n_estimators=100,criterion='gini',max_features='sqrt',max_depth=5)\n rf.fit(X_train, y_train)\n y_score = rf.predict_proba(X_test)\n #y_score = rf.decision_function(X_test)\n y_pred = rf.predict(X_test)\n print(roc_auc_score(y_test,y_score[:,0]))\n metrics_1 ={}\"\"\"\n class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params)\n print(accuracy_score(y_test, y_pred))\n\n\ndef extract_train_test_sets(train_start_time, train_end_time,\n test_start_time, test_end_time, df):\n train_set = df[(df['date_posted'] > train_start_time) & (df[\n 'date_posted'] < train_end_time)]\n test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted'\n ] < test_end_time)]\n return train_set, test_set\n\n\ndef class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params):\n out = open('out.txt', 'a')\n \"\"\"X_train = train_set[features] #X\n y_train = train_set[target] #y\n \n #validation\n X_test = test_set[features] #val_x\n y_test = test_set[target] #val_y\"\"\"\n metrics = {}\n for m, m_param in models_params.items():\n listofparam = get_combos(m_param)\n print('start training for {0}'.format(m))\n out.write('start training for {0}\\n'.format(m))\n for params in listofparam:\n print(params)\n out.write(json.dumps(params))\n model = m(**params)\n model.fit(X_train, y_train)\n y_pred = model.predict_proba(X_test)\n metrics[m] = get_metrics(y_pred[:, 1], y_test)\n print('this is valy')\n print(y_test)\n print('this is y_pred')\n print(y_pred)\n plot_precision_recall(y_test, y_pred[:, 1], model, 'show')\n out.write('----------------------------\\n')\n out.write('Using %s classifier \\n' % models_params)\n out.write(json.dumps(metrics[m]))\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n\n\ndef load_data(csv_file, nrows=None):\n return pd.read_csv(csv_file, nrows=nrows)\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,\n np.newaxis])\n low_range = data_scaled[data_scaled[:, 0].argsort()][:10]\n high_range = data_scaled[data_scaled[:, 0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n\n<function token>\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\ndef fill_empty(data_frame, var, new_var):\n return data_frame[var].fillna(new_var)\n\n\ndef descretize(data_frame, var, num):\n return pd.cut(data_frame[var], num, retbins=True)\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef plot_precision_recall(val_Y, y_pred, model_name, output_type):\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n prec = prec[:-1]\n recall_curve = rec[:-1]\n pct_above_per_thresh = []\n number_scored = len(y_pred)\n for value in thresh:\n num_above_thresh = len(y_pred[y_pred >= value])\n pct_above_thresh = num_above_thresh / float(len(y_pred))\n if pct_above_thresh <= 1:\n pct_above_per_thresh.append(pct_above_thresh)\n else:\n raise Exception\n pct_above_per_thresh = np.array(pct_above_per_thresh)\n plt.clf()\n fig, ax1 = plt.subplots()\n ax1.plot(pct_above_per_thresh, prec, 'b')\n print('PLOTTING STUFF')\n print(pct_above_per_thresh)\n print(prec[:-1])\n ax1.set_xlabel('percent of population')\n ax1.set_ylabel('precision', color='b')\n ax2 = ax1.twinx()\n ax2.plot(pct_above_per_thresh, recall_curve, 'r')\n ax2.set_ylabel('recall', color='r')\n ax1.set_ylim([0, 1])\n ax2.set_xlim([0, 1])\n name = model_name\n plt.title(name)\n if output_type == 'save':\n plt.savefig(name)\n elif output_type == 'show':\n plt.show()\n pdb.set_trace()\n else:\n plt.show()\n pdb.set_trace()\n\n\n<function token>\n\n\ndef kfold_eval(df, target, features):\n models_params = {RandomForestClassifier: {'n_estimators': [100],\n 'criterion': ['gini', 'entropy'], 'max_features': ['sqrt', 'log2'],\n 'max_depth': [5, 10], 'n_jobs': [4], 'min_samples_leaf': [10, 50, \n 100]}, LogisticRegression: {'C': [10 ** -1, 10 ** -2, 10 ** -3],\n 'penalty': ['l1', 'l2']}, KNeighborsClassifier: {'n_neighbors': [5,\n 10, 25, 100], 'p': [1, 2, 3], 'n_jobs': [2]},\n DecisionTreeClassifier: {'max_depth': [5, 10, 15],\n 'min_samples_leaf': [2, 5, 10]}, GradientBoostingClassifier: {\n 'learning_rate': [0.1, 0.01], 'n_estimators': [100], 'max_features':\n ['sqrt', 'log2'], 'max_depth': [1, 2, 3]}, BaggingClassifier: {\n 'max_samples': [0.1, 0.25, 0.65], 'n_jobs': [4]}}\n X = df[features]\n y = df[target]\n print(y)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,\n random_state=0)\n \"\"\"\n kf = KFold(n_splits=2)\n kf.get_n_splits(X)\n #print(kf)\n KFold(n_splits=2,random_state=None,shuffle=False)\n for train_index, test_index in kf.split(X):\n print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n \"\"\"\n \"\"\"rf = RandomForestClassifier(n_estimators=100,criterion='gini',max_features='sqrt',max_depth=5)\n rf.fit(X_train, y_train)\n y_score = rf.predict_proba(X_test)\n #y_score = rf.decision_function(X_test)\n y_pred = rf.predict(X_test)\n print(roc_auc_score(y_test,y_score[:,0]))\n metrics_1 ={}\"\"\"\n class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params)\n print(accuracy_score(y_test, y_pred))\n\n\ndef extract_train_test_sets(train_start_time, train_end_time,\n test_start_time, test_end_time, df):\n train_set = df[(df['date_posted'] > train_start_time) & (df[\n 'date_posted'] < train_end_time)]\n test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted'\n ] < test_end_time)]\n return train_set, test_set\n\n\ndef class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params):\n out = open('out.txt', 'a')\n \"\"\"X_train = train_set[features] #X\n y_train = train_set[target] #y\n \n #validation\n X_test = test_set[features] #val_x\n y_test = test_set[target] #val_y\"\"\"\n metrics = {}\n for m, m_param in models_params.items():\n listofparam = get_combos(m_param)\n print('start training for {0}'.format(m))\n out.write('start training for {0}\\n'.format(m))\n for params in listofparam:\n print(params)\n out.write(json.dumps(params))\n model = m(**params)\n model.fit(X_train, y_train)\n y_pred = model.predict_proba(X_test)\n metrics[m] = get_metrics(y_pred[:, 1], y_test)\n print('this is valy')\n print(y_test)\n print('this is y_pred')\n print(y_pred)\n plot_precision_recall(y_test, y_pred[:, 1], model, 'show')\n out.write('----------------------------\\n')\n out.write('Using %s classifier \\n' % models_params)\n out.write(json.dumps(metrics[m]))\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,\n np.newaxis])\n low_range = data_scaled[data_scaled[:, 0].argsort()][:10]\n high_range = data_scaled[data_scaled[:, 0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n\n<function token>\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\ndef fill_empty(data_frame, var, new_var):\n return data_frame[var].fillna(new_var)\n\n\ndef descretize(data_frame, var, num):\n return pd.cut(data_frame[var], num, retbins=True)\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef plot_precision_recall(val_Y, y_pred, model_name, output_type):\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n prec = prec[:-1]\n recall_curve = rec[:-1]\n pct_above_per_thresh = []\n number_scored = len(y_pred)\n for value in thresh:\n num_above_thresh = len(y_pred[y_pred >= value])\n pct_above_thresh = num_above_thresh / float(len(y_pred))\n if pct_above_thresh <= 1:\n pct_above_per_thresh.append(pct_above_thresh)\n else:\n raise Exception\n pct_above_per_thresh = np.array(pct_above_per_thresh)\n plt.clf()\n fig, ax1 = plt.subplots()\n ax1.plot(pct_above_per_thresh, prec, 'b')\n print('PLOTTING STUFF')\n print(pct_above_per_thresh)\n print(prec[:-1])\n ax1.set_xlabel('percent of population')\n ax1.set_ylabel('precision', color='b')\n ax2 = ax1.twinx()\n ax2.plot(pct_above_per_thresh, recall_curve, 'r')\n ax2.set_ylabel('recall', color='r')\n ax1.set_ylim([0, 1])\n ax2.set_xlim([0, 1])\n name = model_name\n plt.title(name)\n if output_type == 'save':\n plt.savefig(name)\n elif output_type == 'show':\n plt.show()\n pdb.set_trace()\n else:\n plt.show()\n pdb.set_trace()\n\n\n<function token>\n\n\ndef kfold_eval(df, target, features):\n models_params = {RandomForestClassifier: {'n_estimators': [100],\n 'criterion': ['gini', 'entropy'], 'max_features': ['sqrt', 'log2'],\n 'max_depth': [5, 10], 'n_jobs': [4], 'min_samples_leaf': [10, 50, \n 100]}, LogisticRegression: {'C': [10 ** -1, 10 ** -2, 10 ** -3],\n 'penalty': ['l1', 'l2']}, KNeighborsClassifier: {'n_neighbors': [5,\n 10, 25, 100], 'p': [1, 2, 3], 'n_jobs': [2]},\n DecisionTreeClassifier: {'max_depth': [5, 10, 15],\n 'min_samples_leaf': [2, 5, 10]}, GradientBoostingClassifier: {\n 'learning_rate': [0.1, 0.01], 'n_estimators': [100], 'max_features':\n ['sqrt', 'log2'], 'max_depth': [1, 2, 3]}, BaggingClassifier: {\n 'max_samples': [0.1, 0.25, 0.65], 'n_jobs': [4]}}\n X = df[features]\n y = df[target]\n print(y)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,\n random_state=0)\n \"\"\"\n kf = KFold(n_splits=2)\n kf.get_n_splits(X)\n #print(kf)\n KFold(n_splits=2,random_state=None,shuffle=False)\n for train_index, test_index in kf.split(X):\n print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n \"\"\"\n \"\"\"rf = RandomForestClassifier(n_estimators=100,criterion='gini',max_features='sqrt',max_depth=5)\n rf.fit(X_train, y_train)\n y_score = rf.predict_proba(X_test)\n #y_score = rf.decision_function(X_test)\n y_pred = rf.predict(X_test)\n print(roc_auc_score(y_test,y_score[:,0]))\n metrics_1 ={}\"\"\"\n class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params)\n print(accuracy_score(y_test, y_pred))\n\n\ndef extract_train_test_sets(train_start_time, train_end_time,\n test_start_time, test_end_time, df):\n train_set = df[(df['date_posted'] > train_start_time) & (df[\n 'date_posted'] < train_end_time)]\n test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted'\n ] < test_end_time)]\n return train_set, test_set\n\n\ndef class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params):\n out = open('out.txt', 'a')\n \"\"\"X_train = train_set[features] #X\n y_train = train_set[target] #y\n \n #validation\n X_test = test_set[features] #val_x\n y_test = test_set[target] #val_y\"\"\"\n metrics = {}\n for m, m_param in models_params.items():\n listofparam = get_combos(m_param)\n print('start training for {0}'.format(m))\n out.write('start training for {0}\\n'.format(m))\n for params in listofparam:\n print(params)\n out.write(json.dumps(params))\n model = m(**params)\n model.fit(X_train, y_train)\n y_pred = model.predict_proba(X_test)\n metrics[m] = get_metrics(y_pred[:, 1], y_test)\n print('this is valy')\n print(y_test)\n print('this is y_pred')\n print(y_pred)\n plot_precision_recall(y_test, y_pred[:, 1], model, 'show')\n out.write('----------------------------\\n')\n out.write('Using %s classifier \\n' % models_params)\n out.write(json.dumps(metrics[m]))\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,\n np.newaxis])\n low_range = data_scaled[data_scaled[:, 0].argsort()][:10]\n high_range = data_scaled[data_scaled[:, 0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n\n<function token>\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\ndef fill_empty(data_frame, var, new_var):\n return data_frame[var].fillna(new_var)\n\n\ndef descretize(data_frame, var, num):\n return pd.cut(data_frame[var], num, retbins=True)\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef plot_precision_recall(val_Y, y_pred, model_name, output_type):\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n prec = prec[:-1]\n recall_curve = rec[:-1]\n pct_above_per_thresh = []\n number_scored = len(y_pred)\n for value in thresh:\n num_above_thresh = len(y_pred[y_pred >= value])\n pct_above_thresh = num_above_thresh / float(len(y_pred))\n if pct_above_thresh <= 1:\n pct_above_per_thresh.append(pct_above_thresh)\n else:\n raise Exception\n pct_above_per_thresh = np.array(pct_above_per_thresh)\n plt.clf()\n fig, ax1 = plt.subplots()\n ax1.plot(pct_above_per_thresh, prec, 'b')\n print('PLOTTING STUFF')\n print(pct_above_per_thresh)\n print(prec[:-1])\n ax1.set_xlabel('percent of population')\n ax1.set_ylabel('precision', color='b')\n ax2 = ax1.twinx()\n ax2.plot(pct_above_per_thresh, recall_curve, 'r')\n ax2.set_ylabel('recall', color='r')\n ax1.set_ylim([0, 1])\n ax2.set_xlim([0, 1])\n name = model_name\n plt.title(name)\n if output_type == 'save':\n plt.savefig(name)\n elif output_type == 'show':\n plt.show()\n pdb.set_trace()\n else:\n plt.show()\n pdb.set_trace()\n\n\n<function token>\n<function token>\n\n\ndef extract_train_test_sets(train_start_time, train_end_time,\n test_start_time, test_end_time, df):\n train_set = df[(df['date_posted'] > train_start_time) & (df[\n 'date_posted'] < train_end_time)]\n test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted'\n ] < test_end_time)]\n return train_set, test_set\n\n\ndef class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params):\n out = open('out.txt', 'a')\n \"\"\"X_train = train_set[features] #X\n y_train = train_set[target] #y\n \n #validation\n X_test = test_set[features] #val_x\n y_test = test_set[target] #val_y\"\"\"\n metrics = {}\n for m, m_param in models_params.items():\n listofparam = get_combos(m_param)\n print('start training for {0}'.format(m))\n out.write('start training for {0}\\n'.format(m))\n for params in listofparam:\n print(params)\n out.write(json.dumps(params))\n model = m(**params)\n model.fit(X_train, y_train)\n y_pred = model.predict_proba(X_test)\n metrics[m] = get_metrics(y_pred[:, 1], y_test)\n print('this is valy')\n print(y_test)\n print('this is y_pred')\n print(y_pred)\n plot_precision_recall(y_test, y_pred[:, 1], model, 'show')\n out.write('----------------------------\\n')\n out.write('Using %s classifier \\n' % models_params)\n out.write(json.dumps(metrics[m]))\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,\n np.newaxis])\n low_range = data_scaled[data_scaled[:, 0].argsort()][:10]\n high_range = data_scaled[data_scaled[:, 0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n\n<function token>\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\n<function token>\n\n\ndef descretize(data_frame, var, num):\n return pd.cut(data_frame[var], num, retbins=True)\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef plot_precision_recall(val_Y, y_pred, model_name, output_type):\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n prec = prec[:-1]\n recall_curve = rec[:-1]\n pct_above_per_thresh = []\n number_scored = len(y_pred)\n for value in thresh:\n num_above_thresh = len(y_pred[y_pred >= value])\n pct_above_thresh = num_above_thresh / float(len(y_pred))\n if pct_above_thresh <= 1:\n pct_above_per_thresh.append(pct_above_thresh)\n else:\n raise Exception\n pct_above_per_thresh = np.array(pct_above_per_thresh)\n plt.clf()\n fig, ax1 = plt.subplots()\n ax1.plot(pct_above_per_thresh, prec, 'b')\n print('PLOTTING STUFF')\n print(pct_above_per_thresh)\n print(prec[:-1])\n ax1.set_xlabel('percent of population')\n ax1.set_ylabel('precision', color='b')\n ax2 = ax1.twinx()\n ax2.plot(pct_above_per_thresh, recall_curve, 'r')\n ax2.set_ylabel('recall', color='r')\n ax1.set_ylim([0, 1])\n ax2.set_xlim([0, 1])\n name = model_name\n plt.title(name)\n if output_type == 'save':\n plt.savefig(name)\n elif output_type == 'show':\n plt.show()\n pdb.set_trace()\n else:\n plt.show()\n pdb.set_trace()\n\n\n<function token>\n<function token>\n\n\ndef extract_train_test_sets(train_start_time, train_end_time,\n test_start_time, test_end_time, df):\n train_set = df[(df['date_posted'] > train_start_time) & (df[\n 'date_posted'] < train_end_time)]\n test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted'\n ] < test_end_time)]\n return train_set, test_set\n\n\ndef class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params):\n out = open('out.txt', 'a')\n \"\"\"X_train = train_set[features] #X\n y_train = train_set[target] #y\n \n #validation\n X_test = test_set[features] #val_x\n y_test = test_set[target] #val_y\"\"\"\n metrics = {}\n for m, m_param in models_params.items():\n listofparam = get_combos(m_param)\n print('start training for {0}'.format(m))\n out.write('start training for {0}\\n'.format(m))\n for params in listofparam:\n print(params)\n out.write(json.dumps(params))\n model = m(**params)\n model.fit(X_train, y_train)\n y_pred = model.predict_proba(X_test)\n metrics[m] = get_metrics(y_pred[:, 1], y_test)\n print('this is valy')\n print(y_test)\n print('this is y_pred')\n print(y_pred)\n plot_precision_recall(y_test, y_pred[:, 1], model, 'show')\n out.write('----------------------------\\n')\n out.write('Using %s classifier \\n' % models_params)\n out.write(json.dumps(metrics[m]))\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,\n np.newaxis])\n low_range = data_scaled[data_scaled[:, 0].argsort()][:10]\n high_range = data_scaled[data_scaled[:, 0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n\n<function token>\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\n<function token>\n\n\ndef descretize(data_frame, var, num):\n return pd.cut(data_frame[var], num, retbins=True)\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef extract_train_test_sets(train_start_time, train_end_time,\n test_start_time, test_end_time, df):\n train_set = df[(df['date_posted'] > train_start_time) & (df[\n 'date_posted'] < train_end_time)]\n test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted'\n ] < test_end_time)]\n return train_set, test_set\n\n\ndef class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params):\n out = open('out.txt', 'a')\n \"\"\"X_train = train_set[features] #X\n y_train = train_set[target] #y\n \n #validation\n X_test = test_set[features] #val_x\n y_test = test_set[target] #val_y\"\"\"\n metrics = {}\n for m, m_param in models_params.items():\n listofparam = get_combos(m_param)\n print('start training for {0}'.format(m))\n out.write('start training for {0}\\n'.format(m))\n for params in listofparam:\n print(params)\n out.write(json.dumps(params))\n model = m(**params)\n model.fit(X_train, y_train)\n y_pred = model.predict_proba(X_test)\n metrics[m] = get_metrics(y_pred[:, 1], y_test)\n print('this is valy')\n print(y_test)\n print('this is y_pred')\n print(y_pred)\n plot_precision_recall(y_test, y_pred[:, 1], model, 'show')\n out.write('----------------------------\\n')\n out.write('Using %s classifier \\n' % models_params)\n out.write(json.dumps(metrics[m]))\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,\n np.newaxis])\n low_range = data_scaled[data_scaled[:, 0].argsort()][:10]\n high_range = data_scaled[data_scaled[:, 0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n\n<function token>\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\n<function token>\n<function token>\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef extract_train_test_sets(train_start_time, train_end_time,\n test_start_time, test_end_time, df):\n train_set = df[(df['date_posted'] > train_start_time) & (df[\n 'date_posted'] < train_end_time)]\n test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted'\n ] < test_end_time)]\n return train_set, test_set\n\n\ndef class_comp(X_train, X_test, y_train, y_test, target, features,\n models_params):\n out = open('out.txt', 'a')\n \"\"\"X_train = train_set[features] #X\n y_train = train_set[target] #y\n \n #validation\n X_test = test_set[features] #val_x\n y_test = test_set[target] #val_y\"\"\"\n metrics = {}\n for m, m_param in models_params.items():\n listofparam = get_combos(m_param)\n print('start training for {0}'.format(m))\n out.write('start training for {0}\\n'.format(m))\n for params in listofparam:\n print(params)\n out.write(json.dumps(params))\n model = m(**params)\n model.fit(X_train, y_train)\n y_pred = model.predict_proba(X_test)\n metrics[m] = get_metrics(y_pred[:, 1], y_test)\n print('this is valy')\n print(y_test)\n print('this is y_pred')\n print(y_pred)\n plot_precision_recall(y_test, y_pred[:, 1], model, 'show')\n out.write('----------------------------\\n')\n out.write('Using %s classifier \\n' % models_params)\n out.write(json.dumps(metrics[m]))\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,\n np.newaxis])\n low_range = data_scaled[data_scaled[:, 0].argsort()][:10]\n high_range = data_scaled[data_scaled[:, 0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n\n<function token>\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\n<function token>\n<function token>\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef extract_train_test_sets(train_start_time, train_end_time,\n test_start_time, test_end_time, df):\n train_set = df[(df['date_posted'] > train_start_time) & (df[\n 'date_posted'] < train_end_time)]\n test_set = df[(df['date_posted'] > test_start_time) & (df['date_posted'\n ] < test_end_time)]\n return train_set, test_set\n\n\n<function token>\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef scale(data_frame, var_scale):\n data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,\n np.newaxis])\n low_range = data_scaled[data_scaled[:, 0].argsort()][:10]\n high_range = data_scaled[data_scaled[:, 0].argsort()][-10:]\n print('outer range (low) of the distribution:')\n print(low_range)\n print('\\nouter range (high) of the distribution:')\n print(high_range)\n\n\n<function token>\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\n<function token>\n<function token>\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\n<function token>\n<function token>\n\n\ndef dummy_var(data_frame, var):\n return pd.get_dummies(data_frame[var])\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef norm_plot(data_frame, var_name):\n sns.distplot(data_frame[var_name], fit=norm)\n fig = plt.figure()\n res = stats.probplot(data_frame[var_name], plot=plt)\n plt.show()\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef get_metrics(y_pred, val_Y):\n metric_results = {}\n ones = np.sum(val_Y)['SeriousDlqin2yrs'] / float(len(val_Y))\n zeros = 1 - ones\n try:\n metric_results['baseline'] = max(ones, zeros)\n except:\n pdb.set_trace()\n if ones > zeros:\n metric_results['precision_base'] = precision_score(val_Y, np.ones(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.ones[len(val_Y)]\n )\n else:\n metric_results['precision_base'] = precision_score(val_Y, np.zeros(\n len(val_Y)))\n metric_results['recall_base'] = recall_score(val_Y, np.zeros(len(\n val_Y)))\n perf_metrics = [0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5]\n for i in perf_metrics:\n print('Recall AT \\n')\n print(recall_at_k(val_Y, y_pred, i))\n metric_results['precision at' + str([i])] = precision_at_k(val_Y,\n y_pred, i)\n metric_results['recall at' + str([i])] = recall_score(val_Y, y_pred >\n 1 - i)\n metric_results['F1 at' + str([i])] = f1_score(val_Y, y_pred > 1 - i)\n metric_results['ROC'] = roc_auc_score(val_Y, y_pred)\n prec, rec, thresh = precision_recall_curve(val_Y, y_pred)\n metric_results['PREC'] = prec.tolist()\n metric_results['REC'] = rec.tolist()\n metric_results['THRESH'] = thresh.tolist()\n return metric_results\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<code token>\n<import token>\n<docstring token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n" ]
false
98,745
698d9a23877eecfd79204249b13c4e7d2063139d
from w_location import LocationWrapper class CastleWrapper: """ this class is a wrapper for castle. """ def __init__(self, castle): self.castle = castle def current_health(self): return self.castle.current_health def get_location(self): return LocationWrapper(self.castle.location) def get_x(self): return self.get_location().get_x() def get_y(self): return self.get_location().get_y()
[ "from w_location import LocationWrapper\n\n\nclass CastleWrapper:\n \"\"\"\n this class is a wrapper for castle.\n \"\"\"\n\n def __init__(self, castle):\n self.castle = castle\n\n def current_health(self):\n return self.castle.current_health\n\n def get_location(self):\n return LocationWrapper(self.castle.location)\n\n def get_x(self):\n return self.get_location().get_x()\n\n def get_y(self):\n return self.get_location().get_y()\n", "<import token>\n\n\nclass CastleWrapper:\n \"\"\"\n this class is a wrapper for castle.\n \"\"\"\n\n def __init__(self, castle):\n self.castle = castle\n\n def current_health(self):\n return self.castle.current_health\n\n def get_location(self):\n return LocationWrapper(self.castle.location)\n\n def get_x(self):\n return self.get_location().get_x()\n\n def get_y(self):\n return self.get_location().get_y()\n", "<import token>\n\n\nclass CastleWrapper:\n <docstring token>\n\n def __init__(self, castle):\n self.castle = castle\n\n def current_health(self):\n return self.castle.current_health\n\n def get_location(self):\n return LocationWrapper(self.castle.location)\n\n def get_x(self):\n return self.get_location().get_x()\n\n def get_y(self):\n return self.get_location().get_y()\n", "<import token>\n\n\nclass CastleWrapper:\n <docstring token>\n <function token>\n\n def current_health(self):\n return self.castle.current_health\n\n def get_location(self):\n return LocationWrapper(self.castle.location)\n\n def get_x(self):\n return self.get_location().get_x()\n\n def get_y(self):\n return self.get_location().get_y()\n", "<import token>\n\n\nclass CastleWrapper:\n <docstring token>\n <function token>\n\n def current_health(self):\n return self.castle.current_health\n\n def get_location(self):\n return LocationWrapper(self.castle.location)\n <function token>\n\n def get_y(self):\n return self.get_location().get_y()\n", "<import token>\n\n\nclass CastleWrapper:\n <docstring token>\n <function token>\n\n def current_health(self):\n return self.castle.current_health\n\n def get_location(self):\n return LocationWrapper(self.castle.location)\n <function token>\n <function token>\n", "<import token>\n\n\nclass CastleWrapper:\n <docstring token>\n <function token>\n <function token>\n\n def get_location(self):\n return LocationWrapper(self.castle.location)\n <function token>\n <function token>\n", "<import token>\n\n\nclass CastleWrapper:\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<import token>\n<class token>\n" ]
false
98,746
317267d8b041550887b2e071288bb07f7847cb3e
from django.shortcuts import render, redirect from Books.forms import * # Create your views here. def bookcreate(request): template_name = "bookCreate.html" form = BookForm() dict = {} dict["form"] = form query = Book.objects.all() dict["books"] = query if request.method == "POST": form = BookForm(request.POST) if form.is_valid(): form.save() query = Book.objects.all() dict["books"] = query return render(request, template_name, dict) else: dict["form"] = form return render(request, template_name, dict) def viewbook(request, pk): obj = Book.objects.get(id=pk) dict = {} dict["items"] = obj return render(request, "bookview.html", dict) def deletebook(request, pk): obj = Book.objects.get(id=pk).delete() return redirect("createbook") def bookupdate(request, pk): query = Book.objects.get(id=pk) form = Bookupdateform(instance=query) dict = {} dict["form"] = form if request.method == "POST": form = Bookupdateform(instance=query, data=request.POST) form.save() return redirect("createbook") return render(request, "updatebook.html", dict)
[ "from django.shortcuts import render, redirect\nfrom Books.forms import *\n\n\n# Create your views here.\n\ndef bookcreate(request):\n template_name = \"bookCreate.html\"\n form = BookForm()\n dict = {}\n dict[\"form\"] = form\n query = Book.objects.all()\n dict[\"books\"] = query\n if request.method == \"POST\":\n form = BookForm(request.POST)\n if form.is_valid():\n form.save()\n query = Book.objects.all()\n dict[\"books\"] = query\n return render(request, template_name, dict)\n else:\n dict[\"form\"] = form\n return render(request, template_name, dict)\n\n\ndef viewbook(request, pk):\n obj = Book.objects.get(id=pk)\n dict = {}\n dict[\"items\"] = obj\n return render(request, \"bookview.html\", dict)\n\n\ndef deletebook(request, pk):\n obj = Book.objects.get(id=pk).delete()\n return redirect(\"createbook\")\n\n\ndef bookupdate(request, pk):\n query = Book.objects.get(id=pk)\n form = Bookupdateform(instance=query)\n dict = {}\n dict[\"form\"] = form\n if request.method == \"POST\":\n form = Bookupdateform(instance=query, data=request.POST)\n form.save()\n return redirect(\"createbook\")\n return render(request, \"updatebook.html\", dict)\n", "from django.shortcuts import render, redirect\nfrom Books.forms import *\n\n\ndef bookcreate(request):\n template_name = 'bookCreate.html'\n form = BookForm()\n dict = {}\n dict['form'] = form\n query = Book.objects.all()\n dict['books'] = query\n if request.method == 'POST':\n form = BookForm(request.POST)\n if form.is_valid():\n form.save()\n query = Book.objects.all()\n dict['books'] = query\n return render(request, template_name, dict)\n else:\n dict['form'] = form\n return render(request, template_name, dict)\n\n\ndef viewbook(request, pk):\n obj = Book.objects.get(id=pk)\n dict = {}\n dict['items'] = obj\n return render(request, 'bookview.html', dict)\n\n\ndef deletebook(request, pk):\n obj = Book.objects.get(id=pk).delete()\n return redirect('createbook')\n\n\ndef bookupdate(request, pk):\n query = Book.objects.get(id=pk)\n form = Bookupdateform(instance=query)\n dict = {}\n dict['form'] = form\n if request.method == 'POST':\n form = Bookupdateform(instance=query, data=request.POST)\n form.save()\n return redirect('createbook')\n return render(request, 'updatebook.html', dict)\n", "<import token>\n\n\ndef bookcreate(request):\n template_name = 'bookCreate.html'\n form = BookForm()\n dict = {}\n dict['form'] = form\n query = Book.objects.all()\n dict['books'] = query\n if request.method == 'POST':\n form = BookForm(request.POST)\n if form.is_valid():\n form.save()\n query = Book.objects.all()\n dict['books'] = query\n return render(request, template_name, dict)\n else:\n dict['form'] = form\n return render(request, template_name, dict)\n\n\ndef viewbook(request, pk):\n obj = Book.objects.get(id=pk)\n dict = {}\n dict['items'] = obj\n return render(request, 'bookview.html', dict)\n\n\ndef deletebook(request, pk):\n obj = Book.objects.get(id=pk).delete()\n return redirect('createbook')\n\n\ndef bookupdate(request, pk):\n query = Book.objects.get(id=pk)\n form = Bookupdateform(instance=query)\n dict = {}\n dict['form'] = form\n if request.method == 'POST':\n form = Bookupdateform(instance=query, data=request.POST)\n form.save()\n return redirect('createbook')\n return render(request, 'updatebook.html', dict)\n", "<import token>\n\n\ndef bookcreate(request):\n template_name = 'bookCreate.html'\n form = BookForm()\n dict = {}\n dict['form'] = form\n query = Book.objects.all()\n dict['books'] = query\n if request.method == 'POST':\n form = BookForm(request.POST)\n if form.is_valid():\n form.save()\n query = Book.objects.all()\n dict['books'] = query\n return render(request, template_name, dict)\n else:\n dict['form'] = form\n return render(request, template_name, dict)\n\n\ndef viewbook(request, pk):\n obj = Book.objects.get(id=pk)\n dict = {}\n dict['items'] = obj\n return render(request, 'bookview.html', dict)\n\n\n<function token>\n\n\ndef bookupdate(request, pk):\n query = Book.objects.get(id=pk)\n form = Bookupdateform(instance=query)\n dict = {}\n dict['form'] = form\n if request.method == 'POST':\n form = Bookupdateform(instance=query, data=request.POST)\n form.save()\n return redirect('createbook')\n return render(request, 'updatebook.html', dict)\n", "<import token>\n<function token>\n\n\ndef viewbook(request, pk):\n obj = Book.objects.get(id=pk)\n dict = {}\n dict['items'] = obj\n return render(request, 'bookview.html', dict)\n\n\n<function token>\n\n\ndef bookupdate(request, pk):\n query = Book.objects.get(id=pk)\n form = Bookupdateform(instance=query)\n dict = {}\n dict['form'] = form\n if request.method == 'POST':\n form = Bookupdateform(instance=query, data=request.POST)\n form.save()\n return redirect('createbook')\n return render(request, 'updatebook.html', dict)\n", "<import token>\n<function token>\n<function token>\n<function token>\n\n\ndef bookupdate(request, pk):\n query = Book.objects.get(id=pk)\n form = Bookupdateform(instance=query)\n dict = {}\n dict['form'] = form\n if request.method == 'POST':\n form = Bookupdateform(instance=query, data=request.POST)\n form.save()\n return redirect('createbook')\n return render(request, 'updatebook.html', dict)\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n" ]
false
98,747
6a969cc5b8a74ae7399de43bb24b98fdbec58c7a
import json from os import environ from packaging.requirements import Requirement from packaging.specifiers import SpecifierSet import pytest from mach_nix.data.bucket_dict import LazyBucketDict from mach_nix.requirements import parse_reqs_line @pytest.mark.parametrize("input, exp_output", [ ('requests', ('requests', (), None, None, None)) , ('requests[socks] ==2.24.0', ('requests', ('socks',), (SpecifierSet('==2.24.0'),), None, None)) , ('requests[socks,test] 2.24.0', ('requests', ('socks', 'test'), (SpecifierSet('==2.24.0'),), None, None)) , ('python >=2.7,<2.8.0a0', ('python', (), (SpecifierSet('>=2.7,<2.8.0a0'),), None, None)) , ('requests == 2.24.0', ('requests', (), (SpecifierSet('==2.24.0'),), None, None)) , ('pdfminer.six == 20200726', ('pdfminer.six', (), (SpecifierSet('==20200726'),), None, None)) , ('python>= 3.5', ('python', (), (SpecifierSet('>=3.5'),), None, None)) , ('python >=3.5', ('python', (), (SpecifierSet('>=3.5'),), None, None)) , ('python >=2.6, !=3.0.*', ('python', (), (SpecifierSet('>=2.6,!=3.0.*'),), None, None)) , ("unittest2 >=2.0,<3.0 ; python_version == '2.4' or python_version == '2.5'", ('unittest2', (), (SpecifierSet('>=2.0,<3.0'),), None, "python_version == '2.4' or python_version == '2.5'")) , ("pywin32 > 1.0 ; sys.platform == 'win32'", ('pywin32', (), (SpecifierSet('>1.0'),), None, "sys.platform == 'win32'")) , ("certifi (==2016.9.26) ; extra == 'certs'", ('certifi', ('certs',), (SpecifierSet('==2016.9.26'),), None, "extra == 'certs'")) , ("sphinx ; extra == 'docs'", ('sphinx', ('docs',), None, None, "extra == 'docs'")) , ('requests 2.24.0', ('requests', (), (SpecifierSet('==2.24.0'),), None, None)) , ('requests 2.24.0', ('requests', (), (SpecifierSet('==2.24.0'),), None, None)) , ('requests 2.24.0', ('requests', (), (SpecifierSet('==2.24.0'),), None, None)) , ('requests 2.24.0', ('requests', (), (SpecifierSet('==2.24.0'),), None, None)) , ('hdf5 >=1.10.5,<1.10.6.0a0 mpi_mpich_*', ('hdf5', (), (SpecifierSet('>=1.10.5,<1.10.6.0a0'),), 'mpi_mpich_*', None)) , ('blas 1.* openblas', ('blas', (), (SpecifierSet('==1.*'),), 'openblas', None)) , ('blas * openblas', ('blas', (), (SpecifierSet('==*'),), 'openblas', None)) , ('blas 1.1 openblas', ('blas', (), (SpecifierSet('==1.1'),), 'openblas', None)) , ('requests >=2.24.0 build123*', ('requests', (), (SpecifierSet('>=2.24.0'),), 'build123*', None)) , ('requests ==2.24.* build123*', ('requests', (), (SpecifierSet('==2.24.*'),), 'build123*', None)) , ('requests 2.24.* build123*', ('requests', (), (SpecifierSet('==2.24.*'),), 'build123*', None)) , ('requests 2.24.0 build123*', ('requests', (), (SpecifierSet('==2.24.0'),), 'build123*', None)) , ('requests 2.24.0 *bla', ('requests', (), (SpecifierSet('==2.24.0'),), '*bla', None)) , ('requests 2.24.0 *', ('requests', (), (SpecifierSet('==2.24.0'),), '*', None)) , ('requests * *bla', ('requests', (), (SpecifierSet('==*'),), '*bla', None)) , ('requests * *', ('requests', (), (SpecifierSet('==*'),), '*', None)) , ('requests 2.24.0 build123*', ('requests', (), (SpecifierSet('==2.24.0'),), 'build123*', None)) , ('requests 2.24.0 build123*', ('requests', (), (SpecifierSet('==2.24.0'),), 'build123*', None)) , ('requests 2.24.0 build123*', ('requests', (), (SpecifierSet('==2.24.0'),), 'build123*', None)) , ('ruamel.yaml >=0.12.4,<0.16|0.16.5.*', ('ruamel.yaml', (), (SpecifierSet('>=0.12.4,<0.16'), SpecifierSet('==0.16.5.*')), None, None)) , ('openjdk =8|11', ('openjdk', (), (SpecifierSet('==8'), SpecifierSet('==11')), None, None)) , ('python 3.6.9 ab_73_pypy', ('python', (), (SpecifierSet('==3.6.9'),), 'ab_73_pypy', None)) , ('gitpython >=3.0.8,3.0.*', ('gitpython', (), (SpecifierSet('>=3.0.8,==3.0.*'),), None, None)) , ("zest.releaser[recommended] ; extra == 'maintainer'", ('zest.releaser', ('recommended', 'maintainer'), None, None, "extra == 'maintainer'")) , ('pytz (>dev)', ('pytz', (), (), None, None)) , ('libcurl 7.71.1 h20c2e04_1', ('libcurl', (), (SpecifierSet('==7.71.1'),), 'h20c2e04_1', None)) , ('ixmp ==0.1.3 1', ('ixmp', (), (SpecifierSet('==0.1.3',),), '1', None)) ]) def test_parse_requirements(input, exp_output): assert parse_reqs_line(input) == exp_output # Pypi packages contain a lot of invalid requirement syntax. # All lines that can't be parsed by packaging are ignored. # Additionally, some syntax that we don't currently support # are ignored. # All other lines must be parsed without errors. def parse_or_ignore_line(line): lineStripped = line.strip().replace("'", "").replace('"', '') if not len(lineStripped): return if line.startswith("#"): return # We don't currently support requirements with these. unsupported = ( "@", "===", ) if any((x in lineStripped for x in unsupported)): return # We turn the DeprecationWarning raised by # packaging.specifier.LegacySpecifier into an error in # test_parse_all_pypi_reqs below, so this will raise in # that case. try: Requirement(line) except Exception: return False parse_reqs_line(line) def parse_or_ignore_line_conda(line): # lineStripped = line.strip().replace("'", "").replace('"', '') lineStripped = line # if not len(lineStripped): # return # if line.startswith("#"): # return if any(lineStripped.startswith(x) for x in [ ]): return if any(lineStripped.endswith(x) for x in [ ]): return if any((x in lineStripped for x in [ 'blas *.* mkl' ])): return parse_reqs_line(line) # Constructing a packaging.specifiers.LegacySpecifier # issues a warning containing "LegacyVersion". We # turn it into an error here, so we can treat it as # unparseable. @pytest.mark.filterwarnings("error:.*LegacyVersion.*:DeprecationWarning") @pytest.mark.parametrize("bucket", LazyBucketDict.bucket_keys()) def test_parse_all_pypi_reqs(bucket): data_dir = environ.get("PYPI_DATA", default=None) data = LazyBucketDict(f"{data_dir}/sdist") for pname, vers in data.by_bucket(bucket).items(): for ver, pyvers in vers.items(): if isinstance(pyvers, str): continue for pyver, release in pyvers.items(): if isinstance(release, str): continue for key in ("setup_requires", "install_requires"): if key in release: for line in release[key]: parse_or_ignore_line(line) if "extras_require" in release: for extra, lines in release["extras_require"].items(): for line in lines: parse_or_ignore_line(line) def conda_channel_files(): conda_data = environ.get("CONDA_DATA", None) if not conda_data: return [] with open(conda_data) as f: data = json.load(f) for channel, files in data.items(): for file in files: yield file @pytest.mark.skipif(conda_channel_files() == [], reason="no CONDA_DATA provided") @pytest.mark.parametrize("file", conda_channel_files()) def test_parse_all_conda_reqs(file): with open(file) as f: cdata = json.load(f) for pname, pdata in cdata['packages'].items(): for line in pdata['depends']: parse_or_ignore_line_conda(line)
[ "import json\nfrom os import environ\n\nfrom packaging.requirements import Requirement\nfrom packaging.specifiers import SpecifierSet\nimport pytest\n\nfrom mach_nix.data.bucket_dict import LazyBucketDict\nfrom mach_nix.requirements import parse_reqs_line\n\n\[email protected](\"input, exp_output\", [\n\n ('requests', ('requests', (), None, None, None))\n , ('requests[socks] ==2.24.0', ('requests', ('socks',), (SpecifierSet('==2.24.0'),), None, None))\n , ('requests[socks,test] 2.24.0', ('requests', ('socks', 'test'), (SpecifierSet('==2.24.0'),), None, None))\n , ('python >=2.7,<2.8.0a0', ('python', (), (SpecifierSet('>=2.7,<2.8.0a0'),), None, None))\n , ('requests == 2.24.0', ('requests', (), (SpecifierSet('==2.24.0'),), None, None))\n , ('pdfminer.six == 20200726', ('pdfminer.six', (), (SpecifierSet('==20200726'),), None, None))\n , ('python>= 3.5', ('python', (), (SpecifierSet('>=3.5'),), None, None))\n , ('python >=3.5', ('python', (), (SpecifierSet('>=3.5'),), None, None))\n , ('python >=2.6, !=3.0.*', ('python', (), (SpecifierSet('>=2.6,!=3.0.*'),), None, None))\n , (\"unittest2 >=2.0,<3.0 ; python_version == '2.4' or python_version == '2.5'\",\n ('unittest2', (), (SpecifierSet('>=2.0,<3.0'),), None, \"python_version == '2.4' or python_version == '2.5'\"))\n , (\"pywin32 > 1.0 ; sys.platform == 'win32'\", ('pywin32', (), (SpecifierSet('>1.0'),), None, \"sys.platform == 'win32'\"))\n , (\"certifi (==2016.9.26) ; extra == 'certs'\",\n ('certifi', ('certs',), (SpecifierSet('==2016.9.26'),), None, \"extra == 'certs'\"))\n , (\"sphinx ; extra == 'docs'\", ('sphinx', ('docs',), None, None, \"extra == 'docs'\"))\n , ('requests 2.24.0', ('requests', (), (SpecifierSet('==2.24.0'),), None, None))\n , ('requests 2.24.0', ('requests', (), (SpecifierSet('==2.24.0'),), None, None))\n , ('requests 2.24.0', ('requests', (), (SpecifierSet('==2.24.0'),), None, None))\n , ('requests 2.24.0', ('requests', (), (SpecifierSet('==2.24.0'),), None, None))\n , ('hdf5 >=1.10.5,<1.10.6.0a0 mpi_mpich_*',\n ('hdf5', (), (SpecifierSet('>=1.10.5,<1.10.6.0a0'),), 'mpi_mpich_*', None))\n , ('blas 1.* openblas', ('blas', (), (SpecifierSet('==1.*'),), 'openblas', None))\n , ('blas * openblas', ('blas', (), (SpecifierSet('==*'),), 'openblas', None))\n , ('blas 1.1 openblas', ('blas', (), (SpecifierSet('==1.1'),), 'openblas', None))\n , ('requests >=2.24.0 build123*', ('requests', (), (SpecifierSet('>=2.24.0'),), 'build123*', None))\n , ('requests ==2.24.* build123*', ('requests', (), (SpecifierSet('==2.24.*'),), 'build123*', None))\n , ('requests 2.24.* build123*', ('requests', (), (SpecifierSet('==2.24.*'),), 'build123*', None))\n , ('requests 2.24.0 build123*', ('requests', (), (SpecifierSet('==2.24.0'),), 'build123*', None))\n , ('requests 2.24.0 *bla', ('requests', (), (SpecifierSet('==2.24.0'),), '*bla', None))\n , ('requests 2.24.0 *', ('requests', (), (SpecifierSet('==2.24.0'),), '*', None))\n , ('requests * *bla', ('requests', (), (SpecifierSet('==*'),), '*bla', None))\n , ('requests * *', ('requests', (), (SpecifierSet('==*'),), '*', None))\n , ('requests 2.24.0 build123*', ('requests', (), (SpecifierSet('==2.24.0'),), 'build123*', None))\n , ('requests 2.24.0 build123*', ('requests', (), (SpecifierSet('==2.24.0'),), 'build123*', None))\n , ('requests 2.24.0 build123*', ('requests', (), (SpecifierSet('==2.24.0'),), 'build123*', None))\n , ('ruamel.yaml >=0.12.4,<0.16|0.16.5.*',\n ('ruamel.yaml', (), (SpecifierSet('>=0.12.4,<0.16'), SpecifierSet('==0.16.5.*')), None, None))\n , ('openjdk =8|11', ('openjdk', (), (SpecifierSet('==8'), SpecifierSet('==11')), None, None))\n , ('python 3.6.9 ab_73_pypy', ('python', (), (SpecifierSet('==3.6.9'),), 'ab_73_pypy', None))\n , ('gitpython >=3.0.8,3.0.*', ('gitpython', (), (SpecifierSet('>=3.0.8,==3.0.*'),), None, None))\n , (\"zest.releaser[recommended] ; extra == 'maintainer'\",\n ('zest.releaser', ('recommended', 'maintainer'), None, None, \"extra == 'maintainer'\"))\n , ('pytz (>dev)', ('pytz', (), (), None, None))\n , ('libcurl 7.71.1 h20c2e04_1', ('libcurl', (), (SpecifierSet('==7.71.1'),), 'h20c2e04_1', None))\n , ('ixmp ==0.1.3 1', ('ixmp', (), (SpecifierSet('==0.1.3',),), '1', None))\n])\ndef test_parse_requirements(input, exp_output):\n assert parse_reqs_line(input) == exp_output\n\n# Pypi packages contain a lot of invalid requirement syntax.\n# All lines that can't be parsed by packaging are ignored.\n# Additionally, some syntax that we don't currently support\n# are ignored.\n# All other lines must be parsed without errors.\ndef parse_or_ignore_line(line):\n lineStripped = line.strip().replace(\"'\", \"\").replace('\"', '')\n if not len(lineStripped):\n return\n if line.startswith(\"#\"):\n return\n # We don't currently support requirements with these.\n unsupported = (\n \"@\",\n \"===\",\n )\n if any((x in lineStripped for x in unsupported)):\n return\n # We turn the DeprecationWarning raised by\n # packaging.specifier.LegacySpecifier into an error in\n # test_parse_all_pypi_reqs below, so this will raise in\n # that case.\n try:\n Requirement(line)\n except Exception:\n return False\n parse_reqs_line(line)\n\n\ndef parse_or_ignore_line_conda(line):\n # lineStripped = line.strip().replace(\"'\", \"\").replace('\"', '')\n lineStripped = line\n # if not len(lineStripped):\n # return\n # if line.startswith(\"#\"):\n # return\n if any(lineStripped.startswith(x) for x in [\n\n ]):\n return\n if any(lineStripped.endswith(x) for x in [\n\n ]):\n return\n if any((x in lineStripped for x in [\n 'blas *.* mkl'\n ])):\n return\n parse_reqs_line(line)\n\n\n# Constructing a packaging.specifiers.LegacySpecifier\n# issues a warning containing \"LegacyVersion\". We\n# turn it into an error here, so we can treat it as\n# unparseable.\[email protected](\"error:.*LegacyVersion.*:DeprecationWarning\")\[email protected](\"bucket\", LazyBucketDict.bucket_keys())\ndef test_parse_all_pypi_reqs(bucket):\n data_dir = environ.get(\"PYPI_DATA\", default=None)\n data = LazyBucketDict(f\"{data_dir}/sdist\")\n for pname, vers in data.by_bucket(bucket).items():\n for ver, pyvers in vers.items():\n if isinstance(pyvers, str):\n continue\n for pyver, release in pyvers.items():\n if isinstance(release, str):\n continue\n for key in (\"setup_requires\", \"install_requires\"):\n if key in release:\n for line in release[key]:\n parse_or_ignore_line(line)\n if \"extras_require\" in release:\n for extra, lines in release[\"extras_require\"].items():\n for line in lines:\n parse_or_ignore_line(line)\n\n\ndef conda_channel_files():\n conda_data = environ.get(\"CONDA_DATA\", None)\n if not conda_data:\n return []\n with open(conda_data) as f:\n data = json.load(f)\n for channel, files in data.items():\n for file in files:\n yield file\n\n\[email protected](conda_channel_files() == [], reason=\"no CONDA_DATA provided\")\[email protected](\"file\", conda_channel_files())\ndef test_parse_all_conda_reqs(file):\n with open(file) as f:\n cdata = json.load(f)\n for pname, pdata in cdata['packages'].items():\n for line in pdata['depends']:\n parse_or_ignore_line_conda(line)\n", "import json\nfrom os import environ\nfrom packaging.requirements import Requirement\nfrom packaging.specifiers import SpecifierSet\nimport pytest\nfrom mach_nix.data.bucket_dict import LazyBucketDict\nfrom mach_nix.requirements import parse_reqs_line\n\n\[email protected]('input, exp_output', [('requests', ('requests', (),\n None, None, None)), ('requests[socks] ==2.24.0', ('requests', ('socks',\n ), (SpecifierSet('==2.24.0'),), None, None)), (\n 'requests[socks,test] 2.24.0', ('requests', ('socks', 'test'), (\n SpecifierSet('==2.24.0'),), None, None)), ('python >=2.7,<2.8.0a0', (\n 'python', (), (SpecifierSet('>=2.7,<2.8.0a0'),), None, None)), (\n 'requests == 2.24.0', ('requests', (), (SpecifierSet('==2.24.0'),),\n None, None)), ('pdfminer.six == 20200726', ('pdfminer.six', (), (\n SpecifierSet('==20200726'),), None, None)), ('python>= 3.5', ('python',\n (), (SpecifierSet('>=3.5'),), None, None)), ('python >=3.5', ('python',\n (), (SpecifierSet('>=3.5'),), None, None)), ('python >=2.6, !=3.0.*', (\n 'python', (), (SpecifierSet('>=2.6,!=3.0.*'),), None, None)), (\n \"unittest2 >=2.0,<3.0 ; python_version == '2.4' or python_version == '2.5'\"\n , ('unittest2', (), (SpecifierSet('>=2.0,<3.0'),), None,\n \"python_version == '2.4' or python_version == '2.5'\")), (\n \"pywin32 > 1.0 ; sys.platform == 'win32'\", ('pywin32', (), (\n SpecifierSet('>1.0'),), None, \"sys.platform == 'win32'\")), (\n \"certifi (==2016.9.26) ; extra == 'certs'\", ('certifi', ('certs',), (\n SpecifierSet('==2016.9.26'),), None, \"extra == 'certs'\")), (\n \"sphinx ; extra == 'docs'\", ('sphinx', ('docs',), None, None,\n \"extra == 'docs'\")), ('requests 2.24.0', ('requests', (), (SpecifierSet\n ('==2.24.0'),), None, None)), ('requests 2.24.0', ('requests', (), (\n SpecifierSet('==2.24.0'),), None, None)), ('requests 2.24.0', (\n 'requests', (), (SpecifierSet('==2.24.0'),), None, None)), (\n 'requests 2.24.0', ('requests', (), (SpecifierSet('==2.24.0'),), None,\n None)), ('hdf5 >=1.10.5,<1.10.6.0a0 mpi_mpich_*', ('hdf5', (), (\n SpecifierSet('>=1.10.5,<1.10.6.0a0'),), 'mpi_mpich_*', None)), (\n 'blas 1.* openblas', ('blas', (), (SpecifierSet('==1.*'),), 'openblas',\n None)), ('blas * openblas', ('blas', (), (SpecifierSet('==*'),),\n 'openblas', None)), ('blas 1.1 openblas', ('blas', (), (SpecifierSet(\n '==1.1'),), 'openblas', None)), ('requests >=2.24.0 build123*', (\n 'requests', (), (SpecifierSet('>=2.24.0'),), 'build123*', None)), (\n 'requests ==2.24.* build123*', ('requests', (), (SpecifierSet(\n '==2.24.*'),), 'build123*', None)), ('requests 2.24.* build123*', (\n 'requests', (), (SpecifierSet('==2.24.*'),), 'build123*', None)), (\n 'requests 2.24.0 build123*', ('requests', (), (SpecifierSet('==2.24.0')\n ,), 'build123*', None)), ('requests 2.24.0 *bla', ('requests', (), (\n SpecifierSet('==2.24.0'),), '*bla', None)), ('requests 2.24.0 *', (\n 'requests', (), (SpecifierSet('==2.24.0'),), '*', None)), (\n 'requests * *bla', ('requests', (), (SpecifierSet('==*'),), '*bla',\n None)), ('requests * *', ('requests', (), (SpecifierSet('==*'),), '*',\n None)), ('requests 2.24.0 build123*', ('requests', (), (SpecifierSet(\n '==2.24.0'),), 'build123*', None)), ('requests 2.24.0 build123*', (\n 'requests', (), (SpecifierSet('==2.24.0'),), 'build123*', None)), (\n 'requests 2.24.0 build123*', ('requests', (), (SpecifierSet('==2.24.0')\n ,), 'build123*', None)), ('ruamel.yaml >=0.12.4,<0.16|0.16.5.*', (\n 'ruamel.yaml', (), (SpecifierSet('>=0.12.4,<0.16'), SpecifierSet(\n '==0.16.5.*')), None, None)), ('openjdk =8|11', ('openjdk', (), (\n SpecifierSet('==8'), SpecifierSet('==11')), None, None)), (\n 'python 3.6.9 ab_73_pypy', ('python', (), (SpecifierSet('==3.6.9'),),\n 'ab_73_pypy', None)), ('gitpython >=3.0.8,3.0.*', ('gitpython', (), (\n SpecifierSet('>=3.0.8,==3.0.*'),), None, None)), (\n \"zest.releaser[recommended] ; extra == 'maintainer'\", ('zest.releaser',\n ('recommended', 'maintainer'), None, None, \"extra == 'maintainer'\")), (\n 'pytz (>dev)', ('pytz', (), (), None, None)), (\n 'libcurl 7.71.1 h20c2e04_1', ('libcurl', (), (SpecifierSet('==7.71.1'),\n ), 'h20c2e04_1', None)), ('ixmp ==0.1.3 1', ('ixmp', (), (SpecifierSet(\n '==0.1.3'),), '1', None))])\ndef test_parse_requirements(input, exp_output):\n assert parse_reqs_line(input) == exp_output\n\n\ndef parse_or_ignore_line(line):\n lineStripped = line.strip().replace(\"'\", '').replace('\"', '')\n if not len(lineStripped):\n return\n if line.startswith('#'):\n return\n unsupported = '@', '==='\n if any(x in lineStripped for x in unsupported):\n return\n try:\n Requirement(line)\n except Exception:\n return False\n parse_reqs_line(line)\n\n\ndef parse_or_ignore_line_conda(line):\n lineStripped = line\n if any(lineStripped.startswith(x) for x in []):\n return\n if any(lineStripped.endswith(x) for x in []):\n return\n if any(x in lineStripped for x in ['blas *.* mkl']):\n return\n parse_reqs_line(line)\n\n\[email protected]('error:.*LegacyVersion.*:DeprecationWarning')\[email protected]('bucket', LazyBucketDict.bucket_keys())\ndef test_parse_all_pypi_reqs(bucket):\n data_dir = environ.get('PYPI_DATA', default=None)\n data = LazyBucketDict(f'{data_dir}/sdist')\n for pname, vers in data.by_bucket(bucket).items():\n for ver, pyvers in vers.items():\n if isinstance(pyvers, str):\n continue\n for pyver, release in pyvers.items():\n if isinstance(release, str):\n continue\n for key in ('setup_requires', 'install_requires'):\n if key in release:\n for line in release[key]:\n parse_or_ignore_line(line)\n if 'extras_require' in release:\n for extra, lines in release['extras_require'].items():\n for line in lines:\n parse_or_ignore_line(line)\n\n\ndef conda_channel_files():\n conda_data = environ.get('CONDA_DATA', None)\n if not conda_data:\n return []\n with open(conda_data) as f:\n data = json.load(f)\n for channel, files in data.items():\n for file in files:\n yield file\n\n\[email protected](conda_channel_files() == [], reason=\n 'no CONDA_DATA provided')\[email protected]('file', conda_channel_files())\ndef test_parse_all_conda_reqs(file):\n with open(file) as f:\n cdata = json.load(f)\n for pname, pdata in cdata['packages'].items():\n for line in pdata['depends']:\n parse_or_ignore_line_conda(line)\n", "<import token>\n\n\[email protected]('input, exp_output', [('requests', ('requests', (),\n None, None, None)), ('requests[socks] ==2.24.0', ('requests', ('socks',\n ), (SpecifierSet('==2.24.0'),), None, None)), (\n 'requests[socks,test] 2.24.0', ('requests', ('socks', 'test'), (\n SpecifierSet('==2.24.0'),), None, None)), ('python >=2.7,<2.8.0a0', (\n 'python', (), (SpecifierSet('>=2.7,<2.8.0a0'),), None, None)), (\n 'requests == 2.24.0', ('requests', (), (SpecifierSet('==2.24.0'),),\n None, None)), ('pdfminer.six == 20200726', ('pdfminer.six', (), (\n SpecifierSet('==20200726'),), None, None)), ('python>= 3.5', ('python',\n (), (SpecifierSet('>=3.5'),), None, None)), ('python >=3.5', ('python',\n (), (SpecifierSet('>=3.5'),), None, None)), ('python >=2.6, !=3.0.*', (\n 'python', (), (SpecifierSet('>=2.6,!=3.0.*'),), None, None)), (\n \"unittest2 >=2.0,<3.0 ; python_version == '2.4' or python_version == '2.5'\"\n , ('unittest2', (), (SpecifierSet('>=2.0,<3.0'),), None,\n \"python_version == '2.4' or python_version == '2.5'\")), (\n \"pywin32 > 1.0 ; sys.platform == 'win32'\", ('pywin32', (), (\n SpecifierSet('>1.0'),), None, \"sys.platform == 'win32'\")), (\n \"certifi (==2016.9.26) ; extra == 'certs'\", ('certifi', ('certs',), (\n SpecifierSet('==2016.9.26'),), None, \"extra == 'certs'\")), (\n \"sphinx ; extra == 'docs'\", ('sphinx', ('docs',), None, None,\n \"extra == 'docs'\")), ('requests 2.24.0', ('requests', (), (SpecifierSet\n ('==2.24.0'),), None, None)), ('requests 2.24.0', ('requests', (), (\n SpecifierSet('==2.24.0'),), None, None)), ('requests 2.24.0', (\n 'requests', (), (SpecifierSet('==2.24.0'),), None, None)), (\n 'requests 2.24.0', ('requests', (), (SpecifierSet('==2.24.0'),), None,\n None)), ('hdf5 >=1.10.5,<1.10.6.0a0 mpi_mpich_*', ('hdf5', (), (\n SpecifierSet('>=1.10.5,<1.10.6.0a0'),), 'mpi_mpich_*', None)), (\n 'blas 1.* openblas', ('blas', (), (SpecifierSet('==1.*'),), 'openblas',\n None)), ('blas * openblas', ('blas', (), (SpecifierSet('==*'),),\n 'openblas', None)), ('blas 1.1 openblas', ('blas', (), (SpecifierSet(\n '==1.1'),), 'openblas', None)), ('requests >=2.24.0 build123*', (\n 'requests', (), (SpecifierSet('>=2.24.0'),), 'build123*', None)), (\n 'requests ==2.24.* build123*', ('requests', (), (SpecifierSet(\n '==2.24.*'),), 'build123*', None)), ('requests 2.24.* build123*', (\n 'requests', (), (SpecifierSet('==2.24.*'),), 'build123*', None)), (\n 'requests 2.24.0 build123*', ('requests', (), (SpecifierSet('==2.24.0')\n ,), 'build123*', None)), ('requests 2.24.0 *bla', ('requests', (), (\n SpecifierSet('==2.24.0'),), '*bla', None)), ('requests 2.24.0 *', (\n 'requests', (), (SpecifierSet('==2.24.0'),), '*', None)), (\n 'requests * *bla', ('requests', (), (SpecifierSet('==*'),), '*bla',\n None)), ('requests * *', ('requests', (), (SpecifierSet('==*'),), '*',\n None)), ('requests 2.24.0 build123*', ('requests', (), (SpecifierSet(\n '==2.24.0'),), 'build123*', None)), ('requests 2.24.0 build123*', (\n 'requests', (), (SpecifierSet('==2.24.0'),), 'build123*', None)), (\n 'requests 2.24.0 build123*', ('requests', (), (SpecifierSet('==2.24.0')\n ,), 'build123*', None)), ('ruamel.yaml >=0.12.4,<0.16|0.16.5.*', (\n 'ruamel.yaml', (), (SpecifierSet('>=0.12.4,<0.16'), SpecifierSet(\n '==0.16.5.*')), None, None)), ('openjdk =8|11', ('openjdk', (), (\n SpecifierSet('==8'), SpecifierSet('==11')), None, None)), (\n 'python 3.6.9 ab_73_pypy', ('python', (), (SpecifierSet('==3.6.9'),),\n 'ab_73_pypy', None)), ('gitpython >=3.0.8,3.0.*', ('gitpython', (), (\n SpecifierSet('>=3.0.8,==3.0.*'),), None, None)), (\n \"zest.releaser[recommended] ; extra == 'maintainer'\", ('zest.releaser',\n ('recommended', 'maintainer'), None, None, \"extra == 'maintainer'\")), (\n 'pytz (>dev)', ('pytz', (), (), None, None)), (\n 'libcurl 7.71.1 h20c2e04_1', ('libcurl', (), (SpecifierSet('==7.71.1'),\n ), 'h20c2e04_1', None)), ('ixmp ==0.1.3 1', ('ixmp', (), (SpecifierSet(\n '==0.1.3'),), '1', None))])\ndef test_parse_requirements(input, exp_output):\n assert parse_reqs_line(input) == exp_output\n\n\ndef parse_or_ignore_line(line):\n lineStripped = line.strip().replace(\"'\", '').replace('\"', '')\n if not len(lineStripped):\n return\n if line.startswith('#'):\n return\n unsupported = '@', '==='\n if any(x in lineStripped for x in unsupported):\n return\n try:\n Requirement(line)\n except Exception:\n return False\n parse_reqs_line(line)\n\n\ndef parse_or_ignore_line_conda(line):\n lineStripped = line\n if any(lineStripped.startswith(x) for x in []):\n return\n if any(lineStripped.endswith(x) for x in []):\n return\n if any(x in lineStripped for x in ['blas *.* mkl']):\n return\n parse_reqs_line(line)\n\n\[email protected]('error:.*LegacyVersion.*:DeprecationWarning')\[email protected]('bucket', LazyBucketDict.bucket_keys())\ndef test_parse_all_pypi_reqs(bucket):\n data_dir = environ.get('PYPI_DATA', default=None)\n data = LazyBucketDict(f'{data_dir}/sdist')\n for pname, vers in data.by_bucket(bucket).items():\n for ver, pyvers in vers.items():\n if isinstance(pyvers, str):\n continue\n for pyver, release in pyvers.items():\n if isinstance(release, str):\n continue\n for key in ('setup_requires', 'install_requires'):\n if key in release:\n for line in release[key]:\n parse_or_ignore_line(line)\n if 'extras_require' in release:\n for extra, lines in release['extras_require'].items():\n for line in lines:\n parse_or_ignore_line(line)\n\n\ndef conda_channel_files():\n conda_data = environ.get('CONDA_DATA', None)\n if not conda_data:\n return []\n with open(conda_data) as f:\n data = json.load(f)\n for channel, files in data.items():\n for file in files:\n yield file\n\n\[email protected](conda_channel_files() == [], reason=\n 'no CONDA_DATA provided')\[email protected]('file', conda_channel_files())\ndef test_parse_all_conda_reqs(file):\n with open(file) as f:\n cdata = json.load(f)\n for pname, pdata in cdata['packages'].items():\n for line in pdata['depends']:\n parse_or_ignore_line_conda(line)\n", "<import token>\n\n\[email protected]('input, exp_output', [('requests', ('requests', (),\n None, None, None)), ('requests[socks] ==2.24.0', ('requests', ('socks',\n ), (SpecifierSet('==2.24.0'),), None, None)), (\n 'requests[socks,test] 2.24.0', ('requests', ('socks', 'test'), (\n SpecifierSet('==2.24.0'),), None, None)), ('python >=2.7,<2.8.0a0', (\n 'python', (), (SpecifierSet('>=2.7,<2.8.0a0'),), None, None)), (\n 'requests == 2.24.0', ('requests', (), (SpecifierSet('==2.24.0'),),\n None, None)), ('pdfminer.six == 20200726', ('pdfminer.six', (), (\n SpecifierSet('==20200726'),), None, None)), ('python>= 3.5', ('python',\n (), (SpecifierSet('>=3.5'),), None, None)), ('python >=3.5', ('python',\n (), (SpecifierSet('>=3.5'),), None, None)), ('python >=2.6, !=3.0.*', (\n 'python', (), (SpecifierSet('>=2.6,!=3.0.*'),), None, None)), (\n \"unittest2 >=2.0,<3.0 ; python_version == '2.4' or python_version == '2.5'\"\n , ('unittest2', (), (SpecifierSet('>=2.0,<3.0'),), None,\n \"python_version == '2.4' or python_version == '2.5'\")), (\n \"pywin32 > 1.0 ; sys.platform == 'win32'\", ('pywin32', (), (\n SpecifierSet('>1.0'),), None, \"sys.platform == 'win32'\")), (\n \"certifi (==2016.9.26) ; extra == 'certs'\", ('certifi', ('certs',), (\n SpecifierSet('==2016.9.26'),), None, \"extra == 'certs'\")), (\n \"sphinx ; extra == 'docs'\", ('sphinx', ('docs',), None, None,\n \"extra == 'docs'\")), ('requests 2.24.0', ('requests', (), (SpecifierSet\n ('==2.24.0'),), None, None)), ('requests 2.24.0', ('requests', (), (\n SpecifierSet('==2.24.0'),), None, None)), ('requests 2.24.0', (\n 'requests', (), (SpecifierSet('==2.24.0'),), None, None)), (\n 'requests 2.24.0', ('requests', (), (SpecifierSet('==2.24.0'),), None,\n None)), ('hdf5 >=1.10.5,<1.10.6.0a0 mpi_mpich_*', ('hdf5', (), (\n SpecifierSet('>=1.10.5,<1.10.6.0a0'),), 'mpi_mpich_*', None)), (\n 'blas 1.* openblas', ('blas', (), (SpecifierSet('==1.*'),), 'openblas',\n None)), ('blas * openblas', ('blas', (), (SpecifierSet('==*'),),\n 'openblas', None)), ('blas 1.1 openblas', ('blas', (), (SpecifierSet(\n '==1.1'),), 'openblas', None)), ('requests >=2.24.0 build123*', (\n 'requests', (), (SpecifierSet('>=2.24.0'),), 'build123*', None)), (\n 'requests ==2.24.* build123*', ('requests', (), (SpecifierSet(\n '==2.24.*'),), 'build123*', None)), ('requests 2.24.* build123*', (\n 'requests', (), (SpecifierSet('==2.24.*'),), 'build123*', None)), (\n 'requests 2.24.0 build123*', ('requests', (), (SpecifierSet('==2.24.0')\n ,), 'build123*', None)), ('requests 2.24.0 *bla', ('requests', (), (\n SpecifierSet('==2.24.0'),), '*bla', None)), ('requests 2.24.0 *', (\n 'requests', (), (SpecifierSet('==2.24.0'),), '*', None)), (\n 'requests * *bla', ('requests', (), (SpecifierSet('==*'),), '*bla',\n None)), ('requests * *', ('requests', (), (SpecifierSet('==*'),), '*',\n None)), ('requests 2.24.0 build123*', ('requests', (), (SpecifierSet(\n '==2.24.0'),), 'build123*', None)), ('requests 2.24.0 build123*', (\n 'requests', (), (SpecifierSet('==2.24.0'),), 'build123*', None)), (\n 'requests 2.24.0 build123*', ('requests', (), (SpecifierSet('==2.24.0')\n ,), 'build123*', None)), ('ruamel.yaml >=0.12.4,<0.16|0.16.5.*', (\n 'ruamel.yaml', (), (SpecifierSet('>=0.12.4,<0.16'), SpecifierSet(\n '==0.16.5.*')), None, None)), ('openjdk =8|11', ('openjdk', (), (\n SpecifierSet('==8'), SpecifierSet('==11')), None, None)), (\n 'python 3.6.9 ab_73_pypy', ('python', (), (SpecifierSet('==3.6.9'),),\n 'ab_73_pypy', None)), ('gitpython >=3.0.8,3.0.*', ('gitpython', (), (\n SpecifierSet('>=3.0.8,==3.0.*'),), None, None)), (\n \"zest.releaser[recommended] ; extra == 'maintainer'\", ('zest.releaser',\n ('recommended', 'maintainer'), None, None, \"extra == 'maintainer'\")), (\n 'pytz (>dev)', ('pytz', (), (), None, None)), (\n 'libcurl 7.71.1 h20c2e04_1', ('libcurl', (), (SpecifierSet('==7.71.1'),\n ), 'h20c2e04_1', None)), ('ixmp ==0.1.3 1', ('ixmp', (), (SpecifierSet(\n '==0.1.3'),), '1', None))])\ndef test_parse_requirements(input, exp_output):\n assert parse_reqs_line(input) == exp_output\n\n\n<function token>\n\n\ndef parse_or_ignore_line_conda(line):\n lineStripped = line\n if any(lineStripped.startswith(x) for x in []):\n return\n if any(lineStripped.endswith(x) for x in []):\n return\n if any(x in lineStripped for x in ['blas *.* mkl']):\n return\n parse_reqs_line(line)\n\n\[email protected]('error:.*LegacyVersion.*:DeprecationWarning')\[email protected]('bucket', LazyBucketDict.bucket_keys())\ndef test_parse_all_pypi_reqs(bucket):\n data_dir = environ.get('PYPI_DATA', default=None)\n data = LazyBucketDict(f'{data_dir}/sdist')\n for pname, vers in data.by_bucket(bucket).items():\n for ver, pyvers in vers.items():\n if isinstance(pyvers, str):\n continue\n for pyver, release in pyvers.items():\n if isinstance(release, str):\n continue\n for key in ('setup_requires', 'install_requires'):\n if key in release:\n for line in release[key]:\n parse_or_ignore_line(line)\n if 'extras_require' in release:\n for extra, lines in release['extras_require'].items():\n for line in lines:\n parse_or_ignore_line(line)\n\n\ndef conda_channel_files():\n conda_data = environ.get('CONDA_DATA', None)\n if not conda_data:\n return []\n with open(conda_data) as f:\n data = json.load(f)\n for channel, files in data.items():\n for file in files:\n yield file\n\n\[email protected](conda_channel_files() == [], reason=\n 'no CONDA_DATA provided')\[email protected]('file', conda_channel_files())\ndef test_parse_all_conda_reqs(file):\n with open(file) as f:\n cdata = json.load(f)\n for pname, pdata in cdata['packages'].items():\n for line in pdata['depends']:\n parse_or_ignore_line_conda(line)\n", "<import token>\n\n\[email protected]('input, exp_output', [('requests', ('requests', (),\n None, None, None)), ('requests[socks] ==2.24.0', ('requests', ('socks',\n ), (SpecifierSet('==2.24.0'),), None, None)), (\n 'requests[socks,test] 2.24.0', ('requests', ('socks', 'test'), (\n SpecifierSet('==2.24.0'),), None, None)), ('python >=2.7,<2.8.0a0', (\n 'python', (), (SpecifierSet('>=2.7,<2.8.0a0'),), None, None)), (\n 'requests == 2.24.0', ('requests', (), (SpecifierSet('==2.24.0'),),\n None, None)), ('pdfminer.six == 20200726', ('pdfminer.six', (), (\n SpecifierSet('==20200726'),), None, None)), ('python>= 3.5', ('python',\n (), (SpecifierSet('>=3.5'),), None, None)), ('python >=3.5', ('python',\n (), (SpecifierSet('>=3.5'),), None, None)), ('python >=2.6, !=3.0.*', (\n 'python', (), (SpecifierSet('>=2.6,!=3.0.*'),), None, None)), (\n \"unittest2 >=2.0,<3.0 ; python_version == '2.4' or python_version == '2.5'\"\n , ('unittest2', (), (SpecifierSet('>=2.0,<3.0'),), None,\n \"python_version == '2.4' or python_version == '2.5'\")), (\n \"pywin32 > 1.0 ; sys.platform == 'win32'\", ('pywin32', (), (\n SpecifierSet('>1.0'),), None, \"sys.platform == 'win32'\")), (\n \"certifi (==2016.9.26) ; extra == 'certs'\", ('certifi', ('certs',), (\n SpecifierSet('==2016.9.26'),), None, \"extra == 'certs'\")), (\n \"sphinx ; extra == 'docs'\", ('sphinx', ('docs',), None, None,\n \"extra == 'docs'\")), ('requests 2.24.0', ('requests', (), (SpecifierSet\n ('==2.24.0'),), None, None)), ('requests 2.24.0', ('requests', (), (\n SpecifierSet('==2.24.0'),), None, None)), ('requests 2.24.0', (\n 'requests', (), (SpecifierSet('==2.24.0'),), None, None)), (\n 'requests 2.24.0', ('requests', (), (SpecifierSet('==2.24.0'),), None,\n None)), ('hdf5 >=1.10.5,<1.10.6.0a0 mpi_mpich_*', ('hdf5', (), (\n SpecifierSet('>=1.10.5,<1.10.6.0a0'),), 'mpi_mpich_*', None)), (\n 'blas 1.* openblas', ('blas', (), (SpecifierSet('==1.*'),), 'openblas',\n None)), ('blas * openblas', ('blas', (), (SpecifierSet('==*'),),\n 'openblas', None)), ('blas 1.1 openblas', ('blas', (), (SpecifierSet(\n '==1.1'),), 'openblas', None)), ('requests >=2.24.0 build123*', (\n 'requests', (), (SpecifierSet('>=2.24.0'),), 'build123*', None)), (\n 'requests ==2.24.* build123*', ('requests', (), (SpecifierSet(\n '==2.24.*'),), 'build123*', None)), ('requests 2.24.* build123*', (\n 'requests', (), (SpecifierSet('==2.24.*'),), 'build123*', None)), (\n 'requests 2.24.0 build123*', ('requests', (), (SpecifierSet('==2.24.0')\n ,), 'build123*', None)), ('requests 2.24.0 *bla', ('requests', (), (\n SpecifierSet('==2.24.0'),), '*bla', None)), ('requests 2.24.0 *', (\n 'requests', (), (SpecifierSet('==2.24.0'),), '*', None)), (\n 'requests * *bla', ('requests', (), (SpecifierSet('==*'),), '*bla',\n None)), ('requests * *', ('requests', (), (SpecifierSet('==*'),), '*',\n None)), ('requests 2.24.0 build123*', ('requests', (), (SpecifierSet(\n '==2.24.0'),), 'build123*', None)), ('requests 2.24.0 build123*', (\n 'requests', (), (SpecifierSet('==2.24.0'),), 'build123*', None)), (\n 'requests 2.24.0 build123*', ('requests', (), (SpecifierSet('==2.24.0')\n ,), 'build123*', None)), ('ruamel.yaml >=0.12.4,<0.16|0.16.5.*', (\n 'ruamel.yaml', (), (SpecifierSet('>=0.12.4,<0.16'), SpecifierSet(\n '==0.16.5.*')), None, None)), ('openjdk =8|11', ('openjdk', (), (\n SpecifierSet('==8'), SpecifierSet('==11')), None, None)), (\n 'python 3.6.9 ab_73_pypy', ('python', (), (SpecifierSet('==3.6.9'),),\n 'ab_73_pypy', None)), ('gitpython >=3.0.8,3.0.*', ('gitpython', (), (\n SpecifierSet('>=3.0.8,==3.0.*'),), None, None)), (\n \"zest.releaser[recommended] ; extra == 'maintainer'\", ('zest.releaser',\n ('recommended', 'maintainer'), None, None, \"extra == 'maintainer'\")), (\n 'pytz (>dev)', ('pytz', (), (), None, None)), (\n 'libcurl 7.71.1 h20c2e04_1', ('libcurl', (), (SpecifierSet('==7.71.1'),\n ), 'h20c2e04_1', None)), ('ixmp ==0.1.3 1', ('ixmp', (), (SpecifierSet(\n '==0.1.3'),), '1', None))])\ndef test_parse_requirements(input, exp_output):\n assert parse_reqs_line(input) == exp_output\n\n\n<function token>\n\n\ndef parse_or_ignore_line_conda(line):\n lineStripped = line\n if any(lineStripped.startswith(x) for x in []):\n return\n if any(lineStripped.endswith(x) for x in []):\n return\n if any(x in lineStripped for x in ['blas *.* mkl']):\n return\n parse_reqs_line(line)\n\n\[email protected]('error:.*LegacyVersion.*:DeprecationWarning')\[email protected]('bucket', LazyBucketDict.bucket_keys())\ndef test_parse_all_pypi_reqs(bucket):\n data_dir = environ.get('PYPI_DATA', default=None)\n data = LazyBucketDict(f'{data_dir}/sdist')\n for pname, vers in data.by_bucket(bucket).items():\n for ver, pyvers in vers.items():\n if isinstance(pyvers, str):\n continue\n for pyver, release in pyvers.items():\n if isinstance(release, str):\n continue\n for key in ('setup_requires', 'install_requires'):\n if key in release:\n for line in release[key]:\n parse_or_ignore_line(line)\n if 'extras_require' in release:\n for extra, lines in release['extras_require'].items():\n for line in lines:\n parse_or_ignore_line(line)\n\n\n<function token>\n\n\[email protected](conda_channel_files() == [], reason=\n 'no CONDA_DATA provided')\[email protected]('file', conda_channel_files())\ndef test_parse_all_conda_reqs(file):\n with open(file) as f:\n cdata = json.load(f)\n for pname, pdata in cdata['packages'].items():\n for line in pdata['depends']:\n parse_or_ignore_line_conda(line)\n", "<import token>\n<function token>\n<function token>\n\n\ndef parse_or_ignore_line_conda(line):\n lineStripped = line\n if any(lineStripped.startswith(x) for x in []):\n return\n if any(lineStripped.endswith(x) for x in []):\n return\n if any(x in lineStripped for x in ['blas *.* mkl']):\n return\n parse_reqs_line(line)\n\n\[email protected]('error:.*LegacyVersion.*:DeprecationWarning')\[email protected]('bucket', LazyBucketDict.bucket_keys())\ndef test_parse_all_pypi_reqs(bucket):\n data_dir = environ.get('PYPI_DATA', default=None)\n data = LazyBucketDict(f'{data_dir}/sdist')\n for pname, vers in data.by_bucket(bucket).items():\n for ver, pyvers in vers.items():\n if isinstance(pyvers, str):\n continue\n for pyver, release in pyvers.items():\n if isinstance(release, str):\n continue\n for key in ('setup_requires', 'install_requires'):\n if key in release:\n for line in release[key]:\n parse_or_ignore_line(line)\n if 'extras_require' in release:\n for extra, lines in release['extras_require'].items():\n for line in lines:\n parse_or_ignore_line(line)\n\n\n<function token>\n\n\[email protected](conda_channel_files() == [], reason=\n 'no CONDA_DATA provided')\[email protected]('file', conda_channel_files())\ndef test_parse_all_conda_reqs(file):\n with open(file) as f:\n cdata = json.load(f)\n for pname, pdata in cdata['packages'].items():\n for line in pdata['depends']:\n parse_or_ignore_line_conda(line)\n", "<import token>\n<function token>\n<function token>\n\n\ndef parse_or_ignore_line_conda(line):\n lineStripped = line\n if any(lineStripped.startswith(x) for x in []):\n return\n if any(lineStripped.endswith(x) for x in []):\n return\n if any(x in lineStripped for x in ['blas *.* mkl']):\n return\n parse_reqs_line(line)\n\n\n<function token>\n<function token>\n\n\[email protected](conda_channel_files() == [], reason=\n 'no CONDA_DATA provided')\[email protected]('file', conda_channel_files())\ndef test_parse_all_conda_reqs(file):\n with open(file) as f:\n cdata = json.load(f)\n for pname, pdata in cdata['packages'].items():\n for line in pdata['depends']:\n parse_or_ignore_line_conda(line)\n", "<import token>\n<function token>\n<function token>\n\n\ndef parse_or_ignore_line_conda(line):\n lineStripped = line\n if any(lineStripped.startswith(x) for x in []):\n return\n if any(lineStripped.endswith(x) for x in []):\n return\n if any(x in lineStripped for x in ['blas *.* mkl']):\n return\n parse_reqs_line(line)\n\n\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n" ]
false
98,748
d7dab5c8a8de5c11f247aab38c8e3f9f5b86cc7c
# import confidparser to read # 'config.ini' file and obtain # the required data import configparser import io # loading config file config = configparser.ConfigParser() config.read('config.ini') host = config['mongo']['host'] db = config['mongo']['db'] collection = config['mongo']['collection'] bus_id = config['mongo']['busid']
[ "# import confidparser to read\n# 'config.ini' file and obtain\n# the required data\nimport configparser\nimport io\n\n\n# loading config file\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\nhost\t\t= config['mongo']['host']\ndb \t= config['mongo']['db']\ncollection\t= config['mongo']['collection']\nbus_id\t\t= config['mongo']['busid']\n", "import configparser\nimport io\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\nhost = config['mongo']['host']\ndb = config['mongo']['db']\ncollection = config['mongo']['collection']\nbus_id = config['mongo']['busid']\n", "<import token>\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\nhost = config['mongo']['host']\ndb = config['mongo']['db']\ncollection = config['mongo']['collection']\nbus_id = config['mongo']['busid']\n", "<import token>\n<assignment token>\nconfig.read('config.ini')\n<assignment token>\n", "<import token>\n<assignment token>\n<code token>\n<assignment token>\n" ]
false
98,749
48f0bf643f8a3040f5e62285af556cb6605fb06b
from collections import Counter import random import copy as copyModule import math import numpy as np def soujou(xs): re = 1 for x in xs: re *= x return re #utils def eq_list(xs, ys): xc = Counter(xs) yc = Counter(ys) xc.subtract(yc) zs = list(xc.elements()) return len(zs)==0 def diff_list(univ, see, assume_included=True): diff = list(univ) for x in see: if assume_included: diff.remove(x) else: if x in diff: diff.remove(x) return diff def intersection_list(xs, ys): xc = Counter(xs) yc = Counter(ys) zc = xc & yc zs = list(zc.elements()) return zs def floor_half_list(xs): xc = Counter(xs) ys = [] for x,c in xc.items(): for _ in range(c // 2): ys.append(x) return ys def indexs_duplable_front(univ, see): temp = list(univ) res = [] for x in see: i = temp.index(x) res.append(i) temp[i] = None return res def indexs_duplable_back(univ, see): temp = list(reversed(univ)) res = [] for x in see: i = temp.index(x) res.append(len(univ)-1-i) temp[i] = None return res def more_popped_list(xs, xis): xs = list(xs) for xi in xis: xs[xi] = None xs = [x for x in xs if x is not None] return xs #label covering methods #label :== string | tuple[label] def is_type_label(label): if isinstance(label, tuple): return all((is_type_label(x) for x in label)) return isinstance(label, str) def is_type_labels(labels): return all((is_type_label(x) for x in labels)) def normarg_labels(labels): if isinstance(labels, list): return labels else: return [labels] def unique_label(): return "".join(random.choices("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",k=8)) def aster_label(label): if type(label)==tuple: return tuple(aster_label(x) for x in label) else: return label+"*" def unaster_label(label): if type(label)==tuple: return tuple(unaster_label(x) for x in label) else: if label[-1] == "*": return label[:-1] else: return label def prime_label(label): if type(label)==tuple: return tuple(prime_label(x) for x in label) else: return label+"'" def unprime_label(label): if type(label)==tuple: return tuple(unaster_label(x) for x in label) else: if label[-1] == "'": return label[:-1] else: return label def aster_labels(labels): return [aster_label(label) for label in labels] def unaster_labels(labels): return [unaster_label(label) for label in labels] def prime_labels(labels): return [prime_label(label) for label in labels] def unprime_labels(labels): return [unprime_label(label) for label in labels] class CyclicList(list): def __init__(self, *args, **kwargs): list.__init__(self, *args, **kwargs) def __repr__(self): return "CyclicList("+list.__repr__(self)+")" def __str__(self): return "CyclicList("+list.__repr__(self)+")" def __getitem__(self, i): return list.__getitem__(self, i%len(self)) def __setitem__(self, i, v): return list.__setitem__(self, i%len(self), v) class CollateralBool: def __init__(self, trueOrFalse, expression=None): self.trueOrFalse = bool(trueOrFalse) if expression is None: expression = {} self.expression = expression def __bool__(self): return self.trueOrFalse def __and__(x,y): return CollateralBool(x.trueOrFalse and y.trueOrFalse, {"op":"and", "left":x.expression, "right":y.expression}) def __or__(x,y): return CollateralBool(x.trueOrFalse or y.trueOrFalse, {"op":"or", "left":x.expression, "right":y.expression}) def __repr__(self): return f"{self.trueOrFalse}({self.expression})" #f"CollateralBool({self.trueOrFalse}, {self.expression})" def __str__(self): return f"{self.trueOrFalse}({self.expression})" def __getitem__(self, arg): return self.expression[arg] class ExpFloat: def __init__(self, *args): if len(args)==1: moto = args[0] if moto == 0: self.sign = 0 self.ent = -float("inf") elif type(moto)==ExpFloat: self.sign = moto.sign self.ent = moto.ent elif type(moto)==complex: nrm = abs(moto) self.sign = moto / nrm self.ent = math.log(nrm) elif moto > 0: self.sign = 1 self.ent = math.log(moto) else: self.sign = -1 self.ent = math.log(-moto) elif len(args)==2: self.sign = args[0] self.ent = args[1] def __str__(self): if self.sign == 0: return f"0.0" elif type(self.sign)==complex: return f"({self.sign})*exp({self.ent})" elif self.sign == 1: return f"exp({self.ent})" else: return f"-exp({self.ent})" def __repr__(self): return f"ExpFloat({repr(self.sign)},{repr(self.ent)})" @property def value(self): return self.sign * math.exp(self.ent) @property def log(self): return self.ent @property def real(self): if type(self.sign)==complex: return ExpFloat(self.sign.real) * abs(self) else: return ExpFloat(self.sign) * abs(self) @property def imag(self): if type(self.sign)==complex: return ExpFloat(self.sign.imag) * abs(self) else: return ExpFloat(0.0) def __abs__(self): if self.sign == 0: return ExpFloat(0.0) else: return ExpFloat(1, self.ent) def __eq__(self, other): d = abs(self - other) return d.sign == 0 or d.ent < -15 def __lt__(self, other): if type(other)==ExpFloat: if self.sign < other.sign: return True if self.sign > other.sign: return False if self.sign == 0: return False elif self.sign == 1: return self.ent < other.ent else: return self.ent > other.ent else: return self < ExpFloat(other) def __gt__(self, other): if type(other)==ExpFloat: if self.sign > other.sign: return True if self.sign < other.sign: return False if self.sign == 0: return False elif self.sign == 1: return self.ent > other.ent else: return self.ent < other.ent else: return self > ExpFloat(other) def __mul__(self, other): if type(other)==ExpFloat: return ExpFloat(self.sign * other.sign, self.ent + other.ent) else: return self * ExpFloat(other) def __rmul__(self, other): return self * other def __truediv__(self, other): if type(other)==ExpFloat: return ExpFloat(self.sign / other.sign, self.ent - other.ent) else: return self / ExpFloat(other) def __neg__(self): return ExpFloat(-self.sign, self.ent) def __add__(self, other): if type(other)==ExpFloat: if type(self.sign)==complex or type(other.sign)==complex: return ef_complex(self.real+other.real, self.imag+other.imag) if other.sign == 0: return self elif self.sign == 0: return other elif self.sign == 1 and other.sign == -1: return self - (-other) elif self.sign == -1 and other.sign == 1: return other - (-self) elif self.sign == -1 and other.sign == -1: return -( (-self) + (-other) ) # exp(a)+exp(b) = exp(a) * (1 + exp(b-a)) # log(exp(a)+exp(b)) = a + log(1 + exp(b-a)) if self < other: self,other = other,self a = self.ent b = other.ent c = a + np.log1p(math.exp(b-a)) return ExpFloat(1,c) else: return self + ExpFloat(other) def __sub__(self, other): if type(other)==ExpFloat: if type(self.sign)==complex or type(other.sign)==complex: return ef_complex(self.real-other.real, self.imag-other.imag) if other.sign == 0: return self elif self.sign == 0: return -other elif self.sign == 1 and other.sign == -1: return self + (-other) elif self.sign == -1 and other.sign == 1: return -( (-self) + other ) elif self.sign == -1 and other.sign == -1: return (-other) - (-self) if self < other: return -(other - self) # exp(a)-exp(b) = exp(a) * (1 - exp(b-a)) # log(exp(a)-exp(b)) = a + log(1 - exp(b-a)) a = self.ent b = other.ent if b-a > -1e-15: return ExpFloat(0.0) c = a + np.log1p(-math.exp(b-a)) return ExpFloat(1,c) else: return self - ExpFloat(other) def __pow__(self, k): if self.sign==1: return ExpFloat(1, self.ent*k) elif self.sign==0: if k>0: return ExpFloat(0.0) elif k==0: return ExpFloat(1.0) else: raise ValueError else: if int(k) != k: raise ValueError else: return ExpFloat(self.sign**k, self.ent*k) def sqrt(self): if self.sign==1: return ExpFloat(1, self.ent/2) elif self.sign==0: return ExpFloat(0.0) else: raise ValueError def ef_exp(k): return ExpFloat(1,k) def ef_pow(r,k): return ExpFloat(r)**k def ef_cosh(x): return ( ef_exp(x) + ef_exp(-x) ) / 2 def ef_sinh(x): return ( ef_exp(x) - ef_exp(-x) ) / 2 def ef_complex(x,y): if type(x) == ExpFloat and type(y) == ExpFloat: if x == 0 and y == 0: return ExpFloat(0.0) if x.ent >= y.ent: r = x.sign + y.sign * math.exp(y.ent-x.ent) * 1.0j r = ExpFloat(r) r.ent += x.ent return r else: r = x.sign * math.exp(x.ent-y.ent) + y.sign * 1.0j r = ExpFloat(r) r.ent += y.ent return r else: return ef_complex(ExpFloat(x),ExpFloat(y))
[ "from collections import Counter\nimport random\nimport copy as copyModule\nimport math\nimport numpy as np\n\ndef soujou(xs):\n re = 1\n for x in xs:\n re *= x\n return re\n\n#utils\ndef eq_list(xs, ys):\n xc = Counter(xs)\n yc = Counter(ys)\n xc.subtract(yc)\n zs = list(xc.elements())\n return len(zs)==0\n\ndef diff_list(univ, see, assume_included=True):\n diff = list(univ)\n for x in see:\n if assume_included:\n diff.remove(x)\n else:\n if x in diff:\n diff.remove(x)\n\n return diff\n\ndef intersection_list(xs, ys):\n xc = Counter(xs)\n yc = Counter(ys)\n zc = xc & yc\n zs = list(zc.elements())\n return zs\n\ndef floor_half_list(xs):\n xc = Counter(xs)\n ys = []\n for x,c in xc.items():\n for _ in range(c // 2):\n ys.append(x)\n return ys\n\ndef indexs_duplable_front(univ, see):\n temp = list(univ)\n res = []\n for x in see:\n i = temp.index(x)\n res.append(i)\n temp[i] = None\n return res\n\ndef indexs_duplable_back(univ, see):\n temp = list(reversed(univ))\n res = []\n for x in see:\n i = temp.index(x)\n res.append(len(univ)-1-i)\n temp[i] = None\n return res\n\ndef more_popped_list(xs, xis):\n xs = list(xs)\n for xi in xis:\n xs[xi] = None\n xs = [x for x in xs if x is not None]\n return xs\n\n\n#label covering methods\n#label :== string | tuple[label]\ndef is_type_label(label):\n if isinstance(label, tuple):\n return all((is_type_label(x) for x in label))\n return isinstance(label, str)\n\ndef is_type_labels(labels):\n return all((is_type_label(x) for x in labels))\n\ndef normarg_labels(labels):\n if isinstance(labels, list):\n return labels\n else:\n return [labels]\n\ndef unique_label():\n return \"\".join(random.choices(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\",k=8))\n\ndef aster_label(label):\n if type(label)==tuple:\n return tuple(aster_label(x) for x in label)\n else:\n return label+\"*\"\n\ndef unaster_label(label):\n if type(label)==tuple:\n return tuple(unaster_label(x) for x in label)\n else:\n if label[-1] == \"*\":\n return label[:-1]\n else:\n return label\n\ndef prime_label(label):\n if type(label)==tuple:\n return tuple(prime_label(x) for x in label)\n else:\n return label+\"'\"\n\ndef unprime_label(label):\n if type(label)==tuple:\n return tuple(unaster_label(x) for x in label)\n else:\n if label[-1] == \"'\":\n return label[:-1]\n else:\n return label\n\ndef aster_labels(labels):\n return [aster_label(label) for label in labels]\n\ndef unaster_labels(labels):\n return [unaster_label(label) for label in labels]\n\ndef prime_labels(labels):\n return [prime_label(label) for label in labels]\n\ndef unprime_labels(labels):\n return [unprime_label(label) for label in labels]\n\n\n\nclass CyclicList(list):\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n def __repr__(self):\n return \"CyclicList(\"+list.__repr__(self)+\")\"\n def __str__(self):\n return \"CyclicList(\"+list.__repr__(self)+\")\"\n def __getitem__(self, i):\n return list.__getitem__(self, i%len(self))\n def __setitem__(self, i, v):\n return list.__setitem__(self, i%len(self), v)\n\n\n\nclass CollateralBool:\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None: expression = {}\n self.expression = expression\n def __bool__(self):\n return self.trueOrFalse\n def __and__(x,y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {\"op\":\"and\", \"left\":x.expression, \"right\":y.expression})\n def __or__(x,y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {\"op\":\"or\", \"left\":x.expression, \"right\":y.expression})\n def __repr__(self):\n return f\"{self.trueOrFalse}({self.expression})\" #f\"CollateralBool({self.trueOrFalse}, {self.expression})\"\n def __str__(self):\n return f\"{self.trueOrFalse}({self.expression})\"\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\n\nclass ExpFloat:\n def __init__(self, *args):\n if len(args)==1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float(\"inf\")\n elif type(moto)==ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto)==complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args)==2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f\"0.0\"\n elif type(self.sign)==complex:\n return f\"({self.sign})*exp({self.ent})\"\n elif self.sign == 1:\n return f\"exp({self.ent})\"\n else:\n return f\"-exp({self.ent})\"\n\n def __repr__(self):\n return f\"ExpFloat({repr(self.sign)},{repr(self.ent)})\"\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign)==complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign)==complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other)==ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other)==ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other)==ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other)==ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other)==ExpFloat:\n if type(self.sign)==complex or type(other.sign)==complex:\n return ef_complex(self.real+other.real, self.imag+other.imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - (-other)\n elif self.sign == -1 and other.sign == 1:\n return other - (-self)\n elif self.sign == -1 and other.sign == -1:\n return -( (-self) + (-other) )\n\n # exp(a)+exp(b) = exp(a) * (1 + exp(b-a))\n # log(exp(a)+exp(b)) = a + log(1 + exp(b-a))\n if self < other:\n self,other = other,self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b-a))\n return ExpFloat(1,c)\n\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other)==ExpFloat:\n if type(self.sign)==complex or type(other.sign)==complex:\n return ef_complex(self.real-other.real, self.imag-other.imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + (-other)\n elif self.sign == -1 and other.sign == 1:\n return -( (-self) + other )\n elif self.sign == -1 and other.sign == -1:\n return (-other) - (-self)\n\n if self < other:\n return -(other - self)\n\n # exp(a)-exp(b) = exp(a) * (1 - exp(b-a))\n # log(exp(a)-exp(b)) = a + log(1 - exp(b-a))\n a = self.ent\n b = other.ent\n if b-a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b-a))\n return ExpFloat(1,c)\n\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign==1:\n return ExpFloat(1, self.ent*k)\n elif self.sign==0:\n if k>0:\n return ExpFloat(0.0)\n elif k==0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n else:\n if int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign**k, self.ent*k)\n\n def sqrt(self):\n if self.sign==1:\n return ExpFloat(1, self.ent/2)\n elif self.sign==0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\ndef ef_exp(k):\n return ExpFloat(1,k)\n\ndef ef_pow(r,k):\n return ExpFloat(r)**k\n\ndef ef_cosh(x):\n return ( ef_exp(x) + ef_exp(-x) ) / 2\n\ndef ef_sinh(x):\n return ( ef_exp(x) - ef_exp(-x) ) / 2\n\ndef ef_complex(x,y):\n if type(x) == ExpFloat and type(y) == ExpFloat:\n if x == 0 and y == 0:\n return ExpFloat(0.0)\n if x.ent >= y.ent:\n r = x.sign + y.sign * math.exp(y.ent-x.ent) * 1.0j\n r = ExpFloat(r)\n r.ent += x.ent\n return r\n else:\n r = x.sign * math.exp(x.ent-y.ent) + y.sign * 1.0j\n r = ExpFloat(r)\n r.ent += y.ent\n return r\n else:\n return ef_complex(ExpFloat(x),ExpFloat(y))\n\n\n\n", "from collections import Counter\nimport random\nimport copy as copyModule\nimport math\nimport numpy as np\n\n\ndef soujou(xs):\n re = 1\n for x in xs:\n re *= x\n return re\n\n\ndef eq_list(xs, ys):\n xc = Counter(xs)\n yc = Counter(ys)\n xc.subtract(yc)\n zs = list(xc.elements())\n return len(zs) == 0\n\n\ndef diff_list(univ, see, assume_included=True):\n diff = list(univ)\n for x in see:\n if assume_included:\n diff.remove(x)\n elif x in diff:\n diff.remove(x)\n return diff\n\n\ndef intersection_list(xs, ys):\n xc = Counter(xs)\n yc = Counter(ys)\n zc = xc & yc\n zs = list(zc.elements())\n return zs\n\n\ndef floor_half_list(xs):\n xc = Counter(xs)\n ys = []\n for x, c in xc.items():\n for _ in range(c // 2):\n ys.append(x)\n return ys\n\n\ndef indexs_duplable_front(univ, see):\n temp = list(univ)\n res = []\n for x in see:\n i = temp.index(x)\n res.append(i)\n temp[i] = None\n return res\n\n\ndef indexs_duplable_back(univ, see):\n temp = list(reversed(univ))\n res = []\n for x in see:\n i = temp.index(x)\n res.append(len(univ) - 1 - i)\n temp[i] = None\n return res\n\n\ndef more_popped_list(xs, xis):\n xs = list(xs)\n for xi in xis:\n xs[xi] = None\n xs = [x for x in xs if x is not None]\n return xs\n\n\ndef is_type_label(label):\n if isinstance(label, tuple):\n return all(is_type_label(x) for x in label)\n return isinstance(label, str)\n\n\ndef is_type_labels(labels):\n return all(is_type_label(x) for x in labels)\n\n\ndef normarg_labels(labels):\n if isinstance(labels, list):\n return labels\n else:\n return [labels]\n\n\ndef unique_label():\n return ''.join(random.choices(\n 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', k=8))\n\n\ndef aster_label(label):\n if type(label) == tuple:\n return tuple(aster_label(x) for x in label)\n else:\n return label + '*'\n\n\ndef unaster_label(label):\n if type(label) == tuple:\n return tuple(unaster_label(x) for x in label)\n elif label[-1] == '*':\n return label[:-1]\n else:\n return label\n\n\ndef prime_label(label):\n if type(label) == tuple:\n return tuple(prime_label(x) for x in label)\n else:\n return label + \"'\"\n\n\ndef unprime_label(label):\n if type(label) == tuple:\n return tuple(unaster_label(x) for x in label)\n elif label[-1] == \"'\":\n return label[:-1]\n else:\n return label\n\n\ndef aster_labels(labels):\n return [aster_label(label) for label in labels]\n\n\ndef unaster_labels(labels):\n return [unaster_label(label) for label in labels]\n\n\ndef prime_labels(labels):\n return [prime_label(label) for label in labels]\n\n\ndef unprime_labels(labels):\n return [unprime_label(label) for label in labels]\n\n\nclass CyclicList(list):\n\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n\n def __repr__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __str__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n\n def __setitem__(self, i, v):\n return list.__setitem__(self, i % len(self), v)\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\ndef ef_exp(k):\n return ExpFloat(1, k)\n\n\ndef ef_pow(r, k):\n return ExpFloat(r) ** k\n\n\ndef ef_cosh(x):\n return (ef_exp(x) + ef_exp(-x)) / 2\n\n\ndef ef_sinh(x):\n return (ef_exp(x) - ef_exp(-x)) / 2\n\n\ndef ef_complex(x, y):\n if type(x) == ExpFloat and type(y) == ExpFloat:\n if x == 0 and y == 0:\n return ExpFloat(0.0)\n if x.ent >= y.ent:\n r = x.sign + y.sign * math.exp(y.ent - x.ent) * 1.0j\n r = ExpFloat(r)\n r.ent += x.ent\n return r\n else:\n r = x.sign * math.exp(x.ent - y.ent) + y.sign * 1.0j\n r = ExpFloat(r)\n r.ent += y.ent\n return r\n else:\n return ef_complex(ExpFloat(x), ExpFloat(y))\n", "<import token>\n\n\ndef soujou(xs):\n re = 1\n for x in xs:\n re *= x\n return re\n\n\ndef eq_list(xs, ys):\n xc = Counter(xs)\n yc = Counter(ys)\n xc.subtract(yc)\n zs = list(xc.elements())\n return len(zs) == 0\n\n\ndef diff_list(univ, see, assume_included=True):\n diff = list(univ)\n for x in see:\n if assume_included:\n diff.remove(x)\n elif x in diff:\n diff.remove(x)\n return diff\n\n\ndef intersection_list(xs, ys):\n xc = Counter(xs)\n yc = Counter(ys)\n zc = xc & yc\n zs = list(zc.elements())\n return zs\n\n\ndef floor_half_list(xs):\n xc = Counter(xs)\n ys = []\n for x, c in xc.items():\n for _ in range(c // 2):\n ys.append(x)\n return ys\n\n\ndef indexs_duplable_front(univ, see):\n temp = list(univ)\n res = []\n for x in see:\n i = temp.index(x)\n res.append(i)\n temp[i] = None\n return res\n\n\ndef indexs_duplable_back(univ, see):\n temp = list(reversed(univ))\n res = []\n for x in see:\n i = temp.index(x)\n res.append(len(univ) - 1 - i)\n temp[i] = None\n return res\n\n\ndef more_popped_list(xs, xis):\n xs = list(xs)\n for xi in xis:\n xs[xi] = None\n xs = [x for x in xs if x is not None]\n return xs\n\n\ndef is_type_label(label):\n if isinstance(label, tuple):\n return all(is_type_label(x) for x in label)\n return isinstance(label, str)\n\n\ndef is_type_labels(labels):\n return all(is_type_label(x) for x in labels)\n\n\ndef normarg_labels(labels):\n if isinstance(labels, list):\n return labels\n else:\n return [labels]\n\n\ndef unique_label():\n return ''.join(random.choices(\n 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', k=8))\n\n\ndef aster_label(label):\n if type(label) == tuple:\n return tuple(aster_label(x) for x in label)\n else:\n return label + '*'\n\n\ndef unaster_label(label):\n if type(label) == tuple:\n return tuple(unaster_label(x) for x in label)\n elif label[-1] == '*':\n return label[:-1]\n else:\n return label\n\n\ndef prime_label(label):\n if type(label) == tuple:\n return tuple(prime_label(x) for x in label)\n else:\n return label + \"'\"\n\n\ndef unprime_label(label):\n if type(label) == tuple:\n return tuple(unaster_label(x) for x in label)\n elif label[-1] == \"'\":\n return label[:-1]\n else:\n return label\n\n\ndef aster_labels(labels):\n return [aster_label(label) for label in labels]\n\n\ndef unaster_labels(labels):\n return [unaster_label(label) for label in labels]\n\n\ndef prime_labels(labels):\n return [prime_label(label) for label in labels]\n\n\ndef unprime_labels(labels):\n return [unprime_label(label) for label in labels]\n\n\nclass CyclicList(list):\n\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n\n def __repr__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __str__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n\n def __setitem__(self, i, v):\n return list.__setitem__(self, i % len(self), v)\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\ndef ef_exp(k):\n return ExpFloat(1, k)\n\n\ndef ef_pow(r, k):\n return ExpFloat(r) ** k\n\n\ndef ef_cosh(x):\n return (ef_exp(x) + ef_exp(-x)) / 2\n\n\ndef ef_sinh(x):\n return (ef_exp(x) - ef_exp(-x)) / 2\n\n\ndef ef_complex(x, y):\n if type(x) == ExpFloat and type(y) == ExpFloat:\n if x == 0 and y == 0:\n return ExpFloat(0.0)\n if x.ent >= y.ent:\n r = x.sign + y.sign * math.exp(y.ent - x.ent) * 1.0j\n r = ExpFloat(r)\n r.ent += x.ent\n return r\n else:\n r = x.sign * math.exp(x.ent - y.ent) + y.sign * 1.0j\n r = ExpFloat(r)\n r.ent += y.ent\n return r\n else:\n return ef_complex(ExpFloat(x), ExpFloat(y))\n", "<import token>\n\n\ndef soujou(xs):\n re = 1\n for x in xs:\n re *= x\n return re\n\n\ndef eq_list(xs, ys):\n xc = Counter(xs)\n yc = Counter(ys)\n xc.subtract(yc)\n zs = list(xc.elements())\n return len(zs) == 0\n\n\ndef diff_list(univ, see, assume_included=True):\n diff = list(univ)\n for x in see:\n if assume_included:\n diff.remove(x)\n elif x in diff:\n diff.remove(x)\n return diff\n\n\ndef intersection_list(xs, ys):\n xc = Counter(xs)\n yc = Counter(ys)\n zc = xc & yc\n zs = list(zc.elements())\n return zs\n\n\ndef floor_half_list(xs):\n xc = Counter(xs)\n ys = []\n for x, c in xc.items():\n for _ in range(c // 2):\n ys.append(x)\n return ys\n\n\ndef indexs_duplable_front(univ, see):\n temp = list(univ)\n res = []\n for x in see:\n i = temp.index(x)\n res.append(i)\n temp[i] = None\n return res\n\n\n<function token>\n\n\ndef more_popped_list(xs, xis):\n xs = list(xs)\n for xi in xis:\n xs[xi] = None\n xs = [x for x in xs if x is not None]\n return xs\n\n\ndef is_type_label(label):\n if isinstance(label, tuple):\n return all(is_type_label(x) for x in label)\n return isinstance(label, str)\n\n\ndef is_type_labels(labels):\n return all(is_type_label(x) for x in labels)\n\n\ndef normarg_labels(labels):\n if isinstance(labels, list):\n return labels\n else:\n return [labels]\n\n\ndef unique_label():\n return ''.join(random.choices(\n 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', k=8))\n\n\ndef aster_label(label):\n if type(label) == tuple:\n return tuple(aster_label(x) for x in label)\n else:\n return label + '*'\n\n\ndef unaster_label(label):\n if type(label) == tuple:\n return tuple(unaster_label(x) for x in label)\n elif label[-1] == '*':\n return label[:-1]\n else:\n return label\n\n\ndef prime_label(label):\n if type(label) == tuple:\n return tuple(prime_label(x) for x in label)\n else:\n return label + \"'\"\n\n\ndef unprime_label(label):\n if type(label) == tuple:\n return tuple(unaster_label(x) for x in label)\n elif label[-1] == \"'\":\n return label[:-1]\n else:\n return label\n\n\ndef aster_labels(labels):\n return [aster_label(label) for label in labels]\n\n\ndef unaster_labels(labels):\n return [unaster_label(label) for label in labels]\n\n\ndef prime_labels(labels):\n return [prime_label(label) for label in labels]\n\n\ndef unprime_labels(labels):\n return [unprime_label(label) for label in labels]\n\n\nclass CyclicList(list):\n\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n\n def __repr__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __str__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n\n def __setitem__(self, i, v):\n return list.__setitem__(self, i % len(self), v)\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\ndef ef_exp(k):\n return ExpFloat(1, k)\n\n\ndef ef_pow(r, k):\n return ExpFloat(r) ** k\n\n\ndef ef_cosh(x):\n return (ef_exp(x) + ef_exp(-x)) / 2\n\n\ndef ef_sinh(x):\n return (ef_exp(x) - ef_exp(-x)) / 2\n\n\ndef ef_complex(x, y):\n if type(x) == ExpFloat and type(y) == ExpFloat:\n if x == 0 and y == 0:\n return ExpFloat(0.0)\n if x.ent >= y.ent:\n r = x.sign + y.sign * math.exp(y.ent - x.ent) * 1.0j\n r = ExpFloat(r)\n r.ent += x.ent\n return r\n else:\n r = x.sign * math.exp(x.ent - y.ent) + y.sign * 1.0j\n r = ExpFloat(r)\n r.ent += y.ent\n return r\n else:\n return ef_complex(ExpFloat(x), ExpFloat(y))\n", "<import token>\n\n\ndef soujou(xs):\n re = 1\n for x in xs:\n re *= x\n return re\n\n\ndef eq_list(xs, ys):\n xc = Counter(xs)\n yc = Counter(ys)\n xc.subtract(yc)\n zs = list(xc.elements())\n return len(zs) == 0\n\n\ndef diff_list(univ, see, assume_included=True):\n diff = list(univ)\n for x in see:\n if assume_included:\n diff.remove(x)\n elif x in diff:\n diff.remove(x)\n return diff\n\n\ndef intersection_list(xs, ys):\n xc = Counter(xs)\n yc = Counter(ys)\n zc = xc & yc\n zs = list(zc.elements())\n return zs\n\n\ndef floor_half_list(xs):\n xc = Counter(xs)\n ys = []\n for x, c in xc.items():\n for _ in range(c // 2):\n ys.append(x)\n return ys\n\n\ndef indexs_duplable_front(univ, see):\n temp = list(univ)\n res = []\n for x in see:\n i = temp.index(x)\n res.append(i)\n temp[i] = None\n return res\n\n\n<function token>\n\n\ndef more_popped_list(xs, xis):\n xs = list(xs)\n for xi in xis:\n xs[xi] = None\n xs = [x for x in xs if x is not None]\n return xs\n\n\ndef is_type_label(label):\n if isinstance(label, tuple):\n return all(is_type_label(x) for x in label)\n return isinstance(label, str)\n\n\ndef is_type_labels(labels):\n return all(is_type_label(x) for x in labels)\n\n\ndef normarg_labels(labels):\n if isinstance(labels, list):\n return labels\n else:\n return [labels]\n\n\ndef unique_label():\n return ''.join(random.choices(\n 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', k=8))\n\n\ndef aster_label(label):\n if type(label) == tuple:\n return tuple(aster_label(x) for x in label)\n else:\n return label + '*'\n\n\n<function token>\n\n\ndef prime_label(label):\n if type(label) == tuple:\n return tuple(prime_label(x) for x in label)\n else:\n return label + \"'\"\n\n\ndef unprime_label(label):\n if type(label) == tuple:\n return tuple(unaster_label(x) for x in label)\n elif label[-1] == \"'\":\n return label[:-1]\n else:\n return label\n\n\ndef aster_labels(labels):\n return [aster_label(label) for label in labels]\n\n\ndef unaster_labels(labels):\n return [unaster_label(label) for label in labels]\n\n\ndef prime_labels(labels):\n return [prime_label(label) for label in labels]\n\n\ndef unprime_labels(labels):\n return [unprime_label(label) for label in labels]\n\n\nclass CyclicList(list):\n\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n\n def __repr__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __str__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n\n def __setitem__(self, i, v):\n return list.__setitem__(self, i % len(self), v)\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\ndef ef_exp(k):\n return ExpFloat(1, k)\n\n\ndef ef_pow(r, k):\n return ExpFloat(r) ** k\n\n\ndef ef_cosh(x):\n return (ef_exp(x) + ef_exp(-x)) / 2\n\n\ndef ef_sinh(x):\n return (ef_exp(x) - ef_exp(-x)) / 2\n\n\ndef ef_complex(x, y):\n if type(x) == ExpFloat and type(y) == ExpFloat:\n if x == 0 and y == 0:\n return ExpFloat(0.0)\n if x.ent >= y.ent:\n r = x.sign + y.sign * math.exp(y.ent - x.ent) * 1.0j\n r = ExpFloat(r)\n r.ent += x.ent\n return r\n else:\n r = x.sign * math.exp(x.ent - y.ent) + y.sign * 1.0j\n r = ExpFloat(r)\n r.ent += y.ent\n return r\n else:\n return ef_complex(ExpFloat(x), ExpFloat(y))\n", "<import token>\n\n\ndef soujou(xs):\n re = 1\n for x in xs:\n re *= x\n return re\n\n\ndef eq_list(xs, ys):\n xc = Counter(xs)\n yc = Counter(ys)\n xc.subtract(yc)\n zs = list(xc.elements())\n return len(zs) == 0\n\n\ndef diff_list(univ, see, assume_included=True):\n diff = list(univ)\n for x in see:\n if assume_included:\n diff.remove(x)\n elif x in diff:\n diff.remove(x)\n return diff\n\n\ndef intersection_list(xs, ys):\n xc = Counter(xs)\n yc = Counter(ys)\n zc = xc & yc\n zs = list(zc.elements())\n return zs\n\n\ndef floor_half_list(xs):\n xc = Counter(xs)\n ys = []\n for x, c in xc.items():\n for _ in range(c // 2):\n ys.append(x)\n return ys\n\n\ndef indexs_duplable_front(univ, see):\n temp = list(univ)\n res = []\n for x in see:\n i = temp.index(x)\n res.append(i)\n temp[i] = None\n return res\n\n\n<function token>\n\n\ndef more_popped_list(xs, xis):\n xs = list(xs)\n for xi in xis:\n xs[xi] = None\n xs = [x for x in xs if x is not None]\n return xs\n\n\ndef is_type_label(label):\n if isinstance(label, tuple):\n return all(is_type_label(x) for x in label)\n return isinstance(label, str)\n\n\ndef is_type_labels(labels):\n return all(is_type_label(x) for x in labels)\n\n\ndef normarg_labels(labels):\n if isinstance(labels, list):\n return labels\n else:\n return [labels]\n\n\ndef unique_label():\n return ''.join(random.choices(\n 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', k=8))\n\n\n<function token>\n<function token>\n\n\ndef prime_label(label):\n if type(label) == tuple:\n return tuple(prime_label(x) for x in label)\n else:\n return label + \"'\"\n\n\ndef unprime_label(label):\n if type(label) == tuple:\n return tuple(unaster_label(x) for x in label)\n elif label[-1] == \"'\":\n return label[:-1]\n else:\n return label\n\n\ndef aster_labels(labels):\n return [aster_label(label) for label in labels]\n\n\ndef unaster_labels(labels):\n return [unaster_label(label) for label in labels]\n\n\ndef prime_labels(labels):\n return [prime_label(label) for label in labels]\n\n\ndef unprime_labels(labels):\n return [unprime_label(label) for label in labels]\n\n\nclass CyclicList(list):\n\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n\n def __repr__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __str__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n\n def __setitem__(self, i, v):\n return list.__setitem__(self, i % len(self), v)\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\ndef ef_exp(k):\n return ExpFloat(1, k)\n\n\ndef ef_pow(r, k):\n return ExpFloat(r) ** k\n\n\ndef ef_cosh(x):\n return (ef_exp(x) + ef_exp(-x)) / 2\n\n\ndef ef_sinh(x):\n return (ef_exp(x) - ef_exp(-x)) / 2\n\n\ndef ef_complex(x, y):\n if type(x) == ExpFloat and type(y) == ExpFloat:\n if x == 0 and y == 0:\n return ExpFloat(0.0)\n if x.ent >= y.ent:\n r = x.sign + y.sign * math.exp(y.ent - x.ent) * 1.0j\n r = ExpFloat(r)\n r.ent += x.ent\n return r\n else:\n r = x.sign * math.exp(x.ent - y.ent) + y.sign * 1.0j\n r = ExpFloat(r)\n r.ent += y.ent\n return r\n else:\n return ef_complex(ExpFloat(x), ExpFloat(y))\n", "<import token>\n\n\ndef soujou(xs):\n re = 1\n for x in xs:\n re *= x\n return re\n\n\ndef eq_list(xs, ys):\n xc = Counter(xs)\n yc = Counter(ys)\n xc.subtract(yc)\n zs = list(xc.elements())\n return len(zs) == 0\n\n\ndef diff_list(univ, see, assume_included=True):\n diff = list(univ)\n for x in see:\n if assume_included:\n diff.remove(x)\n elif x in diff:\n diff.remove(x)\n return diff\n\n\ndef intersection_list(xs, ys):\n xc = Counter(xs)\n yc = Counter(ys)\n zc = xc & yc\n zs = list(zc.elements())\n return zs\n\n\ndef floor_half_list(xs):\n xc = Counter(xs)\n ys = []\n for x, c in xc.items():\n for _ in range(c // 2):\n ys.append(x)\n return ys\n\n\ndef indexs_duplable_front(univ, see):\n temp = list(univ)\n res = []\n for x in see:\n i = temp.index(x)\n res.append(i)\n temp[i] = None\n return res\n\n\n<function token>\n\n\ndef more_popped_list(xs, xis):\n xs = list(xs)\n for xi in xis:\n xs[xi] = None\n xs = [x for x in xs if x is not None]\n return xs\n\n\ndef is_type_label(label):\n if isinstance(label, tuple):\n return all(is_type_label(x) for x in label)\n return isinstance(label, str)\n\n\ndef is_type_labels(labels):\n return all(is_type_label(x) for x in labels)\n\n\n<function token>\n\n\ndef unique_label():\n return ''.join(random.choices(\n 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', k=8))\n\n\n<function token>\n<function token>\n\n\ndef prime_label(label):\n if type(label) == tuple:\n return tuple(prime_label(x) for x in label)\n else:\n return label + \"'\"\n\n\ndef unprime_label(label):\n if type(label) == tuple:\n return tuple(unaster_label(x) for x in label)\n elif label[-1] == \"'\":\n return label[:-1]\n else:\n return label\n\n\ndef aster_labels(labels):\n return [aster_label(label) for label in labels]\n\n\ndef unaster_labels(labels):\n return [unaster_label(label) for label in labels]\n\n\ndef prime_labels(labels):\n return [prime_label(label) for label in labels]\n\n\ndef unprime_labels(labels):\n return [unprime_label(label) for label in labels]\n\n\nclass CyclicList(list):\n\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n\n def __repr__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __str__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n\n def __setitem__(self, i, v):\n return list.__setitem__(self, i % len(self), v)\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\ndef ef_exp(k):\n return ExpFloat(1, k)\n\n\ndef ef_pow(r, k):\n return ExpFloat(r) ** k\n\n\ndef ef_cosh(x):\n return (ef_exp(x) + ef_exp(-x)) / 2\n\n\ndef ef_sinh(x):\n return (ef_exp(x) - ef_exp(-x)) / 2\n\n\ndef ef_complex(x, y):\n if type(x) == ExpFloat and type(y) == ExpFloat:\n if x == 0 and y == 0:\n return ExpFloat(0.0)\n if x.ent >= y.ent:\n r = x.sign + y.sign * math.exp(y.ent - x.ent) * 1.0j\n r = ExpFloat(r)\n r.ent += x.ent\n return r\n else:\n r = x.sign * math.exp(x.ent - y.ent) + y.sign * 1.0j\n r = ExpFloat(r)\n r.ent += y.ent\n return r\n else:\n return ef_complex(ExpFloat(x), ExpFloat(y))\n", "<import token>\n\n\ndef soujou(xs):\n re = 1\n for x in xs:\n re *= x\n return re\n\n\ndef eq_list(xs, ys):\n xc = Counter(xs)\n yc = Counter(ys)\n xc.subtract(yc)\n zs = list(xc.elements())\n return len(zs) == 0\n\n\ndef diff_list(univ, see, assume_included=True):\n diff = list(univ)\n for x in see:\n if assume_included:\n diff.remove(x)\n elif x in diff:\n diff.remove(x)\n return diff\n\n\ndef intersection_list(xs, ys):\n xc = Counter(xs)\n yc = Counter(ys)\n zc = xc & yc\n zs = list(zc.elements())\n return zs\n\n\ndef floor_half_list(xs):\n xc = Counter(xs)\n ys = []\n for x, c in xc.items():\n for _ in range(c // 2):\n ys.append(x)\n return ys\n\n\ndef indexs_duplable_front(univ, see):\n temp = list(univ)\n res = []\n for x in see:\n i = temp.index(x)\n res.append(i)\n temp[i] = None\n return res\n\n\n<function token>\n\n\ndef more_popped_list(xs, xis):\n xs = list(xs)\n for xi in xis:\n xs[xi] = None\n xs = [x for x in xs if x is not None]\n return xs\n\n\ndef is_type_label(label):\n if isinstance(label, tuple):\n return all(is_type_label(x) for x in label)\n return isinstance(label, str)\n\n\ndef is_type_labels(labels):\n return all(is_type_label(x) for x in labels)\n\n\n<function token>\n\n\ndef unique_label():\n return ''.join(random.choices(\n 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', k=8))\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef unprime_label(label):\n if type(label) == tuple:\n return tuple(unaster_label(x) for x in label)\n elif label[-1] == \"'\":\n return label[:-1]\n else:\n return label\n\n\ndef aster_labels(labels):\n return [aster_label(label) for label in labels]\n\n\ndef unaster_labels(labels):\n return [unaster_label(label) for label in labels]\n\n\ndef prime_labels(labels):\n return [prime_label(label) for label in labels]\n\n\ndef unprime_labels(labels):\n return [unprime_label(label) for label in labels]\n\n\nclass CyclicList(list):\n\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n\n def __repr__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __str__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n\n def __setitem__(self, i, v):\n return list.__setitem__(self, i % len(self), v)\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\ndef ef_exp(k):\n return ExpFloat(1, k)\n\n\ndef ef_pow(r, k):\n return ExpFloat(r) ** k\n\n\ndef ef_cosh(x):\n return (ef_exp(x) + ef_exp(-x)) / 2\n\n\ndef ef_sinh(x):\n return (ef_exp(x) - ef_exp(-x)) / 2\n\n\ndef ef_complex(x, y):\n if type(x) == ExpFloat and type(y) == ExpFloat:\n if x == 0 and y == 0:\n return ExpFloat(0.0)\n if x.ent >= y.ent:\n r = x.sign + y.sign * math.exp(y.ent - x.ent) * 1.0j\n r = ExpFloat(r)\n r.ent += x.ent\n return r\n else:\n r = x.sign * math.exp(x.ent - y.ent) + y.sign * 1.0j\n r = ExpFloat(r)\n r.ent += y.ent\n return r\n else:\n return ef_complex(ExpFloat(x), ExpFloat(y))\n", "<import token>\n\n\ndef soujou(xs):\n re = 1\n for x in xs:\n re *= x\n return re\n\n\ndef eq_list(xs, ys):\n xc = Counter(xs)\n yc = Counter(ys)\n xc.subtract(yc)\n zs = list(xc.elements())\n return len(zs) == 0\n\n\ndef diff_list(univ, see, assume_included=True):\n diff = list(univ)\n for x in see:\n if assume_included:\n diff.remove(x)\n elif x in diff:\n diff.remove(x)\n return diff\n\n\ndef intersection_list(xs, ys):\n xc = Counter(xs)\n yc = Counter(ys)\n zc = xc & yc\n zs = list(zc.elements())\n return zs\n\n\ndef floor_half_list(xs):\n xc = Counter(xs)\n ys = []\n for x, c in xc.items():\n for _ in range(c // 2):\n ys.append(x)\n return ys\n\n\ndef indexs_duplable_front(univ, see):\n temp = list(univ)\n res = []\n for x in see:\n i = temp.index(x)\n res.append(i)\n temp[i] = None\n return res\n\n\n<function token>\n\n\ndef more_popped_list(xs, xis):\n xs = list(xs)\n for xi in xis:\n xs[xi] = None\n xs = [x for x in xs if x is not None]\n return xs\n\n\ndef is_type_label(label):\n if isinstance(label, tuple):\n return all(is_type_label(x) for x in label)\n return isinstance(label, str)\n\n\ndef is_type_labels(labels):\n return all(is_type_label(x) for x in labels)\n\n\n<function token>\n\n\ndef unique_label():\n return ''.join(random.choices(\n 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', k=8))\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef unprime_label(label):\n if type(label) == tuple:\n return tuple(unaster_label(x) for x in label)\n elif label[-1] == \"'\":\n return label[:-1]\n else:\n return label\n\n\n<function token>\n\n\ndef unaster_labels(labels):\n return [unaster_label(label) for label in labels]\n\n\ndef prime_labels(labels):\n return [prime_label(label) for label in labels]\n\n\ndef unprime_labels(labels):\n return [unprime_label(label) for label in labels]\n\n\nclass CyclicList(list):\n\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n\n def __repr__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __str__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n\n def __setitem__(self, i, v):\n return list.__setitem__(self, i % len(self), v)\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\ndef ef_exp(k):\n return ExpFloat(1, k)\n\n\ndef ef_pow(r, k):\n return ExpFloat(r) ** k\n\n\ndef ef_cosh(x):\n return (ef_exp(x) + ef_exp(-x)) / 2\n\n\ndef ef_sinh(x):\n return (ef_exp(x) - ef_exp(-x)) / 2\n\n\ndef ef_complex(x, y):\n if type(x) == ExpFloat and type(y) == ExpFloat:\n if x == 0 and y == 0:\n return ExpFloat(0.0)\n if x.ent >= y.ent:\n r = x.sign + y.sign * math.exp(y.ent - x.ent) * 1.0j\n r = ExpFloat(r)\n r.ent += x.ent\n return r\n else:\n r = x.sign * math.exp(x.ent - y.ent) + y.sign * 1.0j\n r = ExpFloat(r)\n r.ent += y.ent\n return r\n else:\n return ef_complex(ExpFloat(x), ExpFloat(y))\n", "<import token>\n\n\ndef soujou(xs):\n re = 1\n for x in xs:\n re *= x\n return re\n\n\ndef eq_list(xs, ys):\n xc = Counter(xs)\n yc = Counter(ys)\n xc.subtract(yc)\n zs = list(xc.elements())\n return len(zs) == 0\n\n\ndef diff_list(univ, see, assume_included=True):\n diff = list(univ)\n for x in see:\n if assume_included:\n diff.remove(x)\n elif x in diff:\n diff.remove(x)\n return diff\n\n\ndef intersection_list(xs, ys):\n xc = Counter(xs)\n yc = Counter(ys)\n zc = xc & yc\n zs = list(zc.elements())\n return zs\n\n\ndef floor_half_list(xs):\n xc = Counter(xs)\n ys = []\n for x, c in xc.items():\n for _ in range(c // 2):\n ys.append(x)\n return ys\n\n\n<function token>\n<function token>\n\n\ndef more_popped_list(xs, xis):\n xs = list(xs)\n for xi in xis:\n xs[xi] = None\n xs = [x for x in xs if x is not None]\n return xs\n\n\ndef is_type_label(label):\n if isinstance(label, tuple):\n return all(is_type_label(x) for x in label)\n return isinstance(label, str)\n\n\ndef is_type_labels(labels):\n return all(is_type_label(x) for x in labels)\n\n\n<function token>\n\n\ndef unique_label():\n return ''.join(random.choices(\n 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', k=8))\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef unprime_label(label):\n if type(label) == tuple:\n return tuple(unaster_label(x) for x in label)\n elif label[-1] == \"'\":\n return label[:-1]\n else:\n return label\n\n\n<function token>\n\n\ndef unaster_labels(labels):\n return [unaster_label(label) for label in labels]\n\n\ndef prime_labels(labels):\n return [prime_label(label) for label in labels]\n\n\ndef unprime_labels(labels):\n return [unprime_label(label) for label in labels]\n\n\nclass CyclicList(list):\n\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n\n def __repr__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __str__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n\n def __setitem__(self, i, v):\n return list.__setitem__(self, i % len(self), v)\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\ndef ef_exp(k):\n return ExpFloat(1, k)\n\n\ndef ef_pow(r, k):\n return ExpFloat(r) ** k\n\n\ndef ef_cosh(x):\n return (ef_exp(x) + ef_exp(-x)) / 2\n\n\ndef ef_sinh(x):\n return (ef_exp(x) - ef_exp(-x)) / 2\n\n\ndef ef_complex(x, y):\n if type(x) == ExpFloat and type(y) == ExpFloat:\n if x == 0 and y == 0:\n return ExpFloat(0.0)\n if x.ent >= y.ent:\n r = x.sign + y.sign * math.exp(y.ent - x.ent) * 1.0j\n r = ExpFloat(r)\n r.ent += x.ent\n return r\n else:\n r = x.sign * math.exp(x.ent - y.ent) + y.sign * 1.0j\n r = ExpFloat(r)\n r.ent += y.ent\n return r\n else:\n return ef_complex(ExpFloat(x), ExpFloat(y))\n", "<import token>\n\n\ndef soujou(xs):\n re = 1\n for x in xs:\n re *= x\n return re\n\n\ndef eq_list(xs, ys):\n xc = Counter(xs)\n yc = Counter(ys)\n xc.subtract(yc)\n zs = list(xc.elements())\n return len(zs) == 0\n\n\ndef diff_list(univ, see, assume_included=True):\n diff = list(univ)\n for x in see:\n if assume_included:\n diff.remove(x)\n elif x in diff:\n diff.remove(x)\n return diff\n\n\ndef intersection_list(xs, ys):\n xc = Counter(xs)\n yc = Counter(ys)\n zc = xc & yc\n zs = list(zc.elements())\n return zs\n\n\ndef floor_half_list(xs):\n xc = Counter(xs)\n ys = []\n for x, c in xc.items():\n for _ in range(c // 2):\n ys.append(x)\n return ys\n\n\n<function token>\n<function token>\n\n\ndef more_popped_list(xs, xis):\n xs = list(xs)\n for xi in xis:\n xs[xi] = None\n xs = [x for x in xs if x is not None]\n return xs\n\n\ndef is_type_label(label):\n if isinstance(label, tuple):\n return all(is_type_label(x) for x in label)\n return isinstance(label, str)\n\n\ndef is_type_labels(labels):\n return all(is_type_label(x) for x in labels)\n\n\n<function token>\n\n\ndef unique_label():\n return ''.join(random.choices(\n 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', k=8))\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef unprime_label(label):\n if type(label) == tuple:\n return tuple(unaster_label(x) for x in label)\n elif label[-1] == \"'\":\n return label[:-1]\n else:\n return label\n\n\n<function token>\n\n\ndef unaster_labels(labels):\n return [unaster_label(label) for label in labels]\n\n\ndef prime_labels(labels):\n return [prime_label(label) for label in labels]\n\n\ndef unprime_labels(labels):\n return [unprime_label(label) for label in labels]\n\n\nclass CyclicList(list):\n\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n\n def __repr__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __str__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n\n def __setitem__(self, i, v):\n return list.__setitem__(self, i % len(self), v)\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\ndef ef_exp(k):\n return ExpFloat(1, k)\n\n\ndef ef_pow(r, k):\n return ExpFloat(r) ** k\n\n\n<function token>\n\n\ndef ef_sinh(x):\n return (ef_exp(x) - ef_exp(-x)) / 2\n\n\ndef ef_complex(x, y):\n if type(x) == ExpFloat and type(y) == ExpFloat:\n if x == 0 and y == 0:\n return ExpFloat(0.0)\n if x.ent >= y.ent:\n r = x.sign + y.sign * math.exp(y.ent - x.ent) * 1.0j\n r = ExpFloat(r)\n r.ent += x.ent\n return r\n else:\n r = x.sign * math.exp(x.ent - y.ent) + y.sign * 1.0j\n r = ExpFloat(r)\n r.ent += y.ent\n return r\n else:\n return ef_complex(ExpFloat(x), ExpFloat(y))\n", "<import token>\n\n\ndef soujou(xs):\n re = 1\n for x in xs:\n re *= x\n return re\n\n\n<function token>\n\n\ndef diff_list(univ, see, assume_included=True):\n diff = list(univ)\n for x in see:\n if assume_included:\n diff.remove(x)\n elif x in diff:\n diff.remove(x)\n return diff\n\n\ndef intersection_list(xs, ys):\n xc = Counter(xs)\n yc = Counter(ys)\n zc = xc & yc\n zs = list(zc.elements())\n return zs\n\n\ndef floor_half_list(xs):\n xc = Counter(xs)\n ys = []\n for x, c in xc.items():\n for _ in range(c // 2):\n ys.append(x)\n return ys\n\n\n<function token>\n<function token>\n\n\ndef more_popped_list(xs, xis):\n xs = list(xs)\n for xi in xis:\n xs[xi] = None\n xs = [x for x in xs if x is not None]\n return xs\n\n\ndef is_type_label(label):\n if isinstance(label, tuple):\n return all(is_type_label(x) for x in label)\n return isinstance(label, str)\n\n\ndef is_type_labels(labels):\n return all(is_type_label(x) for x in labels)\n\n\n<function token>\n\n\ndef unique_label():\n return ''.join(random.choices(\n 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', k=8))\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef unprime_label(label):\n if type(label) == tuple:\n return tuple(unaster_label(x) for x in label)\n elif label[-1] == \"'\":\n return label[:-1]\n else:\n return label\n\n\n<function token>\n\n\ndef unaster_labels(labels):\n return [unaster_label(label) for label in labels]\n\n\ndef prime_labels(labels):\n return [prime_label(label) for label in labels]\n\n\ndef unprime_labels(labels):\n return [unprime_label(label) for label in labels]\n\n\nclass CyclicList(list):\n\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n\n def __repr__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __str__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n\n def __setitem__(self, i, v):\n return list.__setitem__(self, i % len(self), v)\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\ndef ef_exp(k):\n return ExpFloat(1, k)\n\n\ndef ef_pow(r, k):\n return ExpFloat(r) ** k\n\n\n<function token>\n\n\ndef ef_sinh(x):\n return (ef_exp(x) - ef_exp(-x)) / 2\n\n\ndef ef_complex(x, y):\n if type(x) == ExpFloat and type(y) == ExpFloat:\n if x == 0 and y == 0:\n return ExpFloat(0.0)\n if x.ent >= y.ent:\n r = x.sign + y.sign * math.exp(y.ent - x.ent) * 1.0j\n r = ExpFloat(r)\n r.ent += x.ent\n return r\n else:\n r = x.sign * math.exp(x.ent - y.ent) + y.sign * 1.0j\n r = ExpFloat(r)\n r.ent += y.ent\n return r\n else:\n return ef_complex(ExpFloat(x), ExpFloat(y))\n", "<import token>\n\n\ndef soujou(xs):\n re = 1\n for x in xs:\n re *= x\n return re\n\n\n<function token>\n\n\ndef diff_list(univ, see, assume_included=True):\n diff = list(univ)\n for x in see:\n if assume_included:\n diff.remove(x)\n elif x in diff:\n diff.remove(x)\n return diff\n\n\ndef intersection_list(xs, ys):\n xc = Counter(xs)\n yc = Counter(ys)\n zc = xc & yc\n zs = list(zc.elements())\n return zs\n\n\ndef floor_half_list(xs):\n xc = Counter(xs)\n ys = []\n for x, c in xc.items():\n for _ in range(c // 2):\n ys.append(x)\n return ys\n\n\n<function token>\n<function token>\n\n\ndef more_popped_list(xs, xis):\n xs = list(xs)\n for xi in xis:\n xs[xi] = None\n xs = [x for x in xs if x is not None]\n return xs\n\n\ndef is_type_label(label):\n if isinstance(label, tuple):\n return all(is_type_label(x) for x in label)\n return isinstance(label, str)\n\n\ndef is_type_labels(labels):\n return all(is_type_label(x) for x in labels)\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef unprime_label(label):\n if type(label) == tuple:\n return tuple(unaster_label(x) for x in label)\n elif label[-1] == \"'\":\n return label[:-1]\n else:\n return label\n\n\n<function token>\n\n\ndef unaster_labels(labels):\n return [unaster_label(label) for label in labels]\n\n\ndef prime_labels(labels):\n return [prime_label(label) for label in labels]\n\n\ndef unprime_labels(labels):\n return [unprime_label(label) for label in labels]\n\n\nclass CyclicList(list):\n\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n\n def __repr__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __str__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n\n def __setitem__(self, i, v):\n return list.__setitem__(self, i % len(self), v)\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\ndef ef_exp(k):\n return ExpFloat(1, k)\n\n\ndef ef_pow(r, k):\n return ExpFloat(r) ** k\n\n\n<function token>\n\n\ndef ef_sinh(x):\n return (ef_exp(x) - ef_exp(-x)) / 2\n\n\ndef ef_complex(x, y):\n if type(x) == ExpFloat and type(y) == ExpFloat:\n if x == 0 and y == 0:\n return ExpFloat(0.0)\n if x.ent >= y.ent:\n r = x.sign + y.sign * math.exp(y.ent - x.ent) * 1.0j\n r = ExpFloat(r)\n r.ent += x.ent\n return r\n else:\n r = x.sign * math.exp(x.ent - y.ent) + y.sign * 1.0j\n r = ExpFloat(r)\n r.ent += y.ent\n return r\n else:\n return ef_complex(ExpFloat(x), ExpFloat(y))\n", "<import token>\n\n\ndef soujou(xs):\n re = 1\n for x in xs:\n re *= x\n return re\n\n\n<function token>\n\n\ndef diff_list(univ, see, assume_included=True):\n diff = list(univ)\n for x in see:\n if assume_included:\n diff.remove(x)\n elif x in diff:\n diff.remove(x)\n return diff\n\n\ndef intersection_list(xs, ys):\n xc = Counter(xs)\n yc = Counter(ys)\n zc = xc & yc\n zs = list(zc.elements())\n return zs\n\n\ndef floor_half_list(xs):\n xc = Counter(xs)\n ys = []\n for x, c in xc.items():\n for _ in range(c // 2):\n ys.append(x)\n return ys\n\n\n<function token>\n<function token>\n\n\ndef more_popped_list(xs, xis):\n xs = list(xs)\n for xi in xis:\n xs[xi] = None\n xs = [x for x in xs if x is not None]\n return xs\n\n\ndef is_type_label(label):\n if isinstance(label, tuple):\n return all(is_type_label(x) for x in label)\n return isinstance(label, str)\n\n\ndef is_type_labels(labels):\n return all(is_type_label(x) for x in labels)\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef unprime_label(label):\n if type(label) == tuple:\n return tuple(unaster_label(x) for x in label)\n elif label[-1] == \"'\":\n return label[:-1]\n else:\n return label\n\n\n<function token>\n\n\ndef unaster_labels(labels):\n return [unaster_label(label) for label in labels]\n\n\ndef prime_labels(labels):\n return [prime_label(label) for label in labels]\n\n\ndef unprime_labels(labels):\n return [unprime_label(label) for label in labels]\n\n\nclass CyclicList(list):\n\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n\n def __repr__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __str__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n\n def __setitem__(self, i, v):\n return list.__setitem__(self, i % len(self), v)\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n\n\ndef ef_pow(r, k):\n return ExpFloat(r) ** k\n\n\n<function token>\n\n\ndef ef_sinh(x):\n return (ef_exp(x) - ef_exp(-x)) / 2\n\n\ndef ef_complex(x, y):\n if type(x) == ExpFloat and type(y) == ExpFloat:\n if x == 0 and y == 0:\n return ExpFloat(0.0)\n if x.ent >= y.ent:\n r = x.sign + y.sign * math.exp(y.ent - x.ent) * 1.0j\n r = ExpFloat(r)\n r.ent += x.ent\n return r\n else:\n r = x.sign * math.exp(x.ent - y.ent) + y.sign * 1.0j\n r = ExpFloat(r)\n r.ent += y.ent\n return r\n else:\n return ef_complex(ExpFloat(x), ExpFloat(y))\n", "<import token>\n\n\ndef soujou(xs):\n re = 1\n for x in xs:\n re *= x\n return re\n\n\n<function token>\n\n\ndef diff_list(univ, see, assume_included=True):\n diff = list(univ)\n for x in see:\n if assume_included:\n diff.remove(x)\n elif x in diff:\n diff.remove(x)\n return diff\n\n\ndef intersection_list(xs, ys):\n xc = Counter(xs)\n yc = Counter(ys)\n zc = xc & yc\n zs = list(zc.elements())\n return zs\n\n\ndef floor_half_list(xs):\n xc = Counter(xs)\n ys = []\n for x, c in xc.items():\n for _ in range(c // 2):\n ys.append(x)\n return ys\n\n\n<function token>\n<function token>\n\n\ndef more_popped_list(xs, xis):\n xs = list(xs)\n for xi in xis:\n xs[xi] = None\n xs = [x for x in xs if x is not None]\n return xs\n\n\ndef is_type_label(label):\n if isinstance(label, tuple):\n return all(is_type_label(x) for x in label)\n return isinstance(label, str)\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef unprime_label(label):\n if type(label) == tuple:\n return tuple(unaster_label(x) for x in label)\n elif label[-1] == \"'\":\n return label[:-1]\n else:\n return label\n\n\n<function token>\n\n\ndef unaster_labels(labels):\n return [unaster_label(label) for label in labels]\n\n\ndef prime_labels(labels):\n return [prime_label(label) for label in labels]\n\n\ndef unprime_labels(labels):\n return [unprime_label(label) for label in labels]\n\n\nclass CyclicList(list):\n\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n\n def __repr__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __str__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n\n def __setitem__(self, i, v):\n return list.__setitem__(self, i % len(self), v)\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n\n\ndef ef_pow(r, k):\n return ExpFloat(r) ** k\n\n\n<function token>\n\n\ndef ef_sinh(x):\n return (ef_exp(x) - ef_exp(-x)) / 2\n\n\ndef ef_complex(x, y):\n if type(x) == ExpFloat and type(y) == ExpFloat:\n if x == 0 and y == 0:\n return ExpFloat(0.0)\n if x.ent >= y.ent:\n r = x.sign + y.sign * math.exp(y.ent - x.ent) * 1.0j\n r = ExpFloat(r)\n r.ent += x.ent\n return r\n else:\n r = x.sign * math.exp(x.ent - y.ent) + y.sign * 1.0j\n r = ExpFloat(r)\n r.ent += y.ent\n return r\n else:\n return ef_complex(ExpFloat(x), ExpFloat(y))\n", "<import token>\n\n\ndef soujou(xs):\n re = 1\n for x in xs:\n re *= x\n return re\n\n\n<function token>\n\n\ndef diff_list(univ, see, assume_included=True):\n diff = list(univ)\n for x in see:\n if assume_included:\n diff.remove(x)\n elif x in diff:\n diff.remove(x)\n return diff\n\n\ndef intersection_list(xs, ys):\n xc = Counter(xs)\n yc = Counter(ys)\n zc = xc & yc\n zs = list(zc.elements())\n return zs\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef more_popped_list(xs, xis):\n xs = list(xs)\n for xi in xis:\n xs[xi] = None\n xs = [x for x in xs if x is not None]\n return xs\n\n\ndef is_type_label(label):\n if isinstance(label, tuple):\n return all(is_type_label(x) for x in label)\n return isinstance(label, str)\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef unprime_label(label):\n if type(label) == tuple:\n return tuple(unaster_label(x) for x in label)\n elif label[-1] == \"'\":\n return label[:-1]\n else:\n return label\n\n\n<function token>\n\n\ndef unaster_labels(labels):\n return [unaster_label(label) for label in labels]\n\n\ndef prime_labels(labels):\n return [prime_label(label) for label in labels]\n\n\ndef unprime_labels(labels):\n return [unprime_label(label) for label in labels]\n\n\nclass CyclicList(list):\n\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n\n def __repr__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __str__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n\n def __setitem__(self, i, v):\n return list.__setitem__(self, i % len(self), v)\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n\n\ndef ef_pow(r, k):\n return ExpFloat(r) ** k\n\n\n<function token>\n\n\ndef ef_sinh(x):\n return (ef_exp(x) - ef_exp(-x)) / 2\n\n\ndef ef_complex(x, y):\n if type(x) == ExpFloat and type(y) == ExpFloat:\n if x == 0 and y == 0:\n return ExpFloat(0.0)\n if x.ent >= y.ent:\n r = x.sign + y.sign * math.exp(y.ent - x.ent) * 1.0j\n r = ExpFloat(r)\n r.ent += x.ent\n return r\n else:\n r = x.sign * math.exp(x.ent - y.ent) + y.sign * 1.0j\n r = ExpFloat(r)\n r.ent += y.ent\n return r\n else:\n return ef_complex(ExpFloat(x), ExpFloat(y))\n", "<import token>\n\n\ndef soujou(xs):\n re = 1\n for x in xs:\n re *= x\n return re\n\n\n<function token>\n\n\ndef diff_list(univ, see, assume_included=True):\n diff = list(univ)\n for x in see:\n if assume_included:\n diff.remove(x)\n elif x in diff:\n diff.remove(x)\n return diff\n\n\ndef intersection_list(xs, ys):\n xc = Counter(xs)\n yc = Counter(ys)\n zc = xc & yc\n zs = list(zc.elements())\n return zs\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef more_popped_list(xs, xis):\n xs = list(xs)\n for xi in xis:\n xs[xi] = None\n xs = [x for x in xs if x is not None]\n return xs\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef unprime_label(label):\n if type(label) == tuple:\n return tuple(unaster_label(x) for x in label)\n elif label[-1] == \"'\":\n return label[:-1]\n else:\n return label\n\n\n<function token>\n\n\ndef unaster_labels(labels):\n return [unaster_label(label) for label in labels]\n\n\ndef prime_labels(labels):\n return [prime_label(label) for label in labels]\n\n\ndef unprime_labels(labels):\n return [unprime_label(label) for label in labels]\n\n\nclass CyclicList(list):\n\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n\n def __repr__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __str__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n\n def __setitem__(self, i, v):\n return list.__setitem__(self, i % len(self), v)\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n\n\ndef ef_pow(r, k):\n return ExpFloat(r) ** k\n\n\n<function token>\n\n\ndef ef_sinh(x):\n return (ef_exp(x) - ef_exp(-x)) / 2\n\n\ndef ef_complex(x, y):\n if type(x) == ExpFloat and type(y) == ExpFloat:\n if x == 0 and y == 0:\n return ExpFloat(0.0)\n if x.ent >= y.ent:\n r = x.sign + y.sign * math.exp(y.ent - x.ent) * 1.0j\n r = ExpFloat(r)\n r.ent += x.ent\n return r\n else:\n r = x.sign * math.exp(x.ent - y.ent) + y.sign * 1.0j\n r = ExpFloat(r)\n r.ent += y.ent\n return r\n else:\n return ef_complex(ExpFloat(x), ExpFloat(y))\n", "<import token>\n\n\ndef soujou(xs):\n re = 1\n for x in xs:\n re *= x\n return re\n\n\n<function token>\n\n\ndef diff_list(univ, see, assume_included=True):\n diff = list(univ)\n for x in see:\n if assume_included:\n diff.remove(x)\n elif x in diff:\n diff.remove(x)\n return diff\n\n\ndef intersection_list(xs, ys):\n xc = Counter(xs)\n yc = Counter(ys)\n zc = xc & yc\n zs = list(zc.elements())\n return zs\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef more_popped_list(xs, xis):\n xs = list(xs)\n for xi in xis:\n xs[xi] = None\n xs = [x for x in xs if x is not None]\n return xs\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef unprime_label(label):\n if type(label) == tuple:\n return tuple(unaster_label(x) for x in label)\n elif label[-1] == \"'\":\n return label[:-1]\n else:\n return label\n\n\n<function token>\n\n\ndef unaster_labels(labels):\n return [unaster_label(label) for label in labels]\n\n\ndef prime_labels(labels):\n return [prime_label(label) for label in labels]\n\n\ndef unprime_labels(labels):\n return [unprime_label(label) for label in labels]\n\n\nclass CyclicList(list):\n\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n\n def __repr__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __str__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n\n def __setitem__(self, i, v):\n return list.__setitem__(self, i % len(self), v)\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n\n\ndef ef_pow(r, k):\n return ExpFloat(r) ** k\n\n\n<function token>\n\n\ndef ef_sinh(x):\n return (ef_exp(x) - ef_exp(-x)) / 2\n\n\n<function token>\n", "<import token>\n\n\ndef soujou(xs):\n re = 1\n for x in xs:\n re *= x\n return re\n\n\n<function token>\n\n\ndef diff_list(univ, see, assume_included=True):\n diff = list(univ)\n for x in see:\n if assume_included:\n diff.remove(x)\n elif x in diff:\n diff.remove(x)\n return diff\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef more_popped_list(xs, xis):\n xs = list(xs)\n for xi in xis:\n xs[xi] = None\n xs = [x for x in xs if x is not None]\n return xs\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef unprime_label(label):\n if type(label) == tuple:\n return tuple(unaster_label(x) for x in label)\n elif label[-1] == \"'\":\n return label[:-1]\n else:\n return label\n\n\n<function token>\n\n\ndef unaster_labels(labels):\n return [unaster_label(label) for label in labels]\n\n\ndef prime_labels(labels):\n return [prime_label(label) for label in labels]\n\n\ndef unprime_labels(labels):\n return [unprime_label(label) for label in labels]\n\n\nclass CyclicList(list):\n\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n\n def __repr__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __str__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n\n def __setitem__(self, i, v):\n return list.__setitem__(self, i % len(self), v)\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n\n\ndef ef_pow(r, k):\n return ExpFloat(r) ** k\n\n\n<function token>\n\n\ndef ef_sinh(x):\n return (ef_exp(x) - ef_exp(-x)) / 2\n\n\n<function token>\n", "<import token>\n<function token>\n<function token>\n\n\ndef diff_list(univ, see, assume_included=True):\n diff = list(univ)\n for x in see:\n if assume_included:\n diff.remove(x)\n elif x in diff:\n diff.remove(x)\n return diff\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef more_popped_list(xs, xis):\n xs = list(xs)\n for xi in xis:\n xs[xi] = None\n xs = [x for x in xs if x is not None]\n return xs\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef unprime_label(label):\n if type(label) == tuple:\n return tuple(unaster_label(x) for x in label)\n elif label[-1] == \"'\":\n return label[:-1]\n else:\n return label\n\n\n<function token>\n\n\ndef unaster_labels(labels):\n return [unaster_label(label) for label in labels]\n\n\ndef prime_labels(labels):\n return [prime_label(label) for label in labels]\n\n\ndef unprime_labels(labels):\n return [unprime_label(label) for label in labels]\n\n\nclass CyclicList(list):\n\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n\n def __repr__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __str__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n\n def __setitem__(self, i, v):\n return list.__setitem__(self, i % len(self), v)\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n\n\ndef ef_pow(r, k):\n return ExpFloat(r) ** k\n\n\n<function token>\n\n\ndef ef_sinh(x):\n return (ef_exp(x) - ef_exp(-x)) / 2\n\n\n<function token>\n", "<import token>\n<function token>\n<function token>\n\n\ndef diff_list(univ, see, assume_included=True):\n diff = list(univ)\n for x in see:\n if assume_included:\n diff.remove(x)\n elif x in diff:\n diff.remove(x)\n return diff\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef more_popped_list(xs, xis):\n xs = list(xs)\n for xi in xis:\n xs[xi] = None\n xs = [x for x in xs if x is not None]\n return xs\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef unprime_label(label):\n if type(label) == tuple:\n return tuple(unaster_label(x) for x in label)\n elif label[-1] == \"'\":\n return label[:-1]\n else:\n return label\n\n\n<function token>\n\n\ndef unaster_labels(labels):\n return [unaster_label(label) for label in labels]\n\n\ndef prime_labels(labels):\n return [prime_label(label) for label in labels]\n\n\n<function token>\n\n\nclass CyclicList(list):\n\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n\n def __repr__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __str__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n\n def __setitem__(self, i, v):\n return list.__setitem__(self, i % len(self), v)\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n\n\ndef ef_pow(r, k):\n return ExpFloat(r) ** k\n\n\n<function token>\n\n\ndef ef_sinh(x):\n return (ef_exp(x) - ef_exp(-x)) / 2\n\n\n<function token>\n", "<import token>\n<function token>\n<function token>\n\n\ndef diff_list(univ, see, assume_included=True):\n diff = list(univ)\n for x in see:\n if assume_included:\n diff.remove(x)\n elif x in diff:\n diff.remove(x)\n return diff\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef more_popped_list(xs, xis):\n xs = list(xs)\n for xi in xis:\n xs[xi] = None\n xs = [x for x in xs if x is not None]\n return xs\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef unprime_label(label):\n if type(label) == tuple:\n return tuple(unaster_label(x) for x in label)\n elif label[-1] == \"'\":\n return label[:-1]\n else:\n return label\n\n\n<function token>\n\n\ndef unaster_labels(labels):\n return [unaster_label(label) for label in labels]\n\n\ndef prime_labels(labels):\n return [prime_label(label) for label in labels]\n\n\n<function token>\n\n\nclass CyclicList(list):\n\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n\n def __repr__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __str__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n\n def __setitem__(self, i, v):\n return list.__setitem__(self, i % len(self), v)\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n\n\ndef ef_pow(r, k):\n return ExpFloat(r) ** k\n\n\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n\n\ndef diff_list(univ, see, assume_included=True):\n diff = list(univ)\n for x in see:\n if assume_included:\n diff.remove(x)\n elif x in diff:\n diff.remove(x)\n return diff\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef more_popped_list(xs, xis):\n xs = list(xs)\n for xi in xis:\n xs[xi] = None\n xs = [x for x in xs if x is not None]\n return xs\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef unprime_label(label):\n if type(label) == tuple:\n return tuple(unaster_label(x) for x in label)\n elif label[-1] == \"'\":\n return label[:-1]\n else:\n return label\n\n\n<function token>\n<function token>\n\n\ndef prime_labels(labels):\n return [prime_label(label) for label in labels]\n\n\n<function token>\n\n\nclass CyclicList(list):\n\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n\n def __repr__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __str__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n\n def __setitem__(self, i, v):\n return list.__setitem__(self, i % len(self), v)\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n\n\ndef ef_pow(r, k):\n return ExpFloat(r) ** k\n\n\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n\n\ndef diff_list(univ, see, assume_included=True):\n diff = list(univ)\n for x in see:\n if assume_included:\n diff.remove(x)\n elif x in diff:\n diff.remove(x)\n return diff\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef unprime_label(label):\n if type(label) == tuple:\n return tuple(unaster_label(x) for x in label)\n elif label[-1] == \"'\":\n return label[:-1]\n else:\n return label\n\n\n<function token>\n<function token>\n\n\ndef prime_labels(labels):\n return [prime_label(label) for label in labels]\n\n\n<function token>\n\n\nclass CyclicList(list):\n\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n\n def __repr__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __str__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n\n def __setitem__(self, i, v):\n return list.__setitem__(self, i % len(self), v)\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n\n\ndef ef_pow(r, k):\n return ExpFloat(r) ** k\n\n\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef unprime_label(label):\n if type(label) == tuple:\n return tuple(unaster_label(x) for x in label)\n elif label[-1] == \"'\":\n return label[:-1]\n else:\n return label\n\n\n<function token>\n<function token>\n\n\ndef prime_labels(labels):\n return [prime_label(label) for label in labels]\n\n\n<function token>\n\n\nclass CyclicList(list):\n\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n\n def __repr__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __str__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n\n def __setitem__(self, i, v):\n return list.__setitem__(self, i % len(self), v)\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n\n\ndef ef_pow(r, k):\n return ExpFloat(r) ** k\n\n\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef unprime_label(label):\n if type(label) == tuple:\n return tuple(unaster_label(x) for x in label)\n elif label[-1] == \"'\":\n return label[:-1]\n else:\n return label\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass CyclicList(list):\n\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n\n def __repr__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __str__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n\n def __setitem__(self, i, v):\n return list.__setitem__(self, i % len(self), v)\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n\n\ndef ef_pow(r, k):\n return ExpFloat(r) ** k\n\n\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass CyclicList(list):\n\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n\n def __repr__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __str__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n\n def __setitem__(self, i, v):\n return list.__setitem__(self, i % len(self), v)\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n\n\ndef ef_pow(r, k):\n return ExpFloat(r) ** k\n\n\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass CyclicList(list):\n\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n\n def __repr__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __str__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n\n def __setitem__(self, i, v):\n return list.__setitem__(self, i % len(self), v)\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass CyclicList(list):\n\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n <function token>\n\n def __str__(self):\n return 'CyclicList(' + list.__repr__(self) + ')'\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n\n def __setitem__(self, i, v):\n return list.__setitem__(self, i % len(self), v)\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass CyclicList(list):\n\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n <function token>\n <function token>\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n\n def __setitem__(self, i, v):\n return list.__setitem__(self, i % len(self), v)\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass CyclicList(list):\n\n def __init__(self, *args, **kwargs):\n list.__init__(self, *args, **kwargs)\n <function token>\n <function token>\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n <function token>\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass CyclicList(list):\n <function token>\n <function token>\n <function token>\n\n def __getitem__(self, i):\n return list.__getitem__(self, i % len(self))\n <function token>\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass CyclicList(list):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n\n def __or__(x, y):\n return CollateralBool(x.trueOrFalse or y.trueOrFalse, {'op': 'or',\n 'left': x.expression, 'right': y.expression})\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n\n\nclass CollateralBool:\n\n def __init__(self, trueOrFalse, expression=None):\n self.trueOrFalse = bool(trueOrFalse)\n if expression is None:\n expression = {}\n self.expression = expression\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n <function token>\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n\n\nclass CollateralBool:\n <function token>\n\n def __bool__(self):\n return self.trueOrFalse\n\n def __and__(x, y):\n return CollateralBool(x.trueOrFalse and y.trueOrFalse, {'op': 'and',\n 'left': x.expression, 'right': y.expression})\n <function token>\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n\n\nclass CollateralBool:\n <function token>\n\n def __bool__(self):\n return self.trueOrFalse\n <function token>\n <function token>\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __str__(self):\n return f'{self.trueOrFalse}({self.expression})'\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n\n\nclass CollateralBool:\n <function token>\n\n def __bool__(self):\n return self.trueOrFalse\n <function token>\n <function token>\n\n def __repr__(self):\n return f'{self.trueOrFalse}({self.expression})'\n <function token>\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n\n\nclass CollateralBool:\n <function token>\n\n def __bool__(self):\n return self.trueOrFalse\n <function token>\n <function token>\n <function token>\n <function token>\n\n def __getitem__(self, arg):\n return self.expression[arg]\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n\n\nclass CollateralBool:\n <function token>\n\n def __bool__(self):\n return self.trueOrFalse\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n\n\nclass CollateralBool:\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n<class token>\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n\n def __lt__(self, other):\n if type(other) == ExpFloat:\n if self.sign < other.sign:\n return True\n if self.sign > other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent < other.ent\n else:\n return self.ent > other.ent\n else:\n return self < ExpFloat(other)\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n<class token>\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n <function token>\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n\n def __neg__(self):\n return ExpFloat(-self.sign, self.ent)\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n<class token>\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n\n @property\n def real(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.real) * abs(self)\n else:\n return ExpFloat(self.sign) * abs(self)\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n <function token>\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n <function token>\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n<class token>\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n <function token>\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n <function token>\n\n def __gt__(self, other):\n if type(other) == ExpFloat:\n if self.sign > other.sign:\n return True\n if self.sign < other.sign:\n return False\n if self.sign == 0:\n return False\n elif self.sign == 1:\n return self.ent > other.ent\n else:\n return self.ent < other.ent\n else:\n return self > ExpFloat(other)\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n <function token>\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n<class token>\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n <function token>\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n <function token>\n <function token>\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n <function token>\n\n def __add__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real + other.real, self.imag + other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return other\n elif self.sign == 1 and other.sign == -1:\n return self - -other\n elif self.sign == -1 and other.sign == 1:\n return other - -self\n elif self.sign == -1 and other.sign == -1:\n return -(-self + -other)\n if self < other:\n self, other = other, self\n a = self.ent\n b = other.ent\n c = a + np.log1p(math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self + ExpFloat(other)\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n<class token>\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n\n @property\n def value(self):\n return self.sign * math.exp(self.ent)\n\n @property\n def log(self):\n return self.ent\n <function token>\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n <function token>\n <function token>\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n <function token>\n <function token>\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n<class token>\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n <function token>\n\n @property\n def log(self):\n return self.ent\n <function token>\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n\n def __eq__(self, other):\n d = abs(self - other)\n return d.sign == 0 or d.ent < -15\n <function token>\n <function token>\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n <function token>\n <function token>\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n<class token>\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n <function token>\n\n @property\n def log(self):\n return self.ent\n <function token>\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n <function token>\n <function token>\n <function token>\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n <function token>\n <function token>\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n\n def sqrt(self):\n if self.sign == 1:\n return ExpFloat(1, self.ent / 2)\n elif self.sign == 0:\n return ExpFloat(0.0)\n else:\n raise ValueError\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n<class token>\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n\n def __repr__(self):\n return f'ExpFloat({repr(self.sign)},{repr(self.ent)})'\n <function token>\n\n @property\n def log(self):\n return self.ent\n <function token>\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n <function token>\n <function token>\n <function token>\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n <function token>\n <function token>\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n <function token>\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n<class token>\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n <function token>\n <function token>\n\n @property\n def log(self):\n return self.ent\n <function token>\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n <function token>\n <function token>\n <function token>\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n <function token>\n <function token>\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n\n def __pow__(self, k):\n if self.sign == 1:\n return ExpFloat(1, self.ent * k)\n elif self.sign == 0:\n if k > 0:\n return ExpFloat(0.0)\n elif k == 0:\n return ExpFloat(1.0)\n else:\n raise ValueError\n elif int(k) != k:\n raise ValueError\n else:\n return ExpFloat(self.sign ** k, self.ent * k)\n <function token>\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n<class token>\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n\n def __str__(self):\n if self.sign == 0:\n return f'0.0'\n elif type(self.sign) == complex:\n return f'({self.sign})*exp({self.ent})'\n elif self.sign == 1:\n return f'exp({self.ent})'\n else:\n return f'-exp({self.ent})'\n <function token>\n <function token>\n\n @property\n def log(self):\n return self.ent\n <function token>\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n <function token>\n <function token>\n <function token>\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n <function token>\n <function token>\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n <function token>\n <function token>\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n<class token>\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n <function token>\n <function token>\n <function token>\n\n @property\n def log(self):\n return self.ent\n <function token>\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n <function token>\n <function token>\n <function token>\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n <function token>\n <function token>\n\n def __sub__(self, other):\n if type(other) == ExpFloat:\n if type(self.sign) == complex or type(other.sign) == complex:\n return ef_complex(self.real - other.real, self.imag - other\n .imag)\n if other.sign == 0:\n return self\n elif self.sign == 0:\n return -other\n elif self.sign == 1 and other.sign == -1:\n return self + -other\n elif self.sign == -1 and other.sign == 1:\n return -(-self + other)\n elif self.sign == -1 and other.sign == -1:\n return -other - -self\n if self < other:\n return -(other - self)\n a = self.ent\n b = other.ent\n if b - a > -1e-15:\n return ExpFloat(0.0)\n c = a + np.log1p(-math.exp(b - a))\n return ExpFloat(1, c)\n else:\n return self - ExpFloat(other)\n <function token>\n <function token>\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n<class token>\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n <function token>\n <function token>\n <function token>\n\n @property\n def log(self):\n return self.ent\n <function token>\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n <function token>\n <function token>\n <function token>\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n\n def __rmul__(self, other):\n return self * other\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n<class token>\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n <function token>\n <function token>\n <function token>\n\n @property\n def log(self):\n return self.ent\n <function token>\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n <function token>\n <function token>\n <function token>\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n <function token>\n\n def __truediv__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign / other.sign, self.ent - other.ent)\n else:\n return self / ExpFloat(other)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n<class token>\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n <function token>\n <function token>\n <function token>\n\n @property\n def log(self):\n return self.ent\n <function token>\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n\n def __abs__(self):\n if self.sign == 0:\n return ExpFloat(0.0)\n else:\n return ExpFloat(1, self.ent)\n <function token>\n <function token>\n <function token>\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n<class token>\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n <function token>\n <function token>\n <function token>\n\n @property\n def log(self):\n return self.ent\n <function token>\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n <function token>\n <function token>\n <function token>\n <function token>\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n<class token>\n\n\nclass ExpFloat:\n\n def __init__(self, *args):\n if len(args) == 1:\n moto = args[0]\n if moto == 0:\n self.sign = 0\n self.ent = -float('inf')\n elif type(moto) == ExpFloat:\n self.sign = moto.sign\n self.ent = moto.ent\n elif type(moto) == complex:\n nrm = abs(moto)\n self.sign = moto / nrm\n self.ent = math.log(nrm)\n elif moto > 0:\n self.sign = 1\n self.ent = math.log(moto)\n else:\n self.sign = -1\n self.ent = math.log(-moto)\n elif len(args) == 2:\n self.sign = args[0]\n self.ent = args[1]\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n <function token>\n <function token>\n <function token>\n <function token>\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n<class token>\n\n\nclass ExpFloat:\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def imag(self):\n if type(self.sign) == complex:\n return ExpFloat(self.sign.imag) * abs(self)\n else:\n return ExpFloat(0.0)\n <function token>\n <function token>\n <function token>\n <function token>\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n<class token>\n\n\nclass ExpFloat:\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def __mul__(self, other):\n if type(other) == ExpFloat:\n return ExpFloat(self.sign * other.sign, self.ent + other.ent)\n else:\n return self * ExpFloat(other)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n<class token>\n\n\nclass ExpFloat:\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n<class token>\n<class token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n" ]
false
98,750
631bc861655ae4a2ef7ed7bb03be3dfb14fadd23
import os # cassandra from cassandra.cluster import Cluster class CassandraConsumer: CASSANDRA_NODE_IP = os.environ['CASSANDRA_CLUSTER_SEED_IP'] KEYSPACE = os.environ['KEYSPACE'] TABLE = 'Quotes' cluster = Cluster([CASSANDRA_NODE_IP], port=int(os.environ['CASSANDRA_PORT'])) def __init__(self): self.session = self.cluster.connect() print('successfully connected to cassandra') try: self.session.execute(""" CREATE KEYSPACE IF NOT EXISTS %s WITH replication = { 'class': 'NetworkTopologyStrategy', 'datacenter1' : 1, 'datacenter2' : 2} """ % self.KEYSPACE) except Exception: print('Unable to create keyspace: {}'.format(self.KEYSPACE)) # log.info('Unable to create keyspace: {}'.format(self.KEYSPACE)) # log.info('Setting Keyspace') self.session.set_keyspace(self.KEYSPACE) self.session.execute(""" CREATE TABLE IF NOT EXISTS Quotes ( quoteId int, minPrice float, direct Boolean, carrierIds int, originId int, destinationId int, departureDate timestamp, quoteDateTime timestamp, PRIMARY KEY ((originId, destinationId), departureDate) ) """) # log.info('Table Quotes exists or has been created') def insert_quotes(self, quoteId, minPrice, direct, carrierIds, originId, destinationId, departureDate, quoteDateTime): self.session.execute( "INSERT INTO Quotes (quoteId, minPrice, direct, carrierIds, originId, destinationId, departureDate, quoteDateTime) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)", [quoteId, minPrice, direct, carrierIds, originId, destinationId, departureDate, quoteDateTime]) print("inserted event: ", quoteId, minPrice, direct, carrierIds, originId, destinationId, departureDate, quoteDateTime)
[ "import os\n\n# cassandra\nfrom cassandra.cluster import Cluster\n\n\nclass CassandraConsumer:\n CASSANDRA_NODE_IP = os.environ['CASSANDRA_CLUSTER_SEED_IP']\n KEYSPACE = os.environ['KEYSPACE']\n TABLE = 'Quotes'\n cluster = Cluster([CASSANDRA_NODE_IP], port=int(os.environ['CASSANDRA_PORT']))\n\n def __init__(self):\n self.session = self.cluster.connect()\n print('successfully connected to cassandra')\n try:\n self.session.execute(\"\"\"\n CREATE KEYSPACE IF NOT EXISTS %s\n WITH replication = { 'class': 'NetworkTopologyStrategy', 'datacenter1' : 1, 'datacenter2' : 2}\n \"\"\" % self.KEYSPACE)\n except Exception:\n print('Unable to create keyspace: {}'.format(self.KEYSPACE))\n # log.info('Unable to create keyspace: {}'.format(self.KEYSPACE))\n\n # log.info('Setting Keyspace')\n self.session.set_keyspace(self.KEYSPACE)\n\n self.session.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS Quotes (\n quoteId int,\n minPrice float,\n direct Boolean,\n carrierIds int,\n originId int,\n destinationId int,\n departureDate timestamp,\n quoteDateTime timestamp,\n PRIMARY KEY ((originId, destinationId), departureDate)\n )\n \"\"\")\n # log.info('Table Quotes exists or has been created')\n\n def insert_quotes(self, quoteId, minPrice, direct, carrierIds, originId, destinationId, departureDate,\n quoteDateTime):\n self.session.execute(\n \"INSERT INTO Quotes (quoteId, minPrice, direct, carrierIds, originId, destinationId, departureDate, quoteDateTime) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)\",\n [quoteId, minPrice, direct, carrierIds, originId, destinationId, departureDate, quoteDateTime])\n print(\"inserted event: \", quoteId, minPrice, direct, carrierIds, originId, destinationId, departureDate,\n quoteDateTime)\n\n\n\n\n\n\n\n\n", "import os\nfrom cassandra.cluster import Cluster\n\n\nclass CassandraConsumer:\n CASSANDRA_NODE_IP = os.environ['CASSANDRA_CLUSTER_SEED_IP']\n KEYSPACE = os.environ['KEYSPACE']\n TABLE = 'Quotes'\n cluster = Cluster([CASSANDRA_NODE_IP], port=int(os.environ[\n 'CASSANDRA_PORT']))\n\n def __init__(self):\n self.session = self.cluster.connect()\n print('successfully connected to cassandra')\n try:\n self.session.execute(\n \"\"\"\n CREATE KEYSPACE IF NOT EXISTS %s\n WITH replication = { 'class': 'NetworkTopologyStrategy', 'datacenter1' : 1, 'datacenter2' : 2}\n \"\"\"\n % self.KEYSPACE)\n except Exception:\n print('Unable to create keyspace: {}'.format(self.KEYSPACE))\n self.session.set_keyspace(self.KEYSPACE)\n self.session.execute(\n \"\"\"\n CREATE TABLE IF NOT EXISTS Quotes (\n quoteId int,\n minPrice float,\n direct Boolean,\n carrierIds int,\n originId int,\n destinationId int,\n departureDate timestamp,\n quoteDateTime timestamp,\n PRIMARY KEY ((originId, destinationId), departureDate)\n )\n \"\"\"\n )\n\n def insert_quotes(self, quoteId, minPrice, direct, carrierIds, originId,\n destinationId, departureDate, quoteDateTime):\n self.session.execute(\n 'INSERT INTO Quotes (quoteId, minPrice, direct, carrierIds, originId, destinationId, departureDate, quoteDateTime) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)'\n , [quoteId, minPrice, direct, carrierIds, originId,\n destinationId, departureDate, quoteDateTime])\n print('inserted event: ', quoteId, minPrice, direct, carrierIds,\n originId, destinationId, departureDate, quoteDateTime)\n", "<import token>\n\n\nclass CassandraConsumer:\n CASSANDRA_NODE_IP = os.environ['CASSANDRA_CLUSTER_SEED_IP']\n KEYSPACE = os.environ['KEYSPACE']\n TABLE = 'Quotes'\n cluster = Cluster([CASSANDRA_NODE_IP], port=int(os.environ[\n 'CASSANDRA_PORT']))\n\n def __init__(self):\n self.session = self.cluster.connect()\n print('successfully connected to cassandra')\n try:\n self.session.execute(\n \"\"\"\n CREATE KEYSPACE IF NOT EXISTS %s\n WITH replication = { 'class': 'NetworkTopologyStrategy', 'datacenter1' : 1, 'datacenter2' : 2}\n \"\"\"\n % self.KEYSPACE)\n except Exception:\n print('Unable to create keyspace: {}'.format(self.KEYSPACE))\n self.session.set_keyspace(self.KEYSPACE)\n self.session.execute(\n \"\"\"\n CREATE TABLE IF NOT EXISTS Quotes (\n quoteId int,\n minPrice float,\n direct Boolean,\n carrierIds int,\n originId int,\n destinationId int,\n departureDate timestamp,\n quoteDateTime timestamp,\n PRIMARY KEY ((originId, destinationId), departureDate)\n )\n \"\"\"\n )\n\n def insert_quotes(self, quoteId, minPrice, direct, carrierIds, originId,\n destinationId, departureDate, quoteDateTime):\n self.session.execute(\n 'INSERT INTO Quotes (quoteId, minPrice, direct, carrierIds, originId, destinationId, departureDate, quoteDateTime) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)'\n , [quoteId, minPrice, direct, carrierIds, originId,\n destinationId, departureDate, quoteDateTime])\n print('inserted event: ', quoteId, minPrice, direct, carrierIds,\n originId, destinationId, departureDate, quoteDateTime)\n", "<import token>\n\n\nclass CassandraConsumer:\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self):\n self.session = self.cluster.connect()\n print('successfully connected to cassandra')\n try:\n self.session.execute(\n \"\"\"\n CREATE KEYSPACE IF NOT EXISTS %s\n WITH replication = { 'class': 'NetworkTopologyStrategy', 'datacenter1' : 1, 'datacenter2' : 2}\n \"\"\"\n % self.KEYSPACE)\n except Exception:\n print('Unable to create keyspace: {}'.format(self.KEYSPACE))\n self.session.set_keyspace(self.KEYSPACE)\n self.session.execute(\n \"\"\"\n CREATE TABLE IF NOT EXISTS Quotes (\n quoteId int,\n minPrice float,\n direct Boolean,\n carrierIds int,\n originId int,\n destinationId int,\n departureDate timestamp,\n quoteDateTime timestamp,\n PRIMARY KEY ((originId, destinationId), departureDate)\n )\n \"\"\"\n )\n\n def insert_quotes(self, quoteId, minPrice, direct, carrierIds, originId,\n destinationId, departureDate, quoteDateTime):\n self.session.execute(\n 'INSERT INTO Quotes (quoteId, minPrice, direct, carrierIds, originId, destinationId, departureDate, quoteDateTime) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)'\n , [quoteId, minPrice, direct, carrierIds, originId,\n destinationId, departureDate, quoteDateTime])\n print('inserted event: ', quoteId, minPrice, direct, carrierIds,\n originId, destinationId, departureDate, quoteDateTime)\n", "<import token>\n\n\nclass CassandraConsumer:\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self):\n self.session = self.cluster.connect()\n print('successfully connected to cassandra')\n try:\n self.session.execute(\n \"\"\"\n CREATE KEYSPACE IF NOT EXISTS %s\n WITH replication = { 'class': 'NetworkTopologyStrategy', 'datacenter1' : 1, 'datacenter2' : 2}\n \"\"\"\n % self.KEYSPACE)\n except Exception:\n print('Unable to create keyspace: {}'.format(self.KEYSPACE))\n self.session.set_keyspace(self.KEYSPACE)\n self.session.execute(\n \"\"\"\n CREATE TABLE IF NOT EXISTS Quotes (\n quoteId int,\n minPrice float,\n direct Boolean,\n carrierIds int,\n originId int,\n destinationId int,\n departureDate timestamp,\n quoteDateTime timestamp,\n PRIMARY KEY ((originId, destinationId), departureDate)\n )\n \"\"\"\n )\n <function token>\n", "<import token>\n\n\nclass CassandraConsumer:\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n", "<import token>\n<class token>\n" ]
false
98,751
451ca064c31a5b93b1a6fb341e4adc9e6ca1f476
in_file = open('test.in','r') t = int(in_file.readline().strip()) results = [] for case in range(t): r,c = map(int,in_file.readline().strip().split()) grid = [] result = 'Case #{}:\n'.format(case+1) initials = set() for row in range(r): line = in_file.readline().strip() grid.append(list(line)) for col in range(c): if line[col] != '?': initials.add((row,col,line[col])) for row,col,val in initials: up =0 down =0 left = 0 right = 0 #check up: while True: if row-up-1>=0: if grid[row-up-1][col] == '?': grid[row-up-1][col] = val up+=1 else: break else: break #check down: while True: if row+down+1<r: if grid[row+down+1][col] == '?': grid[row+down+1][col] = val down+=1 else: break else: break #check left: while True: if col-left - 1 >= 0: is_clr = True for a in range(row-up,row+down+1): if grid[a][col-left-1] != '?': is_clr = False if not is_clr: break for a in range(row-up,row+down+1): grid[a][col-left-1] = val left+=1 else: break #check right: while True: if col+right + 1 < c: is_clr = True for a in range(row-up,row+down+1): if grid[a][col+right+1] != '?': is_clr = False if not is_clr: break for a in range(row-up,row+down+1): grid[a][col+right+1] = val right+=1 else: break for row in grid: for col in row: result+=col result+='\n' results.append(result) in_file.close() out_file = open('test.out','w') for result in results: out_file.write(result) print(result) out_file.close()
[ "in_file = open('test.in','r')\r\nt = int(in_file.readline().strip())\r\n\r\n\r\n\r\nresults = []\r\nfor case in range(t):\r\n r,c = map(int,in_file.readline().strip().split())\r\n grid = []\r\n result = 'Case #{}:\\n'.format(case+1)\r\n \r\n initials = set()\r\n \r\n for row in range(r):\r\n line = in_file.readline().strip()\r\n grid.append(list(line))\r\n for col in range(c):\r\n if line[col] != '?':\r\n initials.add((row,col,line[col]))\r\n \r\n \r\n for row,col,val in initials:\r\n up =0\r\n down =0\r\n left = 0\r\n right = 0\r\n #check up:\r\n while True:\r\n if row-up-1>=0:\r\n if grid[row-up-1][col] == '?':\r\n grid[row-up-1][col] = val\r\n up+=1\r\n else:\r\n break\r\n else:\r\n break\r\n #check down:\r\n while True:\r\n if row+down+1<r:\r\n if grid[row+down+1][col] == '?':\r\n grid[row+down+1][col] = val\r\n down+=1\r\n else:\r\n break\r\n else:\r\n break\r\n #check left:\r\n while True:\r\n if col-left - 1 >= 0:\r\n is_clr = True\r\n for a in range(row-up,row+down+1):\r\n if grid[a][col-left-1] != '?':\r\n is_clr = False\r\n if not is_clr:\r\n break\r\n for a in range(row-up,row+down+1):\r\n grid[a][col-left-1] = val\r\n left+=1\r\n else:\r\n break\r\n #check right:\r\n while True:\r\n if col+right + 1 < c:\r\n is_clr = True\r\n for a in range(row-up,row+down+1):\r\n if grid[a][col+right+1] != '?':\r\n is_clr = False\r\n if not is_clr:\r\n break\r\n for a in range(row-up,row+down+1):\r\n grid[a][col+right+1] = val\r\n right+=1\r\n else:\r\n break\r\n \r\n for row in grid:\r\n for col in row:\r\n result+=col\r\n result+='\\n'\r\n results.append(result)\r\n \r\nin_file.close()\r\n\r\n\r\n\r\n\r\nout_file = open('test.out','w')\r\nfor result in results:\r\n out_file.write(result)\r\n print(result)\r\nout_file.close()\r\n\r\n\r\n\r\n\r\n", "in_file = open('test.in', 'r')\nt = int(in_file.readline().strip())\nresults = []\nfor case in range(t):\n r, c = map(int, in_file.readline().strip().split())\n grid = []\n result = 'Case #{}:\\n'.format(case + 1)\n initials = set()\n for row in range(r):\n line = in_file.readline().strip()\n grid.append(list(line))\n for col in range(c):\n if line[col] != '?':\n initials.add((row, col, line[col]))\n for row, col, val in initials:\n up = 0\n down = 0\n left = 0\n right = 0\n while True:\n if row - up - 1 >= 0:\n if grid[row - up - 1][col] == '?':\n grid[row - up - 1][col] = val\n up += 1\n else:\n break\n else:\n break\n while True:\n if row + down + 1 < r:\n if grid[row + down + 1][col] == '?':\n grid[row + down + 1][col] = val\n down += 1\n else:\n break\n else:\n break\n while True:\n if col - left - 1 >= 0:\n is_clr = True\n for a in range(row - up, row + down + 1):\n if grid[a][col - left - 1] != '?':\n is_clr = False\n if not is_clr:\n break\n for a in range(row - up, row + down + 1):\n grid[a][col - left - 1] = val\n left += 1\n else:\n break\n while True:\n if col + right + 1 < c:\n is_clr = True\n for a in range(row - up, row + down + 1):\n if grid[a][col + right + 1] != '?':\n is_clr = False\n if not is_clr:\n break\n for a in range(row - up, row + down + 1):\n grid[a][col + right + 1] = val\n right += 1\n else:\n break\n for row in grid:\n for col in row:\n result += col\n result += '\\n'\n results.append(result)\nin_file.close()\nout_file = open('test.out', 'w')\nfor result in results:\n out_file.write(result)\n print(result)\nout_file.close()\n", "<assignment token>\nfor case in range(t):\n r, c = map(int, in_file.readline().strip().split())\n grid = []\n result = 'Case #{}:\\n'.format(case + 1)\n initials = set()\n for row in range(r):\n line = in_file.readline().strip()\n grid.append(list(line))\n for col in range(c):\n if line[col] != '?':\n initials.add((row, col, line[col]))\n for row, col, val in initials:\n up = 0\n down = 0\n left = 0\n right = 0\n while True:\n if row - up - 1 >= 0:\n if grid[row - up - 1][col] == '?':\n grid[row - up - 1][col] = val\n up += 1\n else:\n break\n else:\n break\n while True:\n if row + down + 1 < r:\n if grid[row + down + 1][col] == '?':\n grid[row + down + 1][col] = val\n down += 1\n else:\n break\n else:\n break\n while True:\n if col - left - 1 >= 0:\n is_clr = True\n for a in range(row - up, row + down + 1):\n if grid[a][col - left - 1] != '?':\n is_clr = False\n if not is_clr:\n break\n for a in range(row - up, row + down + 1):\n grid[a][col - left - 1] = val\n left += 1\n else:\n break\n while True:\n if col + right + 1 < c:\n is_clr = True\n for a in range(row - up, row + down + 1):\n if grid[a][col + right + 1] != '?':\n is_clr = False\n if not is_clr:\n break\n for a in range(row - up, row + down + 1):\n grid[a][col + right + 1] = val\n right += 1\n else:\n break\n for row in grid:\n for col in row:\n result += col\n result += '\\n'\n results.append(result)\nin_file.close()\n<assignment token>\nfor result in results:\n out_file.write(result)\n print(result)\nout_file.close()\n", "<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
98,752
0986f3c59e3c9de33b59b69e72566b0b258b9fba
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'Dialog_Save.ui' # # Created by: PyQt5 UI code generator 5.10.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(400, 180) Dialog.setStyleSheet("") Dialog.setModal(False) self.label = QtWidgets.QLabel(Dialog) self.label.setGeometry(QtCore.QRect(50, 40, 81, 71)) self.label.setText("") self.label.setPixmap(QtGui.QPixmap("tickmark.jpg")) self.label.setScaledContents(True) self.label.setObjectName("label") self.pushButton = QtWidgets.QPushButton(Dialog) self.pushButton.setGeometry(QtCore.QRect(150, 130, 93, 28)) self.pushButton.setObjectName("pushButton") self.label_2 = QtWidgets.QLabel(Dialog) self.label_2.setGeometry(QtCore.QRect(160, 50, 200, 40)) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(16) font.setBold(True) font.setWeight(75) self.label_2.setFont(font) self.label_2.setStyleSheet("") self.label_2.setObjectName("label_2") self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Dialog")) self.pushButton.setText(_translate("Dialog", "OK")) self.label_2.setText(_translate("Dialog", "Team Saved")) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) Dialog = QtWidgets.QDialog() ui = Ui_Dialog() ui.setupUi(Dialog) Dialog.show() sys.exit(app.exec_())
[ "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'Dialog_Save.ui'\n#\n# Created by: PyQt5 UI code generator 5.10.1\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\nclass Ui_Dialog(object):\n def setupUi(self, Dialog):\n Dialog.setObjectName(\"Dialog\")\n Dialog.resize(400, 180)\n Dialog.setStyleSheet(\"\")\n Dialog.setModal(False)\n self.label = QtWidgets.QLabel(Dialog)\n self.label.setGeometry(QtCore.QRect(50, 40, 81, 71))\n self.label.setText(\"\")\n self.label.setPixmap(QtGui.QPixmap(\"tickmark.jpg\"))\n self.label.setScaledContents(True)\n self.label.setObjectName(\"label\")\n self.pushButton = QtWidgets.QPushButton(Dialog)\n self.pushButton.setGeometry(QtCore.QRect(150, 130, 93, 28))\n self.pushButton.setObjectName(\"pushButton\")\n self.label_2 = QtWidgets.QLabel(Dialog)\n self.label_2.setGeometry(QtCore.QRect(160, 50, 200, 40))\n font = QtGui.QFont()\n font.setFamily(\"Arial\")\n font.setPointSize(16)\n font.setBold(True)\n font.setWeight(75)\n self.label_2.setFont(font)\n self.label_2.setStyleSheet(\"\")\n self.label_2.setObjectName(\"label_2\")\n\n self.retranslateUi(Dialog)\n QtCore.QMetaObject.connectSlotsByName(Dialog)\n\n def retranslateUi(self, Dialog):\n _translate = QtCore.QCoreApplication.translate\n Dialog.setWindowTitle(_translate(\"Dialog\", \"Dialog\"))\n self.pushButton.setText(_translate(\"Dialog\", \"OK\"))\n self.label_2.setText(_translate(\"Dialog\", \"Team Saved\"))\n\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n Dialog = QtWidgets.QDialog()\n ui = Ui_Dialog()\n ui.setupUi(Dialog)\n Dialog.show()\n sys.exit(app.exec_())\n\n", "from PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass Ui_Dialog(object):\n\n def setupUi(self, Dialog):\n Dialog.setObjectName('Dialog')\n Dialog.resize(400, 180)\n Dialog.setStyleSheet('')\n Dialog.setModal(False)\n self.label = QtWidgets.QLabel(Dialog)\n self.label.setGeometry(QtCore.QRect(50, 40, 81, 71))\n self.label.setText('')\n self.label.setPixmap(QtGui.QPixmap('tickmark.jpg'))\n self.label.setScaledContents(True)\n self.label.setObjectName('label')\n self.pushButton = QtWidgets.QPushButton(Dialog)\n self.pushButton.setGeometry(QtCore.QRect(150, 130, 93, 28))\n self.pushButton.setObjectName('pushButton')\n self.label_2 = QtWidgets.QLabel(Dialog)\n self.label_2.setGeometry(QtCore.QRect(160, 50, 200, 40))\n font = QtGui.QFont()\n font.setFamily('Arial')\n font.setPointSize(16)\n font.setBold(True)\n font.setWeight(75)\n self.label_2.setFont(font)\n self.label_2.setStyleSheet('')\n self.label_2.setObjectName('label_2')\n self.retranslateUi(Dialog)\n QtCore.QMetaObject.connectSlotsByName(Dialog)\n\n def retranslateUi(self, Dialog):\n _translate = QtCore.QCoreApplication.translate\n Dialog.setWindowTitle(_translate('Dialog', 'Dialog'))\n self.pushButton.setText(_translate('Dialog', 'OK'))\n self.label_2.setText(_translate('Dialog', 'Team Saved'))\n\n\nif __name__ == '__main__':\n import sys\n app = QtWidgets.QApplication(sys.argv)\n Dialog = QtWidgets.QDialog()\n ui = Ui_Dialog()\n ui.setupUi(Dialog)\n Dialog.show()\n sys.exit(app.exec_())\n", "<import token>\n\n\nclass Ui_Dialog(object):\n\n def setupUi(self, Dialog):\n Dialog.setObjectName('Dialog')\n Dialog.resize(400, 180)\n Dialog.setStyleSheet('')\n Dialog.setModal(False)\n self.label = QtWidgets.QLabel(Dialog)\n self.label.setGeometry(QtCore.QRect(50, 40, 81, 71))\n self.label.setText('')\n self.label.setPixmap(QtGui.QPixmap('tickmark.jpg'))\n self.label.setScaledContents(True)\n self.label.setObjectName('label')\n self.pushButton = QtWidgets.QPushButton(Dialog)\n self.pushButton.setGeometry(QtCore.QRect(150, 130, 93, 28))\n self.pushButton.setObjectName('pushButton')\n self.label_2 = QtWidgets.QLabel(Dialog)\n self.label_2.setGeometry(QtCore.QRect(160, 50, 200, 40))\n font = QtGui.QFont()\n font.setFamily('Arial')\n font.setPointSize(16)\n font.setBold(True)\n font.setWeight(75)\n self.label_2.setFont(font)\n self.label_2.setStyleSheet('')\n self.label_2.setObjectName('label_2')\n self.retranslateUi(Dialog)\n QtCore.QMetaObject.connectSlotsByName(Dialog)\n\n def retranslateUi(self, Dialog):\n _translate = QtCore.QCoreApplication.translate\n Dialog.setWindowTitle(_translate('Dialog', 'Dialog'))\n self.pushButton.setText(_translate('Dialog', 'OK'))\n self.label_2.setText(_translate('Dialog', 'Team Saved'))\n\n\nif __name__ == '__main__':\n import sys\n app = QtWidgets.QApplication(sys.argv)\n Dialog = QtWidgets.QDialog()\n ui = Ui_Dialog()\n ui.setupUi(Dialog)\n Dialog.show()\n sys.exit(app.exec_())\n", "<import token>\n\n\nclass Ui_Dialog(object):\n\n def setupUi(self, Dialog):\n Dialog.setObjectName('Dialog')\n Dialog.resize(400, 180)\n Dialog.setStyleSheet('')\n Dialog.setModal(False)\n self.label = QtWidgets.QLabel(Dialog)\n self.label.setGeometry(QtCore.QRect(50, 40, 81, 71))\n self.label.setText('')\n self.label.setPixmap(QtGui.QPixmap('tickmark.jpg'))\n self.label.setScaledContents(True)\n self.label.setObjectName('label')\n self.pushButton = QtWidgets.QPushButton(Dialog)\n self.pushButton.setGeometry(QtCore.QRect(150, 130, 93, 28))\n self.pushButton.setObjectName('pushButton')\n self.label_2 = QtWidgets.QLabel(Dialog)\n self.label_2.setGeometry(QtCore.QRect(160, 50, 200, 40))\n font = QtGui.QFont()\n font.setFamily('Arial')\n font.setPointSize(16)\n font.setBold(True)\n font.setWeight(75)\n self.label_2.setFont(font)\n self.label_2.setStyleSheet('')\n self.label_2.setObjectName('label_2')\n self.retranslateUi(Dialog)\n QtCore.QMetaObject.connectSlotsByName(Dialog)\n\n def retranslateUi(self, Dialog):\n _translate = QtCore.QCoreApplication.translate\n Dialog.setWindowTitle(_translate('Dialog', 'Dialog'))\n self.pushButton.setText(_translate('Dialog', 'OK'))\n self.label_2.setText(_translate('Dialog', 'Team Saved'))\n\n\n<code token>\n", "<import token>\n\n\nclass Ui_Dialog(object):\n\n def setupUi(self, Dialog):\n Dialog.setObjectName('Dialog')\n Dialog.resize(400, 180)\n Dialog.setStyleSheet('')\n Dialog.setModal(False)\n self.label = QtWidgets.QLabel(Dialog)\n self.label.setGeometry(QtCore.QRect(50, 40, 81, 71))\n self.label.setText('')\n self.label.setPixmap(QtGui.QPixmap('tickmark.jpg'))\n self.label.setScaledContents(True)\n self.label.setObjectName('label')\n self.pushButton = QtWidgets.QPushButton(Dialog)\n self.pushButton.setGeometry(QtCore.QRect(150, 130, 93, 28))\n self.pushButton.setObjectName('pushButton')\n self.label_2 = QtWidgets.QLabel(Dialog)\n self.label_2.setGeometry(QtCore.QRect(160, 50, 200, 40))\n font = QtGui.QFont()\n font.setFamily('Arial')\n font.setPointSize(16)\n font.setBold(True)\n font.setWeight(75)\n self.label_2.setFont(font)\n self.label_2.setStyleSheet('')\n self.label_2.setObjectName('label_2')\n self.retranslateUi(Dialog)\n QtCore.QMetaObject.connectSlotsByName(Dialog)\n <function token>\n\n\n<code token>\n", "<import token>\n\n\nclass Ui_Dialog(object):\n <function token>\n <function token>\n\n\n<code token>\n", "<import token>\n<class token>\n<code token>\n" ]
false
98,753
bf0b66735214faa1e0fb240f499c47f7130e3556
''' Given an array of integers, some of the elements appear once, other elements appear twice. ∀ e ∈ arr[int], e ∈ [1, len(arr[int])] Find all elements that appear twice in the array Niave, make a dict, if frequency goes above 1, add the element to an arr[int], return arr. Easy money. Or, for every element see if it appears again in the list, 0(n²), easy money x 2 However, neither of these are 0(n), 0(c) sum 1+2+...+n = ((n+1)(n))/2 Given: [4,3,2,7,8,2,3,1] len() == 8 So sum should be 8*7/2 = 56/2 = 28 28 Loop through each element, subtract the value 4: 24 3: 21 2: 19 7: 12 8: 4 2: 2 3: -1 1: -2 28 - x - y + z + w = -2 seen = set() ans = [] for num in nums: if num in seen: ans.append(num) elif num not in seen: seen.add(num) return ans Ok so I think that I have it. Loop through list. Since we know that the elements must exist in [1,n], we can calculate the index at which any given element must exist at (if we were to sort it). If we look at the element at the target index, and it is the same as the element that we have, add it to our arr[int] Then set the current index to None. Loop through list, swapping elements until they are in the right location. If we see a repeat, setting the current index that we are at to None. Return the arr[int] when done. ''' class Solution: def findDuplicates(self, nums): seen = set() ans = [] for num in nums: if num in seen: ans.append(num) elif num not in seen: seen.add(num) return ans if __name__ == '__main__': s = Solution() print(s.findDuplicates([4,3,2,7,8,2,3,1])) print(s.findDuplicates([1,2]))
[ "'''\nGiven an array of integers, some of the elements\nappear once, other elements appear twice.\n\n∀ e ∈ arr[int], e ∈ [1, len(arr[int])]\n\nFind all elements that appear twice in the array\n\nNiave, make a dict, if frequency goes above 1, add\nthe element to an arr[int], return arr. Easy money.\n\nOr, for every element see if it appears again in the\nlist, 0(n²), easy money x 2\n\nHowever, neither of these are 0(n), 0(c)\n\nsum 1+2+...+n = ((n+1)(n))/2\n\nGiven: [4,3,2,7,8,2,3,1]\nlen() == 8\n\nSo sum should be 8*7/2 = 56/2 = 28\n\n28\n\nLoop through each element, subtract the value\n\n4: 24\n3: 21\n2: 19\n7: 12\n8: 4\n2: 2\n3: -1\n1: -2\n\n28 - x - y + z + w = -2\n\nseen = set()\nans = []\n\nfor num in nums:\n if num in seen:\n ans.append(num)\n\n elif num not in seen:\n seen.add(num)\n\nreturn ans\n\nOk so I think that I have it.\n\nLoop through list. Since we know that\nthe elements must exist in [1,n], we\ncan calculate the index at which any\ngiven element must exist at (if we were\nto sort it).\n\nIf we look at the element at the target\nindex, and it is the same as the element that we have,\nadd it to our arr[int]\n\nThen set the current index to None.\n\nLoop through list, swapping elements until they are in\nthe right location. If we see a repeat, setting the current\nindex that we are at to None.\n\nReturn the arr[int] when done.\n\n\n\n'''\n\n\nclass Solution:\n def findDuplicates(self, nums):\n seen = set()\n ans = []\n\n for num in nums:\n if num in seen:\n ans.append(num)\n\n elif num not in seen:\n seen.add(num)\n\n return ans\n\nif __name__ == '__main__':\n s = Solution()\n\n print(s.findDuplicates([4,3,2,7,8,2,3,1]))\n\n print(s.findDuplicates([1,2]))\n", "<docstring token>\n\n\nclass Solution:\n\n def findDuplicates(self, nums):\n seen = set()\n ans = []\n for num in nums:\n if num in seen:\n ans.append(num)\n elif num not in seen:\n seen.add(num)\n return ans\n\n\nif __name__ == '__main__':\n s = Solution()\n print(s.findDuplicates([4, 3, 2, 7, 8, 2, 3, 1]))\n print(s.findDuplicates([1, 2]))\n", "<docstring token>\n\n\nclass Solution:\n\n def findDuplicates(self, nums):\n seen = set()\n ans = []\n for num in nums:\n if num in seen:\n ans.append(num)\n elif num not in seen:\n seen.add(num)\n return ans\n\n\n<code token>\n", "<docstring token>\n\n\nclass Solution:\n <function token>\n\n\n<code token>\n", "<docstring token>\n<class token>\n<code token>\n" ]
false
98,754
83a596d864b9d0a5d9a7cd4f5da1c22c9cd45bc1
from loxpy import Lox if __name__ == "__main__": Lox.main()
[ "from loxpy import Lox\n\nif __name__ == \"__main__\":\n Lox.main()\n", "from loxpy import Lox\nif __name__ == '__main__':\n Lox.main()\n", "<import token>\nif __name__ == '__main__':\n Lox.main()\n", "<import token>\n<code token>\n" ]
false
98,755
af050c9973279a4ad8eb85f3ef2ecf7c2f7a7b62
# Generated by Django 2.0.5 on 2018-10-03 12:08 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('ActualCost', '0005_auto_20181003_1532'), ] operations = [ migrations.RemoveField( model_name='wastesale', name='cost', ), migrations.RemoveField( model_name='wastesale', name='image', ), ]
[ "# Generated by Django 2.0.5 on 2018-10-03 12:08\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('ActualCost', '0005_auto_20181003_1532'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='wastesale',\n name='cost',\n ),\n migrations.RemoveField(\n model_name='wastesale',\n name='image',\n ),\n ]\n", "from django.db import migrations\n\n\nclass Migration(migrations.Migration):\n dependencies = [('ActualCost', '0005_auto_20181003_1532')]\n operations = [migrations.RemoveField(model_name='wastesale', name=\n 'cost'), migrations.RemoveField(model_name='wastesale', name='image')]\n", "<import token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('ActualCost', '0005_auto_20181003_1532')]\n operations = [migrations.RemoveField(model_name='wastesale', name=\n 'cost'), migrations.RemoveField(model_name='wastesale', name='image')]\n", "<import token>\n\n\nclass Migration(migrations.Migration):\n <assignment token>\n <assignment token>\n", "<import token>\n<class token>\n" ]
false
98,756
0b2dd383e84d193bc26e70c9f544152c3fa620c7
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.modules.module import _IncompatibleKeys from x_transformers import * from x_transformers.autoregressive_wrapper import * from timm import create_model from timm.models.layers.patch_embed import PatchEmbed from copy import deepcopy from einops import rearrange, repeat from dataset import START, PAD, END import numpy as np import math import random from dataset import START, PAD, END device = torch.device("cuda" if torch.cuda.is_available() else "cpu") class CustomARWrapper(AutoregressiveWrapper): def __init__(self, *args, **kwargs): super(CustomARWrapper, self).__init__(*args, **kwargs) @torch.no_grad() def generate(self, start_tokens, seq_len, eos_token=None, temperature=1., filter_logits_fn=top_k, filter_thres=0.9, **kwargs): device = start_tokens.device was_training = self.net.training num_dims = len(start_tokens.shape) if num_dims == 1: start_tokens = start_tokens[None, :] b, t = start_tokens.shape self.net.eval() out = start_tokens mask = kwargs.pop('mask', None) if mask is None: mask = torch.full_like(out, True, dtype=torch.bool, device=out.device) for _ in range(seq_len): x = out[:, -self.max_seq_len:] mask = mask[:, -self.max_seq_len:] # print('arw:',out.shape) logits = self.net(x, mask=mask, **kwargs)[:, -1, :] if filter_logits_fn in {top_k, top_p}: filtered_logits = filter_logits_fn(logits, thres=filter_thres) probs = F.softmax(filtered_logits / temperature, dim=-1) elif filter_logits_fn is entmax: probs = entmax(logits / temperature, alpha=ENTMAX_ALPHA, dim=-1) sample = torch.multinomial(probs, 1) out = torch.cat((out, sample), dim=-1) mask = F.pad(mask, (0, 1), value=True) if eos_token is not None and (torch.cumsum(out == eos_token, 1)[:, -1] >= 1).all(): break out = out[:, t:] if num_dims == 1: out = out.squeeze(0) self.net.train(was_training) return out def forward(self, x, **kwargs): #print(x) xi = x[:, :-1] xo = x[:, 1:] # help auto-solve a frequent area of confusion around input masks in auto-regressive # if user supplies a mask that is only off by one from the source sequence, resolve itfor them mask = kwargs.get('mask', None) if mask is not None and mask.shape[1] == x.shape[1]: mask = mask[:, :-1] kwargs['mask'] = mask out = self.net(xi, **kwargs) # print(out.shape) # print(out.transpose(1,2).shape) # print(xo.shape) loss = F.cross_entropy(out.transpose(1, 2), xo, ignore_index=2) return loss class CustomSwinTransformer(torch.nn.Module): def __init__(self,swin_layer): super(CustomSwinTransformer, self).__init__() self.patch_embed = PatchEmbed(img_size=(112,448),patch_size=4,in_chans=1,embed_dim=192) self.swin_layer = swin_layer self.linear = torch.nn.Linear(1536,256) self.norm = torch.nn.LayerNorm((256,),eps=1e-06) self.avg_pool = torch.nn.AdaptiveAvgPool1d(output_size=1) def forward(self, x): x=self.patch_embed(x) x=self.swin_layer(x) x=self.linear(x) x=self.norm(x) x=self.avg_pool(x) class Swin(nn.Module): def __init__(self, FLAGS, train_dataset, checkpoint=None, temp=.333): super(Swin, self).__init__() self.bos_token = train_dataset.token_to_id[START] self.eos_token = train_dataset.token_to_id[END] self.pad_token = train_dataset.token_to_id[PAD] self.max_seq_len = FLAGS.swin.max_seq_len self.temperature = temp sw = create_model('swin_large_patch4_window7_224',checkpoint_path="/opt/ml/input/data/swin.pth") sl = deepcopy(sw.layers) del sw self.encoder = CustomSwinTransformer(sl) self.decoder = CustomARWrapper( TransformerWrapper( num_tokens=len(train_dataset.id_to_token), max_seq_len=self.max_seq_len, attn_layers=Decoder( dim=FLAGS.swin.decoder.dim, depth=FLAGS.swin.decoder.depth, heads=FLAGS.swin.decoder.heads, attn_on_attn=FLAGS.swin.decoder.args.attn_on_attn, cross_attend=FLAGS.swin.decoder.args.cross_attend, ff_glu=FLAGS.swin.decoder.args.ff_glu, rel_pos_bias=FLAGS.swin.decoder.args.rel_pos_bias, use_scalenorm=FLAGS.swin.decoder.args.use_scalenorm )), pad_value=self.pad_token) self.criterion = ( nn.CrossEntropyLoss() ) if checkpoint is not None: self.load_state_dict(checkpoint) def load_state_dict(self, state_dict, strict=True): total_parameters = 0 matches = 0 mismatches = 0 with torch.no_grad(): for name,param in self.named_parameters(): total_parameters+=1 try: param.copy_(state_dict[name]) matches+=1 except Exception as e: print(f'disable to get parameter : {name}') print(e) mismatches+=1 continue print(f"Load weights : {matches}/{total_parameters} mathches, {mismatches} mismatches.") def forward(self, x: torch.Tensor, expected, is_train, teacher_focing_ratio=None): device = x.device encoded = self.encoder(x.to(device)) dec = self.decoder.generate(torch.LongTensor([self.bos_token] * len(x))[:, None].to(device), self.max_seq_len, eos_token=self.eos_token, context=encoded, temperature=self.temperature) return dec
[ "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn.modules.module import _IncompatibleKeys\n\nfrom x_transformers import *\nfrom x_transformers.autoregressive_wrapper import *\nfrom timm import create_model\nfrom timm.models.layers.patch_embed import PatchEmbed\nfrom copy import deepcopy\nfrom einops import rearrange, repeat\nfrom dataset import START, PAD, END\n\nimport numpy as np\nimport math\nimport random\n\nfrom dataset import START, PAD, END\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\nclass CustomARWrapper(AutoregressiveWrapper):\n def __init__(self, *args, **kwargs):\n super(CustomARWrapper, self).__init__(*args, **kwargs)\n\n @torch.no_grad()\n def generate(self, start_tokens, seq_len, eos_token=None, temperature=1., filter_logits_fn=top_k, filter_thres=0.9,\n **kwargs):\n device = start_tokens.device\n was_training = self.net.training\n num_dims = len(start_tokens.shape)\n\n if num_dims == 1:\n start_tokens = start_tokens[None, :]\n\n b, t = start_tokens.shape\n\n self.net.eval()\n out = start_tokens\n mask = kwargs.pop('mask', None)\n if mask is None:\n mask = torch.full_like(out, True, dtype=torch.bool, device=out.device)\n\n for _ in range(seq_len):\n x = out[:, -self.max_seq_len:]\n mask = mask[:, -self.max_seq_len:]\n # print('arw:',out.shape)\n logits = self.net(x, mask=mask, **kwargs)[:, -1, :]\n\n if filter_logits_fn in {top_k, top_p}:\n filtered_logits = filter_logits_fn(logits, thres=filter_thres)\n probs = F.softmax(filtered_logits / temperature, dim=-1)\n\n elif filter_logits_fn is entmax:\n probs = entmax(logits / temperature, alpha=ENTMAX_ALPHA, dim=-1)\n\n sample = torch.multinomial(probs, 1)\n\n out = torch.cat((out, sample), dim=-1)\n mask = F.pad(mask, (0, 1), value=True)\n\n if eos_token is not None and (torch.cumsum(out == eos_token, 1)[:, -1] >= 1).all():\n break\n\n out = out[:, t:]\n\n if num_dims == 1:\n out = out.squeeze(0)\n\n self.net.train(was_training)\n return out\n\n def forward(self, x, **kwargs):\n #print(x)\n xi = x[:, :-1]\n xo = x[:, 1:]\n\n # help auto-solve a frequent area of confusion around input masks in auto-regressive\n # if user supplies a mask that is only off by one from the source sequence, resolve itfor them\n mask = kwargs.get('mask', None)\n if mask is not None and mask.shape[1] == x.shape[1]:\n mask = mask[:, :-1]\n kwargs['mask'] = mask\n\n out = self.net(xi, **kwargs)\n # print(out.shape)\n # print(out.transpose(1,2).shape)\n # print(xo.shape)\n loss = F.cross_entropy(out.transpose(1, 2), xo, ignore_index=2)\n return loss\n\n\nclass CustomSwinTransformer(torch.nn.Module):\n def __init__(self,swin_layer):\n super(CustomSwinTransformer, self).__init__()\n self.patch_embed = PatchEmbed(img_size=(112,448),patch_size=4,in_chans=1,embed_dim=192)\n self.swin_layer = swin_layer\n self.linear = torch.nn.Linear(1536,256)\n self.norm = torch.nn.LayerNorm((256,),eps=1e-06)\n self.avg_pool = torch.nn.AdaptiveAvgPool1d(output_size=1)\n\n def forward(self, x):\n x=self.patch_embed(x)\n x=self.swin_layer(x)\n x=self.linear(x)\n x=self.norm(x)\n x=self.avg_pool(x)\n\n\n\nclass Swin(nn.Module):\n def __init__(self, FLAGS, train_dataset, checkpoint=None, temp=.333):\n super(Swin, self).__init__()\n self.bos_token = train_dataset.token_to_id[START]\n self.eos_token = train_dataset.token_to_id[END]\n self.pad_token = train_dataset.token_to_id[PAD]\n self.max_seq_len = FLAGS.swin.max_seq_len\n self.temperature = temp\n sw = create_model('swin_large_patch4_window7_224',checkpoint_path=\"/opt/ml/input/data/swin.pth\")\n sl = deepcopy(sw.layers)\n del sw\n self.encoder = CustomSwinTransformer(sl)\n\n self.decoder = CustomARWrapper(\n TransformerWrapper(\n num_tokens=len(train_dataset.id_to_token),\n max_seq_len=self.max_seq_len,\n attn_layers=Decoder(\n dim=FLAGS.swin.decoder.dim,\n depth=FLAGS.swin.decoder.depth,\n heads=FLAGS.swin.decoder.heads,\n attn_on_attn=FLAGS.swin.decoder.args.attn_on_attn,\n cross_attend=FLAGS.swin.decoder.args.cross_attend,\n ff_glu=FLAGS.swin.decoder.args.ff_glu,\n rel_pos_bias=FLAGS.swin.decoder.args.rel_pos_bias,\n use_scalenorm=FLAGS.swin.decoder.args.use_scalenorm\n )),\n pad_value=self.pad_token)\n\n self.criterion = (\n nn.CrossEntropyLoss()\n )\n\n if checkpoint is not None:\n self.load_state_dict(checkpoint)\n\n\n def load_state_dict(self, state_dict, strict=True):\n total_parameters = 0\n matches = 0\n mismatches = 0\n with torch.no_grad():\n for name,param in self.named_parameters():\n total_parameters+=1\n try:\n param.copy_(state_dict[name])\n matches+=1\n except Exception as e:\n print(f'disable to get parameter : {name}')\n print(e)\n mismatches+=1\n continue\n print(f\"Load weights : {matches}/{total_parameters} mathches, {mismatches} mismatches.\")\n\n def forward(self, x: torch.Tensor, expected, is_train, teacher_focing_ratio=None):\n device = x.device\n encoded = self.encoder(x.to(device))\n dec = self.decoder.generate(torch.LongTensor([self.bos_token] * len(x))[:, None].to(device), self.max_seq_len,\n eos_token=self.eos_token, context=encoded, temperature=self.temperature)\n return dec", "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn.modules.module import _IncompatibleKeys\nfrom x_transformers import *\nfrom x_transformers.autoregressive_wrapper import *\nfrom timm import create_model\nfrom timm.models.layers.patch_embed import PatchEmbed\nfrom copy import deepcopy\nfrom einops import rearrange, repeat\nfrom dataset import START, PAD, END\nimport numpy as np\nimport math\nimport random\nfrom dataset import START, PAD, END\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n\nclass CustomARWrapper(AutoregressiveWrapper):\n\n def __init__(self, *args, **kwargs):\n super(CustomARWrapper, self).__init__(*args, **kwargs)\n\n @torch.no_grad()\n def generate(self, start_tokens, seq_len, eos_token=None, temperature=\n 1.0, filter_logits_fn=top_k, filter_thres=0.9, **kwargs):\n device = start_tokens.device\n was_training = self.net.training\n num_dims = len(start_tokens.shape)\n if num_dims == 1:\n start_tokens = start_tokens[None, :]\n b, t = start_tokens.shape\n self.net.eval()\n out = start_tokens\n mask = kwargs.pop('mask', None)\n if mask is None:\n mask = torch.full_like(out, True, dtype=torch.bool, device=out.\n device)\n for _ in range(seq_len):\n x = out[:, -self.max_seq_len:]\n mask = mask[:, -self.max_seq_len:]\n logits = self.net(x, mask=mask, **kwargs)[:, -1, :]\n if filter_logits_fn in {top_k, top_p}:\n filtered_logits = filter_logits_fn(logits, thres=filter_thres)\n probs = F.softmax(filtered_logits / temperature, dim=-1)\n elif filter_logits_fn is entmax:\n probs = entmax(logits / temperature, alpha=ENTMAX_ALPHA, dim=-1\n )\n sample = torch.multinomial(probs, 1)\n out = torch.cat((out, sample), dim=-1)\n mask = F.pad(mask, (0, 1), value=True)\n if eos_token is not None and (torch.cumsum(out == eos_token, 1)\n [:, -1] >= 1).all():\n break\n out = out[:, t:]\n if num_dims == 1:\n out = out.squeeze(0)\n self.net.train(was_training)\n return out\n\n def forward(self, x, **kwargs):\n xi = x[:, :-1]\n xo = x[:, 1:]\n mask = kwargs.get('mask', None)\n if mask is not None and mask.shape[1] == x.shape[1]:\n mask = mask[:, :-1]\n kwargs['mask'] = mask\n out = self.net(xi, **kwargs)\n loss = F.cross_entropy(out.transpose(1, 2), xo, ignore_index=2)\n return loss\n\n\nclass CustomSwinTransformer(torch.nn.Module):\n\n def __init__(self, swin_layer):\n super(CustomSwinTransformer, self).__init__()\n self.patch_embed = PatchEmbed(img_size=(112, 448), patch_size=4,\n in_chans=1, embed_dim=192)\n self.swin_layer = swin_layer\n self.linear = torch.nn.Linear(1536, 256)\n self.norm = torch.nn.LayerNorm((256,), eps=1e-06)\n self.avg_pool = torch.nn.AdaptiveAvgPool1d(output_size=1)\n\n def forward(self, x):\n x = self.patch_embed(x)\n x = self.swin_layer(x)\n x = self.linear(x)\n x = self.norm(x)\n x = self.avg_pool(x)\n\n\nclass Swin(nn.Module):\n\n def __init__(self, FLAGS, train_dataset, checkpoint=None, temp=0.333):\n super(Swin, self).__init__()\n self.bos_token = train_dataset.token_to_id[START]\n self.eos_token = train_dataset.token_to_id[END]\n self.pad_token = train_dataset.token_to_id[PAD]\n self.max_seq_len = FLAGS.swin.max_seq_len\n self.temperature = temp\n sw = create_model('swin_large_patch4_window7_224', checkpoint_path=\n '/opt/ml/input/data/swin.pth')\n sl = deepcopy(sw.layers)\n del sw\n self.encoder = CustomSwinTransformer(sl)\n self.decoder = CustomARWrapper(TransformerWrapper(num_tokens=len(\n train_dataset.id_to_token), max_seq_len=self.max_seq_len,\n attn_layers=Decoder(dim=FLAGS.swin.decoder.dim, depth=FLAGS.\n swin.decoder.depth, heads=FLAGS.swin.decoder.heads,\n attn_on_attn=FLAGS.swin.decoder.args.attn_on_attn, cross_attend\n =FLAGS.swin.decoder.args.cross_attend, ff_glu=FLAGS.swin.\n decoder.args.ff_glu, rel_pos_bias=FLAGS.swin.decoder.args.\n rel_pos_bias, use_scalenorm=FLAGS.swin.decoder.args.\n use_scalenorm)), pad_value=self.pad_token)\n self.criterion = nn.CrossEntropyLoss()\n if checkpoint is not None:\n self.load_state_dict(checkpoint)\n\n def load_state_dict(self, state_dict, strict=True):\n total_parameters = 0\n matches = 0\n mismatches = 0\n with torch.no_grad():\n for name, param in self.named_parameters():\n total_parameters += 1\n try:\n param.copy_(state_dict[name])\n matches += 1\n except Exception as e:\n print(f'disable to get parameter : {name}')\n print(e)\n mismatches += 1\n continue\n print(\n f'Load weights : {matches}/{total_parameters} mathches, {mismatches} mismatches.'\n )\n\n def forward(self, x: torch.Tensor, expected, is_train,\n teacher_focing_ratio=None):\n device = x.device\n encoded = self.encoder(x.to(device))\n dec = self.decoder.generate(torch.LongTensor([self.bos_token] * len\n (x))[:, None].to(device), self.max_seq_len, eos_token=self.\n eos_token, context=encoded, temperature=self.temperature)\n return dec\n", "<import token>\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n\nclass CustomARWrapper(AutoregressiveWrapper):\n\n def __init__(self, *args, **kwargs):\n super(CustomARWrapper, self).__init__(*args, **kwargs)\n\n @torch.no_grad()\n def generate(self, start_tokens, seq_len, eos_token=None, temperature=\n 1.0, filter_logits_fn=top_k, filter_thres=0.9, **kwargs):\n device = start_tokens.device\n was_training = self.net.training\n num_dims = len(start_tokens.shape)\n if num_dims == 1:\n start_tokens = start_tokens[None, :]\n b, t = start_tokens.shape\n self.net.eval()\n out = start_tokens\n mask = kwargs.pop('mask', None)\n if mask is None:\n mask = torch.full_like(out, True, dtype=torch.bool, device=out.\n device)\n for _ in range(seq_len):\n x = out[:, -self.max_seq_len:]\n mask = mask[:, -self.max_seq_len:]\n logits = self.net(x, mask=mask, **kwargs)[:, -1, :]\n if filter_logits_fn in {top_k, top_p}:\n filtered_logits = filter_logits_fn(logits, thres=filter_thres)\n probs = F.softmax(filtered_logits / temperature, dim=-1)\n elif filter_logits_fn is entmax:\n probs = entmax(logits / temperature, alpha=ENTMAX_ALPHA, dim=-1\n )\n sample = torch.multinomial(probs, 1)\n out = torch.cat((out, sample), dim=-1)\n mask = F.pad(mask, (0, 1), value=True)\n if eos_token is not None and (torch.cumsum(out == eos_token, 1)\n [:, -1] >= 1).all():\n break\n out = out[:, t:]\n if num_dims == 1:\n out = out.squeeze(0)\n self.net.train(was_training)\n return out\n\n def forward(self, x, **kwargs):\n xi = x[:, :-1]\n xo = x[:, 1:]\n mask = kwargs.get('mask', None)\n if mask is not None and mask.shape[1] == x.shape[1]:\n mask = mask[:, :-1]\n kwargs['mask'] = mask\n out = self.net(xi, **kwargs)\n loss = F.cross_entropy(out.transpose(1, 2), xo, ignore_index=2)\n return loss\n\n\nclass CustomSwinTransformer(torch.nn.Module):\n\n def __init__(self, swin_layer):\n super(CustomSwinTransformer, self).__init__()\n self.patch_embed = PatchEmbed(img_size=(112, 448), patch_size=4,\n in_chans=1, embed_dim=192)\n self.swin_layer = swin_layer\n self.linear = torch.nn.Linear(1536, 256)\n self.norm = torch.nn.LayerNorm((256,), eps=1e-06)\n self.avg_pool = torch.nn.AdaptiveAvgPool1d(output_size=1)\n\n def forward(self, x):\n x = self.patch_embed(x)\n x = self.swin_layer(x)\n x = self.linear(x)\n x = self.norm(x)\n x = self.avg_pool(x)\n\n\nclass Swin(nn.Module):\n\n def __init__(self, FLAGS, train_dataset, checkpoint=None, temp=0.333):\n super(Swin, self).__init__()\n self.bos_token = train_dataset.token_to_id[START]\n self.eos_token = train_dataset.token_to_id[END]\n self.pad_token = train_dataset.token_to_id[PAD]\n self.max_seq_len = FLAGS.swin.max_seq_len\n self.temperature = temp\n sw = create_model('swin_large_patch4_window7_224', checkpoint_path=\n '/opt/ml/input/data/swin.pth')\n sl = deepcopy(sw.layers)\n del sw\n self.encoder = CustomSwinTransformer(sl)\n self.decoder = CustomARWrapper(TransformerWrapper(num_tokens=len(\n train_dataset.id_to_token), max_seq_len=self.max_seq_len,\n attn_layers=Decoder(dim=FLAGS.swin.decoder.dim, depth=FLAGS.\n swin.decoder.depth, heads=FLAGS.swin.decoder.heads,\n attn_on_attn=FLAGS.swin.decoder.args.attn_on_attn, cross_attend\n =FLAGS.swin.decoder.args.cross_attend, ff_glu=FLAGS.swin.\n decoder.args.ff_glu, rel_pos_bias=FLAGS.swin.decoder.args.\n rel_pos_bias, use_scalenorm=FLAGS.swin.decoder.args.\n use_scalenorm)), pad_value=self.pad_token)\n self.criterion = nn.CrossEntropyLoss()\n if checkpoint is not None:\n self.load_state_dict(checkpoint)\n\n def load_state_dict(self, state_dict, strict=True):\n total_parameters = 0\n matches = 0\n mismatches = 0\n with torch.no_grad():\n for name, param in self.named_parameters():\n total_parameters += 1\n try:\n param.copy_(state_dict[name])\n matches += 1\n except Exception as e:\n print(f'disable to get parameter : {name}')\n print(e)\n mismatches += 1\n continue\n print(\n f'Load weights : {matches}/{total_parameters} mathches, {mismatches} mismatches.'\n )\n\n def forward(self, x: torch.Tensor, expected, is_train,\n teacher_focing_ratio=None):\n device = x.device\n encoded = self.encoder(x.to(device))\n dec = self.decoder.generate(torch.LongTensor([self.bos_token] * len\n (x))[:, None].to(device), self.max_seq_len, eos_token=self.\n eos_token, context=encoded, temperature=self.temperature)\n return dec\n", "<import token>\n<assignment token>\n\n\nclass CustomARWrapper(AutoregressiveWrapper):\n\n def __init__(self, *args, **kwargs):\n super(CustomARWrapper, self).__init__(*args, **kwargs)\n\n @torch.no_grad()\n def generate(self, start_tokens, seq_len, eos_token=None, temperature=\n 1.0, filter_logits_fn=top_k, filter_thres=0.9, **kwargs):\n device = start_tokens.device\n was_training = self.net.training\n num_dims = len(start_tokens.shape)\n if num_dims == 1:\n start_tokens = start_tokens[None, :]\n b, t = start_tokens.shape\n self.net.eval()\n out = start_tokens\n mask = kwargs.pop('mask', None)\n if mask is None:\n mask = torch.full_like(out, True, dtype=torch.bool, device=out.\n device)\n for _ in range(seq_len):\n x = out[:, -self.max_seq_len:]\n mask = mask[:, -self.max_seq_len:]\n logits = self.net(x, mask=mask, **kwargs)[:, -1, :]\n if filter_logits_fn in {top_k, top_p}:\n filtered_logits = filter_logits_fn(logits, thres=filter_thres)\n probs = F.softmax(filtered_logits / temperature, dim=-1)\n elif filter_logits_fn is entmax:\n probs = entmax(logits / temperature, alpha=ENTMAX_ALPHA, dim=-1\n )\n sample = torch.multinomial(probs, 1)\n out = torch.cat((out, sample), dim=-1)\n mask = F.pad(mask, (0, 1), value=True)\n if eos_token is not None and (torch.cumsum(out == eos_token, 1)\n [:, -1] >= 1).all():\n break\n out = out[:, t:]\n if num_dims == 1:\n out = out.squeeze(0)\n self.net.train(was_training)\n return out\n\n def forward(self, x, **kwargs):\n xi = x[:, :-1]\n xo = x[:, 1:]\n mask = kwargs.get('mask', None)\n if mask is not None and mask.shape[1] == x.shape[1]:\n mask = mask[:, :-1]\n kwargs['mask'] = mask\n out = self.net(xi, **kwargs)\n loss = F.cross_entropy(out.transpose(1, 2), xo, ignore_index=2)\n return loss\n\n\nclass CustomSwinTransformer(torch.nn.Module):\n\n def __init__(self, swin_layer):\n super(CustomSwinTransformer, self).__init__()\n self.patch_embed = PatchEmbed(img_size=(112, 448), patch_size=4,\n in_chans=1, embed_dim=192)\n self.swin_layer = swin_layer\n self.linear = torch.nn.Linear(1536, 256)\n self.norm = torch.nn.LayerNorm((256,), eps=1e-06)\n self.avg_pool = torch.nn.AdaptiveAvgPool1d(output_size=1)\n\n def forward(self, x):\n x = self.patch_embed(x)\n x = self.swin_layer(x)\n x = self.linear(x)\n x = self.norm(x)\n x = self.avg_pool(x)\n\n\nclass Swin(nn.Module):\n\n def __init__(self, FLAGS, train_dataset, checkpoint=None, temp=0.333):\n super(Swin, self).__init__()\n self.bos_token = train_dataset.token_to_id[START]\n self.eos_token = train_dataset.token_to_id[END]\n self.pad_token = train_dataset.token_to_id[PAD]\n self.max_seq_len = FLAGS.swin.max_seq_len\n self.temperature = temp\n sw = create_model('swin_large_patch4_window7_224', checkpoint_path=\n '/opt/ml/input/data/swin.pth')\n sl = deepcopy(sw.layers)\n del sw\n self.encoder = CustomSwinTransformer(sl)\n self.decoder = CustomARWrapper(TransformerWrapper(num_tokens=len(\n train_dataset.id_to_token), max_seq_len=self.max_seq_len,\n attn_layers=Decoder(dim=FLAGS.swin.decoder.dim, depth=FLAGS.\n swin.decoder.depth, heads=FLAGS.swin.decoder.heads,\n attn_on_attn=FLAGS.swin.decoder.args.attn_on_attn, cross_attend\n =FLAGS.swin.decoder.args.cross_attend, ff_glu=FLAGS.swin.\n decoder.args.ff_glu, rel_pos_bias=FLAGS.swin.decoder.args.\n rel_pos_bias, use_scalenorm=FLAGS.swin.decoder.args.\n use_scalenorm)), pad_value=self.pad_token)\n self.criterion = nn.CrossEntropyLoss()\n if checkpoint is not None:\n self.load_state_dict(checkpoint)\n\n def load_state_dict(self, state_dict, strict=True):\n total_parameters = 0\n matches = 0\n mismatches = 0\n with torch.no_grad():\n for name, param in self.named_parameters():\n total_parameters += 1\n try:\n param.copy_(state_dict[name])\n matches += 1\n except Exception as e:\n print(f'disable to get parameter : {name}')\n print(e)\n mismatches += 1\n continue\n print(\n f'Load weights : {matches}/{total_parameters} mathches, {mismatches} mismatches.'\n )\n\n def forward(self, x: torch.Tensor, expected, is_train,\n teacher_focing_ratio=None):\n device = x.device\n encoded = self.encoder(x.to(device))\n dec = self.decoder.generate(torch.LongTensor([self.bos_token] * len\n (x))[:, None].to(device), self.max_seq_len, eos_token=self.\n eos_token, context=encoded, temperature=self.temperature)\n return dec\n", "<import token>\n<assignment token>\n\n\nclass CustomARWrapper(AutoregressiveWrapper):\n\n def __init__(self, *args, **kwargs):\n super(CustomARWrapper, self).__init__(*args, **kwargs)\n\n @torch.no_grad()\n def generate(self, start_tokens, seq_len, eos_token=None, temperature=\n 1.0, filter_logits_fn=top_k, filter_thres=0.9, **kwargs):\n device = start_tokens.device\n was_training = self.net.training\n num_dims = len(start_tokens.shape)\n if num_dims == 1:\n start_tokens = start_tokens[None, :]\n b, t = start_tokens.shape\n self.net.eval()\n out = start_tokens\n mask = kwargs.pop('mask', None)\n if mask is None:\n mask = torch.full_like(out, True, dtype=torch.bool, device=out.\n device)\n for _ in range(seq_len):\n x = out[:, -self.max_seq_len:]\n mask = mask[:, -self.max_seq_len:]\n logits = self.net(x, mask=mask, **kwargs)[:, -1, :]\n if filter_logits_fn in {top_k, top_p}:\n filtered_logits = filter_logits_fn(logits, thres=filter_thres)\n probs = F.softmax(filtered_logits / temperature, dim=-1)\n elif filter_logits_fn is entmax:\n probs = entmax(logits / temperature, alpha=ENTMAX_ALPHA, dim=-1\n )\n sample = torch.multinomial(probs, 1)\n out = torch.cat((out, sample), dim=-1)\n mask = F.pad(mask, (0, 1), value=True)\n if eos_token is not None and (torch.cumsum(out == eos_token, 1)\n [:, -1] >= 1).all():\n break\n out = out[:, t:]\n if num_dims == 1:\n out = out.squeeze(0)\n self.net.train(was_training)\n return out\n <function token>\n\n\nclass CustomSwinTransformer(torch.nn.Module):\n\n def __init__(self, swin_layer):\n super(CustomSwinTransformer, self).__init__()\n self.patch_embed = PatchEmbed(img_size=(112, 448), patch_size=4,\n in_chans=1, embed_dim=192)\n self.swin_layer = swin_layer\n self.linear = torch.nn.Linear(1536, 256)\n self.norm = torch.nn.LayerNorm((256,), eps=1e-06)\n self.avg_pool = torch.nn.AdaptiveAvgPool1d(output_size=1)\n\n def forward(self, x):\n x = self.patch_embed(x)\n x = self.swin_layer(x)\n x = self.linear(x)\n x = self.norm(x)\n x = self.avg_pool(x)\n\n\nclass Swin(nn.Module):\n\n def __init__(self, FLAGS, train_dataset, checkpoint=None, temp=0.333):\n super(Swin, self).__init__()\n self.bos_token = train_dataset.token_to_id[START]\n self.eos_token = train_dataset.token_to_id[END]\n self.pad_token = train_dataset.token_to_id[PAD]\n self.max_seq_len = FLAGS.swin.max_seq_len\n self.temperature = temp\n sw = create_model('swin_large_patch4_window7_224', checkpoint_path=\n '/opt/ml/input/data/swin.pth')\n sl = deepcopy(sw.layers)\n del sw\n self.encoder = CustomSwinTransformer(sl)\n self.decoder = CustomARWrapper(TransformerWrapper(num_tokens=len(\n train_dataset.id_to_token), max_seq_len=self.max_seq_len,\n attn_layers=Decoder(dim=FLAGS.swin.decoder.dim, depth=FLAGS.\n swin.decoder.depth, heads=FLAGS.swin.decoder.heads,\n attn_on_attn=FLAGS.swin.decoder.args.attn_on_attn, cross_attend\n =FLAGS.swin.decoder.args.cross_attend, ff_glu=FLAGS.swin.\n decoder.args.ff_glu, rel_pos_bias=FLAGS.swin.decoder.args.\n rel_pos_bias, use_scalenorm=FLAGS.swin.decoder.args.\n use_scalenorm)), pad_value=self.pad_token)\n self.criterion = nn.CrossEntropyLoss()\n if checkpoint is not None:\n self.load_state_dict(checkpoint)\n\n def load_state_dict(self, state_dict, strict=True):\n total_parameters = 0\n matches = 0\n mismatches = 0\n with torch.no_grad():\n for name, param in self.named_parameters():\n total_parameters += 1\n try:\n param.copy_(state_dict[name])\n matches += 1\n except Exception as e:\n print(f'disable to get parameter : {name}')\n print(e)\n mismatches += 1\n continue\n print(\n f'Load weights : {matches}/{total_parameters} mathches, {mismatches} mismatches.'\n )\n\n def forward(self, x: torch.Tensor, expected, is_train,\n teacher_focing_ratio=None):\n device = x.device\n encoded = self.encoder(x.to(device))\n dec = self.decoder.generate(torch.LongTensor([self.bos_token] * len\n (x))[:, None].to(device), self.max_seq_len, eos_token=self.\n eos_token, context=encoded, temperature=self.temperature)\n return dec\n", "<import token>\n<assignment token>\n\n\nclass CustomARWrapper(AutoregressiveWrapper):\n <function token>\n\n @torch.no_grad()\n def generate(self, start_tokens, seq_len, eos_token=None, temperature=\n 1.0, filter_logits_fn=top_k, filter_thres=0.9, **kwargs):\n device = start_tokens.device\n was_training = self.net.training\n num_dims = len(start_tokens.shape)\n if num_dims == 1:\n start_tokens = start_tokens[None, :]\n b, t = start_tokens.shape\n self.net.eval()\n out = start_tokens\n mask = kwargs.pop('mask', None)\n if mask is None:\n mask = torch.full_like(out, True, dtype=torch.bool, device=out.\n device)\n for _ in range(seq_len):\n x = out[:, -self.max_seq_len:]\n mask = mask[:, -self.max_seq_len:]\n logits = self.net(x, mask=mask, **kwargs)[:, -1, :]\n if filter_logits_fn in {top_k, top_p}:\n filtered_logits = filter_logits_fn(logits, thres=filter_thres)\n probs = F.softmax(filtered_logits / temperature, dim=-1)\n elif filter_logits_fn is entmax:\n probs = entmax(logits / temperature, alpha=ENTMAX_ALPHA, dim=-1\n )\n sample = torch.multinomial(probs, 1)\n out = torch.cat((out, sample), dim=-1)\n mask = F.pad(mask, (0, 1), value=True)\n if eos_token is not None and (torch.cumsum(out == eos_token, 1)\n [:, -1] >= 1).all():\n break\n out = out[:, t:]\n if num_dims == 1:\n out = out.squeeze(0)\n self.net.train(was_training)\n return out\n <function token>\n\n\nclass CustomSwinTransformer(torch.nn.Module):\n\n def __init__(self, swin_layer):\n super(CustomSwinTransformer, self).__init__()\n self.patch_embed = PatchEmbed(img_size=(112, 448), patch_size=4,\n in_chans=1, embed_dim=192)\n self.swin_layer = swin_layer\n self.linear = torch.nn.Linear(1536, 256)\n self.norm = torch.nn.LayerNorm((256,), eps=1e-06)\n self.avg_pool = torch.nn.AdaptiveAvgPool1d(output_size=1)\n\n def forward(self, x):\n x = self.patch_embed(x)\n x = self.swin_layer(x)\n x = self.linear(x)\n x = self.norm(x)\n x = self.avg_pool(x)\n\n\nclass Swin(nn.Module):\n\n def __init__(self, FLAGS, train_dataset, checkpoint=None, temp=0.333):\n super(Swin, self).__init__()\n self.bos_token = train_dataset.token_to_id[START]\n self.eos_token = train_dataset.token_to_id[END]\n self.pad_token = train_dataset.token_to_id[PAD]\n self.max_seq_len = FLAGS.swin.max_seq_len\n self.temperature = temp\n sw = create_model('swin_large_patch4_window7_224', checkpoint_path=\n '/opt/ml/input/data/swin.pth')\n sl = deepcopy(sw.layers)\n del sw\n self.encoder = CustomSwinTransformer(sl)\n self.decoder = CustomARWrapper(TransformerWrapper(num_tokens=len(\n train_dataset.id_to_token), max_seq_len=self.max_seq_len,\n attn_layers=Decoder(dim=FLAGS.swin.decoder.dim, depth=FLAGS.\n swin.decoder.depth, heads=FLAGS.swin.decoder.heads,\n attn_on_attn=FLAGS.swin.decoder.args.attn_on_attn, cross_attend\n =FLAGS.swin.decoder.args.cross_attend, ff_glu=FLAGS.swin.\n decoder.args.ff_glu, rel_pos_bias=FLAGS.swin.decoder.args.\n rel_pos_bias, use_scalenorm=FLAGS.swin.decoder.args.\n use_scalenorm)), pad_value=self.pad_token)\n self.criterion = nn.CrossEntropyLoss()\n if checkpoint is not None:\n self.load_state_dict(checkpoint)\n\n def load_state_dict(self, state_dict, strict=True):\n total_parameters = 0\n matches = 0\n mismatches = 0\n with torch.no_grad():\n for name, param in self.named_parameters():\n total_parameters += 1\n try:\n param.copy_(state_dict[name])\n matches += 1\n except Exception as e:\n print(f'disable to get parameter : {name}')\n print(e)\n mismatches += 1\n continue\n print(\n f'Load weights : {matches}/{total_parameters} mathches, {mismatches} mismatches.'\n )\n\n def forward(self, x: torch.Tensor, expected, is_train,\n teacher_focing_ratio=None):\n device = x.device\n encoded = self.encoder(x.to(device))\n dec = self.decoder.generate(torch.LongTensor([self.bos_token] * len\n (x))[:, None].to(device), self.max_seq_len, eos_token=self.\n eos_token, context=encoded, temperature=self.temperature)\n return dec\n", "<import token>\n<assignment token>\n\n\nclass CustomARWrapper(AutoregressiveWrapper):\n <function token>\n <function token>\n <function token>\n\n\nclass CustomSwinTransformer(torch.nn.Module):\n\n def __init__(self, swin_layer):\n super(CustomSwinTransformer, self).__init__()\n self.patch_embed = PatchEmbed(img_size=(112, 448), patch_size=4,\n in_chans=1, embed_dim=192)\n self.swin_layer = swin_layer\n self.linear = torch.nn.Linear(1536, 256)\n self.norm = torch.nn.LayerNorm((256,), eps=1e-06)\n self.avg_pool = torch.nn.AdaptiveAvgPool1d(output_size=1)\n\n def forward(self, x):\n x = self.patch_embed(x)\n x = self.swin_layer(x)\n x = self.linear(x)\n x = self.norm(x)\n x = self.avg_pool(x)\n\n\nclass Swin(nn.Module):\n\n def __init__(self, FLAGS, train_dataset, checkpoint=None, temp=0.333):\n super(Swin, self).__init__()\n self.bos_token = train_dataset.token_to_id[START]\n self.eos_token = train_dataset.token_to_id[END]\n self.pad_token = train_dataset.token_to_id[PAD]\n self.max_seq_len = FLAGS.swin.max_seq_len\n self.temperature = temp\n sw = create_model('swin_large_patch4_window7_224', checkpoint_path=\n '/opt/ml/input/data/swin.pth')\n sl = deepcopy(sw.layers)\n del sw\n self.encoder = CustomSwinTransformer(sl)\n self.decoder = CustomARWrapper(TransformerWrapper(num_tokens=len(\n train_dataset.id_to_token), max_seq_len=self.max_seq_len,\n attn_layers=Decoder(dim=FLAGS.swin.decoder.dim, depth=FLAGS.\n swin.decoder.depth, heads=FLAGS.swin.decoder.heads,\n attn_on_attn=FLAGS.swin.decoder.args.attn_on_attn, cross_attend\n =FLAGS.swin.decoder.args.cross_attend, ff_glu=FLAGS.swin.\n decoder.args.ff_glu, rel_pos_bias=FLAGS.swin.decoder.args.\n rel_pos_bias, use_scalenorm=FLAGS.swin.decoder.args.\n use_scalenorm)), pad_value=self.pad_token)\n self.criterion = nn.CrossEntropyLoss()\n if checkpoint is not None:\n self.load_state_dict(checkpoint)\n\n def load_state_dict(self, state_dict, strict=True):\n total_parameters = 0\n matches = 0\n mismatches = 0\n with torch.no_grad():\n for name, param in self.named_parameters():\n total_parameters += 1\n try:\n param.copy_(state_dict[name])\n matches += 1\n except Exception as e:\n print(f'disable to get parameter : {name}')\n print(e)\n mismatches += 1\n continue\n print(\n f'Load weights : {matches}/{total_parameters} mathches, {mismatches} mismatches.'\n )\n\n def forward(self, x: torch.Tensor, expected, is_train,\n teacher_focing_ratio=None):\n device = x.device\n encoded = self.encoder(x.to(device))\n dec = self.decoder.generate(torch.LongTensor([self.bos_token] * len\n (x))[:, None].to(device), self.max_seq_len, eos_token=self.\n eos_token, context=encoded, temperature=self.temperature)\n return dec\n", "<import token>\n<assignment token>\n<class token>\n\n\nclass CustomSwinTransformer(torch.nn.Module):\n\n def __init__(self, swin_layer):\n super(CustomSwinTransformer, self).__init__()\n self.patch_embed = PatchEmbed(img_size=(112, 448), patch_size=4,\n in_chans=1, embed_dim=192)\n self.swin_layer = swin_layer\n self.linear = torch.nn.Linear(1536, 256)\n self.norm = torch.nn.LayerNorm((256,), eps=1e-06)\n self.avg_pool = torch.nn.AdaptiveAvgPool1d(output_size=1)\n\n def forward(self, x):\n x = self.patch_embed(x)\n x = self.swin_layer(x)\n x = self.linear(x)\n x = self.norm(x)\n x = self.avg_pool(x)\n\n\nclass Swin(nn.Module):\n\n def __init__(self, FLAGS, train_dataset, checkpoint=None, temp=0.333):\n super(Swin, self).__init__()\n self.bos_token = train_dataset.token_to_id[START]\n self.eos_token = train_dataset.token_to_id[END]\n self.pad_token = train_dataset.token_to_id[PAD]\n self.max_seq_len = FLAGS.swin.max_seq_len\n self.temperature = temp\n sw = create_model('swin_large_patch4_window7_224', checkpoint_path=\n '/opt/ml/input/data/swin.pth')\n sl = deepcopy(sw.layers)\n del sw\n self.encoder = CustomSwinTransformer(sl)\n self.decoder = CustomARWrapper(TransformerWrapper(num_tokens=len(\n train_dataset.id_to_token), max_seq_len=self.max_seq_len,\n attn_layers=Decoder(dim=FLAGS.swin.decoder.dim, depth=FLAGS.\n swin.decoder.depth, heads=FLAGS.swin.decoder.heads,\n attn_on_attn=FLAGS.swin.decoder.args.attn_on_attn, cross_attend\n =FLAGS.swin.decoder.args.cross_attend, ff_glu=FLAGS.swin.\n decoder.args.ff_glu, rel_pos_bias=FLAGS.swin.decoder.args.\n rel_pos_bias, use_scalenorm=FLAGS.swin.decoder.args.\n use_scalenorm)), pad_value=self.pad_token)\n self.criterion = nn.CrossEntropyLoss()\n if checkpoint is not None:\n self.load_state_dict(checkpoint)\n\n def load_state_dict(self, state_dict, strict=True):\n total_parameters = 0\n matches = 0\n mismatches = 0\n with torch.no_grad():\n for name, param in self.named_parameters():\n total_parameters += 1\n try:\n param.copy_(state_dict[name])\n matches += 1\n except Exception as e:\n print(f'disable to get parameter : {name}')\n print(e)\n mismatches += 1\n continue\n print(\n f'Load weights : {matches}/{total_parameters} mathches, {mismatches} mismatches.'\n )\n\n def forward(self, x: torch.Tensor, expected, is_train,\n teacher_focing_ratio=None):\n device = x.device\n encoded = self.encoder(x.to(device))\n dec = self.decoder.generate(torch.LongTensor([self.bos_token] * len\n (x))[:, None].to(device), self.max_seq_len, eos_token=self.\n eos_token, context=encoded, temperature=self.temperature)\n return dec\n", "<import token>\n<assignment token>\n<class token>\n\n\nclass CustomSwinTransformer(torch.nn.Module):\n\n def __init__(self, swin_layer):\n super(CustomSwinTransformer, self).__init__()\n self.patch_embed = PatchEmbed(img_size=(112, 448), patch_size=4,\n in_chans=1, embed_dim=192)\n self.swin_layer = swin_layer\n self.linear = torch.nn.Linear(1536, 256)\n self.norm = torch.nn.LayerNorm((256,), eps=1e-06)\n self.avg_pool = torch.nn.AdaptiveAvgPool1d(output_size=1)\n <function token>\n\n\nclass Swin(nn.Module):\n\n def __init__(self, FLAGS, train_dataset, checkpoint=None, temp=0.333):\n super(Swin, self).__init__()\n self.bos_token = train_dataset.token_to_id[START]\n self.eos_token = train_dataset.token_to_id[END]\n self.pad_token = train_dataset.token_to_id[PAD]\n self.max_seq_len = FLAGS.swin.max_seq_len\n self.temperature = temp\n sw = create_model('swin_large_patch4_window7_224', checkpoint_path=\n '/opt/ml/input/data/swin.pth')\n sl = deepcopy(sw.layers)\n del sw\n self.encoder = CustomSwinTransformer(sl)\n self.decoder = CustomARWrapper(TransformerWrapper(num_tokens=len(\n train_dataset.id_to_token), max_seq_len=self.max_seq_len,\n attn_layers=Decoder(dim=FLAGS.swin.decoder.dim, depth=FLAGS.\n swin.decoder.depth, heads=FLAGS.swin.decoder.heads,\n attn_on_attn=FLAGS.swin.decoder.args.attn_on_attn, cross_attend\n =FLAGS.swin.decoder.args.cross_attend, ff_glu=FLAGS.swin.\n decoder.args.ff_glu, rel_pos_bias=FLAGS.swin.decoder.args.\n rel_pos_bias, use_scalenorm=FLAGS.swin.decoder.args.\n use_scalenorm)), pad_value=self.pad_token)\n self.criterion = nn.CrossEntropyLoss()\n if checkpoint is not None:\n self.load_state_dict(checkpoint)\n\n def load_state_dict(self, state_dict, strict=True):\n total_parameters = 0\n matches = 0\n mismatches = 0\n with torch.no_grad():\n for name, param in self.named_parameters():\n total_parameters += 1\n try:\n param.copy_(state_dict[name])\n matches += 1\n except Exception as e:\n print(f'disable to get parameter : {name}')\n print(e)\n mismatches += 1\n continue\n print(\n f'Load weights : {matches}/{total_parameters} mathches, {mismatches} mismatches.'\n )\n\n def forward(self, x: torch.Tensor, expected, is_train,\n teacher_focing_ratio=None):\n device = x.device\n encoded = self.encoder(x.to(device))\n dec = self.decoder.generate(torch.LongTensor([self.bos_token] * len\n (x))[:, None].to(device), self.max_seq_len, eos_token=self.\n eos_token, context=encoded, temperature=self.temperature)\n return dec\n", "<import token>\n<assignment token>\n<class token>\n\n\nclass CustomSwinTransformer(torch.nn.Module):\n <function token>\n <function token>\n\n\nclass Swin(nn.Module):\n\n def __init__(self, FLAGS, train_dataset, checkpoint=None, temp=0.333):\n super(Swin, self).__init__()\n self.bos_token = train_dataset.token_to_id[START]\n self.eos_token = train_dataset.token_to_id[END]\n self.pad_token = train_dataset.token_to_id[PAD]\n self.max_seq_len = FLAGS.swin.max_seq_len\n self.temperature = temp\n sw = create_model('swin_large_patch4_window7_224', checkpoint_path=\n '/opt/ml/input/data/swin.pth')\n sl = deepcopy(sw.layers)\n del sw\n self.encoder = CustomSwinTransformer(sl)\n self.decoder = CustomARWrapper(TransformerWrapper(num_tokens=len(\n train_dataset.id_to_token), max_seq_len=self.max_seq_len,\n attn_layers=Decoder(dim=FLAGS.swin.decoder.dim, depth=FLAGS.\n swin.decoder.depth, heads=FLAGS.swin.decoder.heads,\n attn_on_attn=FLAGS.swin.decoder.args.attn_on_attn, cross_attend\n =FLAGS.swin.decoder.args.cross_attend, ff_glu=FLAGS.swin.\n decoder.args.ff_glu, rel_pos_bias=FLAGS.swin.decoder.args.\n rel_pos_bias, use_scalenorm=FLAGS.swin.decoder.args.\n use_scalenorm)), pad_value=self.pad_token)\n self.criterion = nn.CrossEntropyLoss()\n if checkpoint is not None:\n self.load_state_dict(checkpoint)\n\n def load_state_dict(self, state_dict, strict=True):\n total_parameters = 0\n matches = 0\n mismatches = 0\n with torch.no_grad():\n for name, param in self.named_parameters():\n total_parameters += 1\n try:\n param.copy_(state_dict[name])\n matches += 1\n except Exception as e:\n print(f'disable to get parameter : {name}')\n print(e)\n mismatches += 1\n continue\n print(\n f'Load weights : {matches}/{total_parameters} mathches, {mismatches} mismatches.'\n )\n\n def forward(self, x: torch.Tensor, expected, is_train,\n teacher_focing_ratio=None):\n device = x.device\n encoded = self.encoder(x.to(device))\n dec = self.decoder.generate(torch.LongTensor([self.bos_token] * len\n (x))[:, None].to(device), self.max_seq_len, eos_token=self.\n eos_token, context=encoded, temperature=self.temperature)\n return dec\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n\n\nclass Swin(nn.Module):\n\n def __init__(self, FLAGS, train_dataset, checkpoint=None, temp=0.333):\n super(Swin, self).__init__()\n self.bos_token = train_dataset.token_to_id[START]\n self.eos_token = train_dataset.token_to_id[END]\n self.pad_token = train_dataset.token_to_id[PAD]\n self.max_seq_len = FLAGS.swin.max_seq_len\n self.temperature = temp\n sw = create_model('swin_large_patch4_window7_224', checkpoint_path=\n '/opt/ml/input/data/swin.pth')\n sl = deepcopy(sw.layers)\n del sw\n self.encoder = CustomSwinTransformer(sl)\n self.decoder = CustomARWrapper(TransformerWrapper(num_tokens=len(\n train_dataset.id_to_token), max_seq_len=self.max_seq_len,\n attn_layers=Decoder(dim=FLAGS.swin.decoder.dim, depth=FLAGS.\n swin.decoder.depth, heads=FLAGS.swin.decoder.heads,\n attn_on_attn=FLAGS.swin.decoder.args.attn_on_attn, cross_attend\n =FLAGS.swin.decoder.args.cross_attend, ff_glu=FLAGS.swin.\n decoder.args.ff_glu, rel_pos_bias=FLAGS.swin.decoder.args.\n rel_pos_bias, use_scalenorm=FLAGS.swin.decoder.args.\n use_scalenorm)), pad_value=self.pad_token)\n self.criterion = nn.CrossEntropyLoss()\n if checkpoint is not None:\n self.load_state_dict(checkpoint)\n\n def load_state_dict(self, state_dict, strict=True):\n total_parameters = 0\n matches = 0\n mismatches = 0\n with torch.no_grad():\n for name, param in self.named_parameters():\n total_parameters += 1\n try:\n param.copy_(state_dict[name])\n matches += 1\n except Exception as e:\n print(f'disable to get parameter : {name}')\n print(e)\n mismatches += 1\n continue\n print(\n f'Load weights : {matches}/{total_parameters} mathches, {mismatches} mismatches.'\n )\n\n def forward(self, x: torch.Tensor, expected, is_train,\n teacher_focing_ratio=None):\n device = x.device\n encoded = self.encoder(x.to(device))\n dec = self.decoder.generate(torch.LongTensor([self.bos_token] * len\n (x))[:, None].to(device), self.max_seq_len, eos_token=self.\n eos_token, context=encoded, temperature=self.temperature)\n return dec\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n\n\nclass Swin(nn.Module):\n\n def __init__(self, FLAGS, train_dataset, checkpoint=None, temp=0.333):\n super(Swin, self).__init__()\n self.bos_token = train_dataset.token_to_id[START]\n self.eos_token = train_dataset.token_to_id[END]\n self.pad_token = train_dataset.token_to_id[PAD]\n self.max_seq_len = FLAGS.swin.max_seq_len\n self.temperature = temp\n sw = create_model('swin_large_patch4_window7_224', checkpoint_path=\n '/opt/ml/input/data/swin.pth')\n sl = deepcopy(sw.layers)\n del sw\n self.encoder = CustomSwinTransformer(sl)\n self.decoder = CustomARWrapper(TransformerWrapper(num_tokens=len(\n train_dataset.id_to_token), max_seq_len=self.max_seq_len,\n attn_layers=Decoder(dim=FLAGS.swin.decoder.dim, depth=FLAGS.\n swin.decoder.depth, heads=FLAGS.swin.decoder.heads,\n attn_on_attn=FLAGS.swin.decoder.args.attn_on_attn, cross_attend\n =FLAGS.swin.decoder.args.cross_attend, ff_glu=FLAGS.swin.\n decoder.args.ff_glu, rel_pos_bias=FLAGS.swin.decoder.args.\n rel_pos_bias, use_scalenorm=FLAGS.swin.decoder.args.\n use_scalenorm)), pad_value=self.pad_token)\n self.criterion = nn.CrossEntropyLoss()\n if checkpoint is not None:\n self.load_state_dict(checkpoint)\n\n def load_state_dict(self, state_dict, strict=True):\n total_parameters = 0\n matches = 0\n mismatches = 0\n with torch.no_grad():\n for name, param in self.named_parameters():\n total_parameters += 1\n try:\n param.copy_(state_dict[name])\n matches += 1\n except Exception as e:\n print(f'disable to get parameter : {name}')\n print(e)\n mismatches += 1\n continue\n print(\n f'Load weights : {matches}/{total_parameters} mathches, {mismatches} mismatches.'\n )\n <function token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n\n\nclass Swin(nn.Module):\n\n def __init__(self, FLAGS, train_dataset, checkpoint=None, temp=0.333):\n super(Swin, self).__init__()\n self.bos_token = train_dataset.token_to_id[START]\n self.eos_token = train_dataset.token_to_id[END]\n self.pad_token = train_dataset.token_to_id[PAD]\n self.max_seq_len = FLAGS.swin.max_seq_len\n self.temperature = temp\n sw = create_model('swin_large_patch4_window7_224', checkpoint_path=\n '/opt/ml/input/data/swin.pth')\n sl = deepcopy(sw.layers)\n del sw\n self.encoder = CustomSwinTransformer(sl)\n self.decoder = CustomARWrapper(TransformerWrapper(num_tokens=len(\n train_dataset.id_to_token), max_seq_len=self.max_seq_len,\n attn_layers=Decoder(dim=FLAGS.swin.decoder.dim, depth=FLAGS.\n swin.decoder.depth, heads=FLAGS.swin.decoder.heads,\n attn_on_attn=FLAGS.swin.decoder.args.attn_on_attn, cross_attend\n =FLAGS.swin.decoder.args.cross_attend, ff_glu=FLAGS.swin.\n decoder.args.ff_glu, rel_pos_bias=FLAGS.swin.decoder.args.\n rel_pos_bias, use_scalenorm=FLAGS.swin.decoder.args.\n use_scalenorm)), pad_value=self.pad_token)\n self.criterion = nn.CrossEntropyLoss()\n if checkpoint is not None:\n self.load_state_dict(checkpoint)\n <function token>\n <function token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n\n\nclass Swin(nn.Module):\n <function token>\n <function token>\n <function token>\n", "<import token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n" ]
false
98,757
c60dcf928ec12ee9134642a8e51972480f2b4f1c
from typing import Dict, Tuple from uuid import uuid4 from httpx import AsyncClient from conftest import app_base_url, TestUser from main import app async def get_friends(profile_id: str, conn: AsyncClient) -> Dict: return (await conn.get(f"/profiles/{profile_id}/friends")).json() async def get_mutual_friends(profile_id: str, other_profile_id: str, conn: AsyncClient) -> Dict: return (await conn.get(f"/profiles/{profile_id}/" f"friends/{other_profile_id}/mutual_friends")).json() async def get_friend_suggestions(profile_id: str, conn: AsyncClient) -> Dict: return (await conn.get(f"/profiles/{profile_id}/friend_suggestions")).json() async def get_relationship(profile_id: str, other_profile_id: str, conn: AsyncClient) -> Dict: return (await conn.get( f"/profiles/{profile_id}/relationships/{other_profile_id}")) \ .json() async def send_friendship_request(profile_id: str, other_profile_id: str, conn: AsyncClient) -> Dict: return (await conn.post(f"/profiles/{profile_id}/" f"outgoing_friend_requests/{other_profile_id}")) \ .json() async def accept_friendship_request(profile_id: str, other_profile_id: str, conn: AsyncClient) -> Dict: return (await conn.post(f"/profiles/{profile_id}/" f"friends/{other_profile_id}")).json() async def reject_friendship_request(profile_id: str, requester_profile_id: str, conn: AsyncClient) -> Dict: return (await conn.delete(f"/profiles/{profile_id}/" f"incoming_friend_requests/" f"{requester_profile_id}")).json() async def cancel_outgoing_friend_request(profile_id: str, target_profile_id: str, conn: AsyncClient) -> Dict: return (await conn.delete( f"/profiles/{profile_id}/" f"outgoing_friend_requests/{target_profile_id}")).json() async def remove_friend(profile: TestUser, friend_profile: TestUser) -> Dict: return (await profile.conn.delete(f"/profiles/{profile.id}/" f"friends/{friend_profile.id}")).json() async def become_friends(profile: TestUser, other_profile: TestUser): await send_friendship_request( other_profile.id, profile.id, other_profile.conn) await accept_friendship_request( profile.id, other_profile.id, profile.conn) async def register_user(username: str, email: str, password: str): async with AsyncClient(app=app, base_url=app_base_url) as conn: return await conn.post("/register", json=dict( username=username, email=email, password=password)) async def register_random_user() -> Tuple[Dict, str]: uid = str(uuid4())[:32] username, email, password = uid, f"{uid}@bunnybook.com", "testpassword" return (await register_user(username, email, password)).json(), password async def do_login(email: str, password: str): async with AsyncClient(app=app, base_url=app_base_url) as conn: return await conn.post("/login", json=dict( email=email, password=password))
[ "from typing import Dict, Tuple\nfrom uuid import uuid4\n\nfrom httpx import AsyncClient\n\nfrom conftest import app_base_url, TestUser\nfrom main import app\n\n\nasync def get_friends(profile_id: str, conn: AsyncClient) -> Dict:\n return (await conn.get(f\"/profiles/{profile_id}/friends\")).json()\n\n\nasync def get_mutual_friends(profile_id: str, other_profile_id: str,\n conn: AsyncClient) -> Dict:\n return (await conn.get(f\"/profiles/{profile_id}/\"\n f\"friends/{other_profile_id}/mutual_friends\")).json()\n\n\nasync def get_friend_suggestions(profile_id: str, conn: AsyncClient) -> Dict:\n return (await conn.get(f\"/profiles/{profile_id}/friend_suggestions\")).json()\n\n\nasync def get_relationship(profile_id: str,\n other_profile_id: str,\n conn: AsyncClient) -> Dict:\n return (await conn.get(\n f\"/profiles/{profile_id}/relationships/{other_profile_id}\")) \\\n .json()\n\n\nasync def send_friendship_request(profile_id: str,\n other_profile_id: str,\n conn: AsyncClient) -> Dict:\n return (await conn.post(f\"/profiles/{profile_id}/\"\n f\"outgoing_friend_requests/{other_profile_id}\")) \\\n .json()\n\n\nasync def accept_friendship_request(profile_id: str,\n other_profile_id: str,\n conn: AsyncClient) -> Dict:\n return (await conn.post(f\"/profiles/{profile_id}/\"\n f\"friends/{other_profile_id}\")).json()\n\n\nasync def reject_friendship_request(profile_id: str,\n requester_profile_id: str,\n conn: AsyncClient) -> Dict:\n return (await conn.delete(f\"/profiles/{profile_id}/\"\n f\"incoming_friend_requests/\"\n f\"{requester_profile_id}\")).json()\n\n\nasync def cancel_outgoing_friend_request(profile_id: str,\n target_profile_id: str,\n conn: AsyncClient) -> Dict:\n return (await conn.delete(\n f\"/profiles/{profile_id}/\"\n f\"outgoing_friend_requests/{target_profile_id}\")).json()\n\n\nasync def remove_friend(profile: TestUser, friend_profile: TestUser) -> Dict:\n return (await profile.conn.delete(f\"/profiles/{profile.id}/\"\n f\"friends/{friend_profile.id}\")).json()\n\n\nasync def become_friends(profile: TestUser, other_profile: TestUser):\n await send_friendship_request(\n other_profile.id, profile.id, other_profile.conn)\n await accept_friendship_request(\n profile.id, other_profile.id, profile.conn)\n\n\nasync def register_user(username: str, email: str, password: str):\n async with AsyncClient(app=app,\n base_url=app_base_url) as conn:\n return await conn.post(\"/register\", json=dict(\n username=username,\n email=email,\n password=password))\n\n\nasync def register_random_user() -> Tuple[Dict, str]:\n uid = str(uuid4())[:32]\n username, email, password = uid, f\"{uid}@bunnybook.com\", \"testpassword\"\n return (await register_user(username, email, password)).json(), password\n\n\nasync def do_login(email: str, password: str):\n async with AsyncClient(app=app,\n base_url=app_base_url) as conn:\n return await conn.post(\"/login\", json=dict(\n email=email,\n password=password))\n", "from typing import Dict, Tuple\nfrom uuid import uuid4\nfrom httpx import AsyncClient\nfrom conftest import app_base_url, TestUser\nfrom main import app\n\n\nasync def get_friends(profile_id: str, conn: AsyncClient) ->Dict:\n return (await conn.get(f'/profiles/{profile_id}/friends')).json()\n\n\nasync def get_mutual_friends(profile_id: str, other_profile_id: str, conn:\n AsyncClient) ->Dict:\n return (await conn.get(\n f'/profiles/{profile_id}/friends/{other_profile_id}/mutual_friends')\n ).json()\n\n\nasync def get_friend_suggestions(profile_id: str, conn: AsyncClient) ->Dict:\n return (await conn.get(f'/profiles/{profile_id}/friend_suggestions')).json(\n )\n\n\nasync def get_relationship(profile_id: str, other_profile_id: str, conn:\n AsyncClient) ->Dict:\n return (await conn.get(\n f'/profiles/{profile_id}/relationships/{other_profile_id}')).json()\n\n\nasync def send_friendship_request(profile_id: str, other_profile_id: str,\n conn: AsyncClient) ->Dict:\n return (await conn.post(\n f'/profiles/{profile_id}/outgoing_friend_requests/{other_profile_id}')\n ).json()\n\n\nasync def accept_friendship_request(profile_id: str, other_profile_id: str,\n conn: AsyncClient) ->Dict:\n return (await conn.post(\n f'/profiles/{profile_id}/friends/{other_profile_id}')).json()\n\n\nasync def reject_friendship_request(profile_id: str, requester_profile_id:\n str, conn: AsyncClient) ->Dict:\n return (await conn.delete(\n f'/profiles/{profile_id}/incoming_friend_requests/{requester_profile_id}'\n )).json()\n\n\nasync def cancel_outgoing_friend_request(profile_id: str, target_profile_id:\n str, conn: AsyncClient) ->Dict:\n return (await conn.delete(\n f'/profiles/{profile_id}/outgoing_friend_requests/{target_profile_id}')\n ).json()\n\n\nasync def remove_friend(profile: TestUser, friend_profile: TestUser) ->Dict:\n return (await profile.conn.delete(\n f'/profiles/{profile.id}/friends/{friend_profile.id}')).json()\n\n\nasync def become_friends(profile: TestUser, other_profile: TestUser):\n await send_friendship_request(other_profile.id, profile.id,\n other_profile.conn)\n await accept_friendship_request(profile.id, other_profile.id, profile.conn)\n\n\nasync def register_user(username: str, email: str, password: str):\n async with AsyncClient(app=app, base_url=app_base_url) as conn:\n return await conn.post('/register', json=dict(username=username,\n email=email, password=password))\n\n\nasync def register_random_user() ->Tuple[Dict, str]:\n uid = str(uuid4())[:32]\n username, email, password = uid, f'{uid}@bunnybook.com', 'testpassword'\n return (await register_user(username, email, password)).json(), password\n\n\nasync def do_login(email: str, password: str):\n async with AsyncClient(app=app, base_url=app_base_url) as conn:\n return await conn.post('/login', json=dict(email=email, password=\n password))\n", "<import token>\n\n\nasync def get_friends(profile_id: str, conn: AsyncClient) ->Dict:\n return (await conn.get(f'/profiles/{profile_id}/friends')).json()\n\n\nasync def get_mutual_friends(profile_id: str, other_profile_id: str, conn:\n AsyncClient) ->Dict:\n return (await conn.get(\n f'/profiles/{profile_id}/friends/{other_profile_id}/mutual_friends')\n ).json()\n\n\nasync def get_friend_suggestions(profile_id: str, conn: AsyncClient) ->Dict:\n return (await conn.get(f'/profiles/{profile_id}/friend_suggestions')).json(\n )\n\n\nasync def get_relationship(profile_id: str, other_profile_id: str, conn:\n AsyncClient) ->Dict:\n return (await conn.get(\n f'/profiles/{profile_id}/relationships/{other_profile_id}')).json()\n\n\nasync def send_friendship_request(profile_id: str, other_profile_id: str,\n conn: AsyncClient) ->Dict:\n return (await conn.post(\n f'/profiles/{profile_id}/outgoing_friend_requests/{other_profile_id}')\n ).json()\n\n\nasync def accept_friendship_request(profile_id: str, other_profile_id: str,\n conn: AsyncClient) ->Dict:\n return (await conn.post(\n f'/profiles/{profile_id}/friends/{other_profile_id}')).json()\n\n\nasync def reject_friendship_request(profile_id: str, requester_profile_id:\n str, conn: AsyncClient) ->Dict:\n return (await conn.delete(\n f'/profiles/{profile_id}/incoming_friend_requests/{requester_profile_id}'\n )).json()\n\n\nasync def cancel_outgoing_friend_request(profile_id: str, target_profile_id:\n str, conn: AsyncClient) ->Dict:\n return (await conn.delete(\n f'/profiles/{profile_id}/outgoing_friend_requests/{target_profile_id}')\n ).json()\n\n\nasync def remove_friend(profile: TestUser, friend_profile: TestUser) ->Dict:\n return (await profile.conn.delete(\n f'/profiles/{profile.id}/friends/{friend_profile.id}')).json()\n\n\nasync def become_friends(profile: TestUser, other_profile: TestUser):\n await send_friendship_request(other_profile.id, profile.id,\n other_profile.conn)\n await accept_friendship_request(profile.id, other_profile.id, profile.conn)\n\n\nasync def register_user(username: str, email: str, password: str):\n async with AsyncClient(app=app, base_url=app_base_url) as conn:\n return await conn.post('/register', json=dict(username=username,\n email=email, password=password))\n\n\nasync def register_random_user() ->Tuple[Dict, str]:\n uid = str(uuid4())[:32]\n username, email, password = uid, f'{uid}@bunnybook.com', 'testpassword'\n return (await register_user(username, email, password)).json(), password\n\n\nasync def do_login(email: str, password: str):\n async with AsyncClient(app=app, base_url=app_base_url) as conn:\n return await conn.post('/login', json=dict(email=email, password=\n password))\n", "<import token>\n<code token>\n" ]
false
98,758
3873b5cdb77b5f44157e0236d30cf11c0c0dbd8c
#Ismael Garrido pi_approximation.py def main(): print("This program approximates the value of pi") print("by summing a series of n terms to an extent determined by the user") terms = int(input("Please enter the amount of iterations you want the program to make: ")) result = 0 sign = 1 for n in range(terms): result += sign/(2*n+1) sign = -sign print("The approximated value of pi is", 4*result) main() """ This program approximates the value of pi by summing a series of n terms to an extent determined by the user Please enter the amount of iterations you want the program to make: 1 The approximated value of pi is 4.0 >>> main() This program approximates the value of pi by summing a series of n terms to an extent determined by the user Please enter the amount of iterations you want the program to make: 2 The approximated value of pi is 2.666666666666667 >>> main() This program approximates the value of pi by summing a series of n terms to an extent determined by the user Please enter the amount of iterations you want the program to make: 3 The approximated value of pi is 3.466666666666667 >>> main() This program approximates the value of pi by summing a series of n terms to an extent determined by the user Please enter the amount of iterations you want the program to make: 4 The approximated value of pi is 2.8952380952380956 """
[ "#Ismael Garrido pi_approximation.py\r\n\r\ndef main():\r\n print(\"This program approximates the value of pi\")\r\n print(\"by summing a series of n terms to an extent determined by the user\")\r\n terms = int(input(\"Please enter the amount of iterations you want the program to make: \"))\r\n result = 0\r\n sign = 1\r\n for n in range(terms):\r\n result += sign/(2*n+1)\r\n sign = -sign\r\n print(\"The approximated value of pi is\", 4*result)\r\n\r\nmain()\r\n\r\n\"\"\"\r\nThis program approximates the value of pi\r\nby summing a series of n terms to an extent determined by the user\r\nPlease enter the amount of iterations you want the program to make: 1\r\nThe approximated value of pi is 4.0\r\n>>> main()\r\nThis program approximates the value of pi\r\nby summing a series of n terms to an extent determined by the user\r\nPlease enter the amount of iterations you want the program to make: 2\r\nThe approximated value of pi is 2.666666666666667\r\n>>> main()\r\nThis program approximates the value of pi\r\nby summing a series of n terms to an extent determined by the user\r\nPlease enter the amount of iterations you want the program to make: 3\r\nThe approximated value of pi is 3.466666666666667\r\n>>> main()\r\nThis program approximates the value of pi\r\nby summing a series of n terms to an extent determined by the user\r\nPlease enter the amount of iterations you want the program to make: 4\r\nThe approximated value of pi is 2.8952380952380956\r\n\"\"\"\r\n", "def main():\n print('This program approximates the value of pi')\n print('by summing a series of n terms to an extent determined by the user')\n terms = int(input(\n 'Please enter the amount of iterations you want the program to make: ')\n )\n result = 0\n sign = 1\n for n in range(terms):\n result += sign / (2 * n + 1)\n sign = -sign\n print('The approximated value of pi is', 4 * result)\n\n\nmain()\n<docstring token>\n", "def main():\n print('This program approximates the value of pi')\n print('by summing a series of n terms to an extent determined by the user')\n terms = int(input(\n 'Please enter the amount of iterations you want the program to make: ')\n )\n result = 0\n sign = 1\n for n in range(terms):\n result += sign / (2 * n + 1)\n sign = -sign\n print('The approximated value of pi is', 4 * result)\n\n\n<code token>\n<docstring token>\n", "<function token>\n<code token>\n<docstring token>\n" ]
false
98,759
88faa5db4877951cea639d25854d06d8fc1bb930
t = int(input()) for i in range(t): n = int(input()) words = [input() for i in range(n)] s01 = [] s10 = [] set01 = set() set10 = set() s00 = False s11 = False for i, word in enumerate(words): if word[0] == "1" and word[-1] == "0": s10.append(i+1); set10.add(word) if word[0] == "0" and word[-1] == "1": s01.append(i+1); set01.add(word) if word[0] == "0" and word[-1] == "0": s00 = True if word[0] == "1" and word[-1] == "1": s11 = True s01c = len(s01) s10c = len(s10) if (s01c + s10c == 0) and s00 and s11: print(-1) continue reverse = [] try: while True: if abs(s01c - s10c) <= 1: break if s01c > s10c: i = s01.pop() while words[i-1][::-1] in set10: i = s01.pop(); s01c -= 1; s10c += 1; reverse.append(i) else: i = s10.pop() while words[i-1][::-1] in set01: i = s10.pop() s01c += 1; s10c -= 1; reverse.append(i) except: print(-1) print(len(reverse)) print(" ".join(map(str, reverse)))
[ "t = int(input())\nfor i in range(t):\n n = int(input())\n words = [input() for i in range(n)]\n\n s01 = []\n s10 = []\n set01 = set()\n set10 = set()\n s00 = False\n s11 = False\n for i, word in enumerate(words):\n if word[0] == \"1\" and word[-1] == \"0\": s10.append(i+1); set10.add(word)\n if word[0] == \"0\" and word[-1] == \"1\": s01.append(i+1); set01.add(word)\n if word[0] == \"0\" and word[-1] == \"0\": s00 = True\n if word[0] == \"1\" and word[-1] == \"1\": s11 = True\n \n s01c = len(s01)\n s10c = len(s10)\n\n if (s01c + s10c == 0) and s00 and s11:\n print(-1)\n continue\n \n reverse = []\n try:\n while True:\n if abs(s01c - s10c) <= 1: break\n\n if s01c > s10c:\n i = s01.pop()\n while words[i-1][::-1] in set10: i = s01.pop(); \n s01c -= 1;\n s10c += 1;\n reverse.append(i)\n else:\n i = s10.pop()\n while words[i-1][::-1] in set01: i = s10.pop()\n s01c += 1;\n s10c -= 1;\n reverse.append(i)\n except:\n print(-1)\n print(len(reverse))\n print(\" \".join(map(str, reverse)))\n \n", "t = int(input())\nfor i in range(t):\n n = int(input())\n words = [input() for i in range(n)]\n s01 = []\n s10 = []\n set01 = set()\n set10 = set()\n s00 = False\n s11 = False\n for i, word in enumerate(words):\n if word[0] == '1' and word[-1] == '0':\n s10.append(i + 1)\n set10.add(word)\n if word[0] == '0' and word[-1] == '1':\n s01.append(i + 1)\n set01.add(word)\n if word[0] == '0' and word[-1] == '0':\n s00 = True\n if word[0] == '1' and word[-1] == '1':\n s11 = True\n s01c = len(s01)\n s10c = len(s10)\n if s01c + s10c == 0 and s00 and s11:\n print(-1)\n continue\n reverse = []\n try:\n while True:\n if abs(s01c - s10c) <= 1:\n break\n if s01c > s10c:\n i = s01.pop()\n while words[i - 1][::-1] in set10:\n i = s01.pop()\n s01c -= 1\n s10c += 1\n reverse.append(i)\n else:\n i = s10.pop()\n while words[i - 1][::-1] in set01:\n i = s10.pop()\n s01c += 1\n s10c -= 1\n reverse.append(i)\n except:\n print(-1)\n print(len(reverse))\n print(' '.join(map(str, reverse)))\n", "<assignment token>\nfor i in range(t):\n n = int(input())\n words = [input() for i in range(n)]\n s01 = []\n s10 = []\n set01 = set()\n set10 = set()\n s00 = False\n s11 = False\n for i, word in enumerate(words):\n if word[0] == '1' and word[-1] == '0':\n s10.append(i + 1)\n set10.add(word)\n if word[0] == '0' and word[-1] == '1':\n s01.append(i + 1)\n set01.add(word)\n if word[0] == '0' and word[-1] == '0':\n s00 = True\n if word[0] == '1' and word[-1] == '1':\n s11 = True\n s01c = len(s01)\n s10c = len(s10)\n if s01c + s10c == 0 and s00 and s11:\n print(-1)\n continue\n reverse = []\n try:\n while True:\n if abs(s01c - s10c) <= 1:\n break\n if s01c > s10c:\n i = s01.pop()\n while words[i - 1][::-1] in set10:\n i = s01.pop()\n s01c -= 1\n s10c += 1\n reverse.append(i)\n else:\n i = s10.pop()\n while words[i - 1][::-1] in set01:\n i = s10.pop()\n s01c += 1\n s10c -= 1\n reverse.append(i)\n except:\n print(-1)\n print(len(reverse))\n print(' '.join(map(str, reverse)))\n", "<assignment token>\n<code token>\n" ]
false
98,760
447dd7ae9aee713afea82ceaf1488da2a3fec83b
from rest_framework import serializers from HttpTestcas.models import Testsuite from HttpTestcas.serializers.project import ProjectModuleSerializer # from HttpTestcas.models.testsuite2testcase import Testsuite2Testcase from HttpTestcas.models import Testcases # class Testsuite2TestcaseModuleSerializer(serializers.ModelSerializer): # class Meta: # model = Testsuite2Testcase # fields = ('id', 'name', 'is_delete') class TestSuiteSerializer(serializers.ModelSerializer): project = ProjectModuleSerializer() testcases = serializers.SerializerMethodField() # Testsuite2Testcase = Testsuite2TestcaseModuleSerializer() def get_testcases(self, obj): result = obj.testcases.values('id', 'name', 'is_delete') return result class Meta: model = Testsuite fields = '__all__' class TestCreatsuiteSerializer(serializers.ModelSerializer): class Meta: model = Testsuite exclude = ('status', 'testcases')
[ "from rest_framework import serializers\nfrom HttpTestcas.models import Testsuite\nfrom HttpTestcas.serializers.project import ProjectModuleSerializer\n# from HttpTestcas.models.testsuite2testcase import Testsuite2Testcase\nfrom HttpTestcas.models import Testcases\n\n\n# class Testsuite2TestcaseModuleSerializer(serializers.ModelSerializer):\n# class Meta:\n# model = Testsuite2Testcase\n# fields = ('id', 'name', 'is_delete')\n\n\nclass TestSuiteSerializer(serializers.ModelSerializer):\n project = ProjectModuleSerializer()\n testcases = serializers.SerializerMethodField()\n\n # Testsuite2Testcase = Testsuite2TestcaseModuleSerializer()\n\n def get_testcases(self, obj):\n result = obj.testcases.values('id', 'name', 'is_delete')\n return result\n\n class Meta:\n model = Testsuite\n fields = '__all__'\n\n\nclass TestCreatsuiteSerializer(serializers.ModelSerializer):\n class Meta:\n model = Testsuite\n exclude = ('status', 'testcases')\n", "from rest_framework import serializers\nfrom HttpTestcas.models import Testsuite\nfrom HttpTestcas.serializers.project import ProjectModuleSerializer\nfrom HttpTestcas.models import Testcases\n\n\nclass TestSuiteSerializer(serializers.ModelSerializer):\n project = ProjectModuleSerializer()\n testcases = serializers.SerializerMethodField()\n\n def get_testcases(self, obj):\n result = obj.testcases.values('id', 'name', 'is_delete')\n return result\n\n\n class Meta:\n model = Testsuite\n fields = '__all__'\n\n\nclass TestCreatsuiteSerializer(serializers.ModelSerializer):\n\n\n class Meta:\n model = Testsuite\n exclude = 'status', 'testcases'\n", "<import token>\n\n\nclass TestSuiteSerializer(serializers.ModelSerializer):\n project = ProjectModuleSerializer()\n testcases = serializers.SerializerMethodField()\n\n def get_testcases(self, obj):\n result = obj.testcases.values('id', 'name', 'is_delete')\n return result\n\n\n class Meta:\n model = Testsuite\n fields = '__all__'\n\n\nclass TestCreatsuiteSerializer(serializers.ModelSerializer):\n\n\n class Meta:\n model = Testsuite\n exclude = 'status', 'testcases'\n", "<import token>\n\n\nclass TestSuiteSerializer(serializers.ModelSerializer):\n <assignment token>\n <assignment token>\n\n def get_testcases(self, obj):\n result = obj.testcases.values('id', 'name', 'is_delete')\n return result\n\n\n class Meta:\n model = Testsuite\n fields = '__all__'\n\n\nclass TestCreatsuiteSerializer(serializers.ModelSerializer):\n\n\n class Meta:\n model = Testsuite\n exclude = 'status', 'testcases'\n", "<import token>\n\n\nclass TestSuiteSerializer(serializers.ModelSerializer):\n <assignment token>\n <assignment token>\n <function token>\n\n\n class Meta:\n model = Testsuite\n fields = '__all__'\n\n\nclass TestCreatsuiteSerializer(serializers.ModelSerializer):\n\n\n class Meta:\n model = Testsuite\n exclude = 'status', 'testcases'\n", "<import token>\n<class token>\n\n\nclass TestCreatsuiteSerializer(serializers.ModelSerializer):\n\n\n class Meta:\n model = Testsuite\n exclude = 'status', 'testcases'\n", "<import token>\n<class token>\n<class token>\n" ]
false
98,761
2a68719904eafed473a154fa352139eb74e7a266
import os, sys, subprocess, tempfile, gzip, cStringIO from boto.s3.connection import S3Connection from boto.s3.key import Key conn = S3Connection() bucket = conn.get_bucket("openinternet.widgets.sunlightfoundation.com") base = sys.argv[1] for f in os.listdir(base): combined = os.path.join(base, f) if os.path.isdir(combined): for j in os.listdir(combined): print "uploading", j k = Key(bucket) k.key = os.path.join("data", j) gzdata = cStringIO.StringIO() gzfile = gzip.GzipFile(fileobj=gzdata, mode="wb") gzfile.write(open(os.path.join(combined, j)).read()) gzfile.close() gzdata.seek(0) k.set_metadata('Content-Type', 'application/json') k.set_metadata('Content-Encoding', 'gzip') k.set_contents_from_file(gzdata) k.set_acl('public-read')
[ "import os, sys, subprocess, tempfile, gzip, cStringIO\nfrom boto.s3.connection import S3Connection\nfrom boto.s3.key import Key\n\nconn = S3Connection()\nbucket = conn.get_bucket(\"openinternet.widgets.sunlightfoundation.com\")\n\nbase = sys.argv[1]\nfor f in os.listdir(base):\n combined = os.path.join(base, f)\n if os.path.isdir(combined):\n for j in os.listdir(combined):\n print \"uploading\", j\n\n k = Key(bucket)\n k.key = os.path.join(\"data\", j)\n\n gzdata = cStringIO.StringIO()\n gzfile = gzip.GzipFile(fileobj=gzdata, mode=\"wb\")\n\n gzfile.write(open(os.path.join(combined, j)).read())\n gzfile.close()\n\n gzdata.seek(0)\n\n k.set_metadata('Content-Type', 'application/json')\n k.set_metadata('Content-Encoding', 'gzip')\n k.set_contents_from_file(gzdata)\n k.set_acl('public-read')" ]
true
98,762
a55c30f061b5c76a8cda317a8a1e300256be51d4
import urllib2 print "OK"
[ "import urllib2\nprint \"OK\"" ]
true
98,763
8951b3ed776912900aa4079c780c6b4f400dc6f9
import os from manager.shared import koality_root from manager.shared.script import Script, ShellScript from scripts import package_scripts class Packager(object): version = '0.2-internal-1' packaged_directory = os.path.join('/tmp', 'koality', version) internal_packaged_directory = os.path.abspath(os.path.join(packaged_directory, 'koality')) def run(self, installable=False): self._run_with_exceptions(package_scripts) if installable: self._run_with_exceptions([Packager.RepackageScript, Packager.AddInstallationScripts, Packager.TarScript]) def _run_with_exceptions(self, scripts): for script in scripts: if not script.run(): raise ScriptFailedException(script) return True class RepackageScript(ShellScript): @classmethod def get_script(cls): return cls.multiline( 'rm -rf %s' % Packager.packaged_directory, 'mkdir -p %s' % Packager.packaged_directory, 'cp -r %s %s' % (koality_root, Packager.internal_packaged_directory), 'rm -rf %s' % os.path.join(Packager.internal_packaged_directory, 'manager', 'package'), 'rm -rf %s' % os.path.join(Packager.internal_packaged_directory, 'dependencies', 'cached'), 'rm -rf %s' % os.path.join(Packager.internal_packaged_directory, '.git') ) class AddInstallationScripts(Script): @classmethod def run(cls): install_script_path = os.path.join(Packager.packaged_directory, 'install_script') with open(install_script_path, 'w') as install_script: install_script.write(ShellScript.multiline( '#!/bin/sh', 'cd $(dirname $0)', 'mv koality/* .', 'rm koality/.*', 'rmdir koality', 'sudo ./koality.py install' )) os.chmod(install_script_path, 0777) upgrade_script_path = os.path.join(Packager.packaged_directory, 'upgrade_script') with open(upgrade_script_path, 'w') as upgrade_script: upgrade_script.write(ShellScript.multiline( '#!/bin/sh', 'cd $(dirname $0)', 'oldroot=$(readlink -f /etc/koality/root)', 'newroot=$(readlink -m $oldroot/../%s)' % Packager.version, 'if [ -e "$newroot" ]; then', ' rm -rf $newroot.bak', ' sudo chown -R lt3:lt3 $newroot/..', ' mv $newroot $newroot.bak', 'fi', 'mv koality $newroot', 'cd $newroot', 'sudo ./koality.py upgrade > $(dirname $0)/upgrade.log 2>&1' )) os.chmod(upgrade_script_path, 0777) revert_script_path = os.path.join(Packager.packaged_directory, 'revert_script') with open(revert_script_path, 'w') as revert_script: revert_script.write(ShellScript.multiline( '#!/bin/sh', 'koalityroot=$(readlink -f /etc/koality/root)', 'if [ -e "${koalityroot}.bak" ]; then', ' mv "${koalityroot}.bak" "$koalityroot"', ' sudo service koality restart', 'fi', )) os.chmod(revert_script_path, 0777) return True class TarScript(ShellScript): @classmethod def get_script(cls): tarfile = 'koality-%s.tar.gz' % Packager.version return cls.multiline( 'cd %s' % os.path.join(Packager.packaged_directory, os.pardir), 'tar -czf %s %s' % ( tarfile, Packager.version ), 'rm -rf %s' % Packager.packaged_directory, 'mv %s %s' % ( tarfile, os.path.join(koality_root, os.pardir) ) ) class ScriptFailedException(Exception): pass
[ "import os\n\nfrom manager.shared import koality_root\nfrom manager.shared.script import Script, ShellScript\nfrom scripts import package_scripts\n\n\nclass Packager(object):\n\tversion = '0.2-internal-1'\n\tpackaged_directory = os.path.join('/tmp', 'koality', version)\n\tinternal_packaged_directory = os.path.abspath(os.path.join(packaged_directory, 'koality'))\n\n\tdef run(self, installable=False):\n\t\tself._run_with_exceptions(package_scripts)\n\n\t\tif installable:\n\t\t\tself._run_with_exceptions([Packager.RepackageScript, Packager.AddInstallationScripts, Packager.TarScript])\n\n\tdef _run_with_exceptions(self, scripts):\n\t\tfor script in scripts:\n\t\t\tif not script.run():\n\t\t\t\traise ScriptFailedException(script)\n\t\treturn True\n\n\tclass RepackageScript(ShellScript):\n\t\t@classmethod\n\t\tdef get_script(cls):\n\t\t\treturn cls.multiline(\n\t\t\t\t'rm -rf %s' % Packager.packaged_directory,\n\t\t\t\t'mkdir -p %s' % Packager.packaged_directory,\n\t\t\t\t'cp -r %s %s' % (koality_root, Packager.internal_packaged_directory),\n\t\t\t\t'rm -rf %s' % os.path.join(Packager.internal_packaged_directory, 'manager', 'package'),\n\t\t\t\t'rm -rf %s' % os.path.join(Packager.internal_packaged_directory, 'dependencies', 'cached'),\n\t\t\t\t'rm -rf %s' % os.path.join(Packager.internal_packaged_directory, '.git')\n\t\t\t)\n\n\tclass AddInstallationScripts(Script):\n\t\t@classmethod\n\t\tdef run(cls):\n\t\t\tinstall_script_path = os.path.join(Packager.packaged_directory, 'install_script')\n\t\t\twith open(install_script_path, 'w') as install_script:\n\t\t\t\tinstall_script.write(ShellScript.multiline(\n\t\t\t\t\t'#!/bin/sh',\n\t\t\t\t\t'cd $(dirname $0)',\n\t\t\t\t\t'mv koality/* .',\n\t\t\t\t\t'rm koality/.*',\n\t\t\t\t\t'rmdir koality',\n\t\t\t\t\t'sudo ./koality.py install'\n\t\t\t\t))\n\t\t\t\tos.chmod(install_script_path, 0777)\n\t\t\tupgrade_script_path = os.path.join(Packager.packaged_directory, 'upgrade_script')\n\t\t\twith open(upgrade_script_path, 'w') as upgrade_script:\n\t\t\t\tupgrade_script.write(ShellScript.multiline(\n\t\t\t\t\t'#!/bin/sh',\n\t\t\t\t\t'cd $(dirname $0)',\n\t\t\t\t\t'oldroot=$(readlink -f /etc/koality/root)',\n\t\t\t\t\t'newroot=$(readlink -m $oldroot/../%s)' % Packager.version,\n\t\t\t\t\t'if [ -e \"$newroot\" ]; then',\n\t\t\t\t\t'\trm -rf $newroot.bak',\n\t\t\t\t\t'\tsudo chown -R lt3:lt3 $newroot/..',\n\t\t\t\t\t'\tmv $newroot $newroot.bak',\n\t\t\t\t\t'fi',\n\t\t\t\t\t'mv koality $newroot',\n\t\t\t\t\t'cd $newroot',\n\t\t\t\t\t'sudo ./koality.py upgrade > $(dirname $0)/upgrade.log 2>&1'\n\t\t\t\t))\n\t\t\t\tos.chmod(upgrade_script_path, 0777)\n\t\t\trevert_script_path = os.path.join(Packager.packaged_directory, 'revert_script')\n\t\t\twith open(revert_script_path, 'w') as revert_script:\n\t\t\t\trevert_script.write(ShellScript.multiline(\n\t\t\t\t\t'#!/bin/sh',\n\t\t\t\t\t'koalityroot=$(readlink -f /etc/koality/root)',\n\t\t\t\t\t'if [ -e \"${koalityroot}.bak\" ]; then',\n\t\t\t\t\t'\tmv \"${koalityroot}.bak\" \"$koalityroot\"',\n\t\t\t\t\t'\tsudo service koality restart',\n\t\t\t\t\t'fi',\n\t\t\t\t))\n\t\t\t\tos.chmod(revert_script_path, 0777)\n\t\t\treturn True\n\n\tclass TarScript(ShellScript):\n\t\t@classmethod\n\t\tdef get_script(cls):\n\t\t\ttarfile = 'koality-%s.tar.gz' % Packager.version\n\t\t\treturn cls.multiline(\n\t\t\t\t'cd %s' % os.path.join(Packager.packaged_directory, os.pardir),\n\t\t\t\t'tar -czf %s %s' % (\n\t\t\t\t\ttarfile,\n\t\t\t\t\tPackager.version\n\t\t\t\t),\n\t\t\t\t'rm -rf %s' % Packager.packaged_directory,\n\t\t\t\t'mv %s %s' % (\n\t\t\t\t\ttarfile,\n\t\t\t\t\tos.path.join(koality_root, os.pardir)\n\t\t\t\t)\n\t\t\t)\n\n\nclass ScriptFailedException(Exception):\n\tpass\n" ]
true
98,764
cd11f25af7436028684d75320582855500cf971d
import os, sys, glob import argparse import numpy as np import pyfits # np.seterr(invalid='raise') import polsalt datadir = os.path.dirname(polsalt.__file__)+'/data/' from polsalt.imred import imred from polsalt.specpolwavmap import specpolwavmap from polsalt.specpolextract import specpolextract from polsalt.specpolrawstokes import specpolrawstokes from polsalt.specpolfinalstokes import specpolfinalstokes logfile = 'temp.log' #raw stokes #infile_list = sorted(glob.glob('e*0[6-9].fits')) # subselection infile_list = sorted(glob.glob('e*fits')) specpolrawstokes(infile_list, logfile=logfile) #final stokes #polcal = 'polcal0.txt' # null calibration #infile_list = sorted(glob.glob('*_h[0,2]*.fits')) # subselection polcal = 'polcal.txt' infile_list = sorted(glob.glob('*_h*.fits')) specpolfinalstokes(infile_list, polcal=polcal, logfile=logfile)
[ "import os, sys, glob\nimport argparse\nimport numpy as np\nimport pyfits\n\n# np.seterr(invalid='raise')\n\nimport polsalt\ndatadir = os.path.dirname(polsalt.__file__)+'/data/'\nfrom polsalt.imred import imred\n\nfrom polsalt.specpolwavmap import specpolwavmap\nfrom polsalt.specpolextract import specpolextract\nfrom polsalt.specpolrawstokes import specpolrawstokes\nfrom polsalt.specpolfinalstokes import specpolfinalstokes\n\nlogfile = 'temp.log'\n#raw stokes\n#infile_list = sorted(glob.glob('e*0[6-9].fits')) # subselection\ninfile_list = sorted(glob.glob('e*fits'))\nspecpolrawstokes(infile_list, logfile=logfile)\n\n#final stokes\n#polcal = 'polcal0.txt' # null calibration\n#infile_list = sorted(glob.glob('*_h[0,2]*.fits')) # subselection \npolcal = 'polcal.txt'\ninfile_list = sorted(glob.glob('*_h*.fits'))\nspecpolfinalstokes(infile_list, polcal=polcal, logfile=logfile)\n", "import os, sys, glob\nimport argparse\nimport numpy as np\nimport pyfits\nimport polsalt\ndatadir = os.path.dirname(polsalt.__file__) + '/data/'\nfrom polsalt.imred import imred\nfrom polsalt.specpolwavmap import specpolwavmap\nfrom polsalt.specpolextract import specpolextract\nfrom polsalt.specpolrawstokes import specpolrawstokes\nfrom polsalt.specpolfinalstokes import specpolfinalstokes\nlogfile = 'temp.log'\ninfile_list = sorted(glob.glob('e*fits'))\nspecpolrawstokes(infile_list, logfile=logfile)\npolcal = 'polcal.txt'\ninfile_list = sorted(glob.glob('*_h*.fits'))\nspecpolfinalstokes(infile_list, polcal=polcal, logfile=logfile)\n", "<import token>\ndatadir = os.path.dirname(polsalt.__file__) + '/data/'\n<import token>\nlogfile = 'temp.log'\ninfile_list = sorted(glob.glob('e*fits'))\nspecpolrawstokes(infile_list, logfile=logfile)\npolcal = 'polcal.txt'\ninfile_list = sorted(glob.glob('*_h*.fits'))\nspecpolfinalstokes(infile_list, polcal=polcal, logfile=logfile)\n", "<import token>\n<assignment token>\n<import token>\n<assignment token>\nspecpolrawstokes(infile_list, logfile=logfile)\n<assignment token>\nspecpolfinalstokes(infile_list, polcal=polcal, logfile=logfile)\n", "<import token>\n<assignment token>\n<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
98,765
80182c3dc80ce01595f38568d3d2af63f6f718ba
from abc import ABC, abstractmethod, abstractproperty class IUser(ABC): """ abstract class for homeless shelter site admin """ @property @abstractproperty def user_id(self): pass @property @abstractproperty def username(self): pass @property @abstractproperty def password(self): pass @property @abstractproperty def firstname(self): pass @abstractmethod def lastname(self): pass @abstractmethod def user_type(self): pass class User(IUser): def __init__(self, user_id, username, password, firstname, lastname, user_type): self._user_id = user_id self._username = username self._password = password self._firstname = firstname self._lastname = lastname self._user_type = user_type @property def user_id(self): return self._user_id @property def username(self): return self._username @property def password(self): return self._password @property def firstname(self): return self._firstname @property def lastname(self): return self._lastname @property def user_type(self): return self._user_type
[ "from abc import ABC, abstractmethod, abstractproperty\n\n\nclass IUser(ABC):\n \"\"\"\n abstract class for homeless shelter site admin\n \"\"\"\n\n @property\n @abstractproperty\n def user_id(self):\n pass\n\n @property\n @abstractproperty\n def username(self):\n pass\n\n @property\n @abstractproperty\n def password(self):\n pass\n\n @property\n @abstractproperty\n def firstname(self):\n pass\n\n @abstractmethod\n def lastname(self):\n pass\n\n @abstractmethod\n def user_type(self):\n pass\n\n\nclass User(IUser):\n\n def __init__(self, user_id, username, password, firstname, lastname, user_type):\n self._user_id = user_id\n self._username = username\n self._password = password\n self._firstname = firstname\n self._lastname = lastname\n self._user_type = user_type\n\n @property\n def user_id(self):\n return self._user_id\n\n @property\n def username(self):\n return self._username\n\n @property\n def password(self):\n return self._password\n\n @property\n def firstname(self):\n return self._firstname\n\n @property\n def lastname(self):\n return self._lastname\n\n @property\n def user_type(self):\n return self._user_type\n\n\n", "from abc import ABC, abstractmethod, abstractproperty\n\n\nclass IUser(ABC):\n \"\"\"\n abstract class for homeless shelter site admin\n \"\"\"\n\n @property\n @abstractproperty\n def user_id(self):\n pass\n\n @property\n @abstractproperty\n def username(self):\n pass\n\n @property\n @abstractproperty\n def password(self):\n pass\n\n @property\n @abstractproperty\n def firstname(self):\n pass\n\n @abstractmethod\n def lastname(self):\n pass\n\n @abstractmethod\n def user_type(self):\n pass\n\n\nclass User(IUser):\n\n def __init__(self, user_id, username, password, firstname, lastname,\n user_type):\n self._user_id = user_id\n self._username = username\n self._password = password\n self._firstname = firstname\n self._lastname = lastname\n self._user_type = user_type\n\n @property\n def user_id(self):\n return self._user_id\n\n @property\n def username(self):\n return self._username\n\n @property\n def password(self):\n return self._password\n\n @property\n def firstname(self):\n return self._firstname\n\n @property\n def lastname(self):\n return self._lastname\n\n @property\n def user_type(self):\n return self._user_type\n", "<import token>\n\n\nclass IUser(ABC):\n \"\"\"\n abstract class for homeless shelter site admin\n \"\"\"\n\n @property\n @abstractproperty\n def user_id(self):\n pass\n\n @property\n @abstractproperty\n def username(self):\n pass\n\n @property\n @abstractproperty\n def password(self):\n pass\n\n @property\n @abstractproperty\n def firstname(self):\n pass\n\n @abstractmethod\n def lastname(self):\n pass\n\n @abstractmethod\n def user_type(self):\n pass\n\n\nclass User(IUser):\n\n def __init__(self, user_id, username, password, firstname, lastname,\n user_type):\n self._user_id = user_id\n self._username = username\n self._password = password\n self._firstname = firstname\n self._lastname = lastname\n self._user_type = user_type\n\n @property\n def user_id(self):\n return self._user_id\n\n @property\n def username(self):\n return self._username\n\n @property\n def password(self):\n return self._password\n\n @property\n def firstname(self):\n return self._firstname\n\n @property\n def lastname(self):\n return self._lastname\n\n @property\n def user_type(self):\n return self._user_type\n", "<import token>\n\n\nclass IUser(ABC):\n <docstring token>\n\n @property\n @abstractproperty\n def user_id(self):\n pass\n\n @property\n @abstractproperty\n def username(self):\n pass\n\n @property\n @abstractproperty\n def password(self):\n pass\n\n @property\n @abstractproperty\n def firstname(self):\n pass\n\n @abstractmethod\n def lastname(self):\n pass\n\n @abstractmethod\n def user_type(self):\n pass\n\n\nclass User(IUser):\n\n def __init__(self, user_id, username, password, firstname, lastname,\n user_type):\n self._user_id = user_id\n self._username = username\n self._password = password\n self._firstname = firstname\n self._lastname = lastname\n self._user_type = user_type\n\n @property\n def user_id(self):\n return self._user_id\n\n @property\n def username(self):\n return self._username\n\n @property\n def password(self):\n return self._password\n\n @property\n def firstname(self):\n return self._firstname\n\n @property\n def lastname(self):\n return self._lastname\n\n @property\n def user_type(self):\n return self._user_type\n", "<import token>\n\n\nclass IUser(ABC):\n <docstring token>\n\n @property\n @abstractproperty\n def user_id(self):\n pass\n\n @property\n @abstractproperty\n def username(self):\n pass\n\n @property\n @abstractproperty\n def password(self):\n pass\n\n @property\n @abstractproperty\n def firstname(self):\n pass\n\n @abstractmethod\n def lastname(self):\n pass\n <function token>\n\n\nclass User(IUser):\n\n def __init__(self, user_id, username, password, firstname, lastname,\n user_type):\n self._user_id = user_id\n self._username = username\n self._password = password\n self._firstname = firstname\n self._lastname = lastname\n self._user_type = user_type\n\n @property\n def user_id(self):\n return self._user_id\n\n @property\n def username(self):\n return self._username\n\n @property\n def password(self):\n return self._password\n\n @property\n def firstname(self):\n return self._firstname\n\n @property\n def lastname(self):\n return self._lastname\n\n @property\n def user_type(self):\n return self._user_type\n", "<import token>\n\n\nclass IUser(ABC):\n <docstring token>\n <function token>\n\n @property\n @abstractproperty\n def username(self):\n pass\n\n @property\n @abstractproperty\n def password(self):\n pass\n\n @property\n @abstractproperty\n def firstname(self):\n pass\n\n @abstractmethod\n def lastname(self):\n pass\n <function token>\n\n\nclass User(IUser):\n\n def __init__(self, user_id, username, password, firstname, lastname,\n user_type):\n self._user_id = user_id\n self._username = username\n self._password = password\n self._firstname = firstname\n self._lastname = lastname\n self._user_type = user_type\n\n @property\n def user_id(self):\n return self._user_id\n\n @property\n def username(self):\n return self._username\n\n @property\n def password(self):\n return self._password\n\n @property\n def firstname(self):\n return self._firstname\n\n @property\n def lastname(self):\n return self._lastname\n\n @property\n def user_type(self):\n return self._user_type\n", "<import token>\n\n\nclass IUser(ABC):\n <docstring token>\n <function token>\n\n @property\n @abstractproperty\n def username(self):\n pass\n <function token>\n\n @property\n @abstractproperty\n def firstname(self):\n pass\n\n @abstractmethod\n def lastname(self):\n pass\n <function token>\n\n\nclass User(IUser):\n\n def __init__(self, user_id, username, password, firstname, lastname,\n user_type):\n self._user_id = user_id\n self._username = username\n self._password = password\n self._firstname = firstname\n self._lastname = lastname\n self._user_type = user_type\n\n @property\n def user_id(self):\n return self._user_id\n\n @property\n def username(self):\n return self._username\n\n @property\n def password(self):\n return self._password\n\n @property\n def firstname(self):\n return self._firstname\n\n @property\n def lastname(self):\n return self._lastname\n\n @property\n def user_type(self):\n return self._user_type\n", "<import token>\n\n\nclass IUser(ABC):\n <docstring token>\n <function token>\n\n @property\n @abstractproperty\n def username(self):\n pass\n <function token>\n <function token>\n\n @abstractmethod\n def lastname(self):\n pass\n <function token>\n\n\nclass User(IUser):\n\n def __init__(self, user_id, username, password, firstname, lastname,\n user_type):\n self._user_id = user_id\n self._username = username\n self._password = password\n self._firstname = firstname\n self._lastname = lastname\n self._user_type = user_type\n\n @property\n def user_id(self):\n return self._user_id\n\n @property\n def username(self):\n return self._username\n\n @property\n def password(self):\n return self._password\n\n @property\n def firstname(self):\n return self._firstname\n\n @property\n def lastname(self):\n return self._lastname\n\n @property\n def user_type(self):\n return self._user_type\n", "<import token>\n\n\nclass IUser(ABC):\n <docstring token>\n <function token>\n\n @property\n @abstractproperty\n def username(self):\n pass\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass User(IUser):\n\n def __init__(self, user_id, username, password, firstname, lastname,\n user_type):\n self._user_id = user_id\n self._username = username\n self._password = password\n self._firstname = firstname\n self._lastname = lastname\n self._user_type = user_type\n\n @property\n def user_id(self):\n return self._user_id\n\n @property\n def username(self):\n return self._username\n\n @property\n def password(self):\n return self._password\n\n @property\n def firstname(self):\n return self._firstname\n\n @property\n def lastname(self):\n return self._lastname\n\n @property\n def user_type(self):\n return self._user_type\n", "<import token>\n\n\nclass IUser(ABC):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass User(IUser):\n\n def __init__(self, user_id, username, password, firstname, lastname,\n user_type):\n self._user_id = user_id\n self._username = username\n self._password = password\n self._firstname = firstname\n self._lastname = lastname\n self._user_type = user_type\n\n @property\n def user_id(self):\n return self._user_id\n\n @property\n def username(self):\n return self._username\n\n @property\n def password(self):\n return self._password\n\n @property\n def firstname(self):\n return self._firstname\n\n @property\n def lastname(self):\n return self._lastname\n\n @property\n def user_type(self):\n return self._user_type\n", "<import token>\n<class token>\n\n\nclass User(IUser):\n\n def __init__(self, user_id, username, password, firstname, lastname,\n user_type):\n self._user_id = user_id\n self._username = username\n self._password = password\n self._firstname = firstname\n self._lastname = lastname\n self._user_type = user_type\n\n @property\n def user_id(self):\n return self._user_id\n\n @property\n def username(self):\n return self._username\n\n @property\n def password(self):\n return self._password\n\n @property\n def firstname(self):\n return self._firstname\n\n @property\n def lastname(self):\n return self._lastname\n\n @property\n def user_type(self):\n return self._user_type\n", "<import token>\n<class token>\n\n\nclass User(IUser):\n\n def __init__(self, user_id, username, password, firstname, lastname,\n user_type):\n self._user_id = user_id\n self._username = username\n self._password = password\n self._firstname = firstname\n self._lastname = lastname\n self._user_type = user_type\n\n @property\n def user_id(self):\n return self._user_id\n\n @property\n def username(self):\n return self._username\n\n @property\n def password(self):\n return self._password\n\n @property\n def firstname(self):\n return self._firstname\n\n @property\n def lastname(self):\n return self._lastname\n <function token>\n", "<import token>\n<class token>\n\n\nclass User(IUser):\n\n def __init__(self, user_id, username, password, firstname, lastname,\n user_type):\n self._user_id = user_id\n self._username = username\n self._password = password\n self._firstname = firstname\n self._lastname = lastname\n self._user_type = user_type\n\n @property\n def user_id(self):\n return self._user_id\n <function token>\n\n @property\n def password(self):\n return self._password\n\n @property\n def firstname(self):\n return self._firstname\n\n @property\n def lastname(self):\n return self._lastname\n <function token>\n", "<import token>\n<class token>\n\n\nclass User(IUser):\n\n def __init__(self, user_id, username, password, firstname, lastname,\n user_type):\n self._user_id = user_id\n self._username = username\n self._password = password\n self._firstname = firstname\n self._lastname = lastname\n self._user_type = user_type\n\n @property\n def user_id(self):\n return self._user_id\n <function token>\n\n @property\n def password(self):\n return self._password\n\n @property\n def firstname(self):\n return self._firstname\n <function token>\n <function token>\n", "<import token>\n<class token>\n\n\nclass User(IUser):\n\n def __init__(self, user_id, username, password, firstname, lastname,\n user_type):\n self._user_id = user_id\n self._username = username\n self._password = password\n self._firstname = firstname\n self._lastname = lastname\n self._user_type = user_type\n\n @property\n def user_id(self):\n return self._user_id\n <function token>\n <function token>\n\n @property\n def firstname(self):\n return self._firstname\n <function token>\n <function token>\n", "<import token>\n<class token>\n\n\nclass User(IUser):\n\n def __init__(self, user_id, username, password, firstname, lastname,\n user_type):\n self._user_id = user_id\n self._username = username\n self._password = password\n self._firstname = firstname\n self._lastname = lastname\n self._user_type = user_type\n <function token>\n <function token>\n <function token>\n\n @property\n def firstname(self):\n return self._firstname\n <function token>\n <function token>\n", "<import token>\n<class token>\n\n\nclass User(IUser):\n\n def __init__(self, user_id, username, password, firstname, lastname,\n user_type):\n self._user_id = user_id\n self._username = username\n self._password = password\n self._firstname = firstname\n self._lastname = lastname\n self._user_type = user_type\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<import token>\n<class token>\n\n\nclass User(IUser):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<import token>\n<class token>\n<class token>\n" ]
false
98,766
c0e5d97f8732144b12d6597ccca73c78b56193bb
# Calculate estimated success rate when transfering network from 3pc to 4pc, withut retraining. import numpy as np count3 = np.array([0, 38368,124960]) total3 = count3.sum() count4 = np.array([1737970, 2485090, 3213028]) total4 = count4.sum() p3 = [i/total3 for i in count3] p4 = [i/total4 for i in count4] P = np.array([p3[i]*p4[i] for i in range(3)]).sum() print("When training net N on 3pc dataset, and using it to estimate a 4pc dataset.Then the estimated probability of guessing right, given that the net guesses randomly for an outcome with probabilities p3 and p4, is P = ",\ round(P,3)) p3 = [round(i,3) for i in p3] p4 = [round(i,3) for i in p4] print(p3) print(p4)
[ "# Calculate estimated success rate when transfering network from 3pc to 4pc, withut retraining.\nimport numpy as np\n\ncount3 = np.array([0, 38368,124960])\ntotal3 = count3.sum()\ncount4 = np.array([1737970, 2485090, 3213028])\ntotal4 = count4.sum()\n\np3 = [i/total3 for i in count3]\np4 = [i/total4 for i in count4]\n\nP = np.array([p3[i]*p4[i] for i in range(3)]).sum()\nprint(\"When training net N on 3pc dataset, and using it to estimate a 4pc dataset.Then the estimated probability of guessing right, given that the net guesses randomly for an outcome with probabilities p3 and p4, is P = \",\\\n round(P,3))\n\np3 = [round(i,3) for i in p3]\np4 = [round(i,3) for i in p4]\nprint(p3)\nprint(p4)\n\n", "import numpy as np\ncount3 = np.array([0, 38368, 124960])\ntotal3 = count3.sum()\ncount4 = np.array([1737970, 2485090, 3213028])\ntotal4 = count4.sum()\np3 = [(i / total3) for i in count3]\np4 = [(i / total4) for i in count4]\nP = np.array([(p3[i] * p4[i]) for i in range(3)]).sum()\nprint(\n 'When training net N on 3pc dataset, and using it to estimate a 4pc dataset.Then the estimated probability of guessing right, given that the net guesses randomly for an outcome with probabilities p3 and p4, is P = '\n , round(P, 3))\np3 = [round(i, 3) for i in p3]\np4 = [round(i, 3) for i in p4]\nprint(p3)\nprint(p4)\n", "<import token>\ncount3 = np.array([0, 38368, 124960])\ntotal3 = count3.sum()\ncount4 = np.array([1737970, 2485090, 3213028])\ntotal4 = count4.sum()\np3 = [(i / total3) for i in count3]\np4 = [(i / total4) for i in count4]\nP = np.array([(p3[i] * p4[i]) for i in range(3)]).sum()\nprint(\n 'When training net N on 3pc dataset, and using it to estimate a 4pc dataset.Then the estimated probability of guessing right, given that the net guesses randomly for an outcome with probabilities p3 and p4, is P = '\n , round(P, 3))\np3 = [round(i, 3) for i in p3]\np4 = [round(i, 3) for i in p4]\nprint(p3)\nprint(p4)\n", "<import token>\n<assignment token>\nprint(\n 'When training net N on 3pc dataset, and using it to estimate a 4pc dataset.Then the estimated probability of guessing right, given that the net guesses randomly for an outcome with probabilities p3 and p4, is P = '\n , round(P, 3))\n<assignment token>\nprint(p3)\nprint(p4)\n", "<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
98,767
47f5baa9863622211eb6a812a79ade40939d2717
from .shader import Shader from .shader_program import ShaderProgram from .shader_types import ShaderTypes
[ "from .shader import Shader\r\nfrom .shader_program import ShaderProgram\r\nfrom .shader_types import ShaderTypes", "from .shader import Shader\nfrom .shader_program import ShaderProgram\nfrom .shader_types import ShaderTypes\n", "<import token>\n" ]
false
98,768
0643bd67b08313243acd70b331235138462e8537
# Import necessary libraries import os, sys, shutil, glob, argparse import numpy as np from PIL import Image # Import datasets dependent files from datasets import kitti from datasets import lisa from datasets import voc from datasets import yolo def parse_args(): """ Definition: Parse command line arguments. Parameters: None Returns: args - list of arguments """ parser = argparse.ArgumentParser(description= 'Convert object detection datasets.') parser._action_groups.pop() required = parser.add_argument_group('required arguments') optional = parser.add_argument_group('optional arguments') required.add_argument('--from', dest='from_key', required=True, help='Format to convert dataset from.', choices=['kitti','lisa','voc','yolo'], type=str, nargs=1) required.add_argument('--from-path', dest='from_path', required=True, help='Path to dataset you wish to convert.', type=str, nargs=1) required.add_argument('--to', dest='to_key', required=True, help='Format to convert dataset to', choices=['kitti','lisa','voc','yolo'], type=str, nargs=1) required.add_argument('--to-path', dest='to_path', required=True, help='Path to output dataset to convert to.', type=str, nargs=1) optional.add_argument('-l', '--label', dest='label', required=False, help='Label file necessary for yolo conversion.', type=str, nargs=1) optional.add_argument('-v','--verbose', dest='verbose', required=False, help='Print out during execution of the script.') args = parser.parse_args() return args if __name__ == '__main__': # Parse command line arguments args = parse_args() # If conversion types are same, no conversion necessary (ex. both 'kitti') if args.from_key == args.to_key: print ("No conversion necessary.") exit(0) # If yolo is part of the conversion (either 'to' or 'from' type) if 'yolo' in args.to_key or 'yolo' in args.from_key: # Must contain a label file if not args.label: print ("Error: A label file is necessary for yolo conversion.") exit(0) # Parameters including the label file params = ("'" + args.from_path[0] + "', '" + args.to_path[0] + "', '" + args.label[0] + "'") # Otherwise set up parameters without a label file else: # Parameters without the label file params = ("'" + args.from_path[0] + "', '" + args.to_path[0] + "'") # Evaluate the conversion based on command line parameters eval (args.from_key[0] + '.' + args.to_key[0] + '(' + params + ')') print ("Conversion complete!!")
[ "# Import necessary libraries\nimport os, sys, shutil, glob, argparse\nimport numpy as np\nfrom PIL import Image\n\n# Import datasets dependent files\nfrom datasets import kitti\nfrom datasets import lisa\nfrom datasets import voc\nfrom datasets import yolo\n\ndef parse_args():\n\t\"\"\"\n\tDefinition: Parse command line arguments.\n\n\tParameters: None\n\tReturns: args - list of arguments\n\t\"\"\"\n\tparser = argparse.ArgumentParser(description=\n\t\t'Convert object detection datasets.')\n\tparser._action_groups.pop()\n\trequired = parser.add_argument_group('required arguments')\n\toptional = parser.add_argument_group('optional arguments')\n\trequired.add_argument('--from',\n\t\t\t\t\t\t dest='from_key',\n\t\t\t\t\t\t required=True,\n\t\t\t\t\t\t help='Format to convert dataset from.',\n\t\t\t\t\t\t choices=['kitti','lisa','voc','yolo'],\n\t\t\t\t\t\t type=str, nargs=1)\n\trequired.add_argument('--from-path',\n\t\t\t\t\t\t dest='from_path',\n\t\t\t\t\t\t required=True,\n\t\t\t\t\t\t help='Path to dataset you wish to convert.',\n\t\t\t\t\t\t type=str, nargs=1)\n\trequired.add_argument('--to',\n dest='to_key',\n required=True,\n help='Format to convert dataset to',\n choices=['kitti','lisa','voc','yolo'],\n type=str, nargs=1)\n\trequired.add_argument('--to-path',\n\t\t\t\t\t\t dest='to_path',\n\t\t\t\t\t\t required=True,\n\t\t\t\t\t\t help='Path to output dataset to convert to.',\n\t\t\t\t\t\t type=str, nargs=1)\n\toptional.add_argument('-l', '--label',\n \t\t\t\t\t dest='label',\n \t\t\t\t\t required=False,\n \t\t\t\t\t help='Label file necessary for yolo conversion.',\n \t\t\t\t\t type=str, nargs=1)\n\toptional.add_argument('-v','--verbose',\n dest='verbose',\n required=False,\n help='Print out during execution of the script.')\n\n\targs = parser.parse_args()\n\treturn args\n\nif __name__ == '__main__':\n\t# Parse command line arguments\n\targs = parse_args()\n\n\t# If conversion types are same, no conversion necessary (ex. both 'kitti')\n\tif args.from_key == args.to_key:\n\t\tprint (\"No conversion necessary.\")\n\t\texit(0)\n\n\t# If yolo is part of the conversion (either 'to' or 'from' type)\n\tif 'yolo' in args.to_key or 'yolo' in args.from_key:\n\t\t# Must contain a label file\n\t\tif not args.label:\n\t\t\tprint (\"Error: A label file is necessary for yolo conversion.\")\n\t\t\texit(0)\n\n\t\t# Parameters including the label file\n\t\tparams = (\"'\" + args.from_path[0] + \"', '\" + args.to_path[0] + \"', '\" +\n\t\t\targs.label[0] + \"'\")\n\n\t# Otherwise set up parameters without a label file\n\telse:\n\t\t# Parameters without the label file\n\t\tparams = (\"'\" + args.from_path[0] + \"', '\" + args.to_path[0] + \"'\")\n\n\t# Evaluate the conversion based on command line parameters\n\teval (args.from_key[0] + '.' + args.to_key[0] + '(' + params + ')')\n\n\tprint (\"Conversion complete!!\")\n", "import os, sys, shutil, glob, argparse\nimport numpy as np\nfrom PIL import Image\nfrom datasets import kitti\nfrom datasets import lisa\nfrom datasets import voc\nfrom datasets import yolo\n\n\ndef parse_args():\n \"\"\"\n\tDefinition: Parse command line arguments.\n\n\tParameters: None\n\tReturns: args - list of arguments\n\t\"\"\"\n parser = argparse.ArgumentParser(description=\n 'Convert object detection datasets.')\n parser._action_groups.pop()\n required = parser.add_argument_group('required arguments')\n optional = parser.add_argument_group('optional arguments')\n required.add_argument('--from', dest='from_key', required=True, help=\n 'Format to convert dataset from.', choices=['kitti', 'lisa', 'voc',\n 'yolo'], type=str, nargs=1)\n required.add_argument('--from-path', dest='from_path', required=True,\n help='Path to dataset you wish to convert.', type=str, nargs=1)\n required.add_argument('--to', dest='to_key', required=True, help=\n 'Format to convert dataset to', choices=['kitti', 'lisa', 'voc',\n 'yolo'], type=str, nargs=1)\n required.add_argument('--to-path', dest='to_path', required=True, help=\n 'Path to output dataset to convert to.', type=str, nargs=1)\n optional.add_argument('-l', '--label', dest='label', required=False,\n help='Label file necessary for yolo conversion.', type=str, nargs=1)\n optional.add_argument('-v', '--verbose', dest='verbose', required=False,\n help='Print out during execution of the script.')\n args = parser.parse_args()\n return args\n\n\nif __name__ == '__main__':\n args = parse_args()\n if args.from_key == args.to_key:\n print('No conversion necessary.')\n exit(0)\n if 'yolo' in args.to_key or 'yolo' in args.from_key:\n if not args.label:\n print('Error: A label file is necessary for yolo conversion.')\n exit(0)\n params = \"'\" + args.from_path[0] + \"', '\" + args.to_path[0\n ] + \"', '\" + args.label[0] + \"'\"\n else:\n params = \"'\" + args.from_path[0] + \"', '\" + args.to_path[0] + \"'\"\n eval(args.from_key[0] + '.' + args.to_key[0] + '(' + params + ')')\n print('Conversion complete!!')\n", "<import token>\n\n\ndef parse_args():\n \"\"\"\n\tDefinition: Parse command line arguments.\n\n\tParameters: None\n\tReturns: args - list of arguments\n\t\"\"\"\n parser = argparse.ArgumentParser(description=\n 'Convert object detection datasets.')\n parser._action_groups.pop()\n required = parser.add_argument_group('required arguments')\n optional = parser.add_argument_group('optional arguments')\n required.add_argument('--from', dest='from_key', required=True, help=\n 'Format to convert dataset from.', choices=['kitti', 'lisa', 'voc',\n 'yolo'], type=str, nargs=1)\n required.add_argument('--from-path', dest='from_path', required=True,\n help='Path to dataset you wish to convert.', type=str, nargs=1)\n required.add_argument('--to', dest='to_key', required=True, help=\n 'Format to convert dataset to', choices=['kitti', 'lisa', 'voc',\n 'yolo'], type=str, nargs=1)\n required.add_argument('--to-path', dest='to_path', required=True, help=\n 'Path to output dataset to convert to.', type=str, nargs=1)\n optional.add_argument('-l', '--label', dest='label', required=False,\n help='Label file necessary for yolo conversion.', type=str, nargs=1)\n optional.add_argument('-v', '--verbose', dest='verbose', required=False,\n help='Print out during execution of the script.')\n args = parser.parse_args()\n return args\n\n\nif __name__ == '__main__':\n args = parse_args()\n if args.from_key == args.to_key:\n print('No conversion necessary.')\n exit(0)\n if 'yolo' in args.to_key or 'yolo' in args.from_key:\n if not args.label:\n print('Error: A label file is necessary for yolo conversion.')\n exit(0)\n params = \"'\" + args.from_path[0] + \"', '\" + args.to_path[0\n ] + \"', '\" + args.label[0] + \"'\"\n else:\n params = \"'\" + args.from_path[0] + \"', '\" + args.to_path[0] + \"'\"\n eval(args.from_key[0] + '.' + args.to_key[0] + '(' + params + ')')\n print('Conversion complete!!')\n", "<import token>\n\n\ndef parse_args():\n \"\"\"\n\tDefinition: Parse command line arguments.\n\n\tParameters: None\n\tReturns: args - list of arguments\n\t\"\"\"\n parser = argparse.ArgumentParser(description=\n 'Convert object detection datasets.')\n parser._action_groups.pop()\n required = parser.add_argument_group('required arguments')\n optional = parser.add_argument_group('optional arguments')\n required.add_argument('--from', dest='from_key', required=True, help=\n 'Format to convert dataset from.', choices=['kitti', 'lisa', 'voc',\n 'yolo'], type=str, nargs=1)\n required.add_argument('--from-path', dest='from_path', required=True,\n help='Path to dataset you wish to convert.', type=str, nargs=1)\n required.add_argument('--to', dest='to_key', required=True, help=\n 'Format to convert dataset to', choices=['kitti', 'lisa', 'voc',\n 'yolo'], type=str, nargs=1)\n required.add_argument('--to-path', dest='to_path', required=True, help=\n 'Path to output dataset to convert to.', type=str, nargs=1)\n optional.add_argument('-l', '--label', dest='label', required=False,\n help='Label file necessary for yolo conversion.', type=str, nargs=1)\n optional.add_argument('-v', '--verbose', dest='verbose', required=False,\n help='Print out during execution of the script.')\n args = parser.parse_args()\n return args\n\n\n<code token>\n", "<import token>\n<function token>\n<code token>\n" ]
false
98,769
290cd557e266d96fe17376644e29e919049dccfc
import zlib import sys def blf_unzlib(inputBLF, outputBIN): # BLFの全データ取得 f = open(inputBLF, 'rb') blf_data = f.read() f.close() # 解凍済みデータ保存先ファイル f2 = open(outputBIN, 'wb') filesize = len(blf_data) decompress_data = b'' compress_data = b'' # 先頭ヘッダからサイズ抽出 offset = blf_data[4] + blf_data[5]*0x100 cnt = 0 # 経過表示用カウンタ while True: if offset >= filesize: # offsetがデータ終端に到達 break # zlibパッケージヘッダ抽出 obj_size = blf_data[offset+8] + blf_data[offset+9]*0x100 + blf_data[offset+10]*0x10000 + blf_data[offset+11]*0x1000000 compress_data = blf_data[offset+0x20:offset+obj_size] decompress_data = zlib.decompress(compress_data) f2.write(decompress_data) offset += obj_size if offset+4 >= filesize: break; i = 0 while True: tmp = str.format( "%c%c%c%c" % (blf_data[offset + i + 0], blf_data[offset + i + 1], blf_data[offset + i + 2], blf_data[offset + i + 3]) ) if tmp == 'LOBJ': break elif i >= 4: print('LOBJ not found!') exit() break else: i += 1 offset += i # 経過表示用 if cnt % 100 == 0: print(offset) cnt += 1 f2.close() if __name__=='__main__': inputBLF = 'test.blf' outputBIN = 'test.bin' args = sys.argv # コマンドライン引数がある場合は、引数優先 if len(args) >= 3: inputBLF = args[1] outputBIN = args[2] print("BLF=%s,output=%s" % (inputBLF,outputBIN)) blf_unzlib(inputBLF,outputBIN)
[ "import zlib\nimport sys\n\n\ndef blf_unzlib(inputBLF, outputBIN):\n # BLFの全データ取得\n f = open(inputBLF, 'rb')\n blf_data = f.read()\n f.close()\n \n # 解凍済みデータ保存先ファイル\n f2 = open(outputBIN, 'wb')\n \n filesize = len(blf_data)\n decompress_data = b''\n compress_data = b''\n \n # 先頭ヘッダからサイズ抽出\n offset = blf_data[4] + blf_data[5]*0x100\n \n cnt = 0 # 経過表示用カウンタ\n \n while True:\n if offset >= filesize:\n # offsetがデータ終端に到達\n break\n \n # zlibパッケージヘッダ抽出 \n obj_size = blf_data[offset+8] + blf_data[offset+9]*0x100 + blf_data[offset+10]*0x10000 + blf_data[offset+11]*0x1000000\n \n compress_data = blf_data[offset+0x20:offset+obj_size]\n decompress_data = zlib.decompress(compress_data)\n f2.write(decompress_data)\n \n offset += obj_size\n \n if offset+4 >= filesize:\n break;\n\n i = 0\n while True:\n tmp = str.format( \"%c%c%c%c\" % (blf_data[offset + i + 0], blf_data[offset + i + 1], blf_data[offset + i + 2], blf_data[offset + i + 3]) )\n if tmp == 'LOBJ':\n break\n elif i >= 4:\n print('LOBJ not found!')\n exit()\n break\n else:\n i += 1\n \n offset += i\n \n # 経過表示用\n if cnt % 100 == 0:\n print(offset)\n cnt += 1\n \n f2.close()\n\nif __name__=='__main__':\n inputBLF = 'test.blf'\n outputBIN = 'test.bin'\n\n args = sys.argv\n \n # コマンドライン引数がある場合は、引数優先\n if len(args) >= 3:\n inputBLF = args[1]\n outputBIN = args[2]\n \n print(\"BLF=%s,output=%s\" % (inputBLF,outputBIN))\n \n blf_unzlib(inputBLF,outputBIN)", "import zlib\nimport sys\n\n\ndef blf_unzlib(inputBLF, outputBIN):\n f = open(inputBLF, 'rb')\n blf_data = f.read()\n f.close()\n f2 = open(outputBIN, 'wb')\n filesize = len(blf_data)\n decompress_data = b''\n compress_data = b''\n offset = blf_data[4] + blf_data[5] * 256\n cnt = 0\n while True:\n if offset >= filesize:\n break\n obj_size = blf_data[offset + 8] + blf_data[offset + 9\n ] * 256 + blf_data[offset + 10] * 65536 + blf_data[offset + 11\n ] * 16777216\n compress_data = blf_data[offset + 32:offset + obj_size]\n decompress_data = zlib.decompress(compress_data)\n f2.write(decompress_data)\n offset += obj_size\n if offset + 4 >= filesize:\n break\n i = 0\n while True:\n tmp = str.format('%c%c%c%c' % (blf_data[offset + i + 0],\n blf_data[offset + i + 1], blf_data[offset + i + 2],\n blf_data[offset + i + 3]))\n if tmp == 'LOBJ':\n break\n elif i >= 4:\n print('LOBJ not found!')\n exit()\n break\n else:\n i += 1\n offset += i\n if cnt % 100 == 0:\n print(offset)\n cnt += 1\n f2.close()\n\n\nif __name__ == '__main__':\n inputBLF = 'test.blf'\n outputBIN = 'test.bin'\n args = sys.argv\n if len(args) >= 3:\n inputBLF = args[1]\n outputBIN = args[2]\n print('BLF=%s,output=%s' % (inputBLF, outputBIN))\n blf_unzlib(inputBLF, outputBIN)\n", "<import token>\n\n\ndef blf_unzlib(inputBLF, outputBIN):\n f = open(inputBLF, 'rb')\n blf_data = f.read()\n f.close()\n f2 = open(outputBIN, 'wb')\n filesize = len(blf_data)\n decompress_data = b''\n compress_data = b''\n offset = blf_data[4] + blf_data[5] * 256\n cnt = 0\n while True:\n if offset >= filesize:\n break\n obj_size = blf_data[offset + 8] + blf_data[offset + 9\n ] * 256 + blf_data[offset + 10] * 65536 + blf_data[offset + 11\n ] * 16777216\n compress_data = blf_data[offset + 32:offset + obj_size]\n decompress_data = zlib.decompress(compress_data)\n f2.write(decompress_data)\n offset += obj_size\n if offset + 4 >= filesize:\n break\n i = 0\n while True:\n tmp = str.format('%c%c%c%c' % (blf_data[offset + i + 0],\n blf_data[offset + i + 1], blf_data[offset + i + 2],\n blf_data[offset + i + 3]))\n if tmp == 'LOBJ':\n break\n elif i >= 4:\n print('LOBJ not found!')\n exit()\n break\n else:\n i += 1\n offset += i\n if cnt % 100 == 0:\n print(offset)\n cnt += 1\n f2.close()\n\n\nif __name__ == '__main__':\n inputBLF = 'test.blf'\n outputBIN = 'test.bin'\n args = sys.argv\n if len(args) >= 3:\n inputBLF = args[1]\n outputBIN = args[2]\n print('BLF=%s,output=%s' % (inputBLF, outputBIN))\n blf_unzlib(inputBLF, outputBIN)\n", "<import token>\n\n\ndef blf_unzlib(inputBLF, outputBIN):\n f = open(inputBLF, 'rb')\n blf_data = f.read()\n f.close()\n f2 = open(outputBIN, 'wb')\n filesize = len(blf_data)\n decompress_data = b''\n compress_data = b''\n offset = blf_data[4] + blf_data[5] * 256\n cnt = 0\n while True:\n if offset >= filesize:\n break\n obj_size = blf_data[offset + 8] + blf_data[offset + 9\n ] * 256 + blf_data[offset + 10] * 65536 + blf_data[offset + 11\n ] * 16777216\n compress_data = blf_data[offset + 32:offset + obj_size]\n decompress_data = zlib.decompress(compress_data)\n f2.write(decompress_data)\n offset += obj_size\n if offset + 4 >= filesize:\n break\n i = 0\n while True:\n tmp = str.format('%c%c%c%c' % (blf_data[offset + i + 0],\n blf_data[offset + i + 1], blf_data[offset + i + 2],\n blf_data[offset + i + 3]))\n if tmp == 'LOBJ':\n break\n elif i >= 4:\n print('LOBJ not found!')\n exit()\n break\n else:\n i += 1\n offset += i\n if cnt % 100 == 0:\n print(offset)\n cnt += 1\n f2.close()\n\n\n<code token>\n", "<import token>\n<function token>\n<code token>\n" ]
false
98,770
1cbae3e7cc10420ee3ed33af5773eb09a64a15ae
from django.apps import AppConfig class CoreConfig(AppConfig): name = 'core' verbose_name = "Mis Perris" #Aqui le estamos agregando un nombre para un titulo de Django #solo para que se entienda mejor, luego esto hay que "activarlo" en settings.py
[ "from django.apps import AppConfig\n\n\nclass CoreConfig(AppConfig):\n name = 'core'\n verbose_name = \"Mis Perris\" #Aqui le estamos agregando un nombre para un titulo de Django\n #solo para que se entienda mejor, luego esto hay que \"activarlo\" en settings.py\n", "from django.apps import AppConfig\n\n\nclass CoreConfig(AppConfig):\n name = 'core'\n verbose_name = 'Mis Perris'\n", "<import token>\n\n\nclass CoreConfig(AppConfig):\n name = 'core'\n verbose_name = 'Mis Perris'\n", "<import token>\n\n\nclass CoreConfig(AppConfig):\n <assignment token>\n <assignment token>\n", "<import token>\n<class token>\n" ]
false
98,771
6506b75270a30eddf1a2c2d6181a21c1497bb3ff
import logging from tvsort_sl.app import TvSort tv_sort = TvSort(is_test=True, log_level=logging.INFO)
[ "import logging\n\nfrom tvsort_sl.app import TvSort\n\ntv_sort = TvSort(is_test=True, log_level=logging.INFO)\n", "import logging\nfrom tvsort_sl.app import TvSort\ntv_sort = TvSort(is_test=True, log_level=logging.INFO)\n", "<import token>\ntv_sort = TvSort(is_test=True, log_level=logging.INFO)\n", "<import token>\n<assignment token>\n" ]
false
98,772
8837ba19db69af05f3c763ae3fd7b43bd87c700b
#!/usr/bin/env python3 import argparse import glob import os import sys cmd_home = os.path.dirname(os.path.realpath(__file__)) pipe_home = os.path.normpath(cmd_home + "/..") job_home = cmd_home + "/job_scripts" sys.path.append(pipe_home) from library.config import log_dir from library.job_queue import GridEngineQueue def main(): args = parse_args() q = GridEngineQueue() jid_list = [] for pu in [fastq.split(".")[1] for fastq in glob.glob("{sample}/fastq/{sample}.*.R1.fastq.gz".format(sample=args.sample))]: jid_list.append(q.submit(opt(args.sample), "{job_home}/aln_1.align_sort.sh {sample} {pu}".format(job_home=job_home, sample=args.sample, pu=pu))) jid = ",".join(jid_list) jid = q.submit(opt(args.sample, jid), "{job_home}/aln_2.merge_bam.sh {sample}".format(job_home=job_home, sample=args.sample)) jid = q.submit(opt(args.sample, jid), "{job_home}/aln_3.markdup.sh {sample}".format(job_home=job_home, sample=args.sample)) jid = q.submit(opt(args.sample, jid), "{job_home}/aln_4.indel_realign.sh {sample}".format(job_home=job_home, sample=args.sample)) jid = q.submit(opt(args.sample, jid), "{job_home}/aln_5.bqsr.sh {sample}".format(job_home=job_home, sample=args.sample)) if parentid(args.sample) != "None": q.submit(opt(args.sample, jid), "{job_home}/aln_6.upload_bam.sh {sample}".format(job_home=job_home, sample=args.sample)) def parse_args(): parser = argparse.ArgumentParser(description='Alignment job submitter') parser.add_argument('sample', metavar='sample name') return parser.parse_args() def parentid(sample): with open(sample + "/run_info") as run_info: for line in run_info: if line[:8] == "PARENTID": return line.strip().split("=")[1] def opt(sample, jid=None): opt = "-j y -o {log_dir} -l h_vmem=4G".format(log_dir=log_dir(sample)) if jid is not None: opt = "-hold_jid {jid} {opt}".format(jid=jid, opt=opt) return opt if __name__ == "__main__": main()
[ "#!/usr/bin/env python3\n\nimport argparse\nimport glob\nimport os\nimport sys\n\ncmd_home = os.path.dirname(os.path.realpath(__file__))\npipe_home = os.path.normpath(cmd_home + \"/..\")\njob_home = cmd_home + \"/job_scripts\"\nsys.path.append(pipe_home)\n\nfrom library.config import log_dir\nfrom library.job_queue import GridEngineQueue\n\ndef main():\n args = parse_args()\n q = GridEngineQueue()\n \n jid_list = []\n for pu in [fastq.split(\".\")[1] for fastq in glob.glob(\"{sample}/fastq/{sample}.*.R1.fastq.gz\".format(sample=args.sample))]:\n jid_list.append(q.submit(opt(args.sample), \n \"{job_home}/aln_1.align_sort.sh {sample} {pu}\".format(job_home=job_home, sample=args.sample, pu=pu)))\n jid = \",\".join(jid_list)\n \n jid = q.submit(opt(args.sample, jid), \n \"{job_home}/aln_2.merge_bam.sh {sample}\".format(job_home=job_home, sample=args.sample))\n\n jid = q.submit(opt(args.sample, jid),\n \"{job_home}/aln_3.markdup.sh {sample}\".format(job_home=job_home, sample=args.sample))\n\n jid = q.submit(opt(args.sample, jid),\n \"{job_home}/aln_4.indel_realign.sh {sample}\".format(job_home=job_home, sample=args.sample))\n\n jid = q.submit(opt(args.sample, jid), \n \"{job_home}/aln_5.bqsr.sh {sample}\".format(job_home=job_home, sample=args.sample))\n\n if parentid(args.sample) != \"None\":\n q.submit(opt(args.sample, jid), \n \"{job_home}/aln_6.upload_bam.sh {sample}\".format(job_home=job_home, sample=args.sample))\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Alignment job submitter')\n parser.add_argument('sample', metavar='sample name')\n return parser.parse_args()\n\ndef parentid(sample):\n with open(sample + \"/run_info\") as run_info:\n for line in run_info:\n if line[:8] == \"PARENTID\":\n return line.strip().split(\"=\")[1]\n\ndef opt(sample, jid=None):\n opt = \"-j y -o {log_dir} -l h_vmem=4G\".format(log_dir=log_dir(sample))\n if jid is not None:\n opt = \"-hold_jid {jid} {opt}\".format(jid=jid, opt=opt)\n return opt\n \nif __name__ == \"__main__\":\n main()\n", "import argparse\nimport glob\nimport os\nimport sys\ncmd_home = os.path.dirname(os.path.realpath(__file__))\npipe_home = os.path.normpath(cmd_home + '/..')\njob_home = cmd_home + '/job_scripts'\nsys.path.append(pipe_home)\nfrom library.config import log_dir\nfrom library.job_queue import GridEngineQueue\n\n\ndef main():\n args = parse_args()\n q = GridEngineQueue()\n jid_list = []\n for pu in [fastq.split('.')[1] for fastq in glob.glob(\n '{sample}/fastq/{sample}.*.R1.fastq.gz'.format(sample=args.sample))]:\n jid_list.append(q.submit(opt(args.sample),\n '{job_home}/aln_1.align_sort.sh {sample} {pu}'.format(job_home=\n job_home, sample=args.sample, pu=pu)))\n jid = ','.join(jid_list)\n jid = q.submit(opt(args.sample, jid),\n '{job_home}/aln_2.merge_bam.sh {sample}'.format(job_home=job_home,\n sample=args.sample))\n jid = q.submit(opt(args.sample, jid),\n '{job_home}/aln_3.markdup.sh {sample}'.format(job_home=job_home,\n sample=args.sample))\n jid = q.submit(opt(args.sample, jid),\n '{job_home}/aln_4.indel_realign.sh {sample}'.format(job_home=\n job_home, sample=args.sample))\n jid = q.submit(opt(args.sample, jid),\n '{job_home}/aln_5.bqsr.sh {sample}'.format(job_home=job_home,\n sample=args.sample))\n if parentid(args.sample) != 'None':\n q.submit(opt(args.sample, jid),\n '{job_home}/aln_6.upload_bam.sh {sample}'.format(job_home=\n job_home, sample=args.sample))\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Alignment job submitter')\n parser.add_argument('sample', metavar='sample name')\n return parser.parse_args()\n\n\ndef parentid(sample):\n with open(sample + '/run_info') as run_info:\n for line in run_info:\n if line[:8] == 'PARENTID':\n return line.strip().split('=')[1]\n\n\ndef opt(sample, jid=None):\n opt = '-j y -o {log_dir} -l h_vmem=4G'.format(log_dir=log_dir(sample))\n if jid is not None:\n opt = '-hold_jid {jid} {opt}'.format(jid=jid, opt=opt)\n return opt\n\n\nif __name__ == '__main__':\n main()\n", "<import token>\ncmd_home = os.path.dirname(os.path.realpath(__file__))\npipe_home = os.path.normpath(cmd_home + '/..')\njob_home = cmd_home + '/job_scripts'\nsys.path.append(pipe_home)\n<import token>\n\n\ndef main():\n args = parse_args()\n q = GridEngineQueue()\n jid_list = []\n for pu in [fastq.split('.')[1] for fastq in glob.glob(\n '{sample}/fastq/{sample}.*.R1.fastq.gz'.format(sample=args.sample))]:\n jid_list.append(q.submit(opt(args.sample),\n '{job_home}/aln_1.align_sort.sh {sample} {pu}'.format(job_home=\n job_home, sample=args.sample, pu=pu)))\n jid = ','.join(jid_list)\n jid = q.submit(opt(args.sample, jid),\n '{job_home}/aln_2.merge_bam.sh {sample}'.format(job_home=job_home,\n sample=args.sample))\n jid = q.submit(opt(args.sample, jid),\n '{job_home}/aln_3.markdup.sh {sample}'.format(job_home=job_home,\n sample=args.sample))\n jid = q.submit(opt(args.sample, jid),\n '{job_home}/aln_4.indel_realign.sh {sample}'.format(job_home=\n job_home, sample=args.sample))\n jid = q.submit(opt(args.sample, jid),\n '{job_home}/aln_5.bqsr.sh {sample}'.format(job_home=job_home,\n sample=args.sample))\n if parentid(args.sample) != 'None':\n q.submit(opt(args.sample, jid),\n '{job_home}/aln_6.upload_bam.sh {sample}'.format(job_home=\n job_home, sample=args.sample))\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Alignment job submitter')\n parser.add_argument('sample', metavar='sample name')\n return parser.parse_args()\n\n\ndef parentid(sample):\n with open(sample + '/run_info') as run_info:\n for line in run_info:\n if line[:8] == 'PARENTID':\n return line.strip().split('=')[1]\n\n\ndef opt(sample, jid=None):\n opt = '-j y -o {log_dir} -l h_vmem=4G'.format(log_dir=log_dir(sample))\n if jid is not None:\n opt = '-hold_jid {jid} {opt}'.format(jid=jid, opt=opt)\n return opt\n\n\nif __name__ == '__main__':\n main()\n", "<import token>\n<assignment token>\nsys.path.append(pipe_home)\n<import token>\n\n\ndef main():\n args = parse_args()\n q = GridEngineQueue()\n jid_list = []\n for pu in [fastq.split('.')[1] for fastq in glob.glob(\n '{sample}/fastq/{sample}.*.R1.fastq.gz'.format(sample=args.sample))]:\n jid_list.append(q.submit(opt(args.sample),\n '{job_home}/aln_1.align_sort.sh {sample} {pu}'.format(job_home=\n job_home, sample=args.sample, pu=pu)))\n jid = ','.join(jid_list)\n jid = q.submit(opt(args.sample, jid),\n '{job_home}/aln_2.merge_bam.sh {sample}'.format(job_home=job_home,\n sample=args.sample))\n jid = q.submit(opt(args.sample, jid),\n '{job_home}/aln_3.markdup.sh {sample}'.format(job_home=job_home,\n sample=args.sample))\n jid = q.submit(opt(args.sample, jid),\n '{job_home}/aln_4.indel_realign.sh {sample}'.format(job_home=\n job_home, sample=args.sample))\n jid = q.submit(opt(args.sample, jid),\n '{job_home}/aln_5.bqsr.sh {sample}'.format(job_home=job_home,\n sample=args.sample))\n if parentid(args.sample) != 'None':\n q.submit(opt(args.sample, jid),\n '{job_home}/aln_6.upload_bam.sh {sample}'.format(job_home=\n job_home, sample=args.sample))\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Alignment job submitter')\n parser.add_argument('sample', metavar='sample name')\n return parser.parse_args()\n\n\ndef parentid(sample):\n with open(sample + '/run_info') as run_info:\n for line in run_info:\n if line[:8] == 'PARENTID':\n return line.strip().split('=')[1]\n\n\ndef opt(sample, jid=None):\n opt = '-j y -o {log_dir} -l h_vmem=4G'.format(log_dir=log_dir(sample))\n if jid is not None:\n opt = '-hold_jid {jid} {opt}'.format(jid=jid, opt=opt)\n return opt\n\n\nif __name__ == '__main__':\n main()\n", "<import token>\n<assignment token>\n<code token>\n<import token>\n\n\ndef main():\n args = parse_args()\n q = GridEngineQueue()\n jid_list = []\n for pu in [fastq.split('.')[1] for fastq in glob.glob(\n '{sample}/fastq/{sample}.*.R1.fastq.gz'.format(sample=args.sample))]:\n jid_list.append(q.submit(opt(args.sample),\n '{job_home}/aln_1.align_sort.sh {sample} {pu}'.format(job_home=\n job_home, sample=args.sample, pu=pu)))\n jid = ','.join(jid_list)\n jid = q.submit(opt(args.sample, jid),\n '{job_home}/aln_2.merge_bam.sh {sample}'.format(job_home=job_home,\n sample=args.sample))\n jid = q.submit(opt(args.sample, jid),\n '{job_home}/aln_3.markdup.sh {sample}'.format(job_home=job_home,\n sample=args.sample))\n jid = q.submit(opt(args.sample, jid),\n '{job_home}/aln_4.indel_realign.sh {sample}'.format(job_home=\n job_home, sample=args.sample))\n jid = q.submit(opt(args.sample, jid),\n '{job_home}/aln_5.bqsr.sh {sample}'.format(job_home=job_home,\n sample=args.sample))\n if parentid(args.sample) != 'None':\n q.submit(opt(args.sample, jid),\n '{job_home}/aln_6.upload_bam.sh {sample}'.format(job_home=\n job_home, sample=args.sample))\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Alignment job submitter')\n parser.add_argument('sample', metavar='sample name')\n return parser.parse_args()\n\n\ndef parentid(sample):\n with open(sample + '/run_info') as run_info:\n for line in run_info:\n if line[:8] == 'PARENTID':\n return line.strip().split('=')[1]\n\n\ndef opt(sample, jid=None):\n opt = '-j y -o {log_dir} -l h_vmem=4G'.format(log_dir=log_dir(sample))\n if jid is not None:\n opt = '-hold_jid {jid} {opt}'.format(jid=jid, opt=opt)\n return opt\n\n\n<code token>\n", "<import token>\n<assignment token>\n<code token>\n<import token>\n\n\ndef main():\n args = parse_args()\n q = GridEngineQueue()\n jid_list = []\n for pu in [fastq.split('.')[1] for fastq in glob.glob(\n '{sample}/fastq/{sample}.*.R1.fastq.gz'.format(sample=args.sample))]:\n jid_list.append(q.submit(opt(args.sample),\n '{job_home}/aln_1.align_sort.sh {sample} {pu}'.format(job_home=\n job_home, sample=args.sample, pu=pu)))\n jid = ','.join(jid_list)\n jid = q.submit(opt(args.sample, jid),\n '{job_home}/aln_2.merge_bam.sh {sample}'.format(job_home=job_home,\n sample=args.sample))\n jid = q.submit(opt(args.sample, jid),\n '{job_home}/aln_3.markdup.sh {sample}'.format(job_home=job_home,\n sample=args.sample))\n jid = q.submit(opt(args.sample, jid),\n '{job_home}/aln_4.indel_realign.sh {sample}'.format(job_home=\n job_home, sample=args.sample))\n jid = q.submit(opt(args.sample, jid),\n '{job_home}/aln_5.bqsr.sh {sample}'.format(job_home=job_home,\n sample=args.sample))\n if parentid(args.sample) != 'None':\n q.submit(opt(args.sample, jid),\n '{job_home}/aln_6.upload_bam.sh {sample}'.format(job_home=\n job_home, sample=args.sample))\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Alignment job submitter')\n parser.add_argument('sample', metavar='sample name')\n return parser.parse_args()\n\n\n<function token>\n\n\ndef opt(sample, jid=None):\n opt = '-j y -o {log_dir} -l h_vmem=4G'.format(log_dir=log_dir(sample))\n if jid is not None:\n opt = '-hold_jid {jid} {opt}'.format(jid=jid, opt=opt)\n return opt\n\n\n<code token>\n", "<import token>\n<assignment token>\n<code token>\n<import token>\n<function token>\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Alignment job submitter')\n parser.add_argument('sample', metavar='sample name')\n return parser.parse_args()\n\n\n<function token>\n\n\ndef opt(sample, jid=None):\n opt = '-j y -o {log_dir} -l h_vmem=4G'.format(log_dir=log_dir(sample))\n if jid is not None:\n opt = '-hold_jid {jid} {opt}'.format(jid=jid, opt=opt)\n return opt\n\n\n<code token>\n", "<import token>\n<assignment token>\n<code token>\n<import token>\n<function token>\n<function token>\n<function token>\n\n\ndef opt(sample, jid=None):\n opt = '-j y -o {log_dir} -l h_vmem=4G'.format(log_dir=log_dir(sample))\n if jid is not None:\n opt = '-hold_jid {jid} {opt}'.format(jid=jid, opt=opt)\n return opt\n\n\n<code token>\n", "<import token>\n<assignment token>\n<code token>\n<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n" ]
false
98,773
8571796aba34ba081db99a7128e7fb261326051a
# Copyright (C) 2013-2015 A. Eijkhoudt and others # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. #!/usr/bin/env python # coding: utf-8 # Base Python modules import os import sys import hashlib import traceback import datetime class File(object): def __init__(self, fullpath, config, magic): """ Attempt to parse the file passed via the fullpath variable and store its name, size, owner, group, MACtimes, MD5/SHA1/SHA256 hashes and file magic properties in the object's properties. """ if not fullpath: pass else: try: self.fullpath = str(fullpath) self.name = str(os.path.basename(fullpath)) self.size = str(os.path.getsize(fullpath)) except: raise IOError("""Cannot read basic file information. Permissions problem?""") try: self.owner = str(os.stat(fullpath).st_uid) self.group = str(os.stat(fullpath).st_gid) except: self.owner = -1 self.group = -1 if config.DEBUG: print("""Cannot read owner/group id. File system might not support ownerships.""") try: self.perm = oct(os.stat(fullpath).st_mode) except: self.perm = 'UFORIA_NO_PERM' if config.DEBUG: print("""Cannot read permissions. File system might not support permissions.""") try: timestamp = os.path.getmtime(fullpath) self.mtime = datetime.datetime.fromtimestamp(timestamp).isoformat() except: self.mtime = Null if config.DEBUG: print('File system might not support MACtimes.') try: timestamp = os.path.getatime(fullpath) self.atime = datetime.datetime.fromtimestamp(timestamp).isoformat() except: self.atime = Null if config.DEBUG: print('File system might not support MACtimes.') try: timestamp = os.path.getctime(fullpath) self.ctime = datetime.datetime.fromtimestamp(timestamp).isoformat() except: self.ctime = Null if config.DEBUG: print('File system might not support MACtimes.') try: self.md5 = hashlib.md5() self.sha1 = hashlib.sha1() self.sha256 = hashlib.sha256() with open(fullpath, 'rb') as f: for chunk in iter(lambda: f.read(config.CHUNKSIZE), b''): self.md5.update(chunk) self.sha1.update(chunk) self.sha256.update(chunk) self.md5 = str(self.md5.hexdigest()) self.sha1 = str(self.sha1.hexdigest()) self.sha256 = str(self.sha256.hexdigest()) except: traceback.print_exc(file=sys.stderr) try: magic_default = magic.Magic(magic_file=config.MAGICFILE) magic_mime = magic.Magic(mime=True, magic_file=config.MAGICFILE) except: traceback.print_exc(file=sys.stderr) try: self.ftype = str(magic_default.from_file(fullpath)) self.mtype = str(magic_mime.from_file(fullpath)) self.btype = str(magic_default.from_buffer(open(fullpath).read(65536))) except: traceback.print_exc(file=sys.stderr) if config.DEBUG: print "Filename:\t", self.name print "UID/GID:\t", self.owner + ":" + self.group print "Permissions:\t", self.perm print ("Magic:\t\tF:", self.ftype, "\n\t\tM:", self.mtype, "\n\t\tB:", self.btype) print ("Modified:\t", self.mtime, "\nAccessed:\t", self.atime, "\nChanged:\t", self.ctime) print ("MD5:\t\t", self.md5, "\nSHA1:\t\t", self.sha1, "\nSHA256:\t\t", self.sha256)
[ "# Copyright (C) 2013-2015 A. Eijkhoudt and others\n\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n\n#!/usr/bin/env python\n# coding: utf-8\n\n# Base Python modules\nimport os\nimport sys\nimport hashlib\nimport traceback\nimport datetime\n\n\nclass File(object):\n\n def __init__(self, fullpath, config, magic):\n \"\"\"\n Attempt to parse the file passed via the fullpath variable\n and store its name, size, owner, group, MACtimes,\n MD5/SHA1/SHA256 hashes and file magic properties in the\n object's properties.\n \"\"\"\n if not fullpath:\n pass\n else:\n try:\n self.fullpath = str(fullpath)\n self.name = str(os.path.basename(fullpath))\n self.size = str(os.path.getsize(fullpath))\n except:\n raise IOError(\"\"\"Cannot read basic file information.\n Permissions problem?\"\"\")\n try:\n self.owner = str(os.stat(fullpath).st_uid)\n self.group = str(os.stat(fullpath).st_gid)\n except:\n self.owner = -1\n self.group = -1\n if config.DEBUG:\n print(\"\"\"Cannot read owner/group id.\n File system might not support ownerships.\"\"\")\n try:\n self.perm = oct(os.stat(fullpath).st_mode)\n except:\n self.perm = 'UFORIA_NO_PERM'\n if config.DEBUG:\n print(\"\"\"Cannot read permissions.\n File system might not support permissions.\"\"\")\n try:\n timestamp = os.path.getmtime(fullpath)\n self.mtime = datetime.datetime.fromtimestamp(timestamp).isoformat()\n except:\n self.mtime = Null\n if config.DEBUG:\n print('File system might not support MACtimes.')\n try:\n timestamp = os.path.getatime(fullpath)\n self.atime = datetime.datetime.fromtimestamp(timestamp).isoformat()\n except:\n self.atime = Null\n if config.DEBUG:\n print('File system might not support MACtimes.')\n try:\n timestamp = os.path.getctime(fullpath)\n self.ctime = datetime.datetime.fromtimestamp(timestamp).isoformat()\n except:\n self.ctime = Null\n if config.DEBUG:\n print('File system might not support MACtimes.')\n try:\n self.md5 = hashlib.md5()\n self.sha1 = hashlib.sha1()\n self.sha256 = hashlib.sha256()\n with open(fullpath, 'rb') as f:\n for chunk in iter(lambda: f.read(config.CHUNKSIZE), b''):\n self.md5.update(chunk)\n self.sha1.update(chunk)\n self.sha256.update(chunk)\n self.md5 = str(self.md5.hexdigest())\n self.sha1 = str(self.sha1.hexdigest())\n self.sha256 = str(self.sha256.hexdigest())\n except:\n traceback.print_exc(file=sys.stderr)\n try:\n magic_default = magic.Magic(magic_file=config.MAGICFILE)\n magic_mime = magic.Magic(mime=True,\n magic_file=config.MAGICFILE)\n except:\n traceback.print_exc(file=sys.stderr)\n try: \n self.ftype = str(magic_default.from_file(fullpath))\n self.mtype = str(magic_mime.from_file(fullpath))\n self.btype = str(magic_default.from_buffer(open(fullpath).read(65536)))\n except:\n traceback.print_exc(file=sys.stderr)\n if config.DEBUG:\n print \"Filename:\\t\", self.name\n print \"UID/GID:\\t\", self.owner + \":\" + self.group\n print \"Permissions:\\t\", self.perm\n print (\"Magic:\\t\\tF:\", self.ftype, \"\\n\\t\\tM:\",\n self.mtype, \"\\n\\t\\tB:\", self.btype)\n print (\"Modified:\\t\", self.mtime, \"\\nAccessed:\\t\",\n self.atime, \"\\nChanged:\\t\", self.ctime)\n print (\"MD5:\\t\\t\", self.md5, \"\\nSHA1:\\t\\t\",\n self.sha1, \"\\nSHA256:\\t\\t\", self.sha256)\n" ]
true
98,774
d274f778d563fdbd5abff6aec38ef02555a6b146
#!/usr/bin/env python import roslib; roslib.load_manifest('brsu_hmm_eid_use_cases') import roslib.message import rospy #from brics_actuator.msg import JointTorques from brsu_hmm_eid_messages.msg import obs_arm_JointTorques if __name__ == '__main__': rospy.init_node('set_arm_effort', anonymous=True) while not rospy.is_shutdown(): try: pub = rospy.Publisher('/arm_controller/torque_command', obs_arm_JointTorques) #msg2send = JointTorques() #msg2send.poisonStamp.description = "" #msg2send.poisonStamp.originator = "" #msg2send.poisonStamp.qos = 1 #msg2send.torques = [5,5,5,5,5] msg2send = obs_arm_JointTorques() msg2send.header.stamp.secs = rospy.Time.now().secs msg2send.torques = [5,5,5,5,5] pub.publish(msg2send) rospy.loginfo("publishing...") rospy.sleep(1) except rospy.ROSInterruptException: pass
[ "#!/usr/bin/env python\nimport roslib; roslib.load_manifest('brsu_hmm_eid_use_cases')\nimport roslib.message \nimport rospy\n\n#from brics_actuator.msg import JointTorques\nfrom brsu_hmm_eid_messages.msg import obs_arm_JointTorques\n\nif __name__ == '__main__':\n rospy.init_node('set_arm_effort', anonymous=True)\n \n while not rospy.is_shutdown():\n try:\n pub = rospy.Publisher('/arm_controller/torque_command', obs_arm_JointTorques)\n #msg2send = JointTorques()\n #msg2send.poisonStamp.description = \"\"\n #msg2send.poisonStamp.originator = \"\"\n #msg2send.poisonStamp.qos = 1 \n #msg2send.torques = [5,5,5,5,5]\n msg2send = obs_arm_JointTorques()\n msg2send.header.stamp.secs = rospy.Time.now().secs\n msg2send.torques = [5,5,5,5,5]\n pub.publish(msg2send)\n rospy.loginfo(\"publishing...\")\n rospy.sleep(1)\n except rospy.ROSInterruptException:\n pass", "import roslib\nroslib.load_manifest('brsu_hmm_eid_use_cases')\nimport roslib.message\nimport rospy\nfrom brsu_hmm_eid_messages.msg import obs_arm_JointTorques\nif __name__ == '__main__':\n rospy.init_node('set_arm_effort', anonymous=True)\n while not rospy.is_shutdown():\n try:\n pub = rospy.Publisher('/arm_controller/torque_command',\n obs_arm_JointTorques)\n msg2send = obs_arm_JointTorques()\n msg2send.header.stamp.secs = rospy.Time.now().secs\n msg2send.torques = [5, 5, 5, 5, 5]\n pub.publish(msg2send)\n rospy.loginfo('publishing...')\n rospy.sleep(1)\n except rospy.ROSInterruptException:\n pass\n", "<import token>\nroslib.load_manifest('brsu_hmm_eid_use_cases')\n<import token>\nif __name__ == '__main__':\n rospy.init_node('set_arm_effort', anonymous=True)\n while not rospy.is_shutdown():\n try:\n pub = rospy.Publisher('/arm_controller/torque_command',\n obs_arm_JointTorques)\n msg2send = obs_arm_JointTorques()\n msg2send.header.stamp.secs = rospy.Time.now().secs\n msg2send.torques = [5, 5, 5, 5, 5]\n pub.publish(msg2send)\n rospy.loginfo('publishing...')\n rospy.sleep(1)\n except rospy.ROSInterruptException:\n pass\n", "<import token>\n<code token>\n<import token>\n<code token>\n" ]
false
98,775
ced2377d0e950d10b74cdef14bf89d1fd6235922
#!/usr/bin/env python from __future__ import division import roslib; roslib.load_manifest('galvodirector') import rospy import copy import numpy as N import tf import threading from galvodirector.msg import MsgGalvoCommand from tracking.msg import ArenaState from geometry_msgs.msg import Point, Transform from sensor_msgs.msg import PointCloud, ChannelFloat32 from std_msgs.msg import Header from patterngen.msg import MsgPattern from patterngen.srv import * class NullClass: pass ############################################################################### ############################################################################### ############################################################################### # The class GalvoDirector subscribes to ArenaState, and draws the commanded # pattern into the commanded frame, e.g. draw a grid at the origin of the # "Fly1" frame, or draw a circle at the origin of the "Arena" frame. # # Uses the PatternGen service to compute the various point locations. # Publishes GalvoDriver/pointcloud for the galvos to scan. # ############################################################################### ############################################################################### ############################################################################### class GalvoDirector: def __init__(self): self.initialized = False self.lock = threading.Lock() self.tfrx = tf.TransformListener() # Messages #self.subTF = rospy.Subscriber('tf', Transform, self.Transform_callback) queue_size_arenastate = rospy.get_param('tracking/queue_size_arenastate', 1) self.subArenaState = rospy.Subscriber('ArenaState', ArenaState, self.ArenaState_callback, queue_size=queue_size_arenastate) self.subGalvoCommand = rospy.Subscriber('GalvoDirector/command', MsgGalvoCommand, self.GalvoCommand_callback, queue_size=2) self.pubGalvoPointCloud = rospy.Publisher('GalvoDriver/pointcloud', PointCloud, latch=True) self.pubGalvoPointCloudMm = rospy.Publisher('GalvoDriver/pointcloudmm', PointCloud, latch=True) # Attach to services. try: rospy.wait_for_service('GetPatternPoints') self.GetPatternPoints = rospy.ServiceProxy('GetPatternPoints', SrvGetPatternPoints) except (rospy.ServiceException, IOError), e: print "Service GetPatternPoints not found: %s" % e rospy.core.add_client_shutdown_hook(self.Preshutdown_callback) rospy.on_shutdown(self.OnShutdown_callback) # Calibration data (median values) to convert millimeters to volts, from "roslaunch galvodirector calibrator.launch". self.mx = rospy.get_param('galvodirector/mx', 0.0) #0.05111587 self.bx = rospy.get_param('galvodirector/bx', 0.0) #-0.90610801 self.my = rospy.get_param('galvodirector/my', 0.0) #-0.05003545 self.by = rospy.get_param('galvodirector/by', 0.0) #3.15307329 self.xBeamsink = rospy.get_param('galvodirector/xBeamsink', 0.0) # volts self.yBeamsink = rospy.get_param('galvodirector/yBeamsink', 0.0) # volts self.enable_laser = False self.arenastate = ArenaState() self.pointcloudtemplate_list = [] self.pointcloud_list = [] self.frameidPosition_list = [] self.units = 'millimeters' self.pointcloudBeamsink = PointCloud(header=Header(frame_id='Arena', stamp=rospy.Time.now()), points=[Point(x=self.xBeamsink, y=self.yBeamsink, z=0.0)], channels=[ChannelFloat32(name='intensity', values=[0.0])]) self.pointcloudBeamsinkMm = self.UnitsFromVoltsPointcloud(copy.deepcopy(self.pointcloudBeamsink)) self.timePrev = rospy.Time.now().to_sec() self.initialized = True def Transform_callback(self, tr): # If any of the frames in frameidPosition_list are updated, then publish the pointcloud. for x in tr.transforms: if (x.child_frame_id in self.frameidPosition_list): self.PublishPointcloud() break #rospy.logwarn ('Transform_callback() dt=%0.5f' % (rospy.Time.now().to_sec()-self.timePrev)) # Some of these are slow, e.g. 0.08, 0.1 #self.timePrev = rospy.Time.now().to_sec() def ArenaState_callback(self, arenastate): with self.lock: self.arenastate = arenastate self.PublishPointcloud() def Preshutdown_callback(self, reason=None): self.enable_laser = False self.PublishPointcloud() #self.MoveToBeamsink() def OnShutdown_callback(self): pass # GalvoCommand_callback() # Receive the list of patterns, and store their pointcloud templates (centered at origin). # def GalvoCommand_callback(self, command): if (self.initialized): with self.lock: self.enable_laser = command.enable_laser self.units = command.units # Units apply to all the patterns. #rospy.logwarn('enable_laser: %s' % self.enable_laser) # If patterns were given, then load them into the pointcloudtemplates. if len(command.pattern_list) > 0: # Regenerate all the patterns requested. This "template" is the computed points centered at (0,0). self.pointcloudtemplate_list = [] self.frameidPosition_list = [] for iPattern in range(len(command.pattern_list)): self.frameidPosition_list.append(command.pattern_list[iPattern].frameidPosition) # Save all the target frames for the TF callback. # Compute pattern points, if necessary. if len(command.pattern_list[iPattern].points)==0: gpp = self.GetPatternPoints(SrvGetPatternPointsRequest(pattern=command.pattern_list[iPattern])) pattern = gpp.pattern else: pattern = command.pattern_list[iPattern] # Store the pointcloud templates. self.pointcloudtemplate_list.append(self.PointCloudFromPoints(pattern.frameidPosition, pattern.points)) self.PublishPointcloud() # GetMaxPatternRate() # Get the fastest pattern update rate. # def GetMaxPatternRate(self, pattern_list): hzPatternMax = 0 for pattern in pattern_list: hzPatternMax = max(hzPatternMax, pattern.hzPattern) return hzPatternMax # PublishPointcloud() # If laser enabled, then transform the pointcloudtemplates to their respective frames, # If laser disabled, then use the beamsink pointcloud. # # Publish points to the galvo driver. # def PublishPointcloud(self): if self.initialized: if self.enable_laser: self.pointcloud_list = [] if len(self.pointcloudtemplate_list)>0 and len(self.arenastate.flies)>0: for i in range(len(self.pointcloudtemplate_list)): pointcloud_template = self.pointcloudtemplate_list[i] #t1 = rospy.Time.now().to_sec() try: pointcloud_template.header.stamp = self.tfrx.getLatestCommonTime('Arena', pointcloud_template.header.frame_id) except tf.Exception: pointcloud_template.header.stamp = self.arenastate.flies[0].header.stamp # BUG: Need to make this use the correct fly #. #t2 = rospy.Time.now().to_sec() if self.tfrx.canTransform('Arena', pointcloud_template.header.frame_id, pointcloud_template.header.stamp): try: pointcloud = self.tfrx.transformPointCloud('Arena', pointcloud_template) except tf.Exception, e: rospy.logwarn('Exception transforming pointcloud frame %s->%s: %s' % (pointcloud_template.header.frame_id, 'Arena', e)) else: self.pointcloud_list.append(pointcloud) else: rospy.logwarn ('Cannot transform from frame %s at %s' % (pointcloud_template.header.frame_id, pointcloud_template.header.stamp)) #t3 = rospy.Time.now().to_sec() #rospy.logwarn('GalvoDirector, stamp=%s, wait dt=%0.5f, transform dt=%0.5f' % (pointcloud_template.header.stamp,(t2-t1),(t3-t2))) # BUG: Occasional 0.1 sec times. #rospy.logwarn ('now,pointcloud_template,%s,%s' % (rospy.Time.now(), pointcloud_template.header.stamp)) #rospy.logwarn('tfrx.getLatestCommonTime()=%s, stamp=%s' % (self.tfrx.getLatestCommonTime('Arena', pointcloud_template.header.frame_id),pointcloud_template.header.stamp)) # Publish a pointcloud in volts and mm. pointcloudmm = self.GetUnifiedPointcloud(self.pointcloud_list) pointcloudv = self.VoltsFromUnitsPointcloud(copy.deepcopy(pointcloudmm)) self.pubGalvoPointCloud.publish(pointcloudv) self.pubGalvoPointCloudMm.publish(pointcloudmm) else: # not self.enable_laser # Point laser at the beam sink. self.pointcloudBeamsink.header.stamp=rospy.Time.now() self.pubGalvoPointCloud.publish(self.pointcloudBeamsink) self.pointcloudBeamsinkMm.header.stamp=rospy.Time.now() self.pubGalvoPointCloudMm.publish(self.pointcloudBeamsinkMm) # GetUnifiedPointcloud() # Combine multiple pointclouds into one pointcloud. # def GetUnifiedPointcloud(self, pointcloud_list): pointcloudUnified = PointCloud() pointcloudUnified.points = [] pointcloudUnified.channels = [] if len(pointcloud_list) > 0: pointcloudUnified.header = pointcloud_list[0].header # They all have different headers, but just use the first one. pointcloudUnified.channels.append(ChannelFloat32(name='intensity', values=[])) for pointcloud in pointcloud_list: pointcloudUnified.points.extend(pointcloud.points) pointcloudUnified.channels[0].values.extend(pointcloud.channels[0].values) return pointcloudUnified # AddPatternToTemplates() # Append the requested pattern to the list of pointcloud templates. # def AddPatternToTemplates(self, req_gpp): if (self.initialized): resp_gpp = self.GetPatternPoints(req_gpp) pointcloud = self.PointCloudFromPoints('Arena', resp_gpp.pattern.points) self.pointcloudtemplate_list.append(pointcloud) #rospy.logwarn(resp_gpp.pattern.points) # VoltsFromUnitsPointcloud() # Inplace convert the pointcloud units to volts. # def VoltsFromUnitsPointcloud(self, pointcloud): if self.units == 'millimeters': for point in pointcloud.points: point.x *= self.mx point.x += self.bx point.y *= self.my point.y += self.by # Clip to 10 point.x = min(point.x,+10.0) point.x = max(point.x,-10.0) point.y = min(point.y,+10.0) point.y = max(point.y,-10.0) elif self.units=='volts': pass return pointcloud # UnitsFromVoltsPointcloud() # Inplace convert the pointcloud units to volts. # def UnitsFromVoltsPointcloud(self, pointcloud): if self.units == 'millimeters': for point in pointcloud.points: point.x -= self.bx point.x /= self.mx point.y -= self.by point.y /= self.my elif self.units=='volts': pass return pointcloud # PointCloudFromPoints() # Reformat the given points as a pointcloud. # def PointCloudFromPoints(self, frameidPosition, points): # BUG: add frameidAngle points_xy = [] intensity = [] for i in range(len(points)): points_xy.append(Point(x=points[i].x, y=points[i].y, z=0.0)) intensity.append(1.0)# i.e. LASERON #points[i].z) if len(intensity)>0: intensity[0] = 0.0 # Make sure laser is off when going to start of pattern. pointcloud = PointCloud(header=Header(frame_id=frameidPosition, stamp=rospy.Time.now()), points=points_xy, channels=[ChannelFloat32(name='intensity', values=intensity),]) return pointcloud def Main(self): rospy.spin() if __name__ == '__main__': rospy.init_node('GalvoDirector') gd = GalvoDirector() gd.Main()
[ "#!/usr/bin/env python\nfrom __future__ import division\nimport roslib; roslib.load_manifest('galvodirector')\nimport rospy\nimport copy\nimport numpy as N\nimport tf\nimport threading\n\nfrom galvodirector.msg import MsgGalvoCommand\nfrom tracking.msg import ArenaState\nfrom geometry_msgs.msg import Point, Transform\nfrom sensor_msgs.msg import PointCloud, ChannelFloat32\nfrom std_msgs.msg import Header\nfrom patterngen.msg import MsgPattern\nfrom patterngen.srv import *\n\n\nclass NullClass:\n pass\n \n\n###############################################################################\n###############################################################################\n###############################################################################\n# The class GalvoDirector subscribes to ArenaState, and draws the commanded\n# pattern into the commanded frame, e.g. draw a grid at the origin of the \n# \"Fly1\" frame, or draw a circle at the origin of the \"Arena\" frame.\n#\n# Uses the PatternGen service to compute the various point locations. \n# Publishes GalvoDriver/pointcloud for the galvos to scan.\n#\n###############################################################################\n###############################################################################\n###############################################################################\nclass GalvoDirector:\n\n def __init__(self):\n self.initialized = False\n self.lock = threading.Lock()\n \n self.tfrx = tf.TransformListener()\n\n # Messages\n #self.subTF = rospy.Subscriber('tf', Transform, self.Transform_callback)\n queue_size_arenastate = rospy.get_param('tracking/queue_size_arenastate', 1)\n self.subArenaState = rospy.Subscriber('ArenaState', ArenaState, self.ArenaState_callback, queue_size=queue_size_arenastate)\n\n self.subGalvoCommand = rospy.Subscriber('GalvoDirector/command', MsgGalvoCommand, self.GalvoCommand_callback, queue_size=2)\n self.pubGalvoPointCloud = rospy.Publisher('GalvoDriver/pointcloud', PointCloud, latch=True)\n self.pubGalvoPointCloudMm = rospy.Publisher('GalvoDriver/pointcloudmm', PointCloud, latch=True)\n\n # Attach to services.\n try:\n rospy.wait_for_service('GetPatternPoints')\n self.GetPatternPoints = rospy.ServiceProxy('GetPatternPoints', SrvGetPatternPoints)\n except (rospy.ServiceException, IOError), e:\n print \"Service GetPatternPoints not found: %s\" % e\n\n\n rospy.core.add_client_shutdown_hook(self.Preshutdown_callback)\n rospy.on_shutdown(self.OnShutdown_callback)\n \n # Calibration data (median values) to convert millimeters to volts, from \"roslaunch galvodirector calibrator.launch\".\n self.mx = rospy.get_param('galvodirector/mx', 0.0) #0.05111587\n self.bx = rospy.get_param('galvodirector/bx', 0.0) #-0.90610801\n self.my = rospy.get_param('galvodirector/my', 0.0) #-0.05003545\n self.by = rospy.get_param('galvodirector/by', 0.0) #3.15307329\n \n self.xBeamsink = rospy.get_param('galvodirector/xBeamsink', 0.0) # volts\n self.yBeamsink = rospy.get_param('galvodirector/yBeamsink', 0.0) # volts\n self.enable_laser = False\n \n self.arenastate = ArenaState()\n self.pointcloudtemplate_list = []\n self.pointcloud_list = []\n self.frameidPosition_list = []\n self.units = 'millimeters'\n \n self.pointcloudBeamsink = PointCloud(header=Header(frame_id='Arena', \n stamp=rospy.Time.now()),\n points=[Point(x=self.xBeamsink, \n y=self.yBeamsink, \n z=0.0)],\n channels=[ChannelFloat32(name='intensity',\n values=[0.0])])\n self.pointcloudBeamsinkMm = self.UnitsFromVoltsPointcloud(copy.deepcopy(self.pointcloudBeamsink))\n \n \n \n self.timePrev = rospy.Time.now().to_sec()\n \n self.initialized = True\n\n\n def Transform_callback(self, tr):\n # If any of the frames in frameidPosition_list are updated, then publish the pointcloud.\n for x in tr.transforms:\n if (x.child_frame_id in self.frameidPosition_list):\n self.PublishPointcloud()\n break\n #rospy.logwarn ('Transform_callback() dt=%0.5f' % (rospy.Time.now().to_sec()-self.timePrev)) # Some of these are slow, e.g. 0.08, 0.1\n #self.timePrev = rospy.Time.now().to_sec()\n\n\n def ArenaState_callback(self, arenastate):\n with self.lock:\n self.arenastate = arenastate\n self.PublishPointcloud()\n \n \n def Preshutdown_callback(self, reason=None):\n self.enable_laser = False\n self.PublishPointcloud()\n #self.MoveToBeamsink()\n \n \n def OnShutdown_callback(self):\n pass\n\n\n # GalvoCommand_callback()\n # Receive the list of patterns, and store their pointcloud templates (centered at origin).\n #\n def GalvoCommand_callback(self, command):\n if (self.initialized):\n with self.lock:\n self.enable_laser = command.enable_laser\n self.units = command.units # Units apply to all the patterns.\n #rospy.logwarn('enable_laser: %s' % self.enable_laser)\n \n # If patterns were given, then load them into the pointcloudtemplates.\n if len(command.pattern_list) > 0:\n # Regenerate all the patterns requested. This \"template\" is the computed points centered at (0,0).\n self.pointcloudtemplate_list = []\n self.frameidPosition_list = []\n \n for iPattern in range(len(command.pattern_list)):\n self.frameidPosition_list.append(command.pattern_list[iPattern].frameidPosition) # Save all the target frames for the TF callback.\n \n # Compute pattern points, if necessary.\n if len(command.pattern_list[iPattern].points)==0:\n gpp = self.GetPatternPoints(SrvGetPatternPointsRequest(pattern=command.pattern_list[iPattern]))\n pattern = gpp.pattern\n else:\n pattern = command.pattern_list[iPattern]\n \n # Store the pointcloud templates.\n self.pointcloudtemplate_list.append(self.PointCloudFromPoints(pattern.frameidPosition, pattern.points))\n \n self.PublishPointcloud()\n\n\n # GetMaxPatternRate()\n # Get the fastest pattern update rate.\n #\n def GetMaxPatternRate(self, pattern_list):\n hzPatternMax = 0\n for pattern in pattern_list:\n hzPatternMax = max(hzPatternMax, pattern.hzPattern)\n\n return hzPatternMax\n \n \n \n # PublishPointcloud()\n # If laser enabled, then transform the pointcloudtemplates to their respective frames,\n # If laser disabled, then use the beamsink pointcloud.\n #\n # Publish points to the galvo driver. \n #\n def PublishPointcloud(self): \n\n if self.initialized:\n if self.enable_laser:\n self.pointcloud_list = []\n if len(self.pointcloudtemplate_list)>0 and len(self.arenastate.flies)>0:\n for i in range(len(self.pointcloudtemplate_list)):\n pointcloud_template = self.pointcloudtemplate_list[i]\n #t1 = rospy.Time.now().to_sec()\n \n try:\n pointcloud_template.header.stamp = self.tfrx.getLatestCommonTime('Arena', pointcloud_template.header.frame_id)\n except tf.Exception:\n pointcloud_template.header.stamp = self.arenastate.flies[0].header.stamp # BUG: Need to make this use the correct fly #.\n \n #t2 = rospy.Time.now().to_sec()\n if self.tfrx.canTransform('Arena', \n pointcloud_template.header.frame_id, \n pointcloud_template.header.stamp):\n try:\n pointcloud = self.tfrx.transformPointCloud('Arena', pointcloud_template)\n except tf.Exception, e:\n rospy.logwarn('Exception transforming pointcloud frame %s->%s: %s' % (pointcloud_template.header.frame_id, 'Arena', e))\n else:\n self.pointcloud_list.append(pointcloud)\n else:\n rospy.logwarn ('Cannot transform from frame %s at %s' % (pointcloud_template.header.frame_id, pointcloud_template.header.stamp))\n \n #t3 = rospy.Time.now().to_sec()\n #rospy.logwarn('GalvoDirector, stamp=%s, wait dt=%0.5f, transform dt=%0.5f' % (pointcloud_template.header.stamp,(t2-t1),(t3-t2))) # BUG: Occasional 0.1 sec times.\n #rospy.logwarn ('now,pointcloud_template,%s,%s' % (rospy.Time.now(), pointcloud_template.header.stamp))\n \n #rospy.logwarn('tfrx.getLatestCommonTime()=%s, stamp=%s' % (self.tfrx.getLatestCommonTime('Arena', pointcloud_template.header.frame_id),pointcloud_template.header.stamp))\n \n \n # Publish a pointcloud in volts and mm.\n pointcloudmm = self.GetUnifiedPointcloud(self.pointcloud_list)\n pointcloudv = self.VoltsFromUnitsPointcloud(copy.deepcopy(pointcloudmm))\n self.pubGalvoPointCloud.publish(pointcloudv)\n self.pubGalvoPointCloudMm.publish(pointcloudmm)\n \n else: # not self.enable_laser\n \n # Point laser at the beam sink.\n self.pointcloudBeamsink.header.stamp=rospy.Time.now()\n self.pubGalvoPointCloud.publish(self.pointcloudBeamsink)\n self.pointcloudBeamsinkMm.header.stamp=rospy.Time.now()\n self.pubGalvoPointCloudMm.publish(self.pointcloudBeamsinkMm)\n \n\n # GetUnifiedPointcloud()\n # Combine multiple pointclouds into one pointcloud.\n #\n def GetUnifiedPointcloud(self, pointcloud_list):\n pointcloudUnified = PointCloud()\n pointcloudUnified.points = []\n pointcloudUnified.channels = []\n \n if len(pointcloud_list) > 0:\n pointcloudUnified.header = pointcloud_list[0].header # They all have different headers, but just use the first one.\n pointcloudUnified.channels.append(ChannelFloat32(name='intensity', values=[]))\n \n for pointcloud in pointcloud_list:\n pointcloudUnified.points.extend(pointcloud.points)\n pointcloudUnified.channels[0].values.extend(pointcloud.channels[0].values)\n \n return pointcloudUnified\n \n \n # AddPatternToTemplates()\n # Append the requested pattern to the list of pointcloud templates.\n #\n def AddPatternToTemplates(self, req_gpp):\n if (self.initialized):\n resp_gpp = self.GetPatternPoints(req_gpp)\n pointcloud = self.PointCloudFromPoints('Arena', resp_gpp.pattern.points)\n self.pointcloudtemplate_list.append(pointcloud)\n #rospy.logwarn(resp_gpp.pattern.points)\n\n\n # VoltsFromUnitsPointcloud()\n # Inplace convert the pointcloud units to volts.\n #\n def VoltsFromUnitsPointcloud(self, pointcloud):\n if self.units == 'millimeters':\n for point in pointcloud.points:\n point.x *= self.mx\n point.x += self.bx\n\n point.y *= self.my\n point.y += self.by\n \n # Clip to 10\n point.x = min(point.x,+10.0)\n point.x = max(point.x,-10.0)\n point.y = min(point.y,+10.0)\n point.y = max(point.y,-10.0)\n \n elif self.units=='volts':\n pass\n\n \n return pointcloud\n \n\n # UnitsFromVoltsPointcloud()\n # Inplace convert the pointcloud units to volts.\n #\n def UnitsFromVoltsPointcloud(self, pointcloud):\n if self.units == 'millimeters':\n for point in pointcloud.points:\n point.x -= self.bx\n point.x /= self.mx\n\n point.y -= self.by\n point.y /= self.my\n \n elif self.units=='volts':\n pass\n\n \n return pointcloud\n \n\n # PointCloudFromPoints()\n # Reformat the given points as a pointcloud.\n #\n def PointCloudFromPoints(self, frameidPosition, points): # BUG: add frameidAngle \n points_xy = [] \n intensity = []\n for i in range(len(points)):\n points_xy.append(Point(x=points[i].x,\n y=points[i].y,\n z=0.0))\n intensity.append(1.0)# i.e. LASERON #points[i].z)\n \n if len(intensity)>0:\n intensity[0] = 0.0 # Make sure laser is off when going to start of pattern.\n \n\n pointcloud = PointCloud(header=Header(frame_id=frameidPosition, stamp=rospy.Time.now()),\n points=points_xy,\n channels=[ChannelFloat32(name='intensity',\n values=intensity),])\n return pointcloud \n \n\n def Main(self):\n rospy.spin()\n \n\n\nif __name__ == '__main__':\n rospy.init_node('GalvoDirector')\n gd = GalvoDirector()\n gd.Main()\n \n\n\n" ]
true
98,776
409a431a9dac76da605b18771d81d61ccd6d77b6
from django.contrib import admin from .models import InstagramUser, InstagramPost, Media admin.site.register([InstagramUser, InstagramPost, Media])
[ "from django.contrib import admin\nfrom .models import InstagramUser, InstagramPost, Media\n\n\nadmin.site.register([InstagramUser, InstagramPost, Media])\n", "from django.contrib import admin\nfrom .models import InstagramUser, InstagramPost, Media\nadmin.site.register([InstagramUser, InstagramPost, Media])\n", "<import token>\nadmin.site.register([InstagramUser, InstagramPost, Media])\n", "<import token>\n<code token>\n" ]
false
98,777
1fc0e2847b0986cc2f7014a2ac133f82e6f4472b
import plotter import numpy as np import matrix_io import random import neural_net def stochastic_epoch(network, X, y): order = range(X.shape[0]) random.shuffle(order) for c in order: network.backpropagate(X[c], y[c]) def SGD(network, X, y, epochs): for c in range(epochs): stochastic_epoch(network, X, y) def train_nn(network, X, y, Xtest, ytest): for c in range(10): SGD(network, X, y, 50) print "training error: " + str(network.classification_error(X, y)) print "test error : " + str(network.classification_error(Xtest, ytest)) plotter.plot_2D_model_predictions(network, X, y, "plots/foo/run_" + str(c) + ".png") X, y = matrix_io.load_dataset("data/xor") Xt, yt = matrix_io.load_dataset("data/xor_test") network = neural_net.NeuralNet([2,4,4,1], 3) train_nn(network, X, y, Xt, yt)
[ "import plotter\r\nimport numpy as np\r\nimport matrix_io\r\nimport random\r\n\r\nimport neural_net\r\n\r\ndef stochastic_epoch(network, X, y):\r\n order = range(X.shape[0])\r\n random.shuffle(order)\r\n for c in order:\r\n network.backpropagate(X[c], y[c])\r\n\r\ndef SGD(network, X, y, epochs):\r\n for c in range(epochs):\r\n stochastic_epoch(network, X, y)\r\n\r\ndef train_nn(network, X, y, Xtest, ytest):\r\n for c in range(10):\r\n SGD(network, X, y, 50)\r\n print \"training error: \" + str(network.classification_error(X, y))\r\n print \"test error : \" + str(network.classification_error(Xtest, ytest))\r\n plotter.plot_2D_model_predictions(network, X, y, \"plots/foo/run_\" + str(c) + \".png\")\r\n\r\n\r\n\r\nX, y = matrix_io.load_dataset(\"data/xor\")\r\nXt, yt = matrix_io.load_dataset(\"data/xor_test\")\r\nnetwork = neural_net.NeuralNet([2,4,4,1], 3)\r\ntrain_nn(network, X, y, Xt, yt)\r\n\r\n\r\n" ]
true
98,778
ea85b219096358f6fa3a1a4a57bc5bf32c2b8f60
#!/usr/bin/env python import fnmatch import os import ROOT import sys import math import json import re from optparse import OptionParser def run(command): print command os.system(command) def listFromWorkspace(file, workspace, set): res = [] wsFile = ROOT.TFile(file) argSet = wsFile.Get(workspace).set(set) it = argSet.createIterator() var = it.Next() while var: res.append(var.GetName()) var = it.Next() return res usage = """ """ parser = OptionParser(usage=usage) parser.add_option("--ws", dest="ws", help="The input workspace") parser.add_option("--cfg", dest="cfg", help="json file specifying groups") (options, args) = parser.parse_args() ws = options.ws cfg = options.cfg ROOT.gSystem.Load('$CMSSW_BASE/lib/$SCRAM_ARCH/libHiggsAnalysisCombinedLimit') data = json.load(open(cfg)) #print data paramList = listFromWorkspace(ws, 'w', 'ModelConfig_NuisParams') #print '\n'.join(paramList) for key, val in data.items(): matched = set() #print "** Doing group: " + key for pattern in val: rgx = re.compile(pattern) matched.update(x for x in paramList if re.match(rgx, x)) #print "* Using regex: " + pattern #print matched #print key + ' group = ' + str(len(matched)) print key + ' group = ' + (' '.join(matched))
[ "#!/usr/bin/env python\nimport fnmatch\nimport os\nimport ROOT\nimport sys\nimport math\nimport json\nimport re\nfrom optparse import OptionParser\n\ndef run(command):\n print command\n os.system(command)\n\ndef listFromWorkspace(file, workspace, set):\n res = []\n wsFile = ROOT.TFile(file)\n argSet = wsFile.Get(workspace).set(set)\n it = argSet.createIterator()\n var = it.Next()\n while var:\n res.append(var.GetName())\n var = it.Next()\n return res\n\nusage = \"\"\"\n\"\"\"\nparser = OptionParser(usage=usage)\n\nparser.add_option(\"--ws\", dest=\"ws\", help=\"The input workspace\")\nparser.add_option(\"--cfg\", dest=\"cfg\", help=\"json file specifying groups\")\n\n(options, args) = parser.parse_args()\n\nws = options.ws\ncfg = options.cfg\n\nROOT.gSystem.Load('$CMSSW_BASE/lib/$SCRAM_ARCH/libHiggsAnalysisCombinedLimit')\n\ndata = json.load(open(cfg))\n\n#print data\n\nparamList = listFromWorkspace(ws, 'w', 'ModelConfig_NuisParams')\n#print '\\n'.join(paramList)\n\nfor key, val in data.items():\n matched = set()\n #print \"** Doing group: \" + key\n for pattern in val:\n rgx = re.compile(pattern)\n matched.update(x for x in paramList if re.match(rgx, x))\n #print \"* Using regex: \" + pattern\n #print matched\n #print key + ' group = ' + str(len(matched)) \n print key + ' group = ' + (' '.join(matched))\n \n \n" ]
true
98,779
1faa4261c9a8db58974fb76c9a3b06c798870de7
""" Command line options tests """ import os from ._base import PyconizrTestCase from pyconizr.run import iconize from pyconizr.options import ArgParser class CmdLineTests(PyconizrTestCase): def pyconizr(self, *args): iconize(**dict(vars(ArgParser().parse_args(args)), **self.iconizr.options)) class ArgsTests(CmdLineTests): def test_nopng(self): self.pyconizr('--nopng', '--out-icons', 'icons') png_sprite = os.path.splitext(self.iconizr.sprite.path)[0] + '.png' self.assertNotExists(png_sprite) for icon in self.iconizr.icons: self.assertNotExists(os.path.splitext(icon.path)[0] + '.png')
[ "\"\"\"\r\nCommand line options tests\r\n\"\"\"\r\n\r\nimport os\r\n\r\nfrom ._base import PyconizrTestCase\r\n\r\nfrom pyconizr.run import iconize\r\nfrom pyconizr.options import ArgParser\r\n\r\n\r\nclass CmdLineTests(PyconizrTestCase):\r\n\r\n def pyconizr(self, *args):\r\n iconize(**dict(vars(ArgParser().parse_args(args)),\r\n **self.iconizr.options))\r\n\r\n\r\nclass ArgsTests(CmdLineTests):\r\n\r\n def test_nopng(self):\r\n self.pyconizr('--nopng', '--out-icons', 'icons')\r\n\r\n png_sprite = os.path.splitext(self.iconizr.sprite.path)[0] + '.png'\r\n self.assertNotExists(png_sprite)\r\n\r\n for icon in self.iconizr.icons:\r\n self.assertNotExists(os.path.splitext(icon.path)[0] + '.png')\r\n", "<docstring token>\nimport os\nfrom ._base import PyconizrTestCase\nfrom pyconizr.run import iconize\nfrom pyconizr.options import ArgParser\n\n\nclass CmdLineTests(PyconizrTestCase):\n\n def pyconizr(self, *args):\n iconize(**dict(vars(ArgParser().parse_args(args)), **self.iconizr.\n options))\n\n\nclass ArgsTests(CmdLineTests):\n\n def test_nopng(self):\n self.pyconizr('--nopng', '--out-icons', 'icons')\n png_sprite = os.path.splitext(self.iconizr.sprite.path)[0] + '.png'\n self.assertNotExists(png_sprite)\n for icon in self.iconizr.icons:\n self.assertNotExists(os.path.splitext(icon.path)[0] + '.png')\n", "<docstring token>\n<import token>\n\n\nclass CmdLineTests(PyconizrTestCase):\n\n def pyconizr(self, *args):\n iconize(**dict(vars(ArgParser().parse_args(args)), **self.iconizr.\n options))\n\n\nclass ArgsTests(CmdLineTests):\n\n def test_nopng(self):\n self.pyconizr('--nopng', '--out-icons', 'icons')\n png_sprite = os.path.splitext(self.iconizr.sprite.path)[0] + '.png'\n self.assertNotExists(png_sprite)\n for icon in self.iconizr.icons:\n self.assertNotExists(os.path.splitext(icon.path)[0] + '.png')\n", "<docstring token>\n<import token>\n\n\nclass CmdLineTests(PyconizrTestCase):\n <function token>\n\n\nclass ArgsTests(CmdLineTests):\n\n def test_nopng(self):\n self.pyconizr('--nopng', '--out-icons', 'icons')\n png_sprite = os.path.splitext(self.iconizr.sprite.path)[0] + '.png'\n self.assertNotExists(png_sprite)\n for icon in self.iconizr.icons:\n self.assertNotExists(os.path.splitext(icon.path)[0] + '.png')\n", "<docstring token>\n<import token>\n<class token>\n\n\nclass ArgsTests(CmdLineTests):\n\n def test_nopng(self):\n self.pyconizr('--nopng', '--out-icons', 'icons')\n png_sprite = os.path.splitext(self.iconizr.sprite.path)[0] + '.png'\n self.assertNotExists(png_sprite)\n for icon in self.iconizr.icons:\n self.assertNotExists(os.path.splitext(icon.path)[0] + '.png')\n", "<docstring token>\n<import token>\n<class token>\n\n\nclass ArgsTests(CmdLineTests):\n <function token>\n", "<docstring token>\n<import token>\n<class token>\n<class token>\n" ]
false
98,780
95222f15b38d3ecf4e3922f496250fd9af59ccec
#Cassandra Delieto #Python vs. 3.6 using sublime text editor #1/30/17 from tkinter import * import tkinter as ttk from datetime import datetime from datetime import timedelta import shutil, time, os, sqlite3 import Drill_5 def create_db(self): conn = sqlite3.connect('timestamp.db') with conn: cur = conn.cursor() cur.execute("CREATE TABLE if not exists tbl_timestamp(ID INTEGER PRIMARY KEY, tsp REAL );") cur.execute("""INSERT INTO tbl_timestamp (tsp) VALUES (0.0)""") conn.commit() conn.close() first_run(self) def first_run(self): conn = sqlite3.connect('timestamp.db') with conn: cur = conn.cursor() current_time=time.time() cur.execute("INSERT INTO tbl_timestamp (tsp) VALUES ({})".format(current_time,)) conn.commit() conn.close() timer(self) def timer(self): conn = sqlite3.connect('timestamp.db') with conn: cur = conn.cursor() cur.execute("SELECT tsp FROM tbl_timestamp ORDER BY tsp DESC LIMIT 1 OFFSET 1") recent=cur.fetchone()[0] theTime=time.ctime(recent) print (theTime) self.lr_var.set(theTime) conn.commit() conn.close() if __name__ == "__main__": pass
[ "#Cassandra Delieto\n#Python vs. 3.6 using sublime text editor\n#1/30/17\n\nfrom tkinter import *\nimport tkinter as ttk\nfrom datetime import datetime\nfrom datetime import timedelta\nimport shutil, time, os, sqlite3\nimport Drill_5\n\ndef create_db(self):\n conn = sqlite3.connect('timestamp.db')\n with conn:\n cur = conn.cursor()\n cur.execute(\"CREATE TABLE if not exists tbl_timestamp(ID INTEGER PRIMARY KEY, tsp REAL );\")\n cur.execute(\"\"\"INSERT INTO tbl_timestamp (tsp) VALUES (0.0)\"\"\")\n conn.commit()\n conn.close()\n first_run(self)\n\ndef first_run(self):\n conn = sqlite3.connect('timestamp.db')\n with conn:\n cur = conn.cursor()\n current_time=time.time()\n cur.execute(\"INSERT INTO tbl_timestamp (tsp) VALUES ({})\".format(current_time,))\n conn.commit()\n conn.close()\n timer(self)\n\ndef timer(self):\n conn = sqlite3.connect('timestamp.db')\n with conn:\n cur = conn.cursor()\n cur.execute(\"SELECT tsp FROM tbl_timestamp ORDER BY tsp DESC LIMIT 1 OFFSET 1\")\n recent=cur.fetchone()[0]\n theTime=time.ctime(recent)\n print (theTime)\n self.lr_var.set(theTime)\n conn.commit()\n conn.close()\n\nif __name__ == \"__main__\":\n pass\n", "from tkinter import *\nimport tkinter as ttk\nfrom datetime import datetime\nfrom datetime import timedelta\nimport shutil, time, os, sqlite3\nimport Drill_5\n\n\ndef create_db(self):\n conn = sqlite3.connect('timestamp.db')\n with conn:\n cur = conn.cursor()\n cur.execute(\n 'CREATE TABLE if not exists tbl_timestamp(ID INTEGER PRIMARY KEY, tsp REAL );'\n )\n cur.execute('INSERT INTO tbl_timestamp (tsp) VALUES (0.0)')\n conn.commit()\n conn.close()\n first_run(self)\n\n\ndef first_run(self):\n conn = sqlite3.connect('timestamp.db')\n with conn:\n cur = conn.cursor()\n current_time = time.time()\n cur.execute('INSERT INTO tbl_timestamp (tsp) VALUES ({})'.format(\n current_time))\n conn.commit()\n conn.close()\n timer(self)\n\n\ndef timer(self):\n conn = sqlite3.connect('timestamp.db')\n with conn:\n cur = conn.cursor()\n cur.execute(\n 'SELECT tsp FROM tbl_timestamp ORDER BY tsp DESC LIMIT 1 OFFSET 1')\n recent = cur.fetchone()[0]\n theTime = time.ctime(recent)\n print(theTime)\n self.lr_var.set(theTime)\n conn.commit()\n conn.close()\n\n\nif __name__ == '__main__':\n pass\n", "<import token>\n\n\ndef create_db(self):\n conn = sqlite3.connect('timestamp.db')\n with conn:\n cur = conn.cursor()\n cur.execute(\n 'CREATE TABLE if not exists tbl_timestamp(ID INTEGER PRIMARY KEY, tsp REAL );'\n )\n cur.execute('INSERT INTO tbl_timestamp (tsp) VALUES (0.0)')\n conn.commit()\n conn.close()\n first_run(self)\n\n\ndef first_run(self):\n conn = sqlite3.connect('timestamp.db')\n with conn:\n cur = conn.cursor()\n current_time = time.time()\n cur.execute('INSERT INTO tbl_timestamp (tsp) VALUES ({})'.format(\n current_time))\n conn.commit()\n conn.close()\n timer(self)\n\n\ndef timer(self):\n conn = sqlite3.connect('timestamp.db')\n with conn:\n cur = conn.cursor()\n cur.execute(\n 'SELECT tsp FROM tbl_timestamp ORDER BY tsp DESC LIMIT 1 OFFSET 1')\n recent = cur.fetchone()[0]\n theTime = time.ctime(recent)\n print(theTime)\n self.lr_var.set(theTime)\n conn.commit()\n conn.close()\n\n\nif __name__ == '__main__':\n pass\n", "<import token>\n\n\ndef create_db(self):\n conn = sqlite3.connect('timestamp.db')\n with conn:\n cur = conn.cursor()\n cur.execute(\n 'CREATE TABLE if not exists tbl_timestamp(ID INTEGER PRIMARY KEY, tsp REAL );'\n )\n cur.execute('INSERT INTO tbl_timestamp (tsp) VALUES (0.0)')\n conn.commit()\n conn.close()\n first_run(self)\n\n\ndef first_run(self):\n conn = sqlite3.connect('timestamp.db')\n with conn:\n cur = conn.cursor()\n current_time = time.time()\n cur.execute('INSERT INTO tbl_timestamp (tsp) VALUES ({})'.format(\n current_time))\n conn.commit()\n conn.close()\n timer(self)\n\n\ndef timer(self):\n conn = sqlite3.connect('timestamp.db')\n with conn:\n cur = conn.cursor()\n cur.execute(\n 'SELECT tsp FROM tbl_timestamp ORDER BY tsp DESC LIMIT 1 OFFSET 1')\n recent = cur.fetchone()[0]\n theTime = time.ctime(recent)\n print(theTime)\n self.lr_var.set(theTime)\n conn.commit()\n conn.close()\n\n\n<code token>\n", "<import token>\n\n\ndef create_db(self):\n conn = sqlite3.connect('timestamp.db')\n with conn:\n cur = conn.cursor()\n cur.execute(\n 'CREATE TABLE if not exists tbl_timestamp(ID INTEGER PRIMARY KEY, tsp REAL );'\n )\n cur.execute('INSERT INTO tbl_timestamp (tsp) VALUES (0.0)')\n conn.commit()\n conn.close()\n first_run(self)\n\n\n<function token>\n\n\ndef timer(self):\n conn = sqlite3.connect('timestamp.db')\n with conn:\n cur = conn.cursor()\n cur.execute(\n 'SELECT tsp FROM tbl_timestamp ORDER BY tsp DESC LIMIT 1 OFFSET 1')\n recent = cur.fetchone()[0]\n theTime = time.ctime(recent)\n print(theTime)\n self.lr_var.set(theTime)\n conn.commit()\n conn.close()\n\n\n<code token>\n", "<import token>\n<function token>\n<function token>\n\n\ndef timer(self):\n conn = sqlite3.connect('timestamp.db')\n with conn:\n cur = conn.cursor()\n cur.execute(\n 'SELECT tsp FROM tbl_timestamp ORDER BY tsp DESC LIMIT 1 OFFSET 1')\n recent = cur.fetchone()[0]\n theTime = time.ctime(recent)\n print(theTime)\n self.lr_var.set(theTime)\n conn.commit()\n conn.close()\n\n\n<code token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<code token>\n" ]
false
98,781
b51de95171c8a3bd5f89586ffd39d75d16c04dad
""" :Module: static_reportman.py :Synopsis: Generate post-preproc, etc., QA reports of line for a given dataset :Author: dohmatob elvis dopgima ABIDE use-case example ---------------------- edohmato@is150118:~/CODE/FORKED/pypreprocess/reporting for j in \ $(ls /vaporific/edohmato/pypreprocess_runs/abide/); do echo; echo "Generating QA for $j"; echo; python static_reportman.py \ /vaporific/edohmato/pypreprocess_runs/abide/$j "$j_*/infos_DARTEL.json" $j;\ done """ import sys from pypreprocess.reporting.preproc_reporter import generate_dataset_preproc_report import os import glob from optparse import OptionParser # brag! print "\r\n\t\t +++static-report-man+++\r\n" # configure option parser parser = OptionParser() parser.add_option('--replace-in-path', dest='replace_in_path', default="", help="""specify a token to replace in paths""" ) parser.add_option('--dataset-id', dest='dataset_id', default="UNSPECIFIED!", help="""specify id (i.e short description) of dataset""" ) parser.add_option('--output_dir', dest='output_dir', default=None, help="""specify output directory""" ) parser.add_option('--subject-preproc-data-json-filename-wildcat', dest='subject_preproc_data_json_filename_wildcat', default="sub*/infos.json", help="""specify filename wildcat for json files containing subject preprocessed data""" ) parser.add_option('--n-jobs', dest='n_jobs', default=1, type=int, help="""number of subprocesses to spawn (defaults to 1)""" ) # parse args and opts options, args = parser.parse_args() if len(args) < 1: print ("Error: Insufficient number of arguments\nUse the --help" " option to get help") sys.exit(1) dataset_dir = args[0] output_dir = options.output_dir if not options.output_dir is \ None else dataset_dir subject_json_file_glob = os.path.join( dataset_dir, options.subject_preproc_data_json_filename_wildcat) subject_preproc_data = glob.glob(subject_json_file_glob) # sanitize print ( "Globing subject json file: %s" % subject_json_file_glob) if not subject_preproc_data: raise Warning("No subject json file found!") # generate reports proper generate_dataset_preproc_report( subject_preproc_data, output_dir=output_dir, dataset_id=options.dataset_id, replace_in_path=options.replace_in_path.split(','), n_jobs=options.n_jobs )
[ "\"\"\"\n:Module: static_reportman.py\n:Synopsis: Generate post-preproc, etc., QA reports of line for a given dataset\n:Author: dohmatob elvis dopgima\n\nABIDE use-case example\n----------------------\nedohmato@is150118:~/CODE/FORKED/pypreprocess/reporting for j in \\\n$(ls /vaporific/edohmato/pypreprocess_runs/abide/); do echo;\necho \"Generating QA for $j\"; echo; python static_reportman.py \\\n/vaporific/edohmato/pypreprocess_runs/abide/$j \"$j_*/infos_DARTEL.json\" $j;\\\ndone\n\n\"\"\"\n\nimport sys\nfrom pypreprocess.reporting.preproc_reporter import generate_dataset_preproc_report\nimport os\nimport glob\nfrom optparse import OptionParser\n\n# brag!\nprint \"\\r\\n\\t\\t +++static-report-man+++\\r\\n\"\n\n# configure option parser\nparser = OptionParser()\nparser.add_option('--replace-in-path',\n dest='replace_in_path',\n default=\"\",\n help=\"\"\"specify a token to replace in paths\"\"\"\n )\nparser.add_option('--dataset-id',\n dest='dataset_id',\n default=\"UNSPECIFIED!\",\n help=\"\"\"specify id (i.e short description) of dataset\"\"\"\n )\nparser.add_option('--output_dir',\n dest='output_dir',\n default=None,\n help=\"\"\"specify output directory\"\"\"\n )\nparser.add_option('--subject-preproc-data-json-filename-wildcat',\n dest='subject_preproc_data_json_filename_wildcat',\n default=\"sub*/infos.json\",\n help=\"\"\"specify filename wildcat for json files containing\nsubject preprocessed data\"\"\"\n )\nparser.add_option('--n-jobs',\n dest='n_jobs',\n default=1,\n type=int,\n help=\"\"\"number of subprocesses to spawn (defaults to 1)\"\"\"\n )\n\n# parse args and opts\noptions, args = parser.parse_args()\n\nif len(args) < 1:\n print (\"Error: Insufficient number of arguments\\nUse the --help\"\n \" option to get help\")\n sys.exit(1)\n\ndataset_dir = args[0]\noutput_dir = options.output_dir if not options.output_dir is \\\n None else dataset_dir\n\nsubject_json_file_glob = os.path.join(\n dataset_dir,\n options.subject_preproc_data_json_filename_wildcat)\nsubject_preproc_data = glob.glob(subject_json_file_glob)\n\n# sanitize\nprint (\n \"Globing subject json file: %s\" % subject_json_file_glob)\nif not subject_preproc_data:\n raise Warning(\"No subject json file found!\")\n\n# generate reports proper\ngenerate_dataset_preproc_report(\n subject_preproc_data,\n output_dir=output_dir,\n dataset_id=options.dataset_id,\n replace_in_path=options.replace_in_path.split(','),\n n_jobs=options.n_jobs\n )\n" ]
true
98,782
3c344c08fa341717c0f1aa87ba06980b2864b57e
# -*- coding: utf-8 -*- # @File : random_show.py # @Author: AaronJny # @Date : 2019/10/29 # @Desc : 随机选择情况下的收益情况 import random import numpy as np from dataset import LottoDataSet import utils import settings def get_one_random_sample(): """ 获取一种随机序列 :return: """ front_balls = list(range(settings.FRONT_VOCAB_SIZE)) back_balls = list(range(settings.BACK_VOCAB_SIZE)) return random.sample(front_balls, settings.FRONT_SIZE) + random.sample(back_balls, settings.BACK_SIZE) def simulate(test_np_x, test_np_y): # 获得的奖金总额 money_in = 0 # 买彩票花出去的钱总额 money_out = 0 # 共有多少组数据 samples_num = len(test_np_x['x1']) # 对于每一组数据 for j in range(samples_num): # 这一期的真实开奖结果 outputs = [] for k in range(settings.FRONT_SIZE + settings.BACK_SIZE): outputs.append(np.argmax(test_np_y['y{}'.format(k + 1)][j])) # 每一期彩票买五注 money_out += 10 for k in range(5): balls = get_one_random_sample() # 计算奖金 award = utils.lotto_calculate(outputs, balls) money_in += award print('买彩票花费金钱共{}元,中奖金额共{}元,赚取{}元'.format(money_out, money_in, money_in - money_out)) return money_in - money_out dataset = LottoDataSet(train_data_rate=0.9) # 随机买一百次,并记录每一次收入-支出的差值 results = [] for epoch in range(1, 101): results.append(simulate(dataset.test_np_x, dataset.test_np_y)) # 去除最高的和最低的 results = sorted(results)[1:-1] # 计算平均值 print('mean', sum(results) / len(results))
[ "# -*- coding: utf-8 -*-\n# @File : random_show.py\n# @Author: AaronJny\n# @Date : 2019/10/29\n# @Desc : 随机选择情况下的收益情况\nimport random\nimport numpy as np\nfrom dataset import LottoDataSet\nimport utils\nimport settings\n\n\ndef get_one_random_sample():\n \"\"\"\n 获取一种随机序列\n :return:\n \"\"\"\n front_balls = list(range(settings.FRONT_VOCAB_SIZE))\n back_balls = list(range(settings.BACK_VOCAB_SIZE))\n return random.sample(front_balls, settings.FRONT_SIZE) + random.sample(back_balls, settings.BACK_SIZE)\n\n\ndef simulate(test_np_x, test_np_y):\n # 获得的奖金总额\n money_in = 0\n # 买彩票花出去的钱总额\n money_out = 0\n # 共有多少组数据\n samples_num = len(test_np_x['x1'])\n # 对于每一组数据\n for j in range(samples_num):\n # 这一期的真实开奖结果\n outputs = []\n for k in range(settings.FRONT_SIZE + settings.BACK_SIZE):\n outputs.append(np.argmax(test_np_y['y{}'.format(k + 1)][j]))\n # 每一期彩票买五注\n money_out += 10\n for k in range(5):\n balls = get_one_random_sample()\n # 计算奖金\n award = utils.lotto_calculate(outputs, balls)\n money_in += award\n print('买彩票花费金钱共{}元,中奖金额共{}元,赚取{}元'.format(money_out, money_in, money_in - money_out))\n return money_in - money_out\n\n\ndataset = LottoDataSet(train_data_rate=0.9)\n# 随机买一百次,并记录每一次收入-支出的差值\nresults = []\nfor epoch in range(1, 101):\n results.append(simulate(dataset.test_np_x, dataset.test_np_y))\n# 去除最高的和最低的\nresults = sorted(results)[1:-1]\n# 计算平均值\nprint('mean', sum(results) / len(results))\n", "import random\nimport numpy as np\nfrom dataset import LottoDataSet\nimport utils\nimport settings\n\n\ndef get_one_random_sample():\n \"\"\"\n 获取一种随机序列\n :return:\n \"\"\"\n front_balls = list(range(settings.FRONT_VOCAB_SIZE))\n back_balls = list(range(settings.BACK_VOCAB_SIZE))\n return random.sample(front_balls, settings.FRONT_SIZE) + random.sample(\n back_balls, settings.BACK_SIZE)\n\n\ndef simulate(test_np_x, test_np_y):\n money_in = 0\n money_out = 0\n samples_num = len(test_np_x['x1'])\n for j in range(samples_num):\n outputs = []\n for k in range(settings.FRONT_SIZE + settings.BACK_SIZE):\n outputs.append(np.argmax(test_np_y['y{}'.format(k + 1)][j]))\n money_out += 10\n for k in range(5):\n balls = get_one_random_sample()\n award = utils.lotto_calculate(outputs, balls)\n money_in += award\n print('买彩票花费金钱共{}元,中奖金额共{}元,赚取{}元'.format(money_out, money_in, money_in -\n money_out))\n return money_in - money_out\n\n\ndataset = LottoDataSet(train_data_rate=0.9)\nresults = []\nfor epoch in range(1, 101):\n results.append(simulate(dataset.test_np_x, dataset.test_np_y))\nresults = sorted(results)[1:-1]\nprint('mean', sum(results) / len(results))\n", "<import token>\n\n\ndef get_one_random_sample():\n \"\"\"\n 获取一种随机序列\n :return:\n \"\"\"\n front_balls = list(range(settings.FRONT_VOCAB_SIZE))\n back_balls = list(range(settings.BACK_VOCAB_SIZE))\n return random.sample(front_balls, settings.FRONT_SIZE) + random.sample(\n back_balls, settings.BACK_SIZE)\n\n\ndef simulate(test_np_x, test_np_y):\n money_in = 0\n money_out = 0\n samples_num = len(test_np_x['x1'])\n for j in range(samples_num):\n outputs = []\n for k in range(settings.FRONT_SIZE + settings.BACK_SIZE):\n outputs.append(np.argmax(test_np_y['y{}'.format(k + 1)][j]))\n money_out += 10\n for k in range(5):\n balls = get_one_random_sample()\n award = utils.lotto_calculate(outputs, balls)\n money_in += award\n print('买彩票花费金钱共{}元,中奖金额共{}元,赚取{}元'.format(money_out, money_in, money_in -\n money_out))\n return money_in - money_out\n\n\ndataset = LottoDataSet(train_data_rate=0.9)\nresults = []\nfor epoch in range(1, 101):\n results.append(simulate(dataset.test_np_x, dataset.test_np_y))\nresults = sorted(results)[1:-1]\nprint('mean', sum(results) / len(results))\n", "<import token>\n\n\ndef get_one_random_sample():\n \"\"\"\n 获取一种随机序列\n :return:\n \"\"\"\n front_balls = list(range(settings.FRONT_VOCAB_SIZE))\n back_balls = list(range(settings.BACK_VOCAB_SIZE))\n return random.sample(front_balls, settings.FRONT_SIZE) + random.sample(\n back_balls, settings.BACK_SIZE)\n\n\ndef simulate(test_np_x, test_np_y):\n money_in = 0\n money_out = 0\n samples_num = len(test_np_x['x1'])\n for j in range(samples_num):\n outputs = []\n for k in range(settings.FRONT_SIZE + settings.BACK_SIZE):\n outputs.append(np.argmax(test_np_y['y{}'.format(k + 1)][j]))\n money_out += 10\n for k in range(5):\n balls = get_one_random_sample()\n award = utils.lotto_calculate(outputs, balls)\n money_in += award\n print('买彩票花费金钱共{}元,中奖金额共{}元,赚取{}元'.format(money_out, money_in, money_in -\n money_out))\n return money_in - money_out\n\n\n<assignment token>\nfor epoch in range(1, 101):\n results.append(simulate(dataset.test_np_x, dataset.test_np_y))\n<assignment token>\nprint('mean', sum(results) / len(results))\n", "<import token>\n\n\ndef get_one_random_sample():\n \"\"\"\n 获取一种随机序列\n :return:\n \"\"\"\n front_balls = list(range(settings.FRONT_VOCAB_SIZE))\n back_balls = list(range(settings.BACK_VOCAB_SIZE))\n return random.sample(front_balls, settings.FRONT_SIZE) + random.sample(\n back_balls, settings.BACK_SIZE)\n\n\ndef simulate(test_np_x, test_np_y):\n money_in = 0\n money_out = 0\n samples_num = len(test_np_x['x1'])\n for j in range(samples_num):\n outputs = []\n for k in range(settings.FRONT_SIZE + settings.BACK_SIZE):\n outputs.append(np.argmax(test_np_y['y{}'.format(k + 1)][j]))\n money_out += 10\n for k in range(5):\n balls = get_one_random_sample()\n award = utils.lotto_calculate(outputs, balls)\n money_in += award\n print('买彩票花费金钱共{}元,中奖金额共{}元,赚取{}元'.format(money_out, money_in, money_in -\n money_out))\n return money_in - money_out\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<function token>\n\n\ndef simulate(test_np_x, test_np_y):\n money_in = 0\n money_out = 0\n samples_num = len(test_np_x['x1'])\n for j in range(samples_num):\n outputs = []\n for k in range(settings.FRONT_SIZE + settings.BACK_SIZE):\n outputs.append(np.argmax(test_np_y['y{}'.format(k + 1)][j]))\n money_out += 10\n for k in range(5):\n balls = get_one_random_sample()\n award = utils.lotto_calculate(outputs, balls)\n money_in += award\n print('买彩票花费金钱共{}元,中奖金额共{}元,赚取{}元'.format(money_out, money_in, money_in -\n money_out))\n return money_in - money_out\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<function token>\n<function token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
98,783
547d109a18c766587ad7b951ef255c4c88a7c4e6
#! /usr/bin/env python # Import necessary packages import rospy import rospkg from std_srvs.srv import Empty, EmptyRequest # you import the service message python classes generated from Empty.srv. # Initialise a ROS node with the name 'move_bb8_service_client' rospy.init_node('move_bb8_service_client') rospy.wait_for_service('/move_bb8_in_circle') # Create the connection to the service move_bb8_client = rospy.ServiceProxy('/move_bb8_in_circle', Empty) move_bb8_object = EmptyRequest() result = move_bb8_client(move_bb8_object) print(result)
[ "#! /usr/bin/env python\n\n# Import necessary packages\nimport rospy\nimport rospkg\nfrom std_srvs.srv import Empty, EmptyRequest # you import the service message python classes generated from Empty.srv.\n\n# Initialise a ROS node with the name 'move_bb8_service_client'\nrospy.init_node('move_bb8_service_client')\nrospy.wait_for_service('/move_bb8_in_circle')\n\n# Create the connection to the service\nmove_bb8_client = rospy.ServiceProxy('/move_bb8_in_circle', Empty)\nmove_bb8_object = EmptyRequest()\nresult = move_bb8_client(move_bb8_object)\nprint(result)", "import rospy\nimport rospkg\nfrom std_srvs.srv import Empty, EmptyRequest\nrospy.init_node('move_bb8_service_client')\nrospy.wait_for_service('/move_bb8_in_circle')\nmove_bb8_client = rospy.ServiceProxy('/move_bb8_in_circle', Empty)\nmove_bb8_object = EmptyRequest()\nresult = move_bb8_client(move_bb8_object)\nprint(result)\n", "<import token>\nrospy.init_node('move_bb8_service_client')\nrospy.wait_for_service('/move_bb8_in_circle')\nmove_bb8_client = rospy.ServiceProxy('/move_bb8_in_circle', Empty)\nmove_bb8_object = EmptyRequest()\nresult = move_bb8_client(move_bb8_object)\nprint(result)\n", "<import token>\nrospy.init_node('move_bb8_service_client')\nrospy.wait_for_service('/move_bb8_in_circle')\n<assignment token>\nprint(result)\n", "<import token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
98,784
4a93fc19631f632863070059da5abc976adea3aa
""" https://leetcode.com/problems/find-two-non-overlapping-sub-arrays-each-with-target-sum/ """ class Solution: def minSumOfLengths(self, arr: list[int], target: int) -> int: start, currSum, minLen = 0, 0, float('inf') preMin = [float('inf')] * len(arr) for end, num in enumerate(arr): currSum += num while currSum > target: currSum -= arr[start] start += 1 if currSum == target: currLen = end - start + 1 minLen = min(minLen, currLen + preMin[start - 1]) preMin[end] = min(currLen, preMin[end - 1]) else: preMin[end] = preMin[end - 1] if minLen == float('inf'): return -1 return minLen print(Solution().minSumOfLengths([3, 1, 1, 1, 5, 1, 2, 1], 3))
[ "\"\"\"\nhttps://leetcode.com/problems/find-two-non-overlapping-sub-arrays-each-with-target-sum/\n\"\"\"\n\n\nclass Solution:\n def minSumOfLengths(self, arr: list[int], target: int) -> int:\n start, currSum, minLen = 0, 0, float('inf')\n preMin = [float('inf')] * len(arr)\n for end, num in enumerate(arr):\n currSum += num\n while currSum > target:\n currSum -= arr[start]\n start += 1\n\n if currSum == target:\n currLen = end - start + 1\n minLen = min(minLen, currLen + preMin[start - 1])\n preMin[end] = min(currLen, preMin[end - 1])\n else:\n preMin[end] = preMin[end - 1]\n\n if minLen == float('inf'):\n return -1\n\n return minLen\n\n\nprint(Solution().minSumOfLengths([3, 1, 1, 1, 5, 1, 2, 1],\n 3))\n", "<docstring token>\n\n\nclass Solution:\n\n def minSumOfLengths(self, arr: list[int], target: int) ->int:\n start, currSum, minLen = 0, 0, float('inf')\n preMin = [float('inf')] * len(arr)\n for end, num in enumerate(arr):\n currSum += num\n while currSum > target:\n currSum -= arr[start]\n start += 1\n if currSum == target:\n currLen = end - start + 1\n minLen = min(minLen, currLen + preMin[start - 1])\n preMin[end] = min(currLen, preMin[end - 1])\n else:\n preMin[end] = preMin[end - 1]\n if minLen == float('inf'):\n return -1\n return minLen\n\n\nprint(Solution().minSumOfLengths([3, 1, 1, 1, 5, 1, 2, 1], 3))\n", "<docstring token>\n\n\nclass Solution:\n\n def minSumOfLengths(self, arr: list[int], target: int) ->int:\n start, currSum, minLen = 0, 0, float('inf')\n preMin = [float('inf')] * len(arr)\n for end, num in enumerate(arr):\n currSum += num\n while currSum > target:\n currSum -= arr[start]\n start += 1\n if currSum == target:\n currLen = end - start + 1\n minLen = min(minLen, currLen + preMin[start - 1])\n preMin[end] = min(currLen, preMin[end - 1])\n else:\n preMin[end] = preMin[end - 1]\n if minLen == float('inf'):\n return -1\n return minLen\n\n\n<code token>\n", "<docstring token>\n\n\nclass Solution:\n <function token>\n\n\n<code token>\n", "<docstring token>\n<class token>\n<code token>\n" ]
false
98,785
c74bcb61b0b1898a8196506e96973d97bd3fa90e
from cesar_cipher import cesar_cipher from unittest import TestCase class TestCesarCipher(TestCase): def test_empty_to_word_returns_empty(self): self.assertEqual("", cesar_cipher("", 0), 'I expected a empty word') def test_a_to_returns_b(self): self.assertEqual("b", cesar_cipher("a", 1)) def test_a_to_returns_c(self): self.assertEqual("c", cesar_cipher("a", 2)) def test_ab_with_shift_1_to_returns_bc(self): self.assertEqual("bc", cesar_cipher("ab", 1))
[ "from cesar_cipher import cesar_cipher\nfrom unittest import TestCase\n\nclass TestCesarCipher(TestCase):\n\n def test_empty_to_word_returns_empty(self):\n self.assertEqual(\"\", cesar_cipher(\"\", 0), 'I expected a empty word')\n\n def test_a_to_returns_b(self):\n self.assertEqual(\"b\", cesar_cipher(\"a\", 1))\n\n def test_a_to_returns_c(self):\n self.assertEqual(\"c\", cesar_cipher(\"a\", 2))\n\n def test_ab_with_shift_1_to_returns_bc(self):\n self.assertEqual(\"bc\", cesar_cipher(\"ab\", 1))\n", "from cesar_cipher import cesar_cipher\nfrom unittest import TestCase\n\n\nclass TestCesarCipher(TestCase):\n\n def test_empty_to_word_returns_empty(self):\n self.assertEqual('', cesar_cipher('', 0), 'I expected a empty word')\n\n def test_a_to_returns_b(self):\n self.assertEqual('b', cesar_cipher('a', 1))\n\n def test_a_to_returns_c(self):\n self.assertEqual('c', cesar_cipher('a', 2))\n\n def test_ab_with_shift_1_to_returns_bc(self):\n self.assertEqual('bc', cesar_cipher('ab', 1))\n", "<import token>\n\n\nclass TestCesarCipher(TestCase):\n\n def test_empty_to_word_returns_empty(self):\n self.assertEqual('', cesar_cipher('', 0), 'I expected a empty word')\n\n def test_a_to_returns_b(self):\n self.assertEqual('b', cesar_cipher('a', 1))\n\n def test_a_to_returns_c(self):\n self.assertEqual('c', cesar_cipher('a', 2))\n\n def test_ab_with_shift_1_to_returns_bc(self):\n self.assertEqual('bc', cesar_cipher('ab', 1))\n", "<import token>\n\n\nclass TestCesarCipher(TestCase):\n\n def test_empty_to_word_returns_empty(self):\n self.assertEqual('', cesar_cipher('', 0), 'I expected a empty word')\n\n def test_a_to_returns_b(self):\n self.assertEqual('b', cesar_cipher('a', 1))\n\n def test_a_to_returns_c(self):\n self.assertEqual('c', cesar_cipher('a', 2))\n <function token>\n", "<import token>\n\n\nclass TestCesarCipher(TestCase):\n <function token>\n\n def test_a_to_returns_b(self):\n self.assertEqual('b', cesar_cipher('a', 1))\n\n def test_a_to_returns_c(self):\n self.assertEqual('c', cesar_cipher('a', 2))\n <function token>\n", "<import token>\n\n\nclass TestCesarCipher(TestCase):\n <function token>\n\n def test_a_to_returns_b(self):\n self.assertEqual('b', cesar_cipher('a', 1))\n <function token>\n <function token>\n", "<import token>\n\n\nclass TestCesarCipher(TestCase):\n <function token>\n <function token>\n <function token>\n <function token>\n", "<import token>\n<class token>\n" ]
false
98,786
646aadfa676bbd4f476f22e101b027dea97030c1
import numpy as np def recursive_dynamic_imp(n, val_array): if val_array[n] != -1: return val_array[n] else: val_array[n] = recursive_dynamic_imp(n-1,val_array)+\ recursive_dynamic_imp(n-2,val_array) return val_array[n] def recursive_dynamic(n): val_array = np.full(n+1,-1, dtype=np.int64) val_array[0] = 0 val_array[1] = 1 return recursive_dynamic_imp(n, val_array) def iterative(n): if n < 2: return n # initial values fh = np.int64(1) fl = np.int64(0) for i in range(2,n+1): # Save in temp location temp = fh # get new high value fh = fh+fl # save old value in low value fl = temp return fh def build_power_matrix(A, n): if n == 1: return A if n%2 == 0: Anew = build_power_matrix(A,n//2) return np.matmul(Anew,Anew) else: Aev = build_power_matrix(A,n//2) return np.matmul(Aev,np.matmul(Aev,A)) def power_matrix(n): if n == 0: return 0 if n <= 2: return 1 init_vec = np.array([[1],[1]], dtype=np.int64) A = np.array([[1,1],[1,0]], dtype=np.int64) A_power = build_power_matrix(A,n-2) return np.matmul(A_power,init_vec)[0][0]
[ "import numpy as np\n\ndef recursive_dynamic_imp(n, val_array):\n if val_array[n] != -1:\n return val_array[n]\n else:\n val_array[n] = recursive_dynamic_imp(n-1,val_array)+\\\n recursive_dynamic_imp(n-2,val_array)\n return val_array[n]\n\ndef recursive_dynamic(n):\n val_array = np.full(n+1,-1, dtype=np.int64)\n val_array[0] = 0\n val_array[1] = 1\n return recursive_dynamic_imp(n, val_array)\n\ndef iterative(n):\n if n < 2:\n return n\n # initial values\n fh = np.int64(1)\n fl = np.int64(0)\n for i in range(2,n+1):\n # Save in temp location\n temp = fh\n # get new high value\n fh = fh+fl\n # save old value in low value\n fl = temp\n return fh\n\ndef build_power_matrix(A, n):\n if n == 1:\n return A\n if n%2 == 0:\n Anew = build_power_matrix(A,n//2)\n return np.matmul(Anew,Anew)\n else:\n Aev = build_power_matrix(A,n//2)\n return np.matmul(Aev,np.matmul(Aev,A))\n\ndef power_matrix(n):\n if n == 0:\n return 0\n if n <= 2:\n return 1\n init_vec = np.array([[1],[1]], dtype=np.int64)\n A = np.array([[1,1],[1,0]], dtype=np.int64)\n A_power = build_power_matrix(A,n-2)\n return np.matmul(A_power,init_vec)[0][0]\n", "import numpy as np\n\n\ndef recursive_dynamic_imp(n, val_array):\n if val_array[n] != -1:\n return val_array[n]\n else:\n val_array[n] = recursive_dynamic_imp(n - 1, val_array\n ) + recursive_dynamic_imp(n - 2, val_array)\n return val_array[n]\n\n\ndef recursive_dynamic(n):\n val_array = np.full(n + 1, -1, dtype=np.int64)\n val_array[0] = 0\n val_array[1] = 1\n return recursive_dynamic_imp(n, val_array)\n\n\ndef iterative(n):\n if n < 2:\n return n\n fh = np.int64(1)\n fl = np.int64(0)\n for i in range(2, n + 1):\n temp = fh\n fh = fh + fl\n fl = temp\n return fh\n\n\ndef build_power_matrix(A, n):\n if n == 1:\n return A\n if n % 2 == 0:\n Anew = build_power_matrix(A, n // 2)\n return np.matmul(Anew, Anew)\n else:\n Aev = build_power_matrix(A, n // 2)\n return np.matmul(Aev, np.matmul(Aev, A))\n\n\ndef power_matrix(n):\n if n == 0:\n return 0\n if n <= 2:\n return 1\n init_vec = np.array([[1], [1]], dtype=np.int64)\n A = np.array([[1, 1], [1, 0]], dtype=np.int64)\n A_power = build_power_matrix(A, n - 2)\n return np.matmul(A_power, init_vec)[0][0]\n", "<import token>\n\n\ndef recursive_dynamic_imp(n, val_array):\n if val_array[n] != -1:\n return val_array[n]\n else:\n val_array[n] = recursive_dynamic_imp(n - 1, val_array\n ) + recursive_dynamic_imp(n - 2, val_array)\n return val_array[n]\n\n\ndef recursive_dynamic(n):\n val_array = np.full(n + 1, -1, dtype=np.int64)\n val_array[0] = 0\n val_array[1] = 1\n return recursive_dynamic_imp(n, val_array)\n\n\ndef iterative(n):\n if n < 2:\n return n\n fh = np.int64(1)\n fl = np.int64(0)\n for i in range(2, n + 1):\n temp = fh\n fh = fh + fl\n fl = temp\n return fh\n\n\ndef build_power_matrix(A, n):\n if n == 1:\n return A\n if n % 2 == 0:\n Anew = build_power_matrix(A, n // 2)\n return np.matmul(Anew, Anew)\n else:\n Aev = build_power_matrix(A, n // 2)\n return np.matmul(Aev, np.matmul(Aev, A))\n\n\ndef power_matrix(n):\n if n == 0:\n return 0\n if n <= 2:\n return 1\n init_vec = np.array([[1], [1]], dtype=np.int64)\n A = np.array([[1, 1], [1, 0]], dtype=np.int64)\n A_power = build_power_matrix(A, n - 2)\n return np.matmul(A_power, init_vec)[0][0]\n", "<import token>\n<function token>\n\n\ndef recursive_dynamic(n):\n val_array = np.full(n + 1, -1, dtype=np.int64)\n val_array[0] = 0\n val_array[1] = 1\n return recursive_dynamic_imp(n, val_array)\n\n\ndef iterative(n):\n if n < 2:\n return n\n fh = np.int64(1)\n fl = np.int64(0)\n for i in range(2, n + 1):\n temp = fh\n fh = fh + fl\n fl = temp\n return fh\n\n\ndef build_power_matrix(A, n):\n if n == 1:\n return A\n if n % 2 == 0:\n Anew = build_power_matrix(A, n // 2)\n return np.matmul(Anew, Anew)\n else:\n Aev = build_power_matrix(A, n // 2)\n return np.matmul(Aev, np.matmul(Aev, A))\n\n\ndef power_matrix(n):\n if n == 0:\n return 0\n if n <= 2:\n return 1\n init_vec = np.array([[1], [1]], dtype=np.int64)\n A = np.array([[1, 1], [1, 0]], dtype=np.int64)\n A_power = build_power_matrix(A, n - 2)\n return np.matmul(A_power, init_vec)[0][0]\n", "<import token>\n<function token>\n\n\ndef recursive_dynamic(n):\n val_array = np.full(n + 1, -1, dtype=np.int64)\n val_array[0] = 0\n val_array[1] = 1\n return recursive_dynamic_imp(n, val_array)\n\n\ndef iterative(n):\n if n < 2:\n return n\n fh = np.int64(1)\n fl = np.int64(0)\n for i in range(2, n + 1):\n temp = fh\n fh = fh + fl\n fl = temp\n return fh\n\n\ndef build_power_matrix(A, n):\n if n == 1:\n return A\n if n % 2 == 0:\n Anew = build_power_matrix(A, n // 2)\n return np.matmul(Anew, Anew)\n else:\n Aev = build_power_matrix(A, n // 2)\n return np.matmul(Aev, np.matmul(Aev, A))\n\n\n<function token>\n", "<import token>\n<function token>\n\n\ndef recursive_dynamic(n):\n val_array = np.full(n + 1, -1, dtype=np.int64)\n val_array[0] = 0\n val_array[1] = 1\n return recursive_dynamic_imp(n, val_array)\n\n\ndef iterative(n):\n if n < 2:\n return n\n fh = np.int64(1)\n fl = np.int64(0)\n for i in range(2, n + 1):\n temp = fh\n fh = fh + fl\n fl = temp\n return fh\n\n\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n\n\ndef iterative(n):\n if n < 2:\n return n\n fh = np.int64(1)\n fl = np.int64(0)\n for i in range(2, n + 1):\n temp = fh\n fh = fh + fl\n fl = temp\n return fh\n\n\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n" ]
false
98,787
41cf20148a1c403b0922ab41c93b4a2a09e70a02
""" Copyright 2017 Neural Networks and Deep Learning lab, MIPT Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from deeppavlov.core.commands.utils import expand_path from deeppavlov.core.common.log import get_logger from abc import ABCMeta, abstractmethod """ :class:`deeppavlov.models.model.Serializable` is an abstract base class that expresses the interface for all models that can serialize data to a path. """ log = get_logger(__name__) class Serializable(metaclass=ABCMeta): """ :attr: `_ser_dir` is a name of a serialization dir, can be default or set in json config :attr: `_ser_file` is a name of a serialization file (usually binary model file), can be default or set in json config :attr: `ser_path` is a path to model serialization dir or file (it depends on the model type). It is always an empty string and is ignored if it is not set in json config. """ def __init__(self, save_path, load_path=None, mode='infer', *args, **kwargs): if save_path: self.save_path = expand_path(save_path) self.save_path.parent.mkdir(parents=True, exist_ok=True) else: self.save_path = None if load_path: self.load_path = expand_path(load_path) if mode != 'train' and self.save_path and self.load_path != self.save_path: log.warning("Load path '{}' differs from save path '{}' in '{}' mode for {}." .format(self.load_path, self.save_path, mode, self.__class__.__name__)) elif mode != 'train' and self.save_path: self.load_path = self.save_path log.warning("No load path is set for {} in '{}' mode. Using save path instead" .format(self.__class__.__name__, mode)) else: self.load_path = None log.warning("No load path is set for {}!".format(self.__class__.__name__)) @abstractmethod def save(self, *args, **kwargs): pass @abstractmethod def load(self, *args, **kwargs): pass
[ "\"\"\"\nCopyright 2017 Neural Networks and Deep Learning lab, MIPT\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nfrom deeppavlov.core.commands.utils import expand_path\nfrom deeppavlov.core.common.log import get_logger\nfrom abc import ABCMeta, abstractmethod\n\n\"\"\"\n:class:`deeppavlov.models.model.Serializable` is an abstract base class that expresses the interface\nfor all models that can serialize data to a path.\n\"\"\"\n\nlog = get_logger(__name__)\n\n\nclass Serializable(metaclass=ABCMeta):\n \"\"\"\n :attr: `_ser_dir` is a name of a serialization dir, can be default or set in json config\n :attr: `_ser_file` is a name of a serialization file (usually binary model file),\n can be default or set in json config\n :attr: `ser_path` is a path to model serialization dir or file (it depends on the model type).\n It is always an empty string and is ignored if it is not set in json config.\n \"\"\"\n\n def __init__(self, save_path, load_path=None, mode='infer', *args, **kwargs):\n\n if save_path:\n self.save_path = expand_path(save_path)\n self.save_path.parent.mkdir(parents=True, exist_ok=True)\n else:\n self.save_path = None\n\n if load_path:\n self.load_path = expand_path(load_path)\n if mode != 'train' and self.save_path and self.load_path != self.save_path:\n log.warning(\"Load path '{}' differs from save path '{}' in '{}' mode for {}.\"\n .format(self.load_path, self.save_path, mode, self.__class__.__name__))\n elif mode != 'train' and self.save_path:\n self.load_path = self.save_path\n log.warning(\"No load path is set for {} in '{}' mode. Using save path instead\"\n .format(self.__class__.__name__, mode))\n else:\n self.load_path = None\n log.warning(\"No load path is set for {}!\".format(self.__class__.__name__))\n\n @abstractmethod\n def save(self, *args, **kwargs):\n pass\n\n @abstractmethod\n def load(self, *args, **kwargs):\n pass\n", "<docstring token>\nfrom deeppavlov.core.commands.utils import expand_path\nfrom deeppavlov.core.common.log import get_logger\nfrom abc import ABCMeta, abstractmethod\n<docstring token>\nlog = get_logger(__name__)\n\n\nclass Serializable(metaclass=ABCMeta):\n \"\"\"\n :attr: `_ser_dir` is a name of a serialization dir, can be default or set in json config\n :attr: `_ser_file` is a name of a serialization file (usually binary model file),\n can be default or set in json config\n :attr: `ser_path` is a path to model serialization dir or file (it depends on the model type).\n It is always an empty string and is ignored if it is not set in json config.\n \"\"\"\n\n def __init__(self, save_path, load_path=None, mode='infer', *args, **kwargs\n ):\n if save_path:\n self.save_path = expand_path(save_path)\n self.save_path.parent.mkdir(parents=True, exist_ok=True)\n else:\n self.save_path = None\n if load_path:\n self.load_path = expand_path(load_path)\n if (mode != 'train' and self.save_path and self.load_path !=\n self.save_path):\n log.warning(\n \"Load path '{}' differs from save path '{}' in '{}' mode for {}.\"\n .format(self.load_path, self.save_path, mode, self.\n __class__.__name__))\n elif mode != 'train' and self.save_path:\n self.load_path = self.save_path\n log.warning(\n \"No load path is set for {} in '{}' mode. Using save path instead\"\n .format(self.__class__.__name__, mode))\n else:\n self.load_path = None\n log.warning('No load path is set for {}!'.format(self.__class__\n .__name__))\n\n @abstractmethod\n def save(self, *args, **kwargs):\n pass\n\n @abstractmethod\n def load(self, *args, **kwargs):\n pass\n", "<docstring token>\n<import token>\n<docstring token>\nlog = get_logger(__name__)\n\n\nclass Serializable(metaclass=ABCMeta):\n \"\"\"\n :attr: `_ser_dir` is a name of a serialization dir, can be default or set in json config\n :attr: `_ser_file` is a name of a serialization file (usually binary model file),\n can be default or set in json config\n :attr: `ser_path` is a path to model serialization dir or file (it depends on the model type).\n It is always an empty string and is ignored if it is not set in json config.\n \"\"\"\n\n def __init__(self, save_path, load_path=None, mode='infer', *args, **kwargs\n ):\n if save_path:\n self.save_path = expand_path(save_path)\n self.save_path.parent.mkdir(parents=True, exist_ok=True)\n else:\n self.save_path = None\n if load_path:\n self.load_path = expand_path(load_path)\n if (mode != 'train' and self.save_path and self.load_path !=\n self.save_path):\n log.warning(\n \"Load path '{}' differs from save path '{}' in '{}' mode for {}.\"\n .format(self.load_path, self.save_path, mode, self.\n __class__.__name__))\n elif mode != 'train' and self.save_path:\n self.load_path = self.save_path\n log.warning(\n \"No load path is set for {} in '{}' mode. Using save path instead\"\n .format(self.__class__.__name__, mode))\n else:\n self.load_path = None\n log.warning('No load path is set for {}!'.format(self.__class__\n .__name__))\n\n @abstractmethod\n def save(self, *args, **kwargs):\n pass\n\n @abstractmethod\n def load(self, *args, **kwargs):\n pass\n", "<docstring token>\n<import token>\n<docstring token>\n<assignment token>\n\n\nclass Serializable(metaclass=ABCMeta):\n \"\"\"\n :attr: `_ser_dir` is a name of a serialization dir, can be default or set in json config\n :attr: `_ser_file` is a name of a serialization file (usually binary model file),\n can be default or set in json config\n :attr: `ser_path` is a path to model serialization dir or file (it depends on the model type).\n It is always an empty string and is ignored if it is not set in json config.\n \"\"\"\n\n def __init__(self, save_path, load_path=None, mode='infer', *args, **kwargs\n ):\n if save_path:\n self.save_path = expand_path(save_path)\n self.save_path.parent.mkdir(parents=True, exist_ok=True)\n else:\n self.save_path = None\n if load_path:\n self.load_path = expand_path(load_path)\n if (mode != 'train' and self.save_path and self.load_path !=\n self.save_path):\n log.warning(\n \"Load path '{}' differs from save path '{}' in '{}' mode for {}.\"\n .format(self.load_path, self.save_path, mode, self.\n __class__.__name__))\n elif mode != 'train' and self.save_path:\n self.load_path = self.save_path\n log.warning(\n \"No load path is set for {} in '{}' mode. Using save path instead\"\n .format(self.__class__.__name__, mode))\n else:\n self.load_path = None\n log.warning('No load path is set for {}!'.format(self.__class__\n .__name__))\n\n @abstractmethod\n def save(self, *args, **kwargs):\n pass\n\n @abstractmethod\n def load(self, *args, **kwargs):\n pass\n", "<docstring token>\n<import token>\n<docstring token>\n<assignment token>\n\n\nclass Serializable(metaclass=ABCMeta):\n <docstring token>\n\n def __init__(self, save_path, load_path=None, mode='infer', *args, **kwargs\n ):\n if save_path:\n self.save_path = expand_path(save_path)\n self.save_path.parent.mkdir(parents=True, exist_ok=True)\n else:\n self.save_path = None\n if load_path:\n self.load_path = expand_path(load_path)\n if (mode != 'train' and self.save_path and self.load_path !=\n self.save_path):\n log.warning(\n \"Load path '{}' differs from save path '{}' in '{}' mode for {}.\"\n .format(self.load_path, self.save_path, mode, self.\n __class__.__name__))\n elif mode != 'train' and self.save_path:\n self.load_path = self.save_path\n log.warning(\n \"No load path is set for {} in '{}' mode. Using save path instead\"\n .format(self.__class__.__name__, mode))\n else:\n self.load_path = None\n log.warning('No load path is set for {}!'.format(self.__class__\n .__name__))\n\n @abstractmethod\n def save(self, *args, **kwargs):\n pass\n\n @abstractmethod\n def load(self, *args, **kwargs):\n pass\n", "<docstring token>\n<import token>\n<docstring token>\n<assignment token>\n\n\nclass Serializable(metaclass=ABCMeta):\n <docstring token>\n\n def __init__(self, save_path, load_path=None, mode='infer', *args, **kwargs\n ):\n if save_path:\n self.save_path = expand_path(save_path)\n self.save_path.parent.mkdir(parents=True, exist_ok=True)\n else:\n self.save_path = None\n if load_path:\n self.load_path = expand_path(load_path)\n if (mode != 'train' and self.save_path and self.load_path !=\n self.save_path):\n log.warning(\n \"Load path '{}' differs from save path '{}' in '{}' mode for {}.\"\n .format(self.load_path, self.save_path, mode, self.\n __class__.__name__))\n elif mode != 'train' and self.save_path:\n self.load_path = self.save_path\n log.warning(\n \"No load path is set for {} in '{}' mode. Using save path instead\"\n .format(self.__class__.__name__, mode))\n else:\n self.load_path = None\n log.warning('No load path is set for {}!'.format(self.__class__\n .__name__))\n\n @abstractmethod\n def save(self, *args, **kwargs):\n pass\n <function token>\n", "<docstring token>\n<import token>\n<docstring token>\n<assignment token>\n\n\nclass Serializable(metaclass=ABCMeta):\n <docstring token>\n\n def __init__(self, save_path, load_path=None, mode='infer', *args, **kwargs\n ):\n if save_path:\n self.save_path = expand_path(save_path)\n self.save_path.parent.mkdir(parents=True, exist_ok=True)\n else:\n self.save_path = None\n if load_path:\n self.load_path = expand_path(load_path)\n if (mode != 'train' and self.save_path and self.load_path !=\n self.save_path):\n log.warning(\n \"Load path '{}' differs from save path '{}' in '{}' mode for {}.\"\n .format(self.load_path, self.save_path, mode, self.\n __class__.__name__))\n elif mode != 'train' and self.save_path:\n self.load_path = self.save_path\n log.warning(\n \"No load path is set for {} in '{}' mode. Using save path instead\"\n .format(self.__class__.__name__, mode))\n else:\n self.load_path = None\n log.warning('No load path is set for {}!'.format(self.__class__\n .__name__))\n <function token>\n <function token>\n", "<docstring token>\n<import token>\n<docstring token>\n<assignment token>\n\n\nclass Serializable(metaclass=ABCMeta):\n <docstring token>\n <function token>\n <function token>\n <function token>\n", "<docstring token>\n<import token>\n<docstring token>\n<assignment token>\n<class token>\n" ]
false
98,788
7ff3bb98d6b3644751ddb673158118b533744bf2
import pytest from thumbor.engines import BaseEngine @pytest.fixture def config(config): config.FILTERS = [ 'thumbor_video_engine.filters.format', 'thumbor_video_engine.filters.still', ] return config @pytest.mark.gen_test @pytest.mark.parametrize('pos', ['', '00:00:00']) def test_still_filter(http_client, base_url, pos): response = yield http_client.fetch( "%s/unsafe/filters:still(%s)/hotdog.mp4" % (base_url, pos)) assert response.code == 200 assert response.headers.get('content-type') == 'image/jpeg' assert BaseEngine.get_mimetype(response.body) == 'image/jpeg' @pytest.mark.gen_test @pytest.mark.parametrize('format,mime_type', [ ('webp', 'image/webp'), ('jpg', 'image/jpeg'), ('zpg', 'image/jpeg'), ]) def test_still_filter_with_format(http_client, base_url, format, mime_type): response = yield http_client.fetch( "%s/unsafe/filters:still():format(%s)/hotdog.mp4" % (base_url, format)) assert response.code == 200 assert response.headers.get('content-type') == mime_type assert BaseEngine.get_mimetype(response.body) == mime_type
[ "import pytest\n\nfrom thumbor.engines import BaseEngine\n\n\[email protected]\ndef config(config):\n config.FILTERS = [\n 'thumbor_video_engine.filters.format',\n 'thumbor_video_engine.filters.still',\n ]\n return config\n\n\[email protected]_test\[email protected]('pos', ['', '00:00:00'])\ndef test_still_filter(http_client, base_url, pos):\n response = yield http_client.fetch(\n \"%s/unsafe/filters:still(%s)/hotdog.mp4\" % (base_url, pos))\n\n assert response.code == 200\n assert response.headers.get('content-type') == 'image/jpeg'\n\n assert BaseEngine.get_mimetype(response.body) == 'image/jpeg'\n\n\[email protected]_test\[email protected]('format,mime_type', [\n ('webp', 'image/webp'),\n ('jpg', 'image/jpeg'),\n ('zpg', 'image/jpeg'),\n])\ndef test_still_filter_with_format(http_client, base_url, format, mime_type):\n response = yield http_client.fetch(\n \"%s/unsafe/filters:still():format(%s)/hotdog.mp4\" % (base_url, format))\n\n assert response.code == 200\n assert response.headers.get('content-type') == mime_type\n\n assert BaseEngine.get_mimetype(response.body) == mime_type\n", "import pytest\nfrom thumbor.engines import BaseEngine\n\n\[email protected]\ndef config(config):\n config.FILTERS = ['thumbor_video_engine.filters.format',\n 'thumbor_video_engine.filters.still']\n return config\n\n\[email protected]_test\[email protected]('pos', ['', '00:00:00'])\ndef test_still_filter(http_client, base_url, pos):\n response = yield http_client.fetch(\n '%s/unsafe/filters:still(%s)/hotdog.mp4' % (base_url, pos))\n assert response.code == 200\n assert response.headers.get('content-type') == 'image/jpeg'\n assert BaseEngine.get_mimetype(response.body) == 'image/jpeg'\n\n\[email protected]_test\[email protected]('format,mime_type', [('webp', 'image/webp'), (\n 'jpg', 'image/jpeg'), ('zpg', 'image/jpeg')])\ndef test_still_filter_with_format(http_client, base_url, format, mime_type):\n response = yield http_client.fetch(\n '%s/unsafe/filters:still():format(%s)/hotdog.mp4' % (base_url, format))\n assert response.code == 200\n assert response.headers.get('content-type') == mime_type\n assert BaseEngine.get_mimetype(response.body) == mime_type\n", "<import token>\n\n\[email protected]\ndef config(config):\n config.FILTERS = ['thumbor_video_engine.filters.format',\n 'thumbor_video_engine.filters.still']\n return config\n\n\[email protected]_test\[email protected]('pos', ['', '00:00:00'])\ndef test_still_filter(http_client, base_url, pos):\n response = yield http_client.fetch(\n '%s/unsafe/filters:still(%s)/hotdog.mp4' % (base_url, pos))\n assert response.code == 200\n assert response.headers.get('content-type') == 'image/jpeg'\n assert BaseEngine.get_mimetype(response.body) == 'image/jpeg'\n\n\[email protected]_test\[email protected]('format,mime_type', [('webp', 'image/webp'), (\n 'jpg', 'image/jpeg'), ('zpg', 'image/jpeg')])\ndef test_still_filter_with_format(http_client, base_url, format, mime_type):\n response = yield http_client.fetch(\n '%s/unsafe/filters:still():format(%s)/hotdog.mp4' % (base_url, format))\n assert response.code == 200\n assert response.headers.get('content-type') == mime_type\n assert BaseEngine.get_mimetype(response.body) == mime_type\n", "<import token>\n<function token>\n\n\[email protected]_test\[email protected]('pos', ['', '00:00:00'])\ndef test_still_filter(http_client, base_url, pos):\n response = yield http_client.fetch(\n '%s/unsafe/filters:still(%s)/hotdog.mp4' % (base_url, pos))\n assert response.code == 200\n assert response.headers.get('content-type') == 'image/jpeg'\n assert BaseEngine.get_mimetype(response.body) == 'image/jpeg'\n\n\[email protected]_test\[email protected]('format,mime_type', [('webp', 'image/webp'), (\n 'jpg', 'image/jpeg'), ('zpg', 'image/jpeg')])\ndef test_still_filter_with_format(http_client, base_url, format, mime_type):\n response = yield http_client.fetch(\n '%s/unsafe/filters:still():format(%s)/hotdog.mp4' % (base_url, format))\n assert response.code == 200\n assert response.headers.get('content-type') == mime_type\n assert BaseEngine.get_mimetype(response.body) == mime_type\n", "<import token>\n<function token>\n<function token>\n\n\[email protected]_test\[email protected]('format,mime_type', [('webp', 'image/webp'), (\n 'jpg', 'image/jpeg'), ('zpg', 'image/jpeg')])\ndef test_still_filter_with_format(http_client, base_url, format, mime_type):\n response = yield http_client.fetch(\n '%s/unsafe/filters:still():format(%s)/hotdog.mp4' % (base_url, format))\n assert response.code == 200\n assert response.headers.get('content-type') == mime_type\n assert BaseEngine.get_mimetype(response.body) == mime_type\n", "<import token>\n<function token>\n<function token>\n<function token>\n" ]
false
98,789
5abee515fda12699b86a2485a299e34a7d29435b
from libraries import * ITEMS_PER_ARTICLES = 20 def feed(request): articles = Article.objects.filter(aprobat = True).order_by('-data')[:10] f = feedgenerator.Atom1Feed( title=u"Lifeit",link=u"http://lifeit.ro",description=u"Este un blog dedicat programari si tot ce tine de informatica.", language=u"ro",author_name=u"Lifeit",feed_url=u"http://http://lifeit.ro/feed") for i in articles: f.add_item(title=i.title,link=u"http://lifeit.ro//views/article/?id="+str(i.id),pubdate=i.data,description=i.body) return HttpResponse(f.writeString('UTF-8'),content_type="application/xhtml+xml") def home (request): menu = [] article = [] for i in Menu.objects.order_by('order'): menu.append({'menu':i,'undermenu1':i.undermenu.order_by('order')}) articles = Article.objects.order_by("-data") for i in articles: if i.data <= datetime.date.today() and i.aprobat: article.append(i) articles = article paginator = Paginator(articles,ITEMS_PER_ARTICLES) try: page_number = int(request.GET['page']) page_n = True except (KeyError, ValueError): page_number = 1 page_n = False try: page = paginator.page(page_number) except InvalidPage: page = paginator.page(1) link = Links.objects.all() return render_to_response("home.html",RequestContext(request,{'link':link,'menu':menu,"articles":page,'articles_paginator':paginator.num_pages > 1,'articles_page_n':page_number,'page_n':page_n, 'has_prev': page.has_previous(),'has_next': page.has_next(), 'page': page_number,'pages': paginator.num_pages,'next_page': page_number + 1,'prev_page': page_number - 1,"id":page_number})) def email(request): if request.method == "POST": form = AddEmailForm(request.POST) if form.is_valid(): try: email = Newslatter.objects.create(email=form.cleaned_data['email'],cod=random.randrange(10001, 100000)) mesaj = "Linkul este pentru a finaliza abonarea http://" + request.META.get('HTTP_HOST') + "/abonare/" + email.email + "/" + str(email.cod) send_mail("Abonare", mesaj , "[email protected]", [email.email]) return render_to_response("ajax/email.html",RequestContext(request,{'form':form,'mesaj':"Verifica adresa de email pentru a te putea abona"})) except: email = Newslatter.objects.get(email=form.cleaned_data['email']) if not email.active: mesaj = "Linkul este pentru a te abona http://" + request.META.get('HTTP_HOST') + "/abonare/" + email.email + "/" + str(email.cod) send_mail("Abonare", mesaj , "[email protected]", [email.email]) return render_to_response("ajax/email.html",RequestContext(request,{'form':form,'mesaj':"Email mai este in baza de date dar nu a fost activat asa ca se trimite un nou email "})) else: return render_to_response("ajax/email.html",RequestContext(request,{'form':form,'mesaj':"Email este in baza de date si activat"})) else: form = AddEmailForm() return render_to_response("ajax/email.html",RequestContext(request,{'form':form})) def article(request): if 'id' in request.GET: menu = [] for i in Menu.objects.order_by('order'): menu.append({'menu':i,'undermenu1':i.undermenu.order_by('order')}) link = Links.objects.all() id=request.GET["id"] article = Article.objects.get(id=id) return render_to_response("article.html",RequestContext(request,{'article':article,'menu':menu,'link':link})) def menu(request,menu1,url): if menu1 == "menu": try: menu2 = Menu.objects.get(url=url) except: return Http404() if menu1 == "undermenu": try: menu2 = UnderMenu.objects.get(url=url) except: return Http404() menu = [] for i in Menu.objects.order_by('order'): menu.append({'menu':i,'undermenu1':i.undermenu.order_by('order')}) link = Links.objects.all() date = datetime.date.today() return render_to_response("menu1.html",RequestContext(request,{'menu2':menu2,'data':date,'menu':menu,'menu1':menu1,'url':url,'link':link})) def newslatter(request): article = Article.objects.all() articles = [] for i in article: if i.data == datetime.date.today() and i.aprobat: articles.append(i) return render_to_response("newslatter.html",{'articles':articles,'ip':"http://lifeit.ro",'data':datetime.date.today()}) def user(request): pass def email_a(request,abonare,email,cod): try: email = Newslatter.objects.get(email=email,cod=cod) menu = [] article = [] for i in Menu.objects.order_by('order'): menu.append({'menu':i,'undermenu1':i.undermenu.order_by('order')}) articles = Article.objects.order_by("-data") for i in articles: if i.data <= datetime.date.today() and i.aprobat: article.append(i) link = Links.objects.all() if abonare == "abonare": email.active = True email.save() return render_to_response("abonare.html",RequestContext(request,{'menu':menu,'articles':article,'link':link,'message':"Ai fost abonat cu succes"})) if abonare == "dezabonare": email.delete() return render_to_response("abonare.html",RequestContext(request,{'menu':menu,'articles':article,'link':link,'message':"Ai fost dezabonat cu succes "})) except: return Http404() def newslatter_a(request,data): menu = [] article = [] for i in Menu.objects.order_by('order'): menu.append({'menu':i,'undermenu1':i.undermenu.order_by('order')}) articles = Article.objects.order_by("-data") for i in articles: if i.data <= datetime.date.today() and i.aprobat: article.append(i) link = Links.objects.all() return render_to_response("newslatter_a.html",RequestContext(request,{'menu':menu,'articles':article,'link':link,'data':data})) def robot(request): return HttpResponse("");
[ "from libraries import *\n\nITEMS_PER_ARTICLES = 20\n\n\ndef feed(request):\n articles = Article.objects.filter(aprobat = True).order_by('-data')[:10]\n f = feedgenerator.Atom1Feed( title=u\"Lifeit\",link=u\"http://lifeit.ro\",description=u\"Este un blog dedicat programari si tot ce tine de informatica.\",\n language=u\"ro\",author_name=u\"Lifeit\",feed_url=u\"http://http://lifeit.ro/feed\")\n\n for i in articles:\n f.add_item(title=i.title,link=u\"http://lifeit.ro//views/article/?id=\"+str(i.id),pubdate=i.data,description=i.body)\n return HttpResponse(f.writeString('UTF-8'),content_type=\"application/xhtml+xml\")\n\n\ndef home (request):\n menu = []\n article = []\n\n for i in Menu.objects.order_by('order'):\n menu.append({'menu':i,'undermenu1':i.undermenu.order_by('order')})\n\n articles = Article.objects.order_by(\"-data\")\n for i in articles:\n if i.data <= datetime.date.today() and i.aprobat:\n article.append(i)\n\n articles = article\n\n paginator = Paginator(articles,ITEMS_PER_ARTICLES)\n try:\n page_number = int(request.GET['page'])\n page_n = True\n except (KeyError, ValueError):\n page_number = 1\n page_n = False\n try:\n page = paginator.page(page_number)\n except InvalidPage:\n page = paginator.page(1)\n\n link = Links.objects.all()\n\n return render_to_response(\"home.html\",RequestContext(request,{'link':link,'menu':menu,\"articles\":page,'articles_paginator':paginator.num_pages > 1,'articles_page_n':page_number,'page_n':page_n,\n 'has_prev': page.has_previous(),'has_next': page.has_next(), 'page': page_number,'pages': paginator.num_pages,'next_page': page_number + 1,'prev_page': page_number - 1,\"id\":page_number}))\n\n\ndef email(request):\n if request.method == \"POST\":\n form = AddEmailForm(request.POST)\n if form.is_valid():\n try:\n email = Newslatter.objects.create(email=form.cleaned_data['email'],cod=random.randrange(10001, 100000))\n mesaj = \"Linkul este pentru a finaliza abonarea http://\" + request.META.get('HTTP_HOST') + \"/abonare/\" + email.email + \"/\" + str(email.cod) \n send_mail(\"Abonare\", mesaj , \"[email protected]\", [email.email]) \n return render_to_response(\"ajax/email.html\",RequestContext(request,{'form':form,'mesaj':\"Verifica adresa de email pentru a te putea abona\"}))\n except:\n email = Newslatter.objects.get(email=form.cleaned_data['email'])\n if not email.active:\n mesaj = \"Linkul este pentru a te abona http://\" + request.META.get('HTTP_HOST') + \"/abonare/\" + email.email + \"/\" + str(email.cod) \n send_mail(\"Abonare\", mesaj , \"[email protected]\", [email.email]) \n return render_to_response(\"ajax/email.html\",RequestContext(request,{'form':form,'mesaj':\"Email mai este in baza de date dar nu a fost activat asa ca se trimite un nou email \"}))\n else:\n return render_to_response(\"ajax/email.html\",RequestContext(request,{'form':form,'mesaj':\"Email este in baza de date si activat\"}))\n else:\n form = AddEmailForm()\n return render_to_response(\"ajax/email.html\",RequestContext(request,{'form':form}))\n\n\ndef article(request):\n if 'id' in request.GET:\n menu = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu':i,'undermenu1':i.undermenu.order_by('order')})\n\n link = Links.objects.all()\n\n id=request.GET[\"id\"]\n article = Article.objects.get(id=id)\n\n return render_to_response(\"article.html\",RequestContext(request,{'article':article,'menu':menu,'link':link}))\n\n\ndef menu(request,menu1,url):\n if menu1 == \"menu\":\n try:\n menu2 = Menu.objects.get(url=url)\n except:\n return Http404()\n if menu1 == \"undermenu\":\n try:\n menu2 = UnderMenu.objects.get(url=url)\n except:\n return Http404()\n menu = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu':i,'undermenu1':i.undermenu.order_by('order')})\n\n link = Links.objects.all()\n date = datetime.date.today()\n\n return render_to_response(\"menu1.html\",RequestContext(request,{'menu2':menu2,'data':date,'menu':menu,'menu1':menu1,'url':url,'link':link}))\n\n\ndef newslatter(request):\n article = Article.objects.all()\n articles = []\n for i in article:\n if i.data == datetime.date.today() and i.aprobat:\n articles.append(i)\n return render_to_response(\"newslatter.html\",{'articles':articles,'ip':\"http://lifeit.ro\",'data':datetime.date.today()})\n\n\ndef user(request):\n pass\n\n\ndef email_a(request,abonare,email,cod):\n try:\n email = Newslatter.objects.get(email=email,cod=cod)\n menu = []\n article = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu':i,'undermenu1':i.undermenu.order_by('order')})\n\n articles = Article.objects.order_by(\"-data\")\n for i in articles:\n if i.data <= datetime.date.today() and i.aprobat:\n article.append(i)\n link = Links.objects.all()\n\n if abonare == \"abonare\":\n email.active = True\n email.save()\n return render_to_response(\"abonare.html\",RequestContext(request,{'menu':menu,'articles':article,'link':link,'message':\"Ai fost abonat cu succes\"}))\n if abonare == \"dezabonare\":\n email.delete()\n return render_to_response(\"abonare.html\",RequestContext(request,{'menu':menu,'articles':article,'link':link,'message':\"Ai fost dezabonat cu succes \"}))\n except:\n return Http404()\n\ndef newslatter_a(request,data):\n menu = []\n article = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu':i,'undermenu1':i.undermenu.order_by('order')})\n\n articles = Article.objects.order_by(\"-data\")\n for i in articles:\n if i.data <= datetime.date.today() and i.aprobat:\n article.append(i)\n link = Links.objects.all()\n\n return render_to_response(\"newslatter_a.html\",RequestContext(request,{'menu':menu,'articles':article,'link':link,'data':data}))\n\n\ndef robot(request):\n return HttpResponse(\"\");\n", "from libraries import *\nITEMS_PER_ARTICLES = 20\n\n\ndef feed(request):\n articles = Article.objects.filter(aprobat=True).order_by('-data')[:10]\n f = feedgenerator.Atom1Feed(title=u'Lifeit', link=u'http://lifeit.ro',\n description=\n u'Este un blog dedicat programari si tot ce tine de informatica.',\n language=u'ro', author_name=u'Lifeit', feed_url=\n u'http://http://lifeit.ro/feed')\n for i in articles:\n f.add_item(title=i.title, link=\n u'http://lifeit.ro//views/article/?id=' + str(i.id), pubdate=i.\n data, description=i.body)\n return HttpResponse(f.writeString('UTF-8'), content_type=\n 'application/xhtml+xml')\n\n\ndef home(request):\n menu = []\n article = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by('order')})\n articles = Article.objects.order_by('-data')\n for i in articles:\n if i.data <= datetime.date.today() and i.aprobat:\n article.append(i)\n articles = article\n paginator = Paginator(articles, ITEMS_PER_ARTICLES)\n try:\n page_number = int(request.GET['page'])\n page_n = True\n except (KeyError, ValueError):\n page_number = 1\n page_n = False\n try:\n page = paginator.page(page_number)\n except InvalidPage:\n page = paginator.page(1)\n link = Links.objects.all()\n return render_to_response('home.html', RequestContext(request, {'link':\n link, 'menu': menu, 'articles': page, 'articles_paginator': \n paginator.num_pages > 1, 'articles_page_n': page_number, 'page_n':\n page_n, 'has_prev': page.has_previous(), 'has_next': page.has_next(\n ), 'page': page_number, 'pages': paginator.num_pages, 'next_page': \n page_number + 1, 'prev_page': page_number - 1, 'id': page_number}))\n\n\ndef email(request):\n if request.method == 'POST':\n form = AddEmailForm(request.POST)\n if form.is_valid():\n try:\n email = Newslatter.objects.create(email=form.cleaned_data[\n 'email'], cod=random.randrange(10001, 100000))\n mesaj = ('Linkul este pentru a finaliza abonarea http://' +\n request.META.get('HTTP_HOST') + '/abonare/' + email.\n email + '/' + str(email.cod))\n send_mail('Abonare', mesaj, '[email protected]', [email.\n email])\n return render_to_response('ajax/email.html', RequestContext\n (request, {'form': form, 'mesaj':\n 'Verifica adresa de email pentru a te putea abona'}))\n except:\n email = Newslatter.objects.get(email=form.cleaned_data['email']\n )\n if not email.active:\n mesaj = ('Linkul este pentru a te abona http://' +\n request.META.get('HTTP_HOST') + '/abonare/' + email\n .email + '/' + str(email.cod))\n send_mail('Abonare', mesaj, '[email protected]', [\n email.email])\n return render_to_response('ajax/email.html',\n RequestContext(request, {'form': form, 'mesaj':\n 'Email mai este in baza de date dar nu a fost activat asa ca se trimite un nou email '\n }))\n else:\n return render_to_response('ajax/email.html',\n RequestContext(request, {'form': form, 'mesaj':\n 'Email este in baza de date si activat'}))\n else:\n form = AddEmailForm()\n return render_to_response('ajax/email.html', RequestContext(request, {\n 'form': form}))\n\n\ndef article(request):\n if 'id' in request.GET:\n menu = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by(\n 'order')})\n link = Links.objects.all()\n id = request.GET['id']\n article = Article.objects.get(id=id)\n return render_to_response('article.html', RequestContext(request, {\n 'article': article, 'menu': menu, 'link': link}))\n\n\ndef menu(request, menu1, url):\n if menu1 == 'menu':\n try:\n menu2 = Menu.objects.get(url=url)\n except:\n return Http404()\n if menu1 == 'undermenu':\n try:\n menu2 = UnderMenu.objects.get(url=url)\n except:\n return Http404()\n menu = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by('order')})\n link = Links.objects.all()\n date = datetime.date.today()\n return render_to_response('menu1.html', RequestContext(request, {\n 'menu2': menu2, 'data': date, 'menu': menu, 'menu1': menu1, 'url':\n url, 'link': link}))\n\n\ndef newslatter(request):\n article = Article.objects.all()\n articles = []\n for i in article:\n if i.data == datetime.date.today() and i.aprobat:\n articles.append(i)\n return render_to_response('newslatter.html', {'articles': articles,\n 'ip': 'http://lifeit.ro', 'data': datetime.date.today()})\n\n\ndef user(request):\n pass\n\n\ndef email_a(request, abonare, email, cod):\n try:\n email = Newslatter.objects.get(email=email, cod=cod)\n menu = []\n article = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by(\n 'order')})\n articles = Article.objects.order_by('-data')\n for i in articles:\n if i.data <= datetime.date.today() and i.aprobat:\n article.append(i)\n link = Links.objects.all()\n if abonare == 'abonare':\n email.active = True\n email.save()\n return render_to_response('abonare.html', RequestContext(\n request, {'menu': menu, 'articles': article, 'link': link,\n 'message': 'Ai fost abonat cu succes'}))\n if abonare == 'dezabonare':\n email.delete()\n return render_to_response('abonare.html', RequestContext(\n request, {'menu': menu, 'articles': article, 'link': link,\n 'message': 'Ai fost dezabonat cu succes '}))\n except:\n return Http404()\n\n\ndef newslatter_a(request, data):\n menu = []\n article = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by('order')})\n articles = Article.objects.order_by('-data')\n for i in articles:\n if i.data <= datetime.date.today() and i.aprobat:\n article.append(i)\n link = Links.objects.all()\n return render_to_response('newslatter_a.html', RequestContext(request,\n {'menu': menu, 'articles': article, 'link': link, 'data': data}))\n\n\ndef robot(request):\n return HttpResponse('')\n", "<import token>\nITEMS_PER_ARTICLES = 20\n\n\ndef feed(request):\n articles = Article.objects.filter(aprobat=True).order_by('-data')[:10]\n f = feedgenerator.Atom1Feed(title=u'Lifeit', link=u'http://lifeit.ro',\n description=\n u'Este un blog dedicat programari si tot ce tine de informatica.',\n language=u'ro', author_name=u'Lifeit', feed_url=\n u'http://http://lifeit.ro/feed')\n for i in articles:\n f.add_item(title=i.title, link=\n u'http://lifeit.ro//views/article/?id=' + str(i.id), pubdate=i.\n data, description=i.body)\n return HttpResponse(f.writeString('UTF-8'), content_type=\n 'application/xhtml+xml')\n\n\ndef home(request):\n menu = []\n article = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by('order')})\n articles = Article.objects.order_by('-data')\n for i in articles:\n if i.data <= datetime.date.today() and i.aprobat:\n article.append(i)\n articles = article\n paginator = Paginator(articles, ITEMS_PER_ARTICLES)\n try:\n page_number = int(request.GET['page'])\n page_n = True\n except (KeyError, ValueError):\n page_number = 1\n page_n = False\n try:\n page = paginator.page(page_number)\n except InvalidPage:\n page = paginator.page(1)\n link = Links.objects.all()\n return render_to_response('home.html', RequestContext(request, {'link':\n link, 'menu': menu, 'articles': page, 'articles_paginator': \n paginator.num_pages > 1, 'articles_page_n': page_number, 'page_n':\n page_n, 'has_prev': page.has_previous(), 'has_next': page.has_next(\n ), 'page': page_number, 'pages': paginator.num_pages, 'next_page': \n page_number + 1, 'prev_page': page_number - 1, 'id': page_number}))\n\n\ndef email(request):\n if request.method == 'POST':\n form = AddEmailForm(request.POST)\n if form.is_valid():\n try:\n email = Newslatter.objects.create(email=form.cleaned_data[\n 'email'], cod=random.randrange(10001, 100000))\n mesaj = ('Linkul este pentru a finaliza abonarea http://' +\n request.META.get('HTTP_HOST') + '/abonare/' + email.\n email + '/' + str(email.cod))\n send_mail('Abonare', mesaj, '[email protected]', [email.\n email])\n return render_to_response('ajax/email.html', RequestContext\n (request, {'form': form, 'mesaj':\n 'Verifica adresa de email pentru a te putea abona'}))\n except:\n email = Newslatter.objects.get(email=form.cleaned_data['email']\n )\n if not email.active:\n mesaj = ('Linkul este pentru a te abona http://' +\n request.META.get('HTTP_HOST') + '/abonare/' + email\n .email + '/' + str(email.cod))\n send_mail('Abonare', mesaj, '[email protected]', [\n email.email])\n return render_to_response('ajax/email.html',\n RequestContext(request, {'form': form, 'mesaj':\n 'Email mai este in baza de date dar nu a fost activat asa ca se trimite un nou email '\n }))\n else:\n return render_to_response('ajax/email.html',\n RequestContext(request, {'form': form, 'mesaj':\n 'Email este in baza de date si activat'}))\n else:\n form = AddEmailForm()\n return render_to_response('ajax/email.html', RequestContext(request, {\n 'form': form}))\n\n\ndef article(request):\n if 'id' in request.GET:\n menu = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by(\n 'order')})\n link = Links.objects.all()\n id = request.GET['id']\n article = Article.objects.get(id=id)\n return render_to_response('article.html', RequestContext(request, {\n 'article': article, 'menu': menu, 'link': link}))\n\n\ndef menu(request, menu1, url):\n if menu1 == 'menu':\n try:\n menu2 = Menu.objects.get(url=url)\n except:\n return Http404()\n if menu1 == 'undermenu':\n try:\n menu2 = UnderMenu.objects.get(url=url)\n except:\n return Http404()\n menu = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by('order')})\n link = Links.objects.all()\n date = datetime.date.today()\n return render_to_response('menu1.html', RequestContext(request, {\n 'menu2': menu2, 'data': date, 'menu': menu, 'menu1': menu1, 'url':\n url, 'link': link}))\n\n\ndef newslatter(request):\n article = Article.objects.all()\n articles = []\n for i in article:\n if i.data == datetime.date.today() and i.aprobat:\n articles.append(i)\n return render_to_response('newslatter.html', {'articles': articles,\n 'ip': 'http://lifeit.ro', 'data': datetime.date.today()})\n\n\ndef user(request):\n pass\n\n\ndef email_a(request, abonare, email, cod):\n try:\n email = Newslatter.objects.get(email=email, cod=cod)\n menu = []\n article = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by(\n 'order')})\n articles = Article.objects.order_by('-data')\n for i in articles:\n if i.data <= datetime.date.today() and i.aprobat:\n article.append(i)\n link = Links.objects.all()\n if abonare == 'abonare':\n email.active = True\n email.save()\n return render_to_response('abonare.html', RequestContext(\n request, {'menu': menu, 'articles': article, 'link': link,\n 'message': 'Ai fost abonat cu succes'}))\n if abonare == 'dezabonare':\n email.delete()\n return render_to_response('abonare.html', RequestContext(\n request, {'menu': menu, 'articles': article, 'link': link,\n 'message': 'Ai fost dezabonat cu succes '}))\n except:\n return Http404()\n\n\ndef newslatter_a(request, data):\n menu = []\n article = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by('order')})\n articles = Article.objects.order_by('-data')\n for i in articles:\n if i.data <= datetime.date.today() and i.aprobat:\n article.append(i)\n link = Links.objects.all()\n return render_to_response('newslatter_a.html', RequestContext(request,\n {'menu': menu, 'articles': article, 'link': link, 'data': data}))\n\n\ndef robot(request):\n return HttpResponse('')\n", "<import token>\n<assignment token>\n\n\ndef feed(request):\n articles = Article.objects.filter(aprobat=True).order_by('-data')[:10]\n f = feedgenerator.Atom1Feed(title=u'Lifeit', link=u'http://lifeit.ro',\n description=\n u'Este un blog dedicat programari si tot ce tine de informatica.',\n language=u'ro', author_name=u'Lifeit', feed_url=\n u'http://http://lifeit.ro/feed')\n for i in articles:\n f.add_item(title=i.title, link=\n u'http://lifeit.ro//views/article/?id=' + str(i.id), pubdate=i.\n data, description=i.body)\n return HttpResponse(f.writeString('UTF-8'), content_type=\n 'application/xhtml+xml')\n\n\ndef home(request):\n menu = []\n article = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by('order')})\n articles = Article.objects.order_by('-data')\n for i in articles:\n if i.data <= datetime.date.today() and i.aprobat:\n article.append(i)\n articles = article\n paginator = Paginator(articles, ITEMS_PER_ARTICLES)\n try:\n page_number = int(request.GET['page'])\n page_n = True\n except (KeyError, ValueError):\n page_number = 1\n page_n = False\n try:\n page = paginator.page(page_number)\n except InvalidPage:\n page = paginator.page(1)\n link = Links.objects.all()\n return render_to_response('home.html', RequestContext(request, {'link':\n link, 'menu': menu, 'articles': page, 'articles_paginator': \n paginator.num_pages > 1, 'articles_page_n': page_number, 'page_n':\n page_n, 'has_prev': page.has_previous(), 'has_next': page.has_next(\n ), 'page': page_number, 'pages': paginator.num_pages, 'next_page': \n page_number + 1, 'prev_page': page_number - 1, 'id': page_number}))\n\n\ndef email(request):\n if request.method == 'POST':\n form = AddEmailForm(request.POST)\n if form.is_valid():\n try:\n email = Newslatter.objects.create(email=form.cleaned_data[\n 'email'], cod=random.randrange(10001, 100000))\n mesaj = ('Linkul este pentru a finaliza abonarea http://' +\n request.META.get('HTTP_HOST') + '/abonare/' + email.\n email + '/' + str(email.cod))\n send_mail('Abonare', mesaj, '[email protected]', [email.\n email])\n return render_to_response('ajax/email.html', RequestContext\n (request, {'form': form, 'mesaj':\n 'Verifica adresa de email pentru a te putea abona'}))\n except:\n email = Newslatter.objects.get(email=form.cleaned_data['email']\n )\n if not email.active:\n mesaj = ('Linkul este pentru a te abona http://' +\n request.META.get('HTTP_HOST') + '/abonare/' + email\n .email + '/' + str(email.cod))\n send_mail('Abonare', mesaj, '[email protected]', [\n email.email])\n return render_to_response('ajax/email.html',\n RequestContext(request, {'form': form, 'mesaj':\n 'Email mai este in baza de date dar nu a fost activat asa ca se trimite un nou email '\n }))\n else:\n return render_to_response('ajax/email.html',\n RequestContext(request, {'form': form, 'mesaj':\n 'Email este in baza de date si activat'}))\n else:\n form = AddEmailForm()\n return render_to_response('ajax/email.html', RequestContext(request, {\n 'form': form}))\n\n\ndef article(request):\n if 'id' in request.GET:\n menu = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by(\n 'order')})\n link = Links.objects.all()\n id = request.GET['id']\n article = Article.objects.get(id=id)\n return render_to_response('article.html', RequestContext(request, {\n 'article': article, 'menu': menu, 'link': link}))\n\n\ndef menu(request, menu1, url):\n if menu1 == 'menu':\n try:\n menu2 = Menu.objects.get(url=url)\n except:\n return Http404()\n if menu1 == 'undermenu':\n try:\n menu2 = UnderMenu.objects.get(url=url)\n except:\n return Http404()\n menu = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by('order')})\n link = Links.objects.all()\n date = datetime.date.today()\n return render_to_response('menu1.html', RequestContext(request, {\n 'menu2': menu2, 'data': date, 'menu': menu, 'menu1': menu1, 'url':\n url, 'link': link}))\n\n\ndef newslatter(request):\n article = Article.objects.all()\n articles = []\n for i in article:\n if i.data == datetime.date.today() and i.aprobat:\n articles.append(i)\n return render_to_response('newslatter.html', {'articles': articles,\n 'ip': 'http://lifeit.ro', 'data': datetime.date.today()})\n\n\ndef user(request):\n pass\n\n\ndef email_a(request, abonare, email, cod):\n try:\n email = Newslatter.objects.get(email=email, cod=cod)\n menu = []\n article = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by(\n 'order')})\n articles = Article.objects.order_by('-data')\n for i in articles:\n if i.data <= datetime.date.today() and i.aprobat:\n article.append(i)\n link = Links.objects.all()\n if abonare == 'abonare':\n email.active = True\n email.save()\n return render_to_response('abonare.html', RequestContext(\n request, {'menu': menu, 'articles': article, 'link': link,\n 'message': 'Ai fost abonat cu succes'}))\n if abonare == 'dezabonare':\n email.delete()\n return render_to_response('abonare.html', RequestContext(\n request, {'menu': menu, 'articles': article, 'link': link,\n 'message': 'Ai fost dezabonat cu succes '}))\n except:\n return Http404()\n\n\ndef newslatter_a(request, data):\n menu = []\n article = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by('order')})\n articles = Article.objects.order_by('-data')\n for i in articles:\n if i.data <= datetime.date.today() and i.aprobat:\n article.append(i)\n link = Links.objects.all()\n return render_to_response('newslatter_a.html', RequestContext(request,\n {'menu': menu, 'articles': article, 'link': link, 'data': data}))\n\n\ndef robot(request):\n return HttpResponse('')\n", "<import token>\n<assignment token>\n\n\ndef feed(request):\n articles = Article.objects.filter(aprobat=True).order_by('-data')[:10]\n f = feedgenerator.Atom1Feed(title=u'Lifeit', link=u'http://lifeit.ro',\n description=\n u'Este un blog dedicat programari si tot ce tine de informatica.',\n language=u'ro', author_name=u'Lifeit', feed_url=\n u'http://http://lifeit.ro/feed')\n for i in articles:\n f.add_item(title=i.title, link=\n u'http://lifeit.ro//views/article/?id=' + str(i.id), pubdate=i.\n data, description=i.body)\n return HttpResponse(f.writeString('UTF-8'), content_type=\n 'application/xhtml+xml')\n\n\ndef home(request):\n menu = []\n article = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by('order')})\n articles = Article.objects.order_by('-data')\n for i in articles:\n if i.data <= datetime.date.today() and i.aprobat:\n article.append(i)\n articles = article\n paginator = Paginator(articles, ITEMS_PER_ARTICLES)\n try:\n page_number = int(request.GET['page'])\n page_n = True\n except (KeyError, ValueError):\n page_number = 1\n page_n = False\n try:\n page = paginator.page(page_number)\n except InvalidPage:\n page = paginator.page(1)\n link = Links.objects.all()\n return render_to_response('home.html', RequestContext(request, {'link':\n link, 'menu': menu, 'articles': page, 'articles_paginator': \n paginator.num_pages > 1, 'articles_page_n': page_number, 'page_n':\n page_n, 'has_prev': page.has_previous(), 'has_next': page.has_next(\n ), 'page': page_number, 'pages': paginator.num_pages, 'next_page': \n page_number + 1, 'prev_page': page_number - 1, 'id': page_number}))\n\n\ndef email(request):\n if request.method == 'POST':\n form = AddEmailForm(request.POST)\n if form.is_valid():\n try:\n email = Newslatter.objects.create(email=form.cleaned_data[\n 'email'], cod=random.randrange(10001, 100000))\n mesaj = ('Linkul este pentru a finaliza abonarea http://' +\n request.META.get('HTTP_HOST') + '/abonare/' + email.\n email + '/' + str(email.cod))\n send_mail('Abonare', mesaj, '[email protected]', [email.\n email])\n return render_to_response('ajax/email.html', RequestContext\n (request, {'form': form, 'mesaj':\n 'Verifica adresa de email pentru a te putea abona'}))\n except:\n email = Newslatter.objects.get(email=form.cleaned_data['email']\n )\n if not email.active:\n mesaj = ('Linkul este pentru a te abona http://' +\n request.META.get('HTTP_HOST') + '/abonare/' + email\n .email + '/' + str(email.cod))\n send_mail('Abonare', mesaj, '[email protected]', [\n email.email])\n return render_to_response('ajax/email.html',\n RequestContext(request, {'form': form, 'mesaj':\n 'Email mai este in baza de date dar nu a fost activat asa ca se trimite un nou email '\n }))\n else:\n return render_to_response('ajax/email.html',\n RequestContext(request, {'form': form, 'mesaj':\n 'Email este in baza de date si activat'}))\n else:\n form = AddEmailForm()\n return render_to_response('ajax/email.html', RequestContext(request, {\n 'form': form}))\n\n\ndef article(request):\n if 'id' in request.GET:\n menu = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by(\n 'order')})\n link = Links.objects.all()\n id = request.GET['id']\n article = Article.objects.get(id=id)\n return render_to_response('article.html', RequestContext(request, {\n 'article': article, 'menu': menu, 'link': link}))\n\n\ndef menu(request, menu1, url):\n if menu1 == 'menu':\n try:\n menu2 = Menu.objects.get(url=url)\n except:\n return Http404()\n if menu1 == 'undermenu':\n try:\n menu2 = UnderMenu.objects.get(url=url)\n except:\n return Http404()\n menu = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by('order')})\n link = Links.objects.all()\n date = datetime.date.today()\n return render_to_response('menu1.html', RequestContext(request, {\n 'menu2': menu2, 'data': date, 'menu': menu, 'menu1': menu1, 'url':\n url, 'link': link}))\n\n\ndef newslatter(request):\n article = Article.objects.all()\n articles = []\n for i in article:\n if i.data == datetime.date.today() and i.aprobat:\n articles.append(i)\n return render_to_response('newslatter.html', {'articles': articles,\n 'ip': 'http://lifeit.ro', 'data': datetime.date.today()})\n\n\n<function token>\n\n\ndef email_a(request, abonare, email, cod):\n try:\n email = Newslatter.objects.get(email=email, cod=cod)\n menu = []\n article = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by(\n 'order')})\n articles = Article.objects.order_by('-data')\n for i in articles:\n if i.data <= datetime.date.today() and i.aprobat:\n article.append(i)\n link = Links.objects.all()\n if abonare == 'abonare':\n email.active = True\n email.save()\n return render_to_response('abonare.html', RequestContext(\n request, {'menu': menu, 'articles': article, 'link': link,\n 'message': 'Ai fost abonat cu succes'}))\n if abonare == 'dezabonare':\n email.delete()\n return render_to_response('abonare.html', RequestContext(\n request, {'menu': menu, 'articles': article, 'link': link,\n 'message': 'Ai fost dezabonat cu succes '}))\n except:\n return Http404()\n\n\ndef newslatter_a(request, data):\n menu = []\n article = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by('order')})\n articles = Article.objects.order_by('-data')\n for i in articles:\n if i.data <= datetime.date.today() and i.aprobat:\n article.append(i)\n link = Links.objects.all()\n return render_to_response('newslatter_a.html', RequestContext(request,\n {'menu': menu, 'articles': article, 'link': link, 'data': data}))\n\n\ndef robot(request):\n return HttpResponse('')\n", "<import token>\n<assignment token>\n\n\ndef feed(request):\n articles = Article.objects.filter(aprobat=True).order_by('-data')[:10]\n f = feedgenerator.Atom1Feed(title=u'Lifeit', link=u'http://lifeit.ro',\n description=\n u'Este un blog dedicat programari si tot ce tine de informatica.',\n language=u'ro', author_name=u'Lifeit', feed_url=\n u'http://http://lifeit.ro/feed')\n for i in articles:\n f.add_item(title=i.title, link=\n u'http://lifeit.ro//views/article/?id=' + str(i.id), pubdate=i.\n data, description=i.body)\n return HttpResponse(f.writeString('UTF-8'), content_type=\n 'application/xhtml+xml')\n\n\ndef home(request):\n menu = []\n article = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by('order')})\n articles = Article.objects.order_by('-data')\n for i in articles:\n if i.data <= datetime.date.today() and i.aprobat:\n article.append(i)\n articles = article\n paginator = Paginator(articles, ITEMS_PER_ARTICLES)\n try:\n page_number = int(request.GET['page'])\n page_n = True\n except (KeyError, ValueError):\n page_number = 1\n page_n = False\n try:\n page = paginator.page(page_number)\n except InvalidPage:\n page = paginator.page(1)\n link = Links.objects.all()\n return render_to_response('home.html', RequestContext(request, {'link':\n link, 'menu': menu, 'articles': page, 'articles_paginator': \n paginator.num_pages > 1, 'articles_page_n': page_number, 'page_n':\n page_n, 'has_prev': page.has_previous(), 'has_next': page.has_next(\n ), 'page': page_number, 'pages': paginator.num_pages, 'next_page': \n page_number + 1, 'prev_page': page_number - 1, 'id': page_number}))\n\n\ndef email(request):\n if request.method == 'POST':\n form = AddEmailForm(request.POST)\n if form.is_valid():\n try:\n email = Newslatter.objects.create(email=form.cleaned_data[\n 'email'], cod=random.randrange(10001, 100000))\n mesaj = ('Linkul este pentru a finaliza abonarea http://' +\n request.META.get('HTTP_HOST') + '/abonare/' + email.\n email + '/' + str(email.cod))\n send_mail('Abonare', mesaj, '[email protected]', [email.\n email])\n return render_to_response('ajax/email.html', RequestContext\n (request, {'form': form, 'mesaj':\n 'Verifica adresa de email pentru a te putea abona'}))\n except:\n email = Newslatter.objects.get(email=form.cleaned_data['email']\n )\n if not email.active:\n mesaj = ('Linkul este pentru a te abona http://' +\n request.META.get('HTTP_HOST') + '/abonare/' + email\n .email + '/' + str(email.cod))\n send_mail('Abonare', mesaj, '[email protected]', [\n email.email])\n return render_to_response('ajax/email.html',\n RequestContext(request, {'form': form, 'mesaj':\n 'Email mai este in baza de date dar nu a fost activat asa ca se trimite un nou email '\n }))\n else:\n return render_to_response('ajax/email.html',\n RequestContext(request, {'form': form, 'mesaj':\n 'Email este in baza de date si activat'}))\n else:\n form = AddEmailForm()\n return render_to_response('ajax/email.html', RequestContext(request, {\n 'form': form}))\n\n\ndef article(request):\n if 'id' in request.GET:\n menu = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by(\n 'order')})\n link = Links.objects.all()\n id = request.GET['id']\n article = Article.objects.get(id=id)\n return render_to_response('article.html', RequestContext(request, {\n 'article': article, 'menu': menu, 'link': link}))\n\n\ndef menu(request, menu1, url):\n if menu1 == 'menu':\n try:\n menu2 = Menu.objects.get(url=url)\n except:\n return Http404()\n if menu1 == 'undermenu':\n try:\n menu2 = UnderMenu.objects.get(url=url)\n except:\n return Http404()\n menu = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by('order')})\n link = Links.objects.all()\n date = datetime.date.today()\n return render_to_response('menu1.html', RequestContext(request, {\n 'menu2': menu2, 'data': date, 'menu': menu, 'menu1': menu1, 'url':\n url, 'link': link}))\n\n\ndef newslatter(request):\n article = Article.objects.all()\n articles = []\n for i in article:\n if i.data == datetime.date.today() and i.aprobat:\n articles.append(i)\n return render_to_response('newslatter.html', {'articles': articles,\n 'ip': 'http://lifeit.ro', 'data': datetime.date.today()})\n\n\n<function token>\n<function token>\n\n\ndef newslatter_a(request, data):\n menu = []\n article = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by('order')})\n articles = Article.objects.order_by('-data')\n for i in articles:\n if i.data <= datetime.date.today() and i.aprobat:\n article.append(i)\n link = Links.objects.all()\n return render_to_response('newslatter_a.html', RequestContext(request,\n {'menu': menu, 'articles': article, 'link': link, 'data': data}))\n\n\ndef robot(request):\n return HttpResponse('')\n", "<import token>\n<assignment token>\n\n\ndef feed(request):\n articles = Article.objects.filter(aprobat=True).order_by('-data')[:10]\n f = feedgenerator.Atom1Feed(title=u'Lifeit', link=u'http://lifeit.ro',\n description=\n u'Este un blog dedicat programari si tot ce tine de informatica.',\n language=u'ro', author_name=u'Lifeit', feed_url=\n u'http://http://lifeit.ro/feed')\n for i in articles:\n f.add_item(title=i.title, link=\n u'http://lifeit.ro//views/article/?id=' + str(i.id), pubdate=i.\n data, description=i.body)\n return HttpResponse(f.writeString('UTF-8'), content_type=\n 'application/xhtml+xml')\n\n\n<function token>\n\n\ndef email(request):\n if request.method == 'POST':\n form = AddEmailForm(request.POST)\n if form.is_valid():\n try:\n email = Newslatter.objects.create(email=form.cleaned_data[\n 'email'], cod=random.randrange(10001, 100000))\n mesaj = ('Linkul este pentru a finaliza abonarea http://' +\n request.META.get('HTTP_HOST') + '/abonare/' + email.\n email + '/' + str(email.cod))\n send_mail('Abonare', mesaj, '[email protected]', [email.\n email])\n return render_to_response('ajax/email.html', RequestContext\n (request, {'form': form, 'mesaj':\n 'Verifica adresa de email pentru a te putea abona'}))\n except:\n email = Newslatter.objects.get(email=form.cleaned_data['email']\n )\n if not email.active:\n mesaj = ('Linkul este pentru a te abona http://' +\n request.META.get('HTTP_HOST') + '/abonare/' + email\n .email + '/' + str(email.cod))\n send_mail('Abonare', mesaj, '[email protected]', [\n email.email])\n return render_to_response('ajax/email.html',\n RequestContext(request, {'form': form, 'mesaj':\n 'Email mai este in baza de date dar nu a fost activat asa ca se trimite un nou email '\n }))\n else:\n return render_to_response('ajax/email.html',\n RequestContext(request, {'form': form, 'mesaj':\n 'Email este in baza de date si activat'}))\n else:\n form = AddEmailForm()\n return render_to_response('ajax/email.html', RequestContext(request, {\n 'form': form}))\n\n\ndef article(request):\n if 'id' in request.GET:\n menu = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by(\n 'order')})\n link = Links.objects.all()\n id = request.GET['id']\n article = Article.objects.get(id=id)\n return render_to_response('article.html', RequestContext(request, {\n 'article': article, 'menu': menu, 'link': link}))\n\n\ndef menu(request, menu1, url):\n if menu1 == 'menu':\n try:\n menu2 = Menu.objects.get(url=url)\n except:\n return Http404()\n if menu1 == 'undermenu':\n try:\n menu2 = UnderMenu.objects.get(url=url)\n except:\n return Http404()\n menu = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by('order')})\n link = Links.objects.all()\n date = datetime.date.today()\n return render_to_response('menu1.html', RequestContext(request, {\n 'menu2': menu2, 'data': date, 'menu': menu, 'menu1': menu1, 'url':\n url, 'link': link}))\n\n\ndef newslatter(request):\n article = Article.objects.all()\n articles = []\n for i in article:\n if i.data == datetime.date.today() and i.aprobat:\n articles.append(i)\n return render_to_response('newslatter.html', {'articles': articles,\n 'ip': 'http://lifeit.ro', 'data': datetime.date.today()})\n\n\n<function token>\n<function token>\n\n\ndef newslatter_a(request, data):\n menu = []\n article = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by('order')})\n articles = Article.objects.order_by('-data')\n for i in articles:\n if i.data <= datetime.date.today() and i.aprobat:\n article.append(i)\n link = Links.objects.all()\n return render_to_response('newslatter_a.html', RequestContext(request,\n {'menu': menu, 'articles': article, 'link': link, 'data': data}))\n\n\ndef robot(request):\n return HttpResponse('')\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef email(request):\n if request.method == 'POST':\n form = AddEmailForm(request.POST)\n if form.is_valid():\n try:\n email = Newslatter.objects.create(email=form.cleaned_data[\n 'email'], cod=random.randrange(10001, 100000))\n mesaj = ('Linkul este pentru a finaliza abonarea http://' +\n request.META.get('HTTP_HOST') + '/abonare/' + email.\n email + '/' + str(email.cod))\n send_mail('Abonare', mesaj, '[email protected]', [email.\n email])\n return render_to_response('ajax/email.html', RequestContext\n (request, {'form': form, 'mesaj':\n 'Verifica adresa de email pentru a te putea abona'}))\n except:\n email = Newslatter.objects.get(email=form.cleaned_data['email']\n )\n if not email.active:\n mesaj = ('Linkul este pentru a te abona http://' +\n request.META.get('HTTP_HOST') + '/abonare/' + email\n .email + '/' + str(email.cod))\n send_mail('Abonare', mesaj, '[email protected]', [\n email.email])\n return render_to_response('ajax/email.html',\n RequestContext(request, {'form': form, 'mesaj':\n 'Email mai este in baza de date dar nu a fost activat asa ca se trimite un nou email '\n }))\n else:\n return render_to_response('ajax/email.html',\n RequestContext(request, {'form': form, 'mesaj':\n 'Email este in baza de date si activat'}))\n else:\n form = AddEmailForm()\n return render_to_response('ajax/email.html', RequestContext(request, {\n 'form': form}))\n\n\ndef article(request):\n if 'id' in request.GET:\n menu = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by(\n 'order')})\n link = Links.objects.all()\n id = request.GET['id']\n article = Article.objects.get(id=id)\n return render_to_response('article.html', RequestContext(request, {\n 'article': article, 'menu': menu, 'link': link}))\n\n\ndef menu(request, menu1, url):\n if menu1 == 'menu':\n try:\n menu2 = Menu.objects.get(url=url)\n except:\n return Http404()\n if menu1 == 'undermenu':\n try:\n menu2 = UnderMenu.objects.get(url=url)\n except:\n return Http404()\n menu = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by('order')})\n link = Links.objects.all()\n date = datetime.date.today()\n return render_to_response('menu1.html', RequestContext(request, {\n 'menu2': menu2, 'data': date, 'menu': menu, 'menu1': menu1, 'url':\n url, 'link': link}))\n\n\ndef newslatter(request):\n article = Article.objects.all()\n articles = []\n for i in article:\n if i.data == datetime.date.today() and i.aprobat:\n articles.append(i)\n return render_to_response('newslatter.html', {'articles': articles,\n 'ip': 'http://lifeit.ro', 'data': datetime.date.today()})\n\n\n<function token>\n<function token>\n\n\ndef newslatter_a(request, data):\n menu = []\n article = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by('order')})\n articles = Article.objects.order_by('-data')\n for i in articles:\n if i.data <= datetime.date.today() and i.aprobat:\n article.append(i)\n link = Links.objects.all()\n return render_to_response('newslatter_a.html', RequestContext(request,\n {'menu': menu, 'articles': article, 'link': link, 'data': data}))\n\n\ndef robot(request):\n return HttpResponse('')\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef email(request):\n if request.method == 'POST':\n form = AddEmailForm(request.POST)\n if form.is_valid():\n try:\n email = Newslatter.objects.create(email=form.cleaned_data[\n 'email'], cod=random.randrange(10001, 100000))\n mesaj = ('Linkul este pentru a finaliza abonarea http://' +\n request.META.get('HTTP_HOST') + '/abonare/' + email.\n email + '/' + str(email.cod))\n send_mail('Abonare', mesaj, '[email protected]', [email.\n email])\n return render_to_response('ajax/email.html', RequestContext\n (request, {'form': form, 'mesaj':\n 'Verifica adresa de email pentru a te putea abona'}))\n except:\n email = Newslatter.objects.get(email=form.cleaned_data['email']\n )\n if not email.active:\n mesaj = ('Linkul este pentru a te abona http://' +\n request.META.get('HTTP_HOST') + '/abonare/' + email\n .email + '/' + str(email.cod))\n send_mail('Abonare', mesaj, '[email protected]', [\n email.email])\n return render_to_response('ajax/email.html',\n RequestContext(request, {'form': form, 'mesaj':\n 'Email mai este in baza de date dar nu a fost activat asa ca se trimite un nou email '\n }))\n else:\n return render_to_response('ajax/email.html',\n RequestContext(request, {'form': form, 'mesaj':\n 'Email este in baza de date si activat'}))\n else:\n form = AddEmailForm()\n return render_to_response('ajax/email.html', RequestContext(request, {\n 'form': form}))\n\n\ndef article(request):\n if 'id' in request.GET:\n menu = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by(\n 'order')})\n link = Links.objects.all()\n id = request.GET['id']\n article = Article.objects.get(id=id)\n return render_to_response('article.html', RequestContext(request, {\n 'article': article, 'menu': menu, 'link': link}))\n\n\ndef menu(request, menu1, url):\n if menu1 == 'menu':\n try:\n menu2 = Menu.objects.get(url=url)\n except:\n return Http404()\n if menu1 == 'undermenu':\n try:\n menu2 = UnderMenu.objects.get(url=url)\n except:\n return Http404()\n menu = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by('order')})\n link = Links.objects.all()\n date = datetime.date.today()\n return render_to_response('menu1.html', RequestContext(request, {\n 'menu2': menu2, 'data': date, 'menu': menu, 'menu1': menu1, 'url':\n url, 'link': link}))\n\n\ndef newslatter(request):\n article = Article.objects.all()\n articles = []\n for i in article:\n if i.data == datetime.date.today() and i.aprobat:\n articles.append(i)\n return render_to_response('newslatter.html', {'articles': articles,\n 'ip': 'http://lifeit.ro', 'data': datetime.date.today()})\n\n\n<function token>\n<function token>\n\n\ndef newslatter_a(request, data):\n menu = []\n article = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by('order')})\n articles = Article.objects.order_by('-data')\n for i in articles:\n if i.data <= datetime.date.today() and i.aprobat:\n article.append(i)\n link = Links.objects.all()\n return render_to_response('newslatter_a.html', RequestContext(request,\n {'menu': menu, 'articles': article, 'link': link, 'data': data}))\n\n\n<function token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef email(request):\n if request.method == 'POST':\n form = AddEmailForm(request.POST)\n if form.is_valid():\n try:\n email = Newslatter.objects.create(email=form.cleaned_data[\n 'email'], cod=random.randrange(10001, 100000))\n mesaj = ('Linkul este pentru a finaliza abonarea http://' +\n request.META.get('HTTP_HOST') + '/abonare/' + email.\n email + '/' + str(email.cod))\n send_mail('Abonare', mesaj, '[email protected]', [email.\n email])\n return render_to_response('ajax/email.html', RequestContext\n (request, {'form': form, 'mesaj':\n 'Verifica adresa de email pentru a te putea abona'}))\n except:\n email = Newslatter.objects.get(email=form.cleaned_data['email']\n )\n if not email.active:\n mesaj = ('Linkul este pentru a te abona http://' +\n request.META.get('HTTP_HOST') + '/abonare/' + email\n .email + '/' + str(email.cod))\n send_mail('Abonare', mesaj, '[email protected]', [\n email.email])\n return render_to_response('ajax/email.html',\n RequestContext(request, {'form': form, 'mesaj':\n 'Email mai este in baza de date dar nu a fost activat asa ca se trimite un nou email '\n }))\n else:\n return render_to_response('ajax/email.html',\n RequestContext(request, {'form': form, 'mesaj':\n 'Email este in baza de date si activat'}))\n else:\n form = AddEmailForm()\n return render_to_response('ajax/email.html', RequestContext(request, {\n 'form': form}))\n\n\ndef article(request):\n if 'id' in request.GET:\n menu = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by(\n 'order')})\n link = Links.objects.all()\n id = request.GET['id']\n article = Article.objects.get(id=id)\n return render_to_response('article.html', RequestContext(request, {\n 'article': article, 'menu': menu, 'link': link}))\n\n\ndef menu(request, menu1, url):\n if menu1 == 'menu':\n try:\n menu2 = Menu.objects.get(url=url)\n except:\n return Http404()\n if menu1 == 'undermenu':\n try:\n menu2 = UnderMenu.objects.get(url=url)\n except:\n return Http404()\n menu = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by('order')})\n link = Links.objects.all()\n date = datetime.date.today()\n return render_to_response('menu1.html', RequestContext(request, {\n 'menu2': menu2, 'data': date, 'menu': menu, 'menu1': menu1, 'url':\n url, 'link': link}))\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef newslatter_a(request, data):\n menu = []\n article = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by('order')})\n articles = Article.objects.order_by('-data')\n for i in articles:\n if i.data <= datetime.date.today() and i.aprobat:\n article.append(i)\n link = Links.objects.all()\n return render_to_response('newslatter_a.html', RequestContext(request,\n {'menu': menu, 'articles': article, 'link': link, 'data': data}))\n\n\n<function token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef email(request):\n if request.method == 'POST':\n form = AddEmailForm(request.POST)\n if form.is_valid():\n try:\n email = Newslatter.objects.create(email=form.cleaned_data[\n 'email'], cod=random.randrange(10001, 100000))\n mesaj = ('Linkul este pentru a finaliza abonarea http://' +\n request.META.get('HTTP_HOST') + '/abonare/' + email.\n email + '/' + str(email.cod))\n send_mail('Abonare', mesaj, '[email protected]', [email.\n email])\n return render_to_response('ajax/email.html', RequestContext\n (request, {'form': form, 'mesaj':\n 'Verifica adresa de email pentru a te putea abona'}))\n except:\n email = Newslatter.objects.get(email=form.cleaned_data['email']\n )\n if not email.active:\n mesaj = ('Linkul este pentru a te abona http://' +\n request.META.get('HTTP_HOST') + '/abonare/' + email\n .email + '/' + str(email.cod))\n send_mail('Abonare', mesaj, '[email protected]', [\n email.email])\n return render_to_response('ajax/email.html',\n RequestContext(request, {'form': form, 'mesaj':\n 'Email mai este in baza de date dar nu a fost activat asa ca se trimite un nou email '\n }))\n else:\n return render_to_response('ajax/email.html',\n RequestContext(request, {'form': form, 'mesaj':\n 'Email este in baza de date si activat'}))\n else:\n form = AddEmailForm()\n return render_to_response('ajax/email.html', RequestContext(request, {\n 'form': form}))\n\n\ndef article(request):\n if 'id' in request.GET:\n menu = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by(\n 'order')})\n link = Links.objects.all()\n id = request.GET['id']\n article = Article.objects.get(id=id)\n return render_to_response('article.html', RequestContext(request, {\n 'article': article, 'menu': menu, 'link': link}))\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef newslatter_a(request, data):\n menu = []\n article = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by('order')})\n articles = Article.objects.order_by('-data')\n for i in articles:\n if i.data <= datetime.date.today() and i.aprobat:\n article.append(i)\n link = Links.objects.all()\n return render_to_response('newslatter_a.html', RequestContext(request,\n {'menu': menu, 'articles': article, 'link': link, 'data': data}))\n\n\n<function token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef email(request):\n if request.method == 'POST':\n form = AddEmailForm(request.POST)\n if form.is_valid():\n try:\n email = Newslatter.objects.create(email=form.cleaned_data[\n 'email'], cod=random.randrange(10001, 100000))\n mesaj = ('Linkul este pentru a finaliza abonarea http://' +\n request.META.get('HTTP_HOST') + '/abonare/' + email.\n email + '/' + str(email.cod))\n send_mail('Abonare', mesaj, '[email protected]', [email.\n email])\n return render_to_response('ajax/email.html', RequestContext\n (request, {'form': form, 'mesaj':\n 'Verifica adresa de email pentru a te putea abona'}))\n except:\n email = Newslatter.objects.get(email=form.cleaned_data['email']\n )\n if not email.active:\n mesaj = ('Linkul este pentru a te abona http://' +\n request.META.get('HTTP_HOST') + '/abonare/' + email\n .email + '/' + str(email.cod))\n send_mail('Abonare', mesaj, '[email protected]', [\n email.email])\n return render_to_response('ajax/email.html',\n RequestContext(request, {'form': form, 'mesaj':\n 'Email mai este in baza de date dar nu a fost activat asa ca se trimite un nou email '\n }))\n else:\n return render_to_response('ajax/email.html',\n RequestContext(request, {'form': form, 'mesaj':\n 'Email este in baza de date si activat'}))\n else:\n form = AddEmailForm()\n return render_to_response('ajax/email.html', RequestContext(request, {\n 'form': form}))\n\n\ndef article(request):\n if 'id' in request.GET:\n menu = []\n for i in Menu.objects.order_by('order'):\n menu.append({'menu': i, 'undermenu1': i.undermenu.order_by(\n 'order')})\n link = Links.objects.all()\n id = request.GET['id']\n article = Article.objects.get(id=id)\n return render_to_response('article.html', RequestContext(request, {\n 'article': article, 'menu': menu, 'link': link}))\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef email(request):\n if request.method == 'POST':\n form = AddEmailForm(request.POST)\n if form.is_valid():\n try:\n email = Newslatter.objects.create(email=form.cleaned_data[\n 'email'], cod=random.randrange(10001, 100000))\n mesaj = ('Linkul este pentru a finaliza abonarea http://' +\n request.META.get('HTTP_HOST') + '/abonare/' + email.\n email + '/' + str(email.cod))\n send_mail('Abonare', mesaj, '[email protected]', [email.\n email])\n return render_to_response('ajax/email.html', RequestContext\n (request, {'form': form, 'mesaj':\n 'Verifica adresa de email pentru a te putea abona'}))\n except:\n email = Newslatter.objects.get(email=form.cleaned_data['email']\n )\n if not email.active:\n mesaj = ('Linkul este pentru a te abona http://' +\n request.META.get('HTTP_HOST') + '/abonare/' + email\n .email + '/' + str(email.cod))\n send_mail('Abonare', mesaj, '[email protected]', [\n email.email])\n return render_to_response('ajax/email.html',\n RequestContext(request, {'form': form, 'mesaj':\n 'Email mai este in baza de date dar nu a fost activat asa ca se trimite un nou email '\n }))\n else:\n return render_to_response('ajax/email.html',\n RequestContext(request, {'form': form, 'mesaj':\n 'Email este in baza de date si activat'}))\n else:\n form = AddEmailForm()\n return render_to_response('ajax/email.html', RequestContext(request, {\n 'form': form}))\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n" ]
false
98,790
356fb25eabbcb09ba89b05a61c699b27b2140227
#-*- coding: utf-8 -*- # # example_site/home/views.py # import logging from django.views.generic import TemplateView from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.contrib.auth import REDIRECT_FIELD_NAME from django.urls import reverse log = logging.getLogger('example.home.views') # # Home # class HomePageView(TemplateView): template_name = "home/home.html" redirect_field_name = REDIRECT_FIELD_NAME def dispatch(self, *args, **kwargs): # Either way works, with or with out the reverse function. #kwargs[self.redirect_field_name] = reverse('home-page') kwargs[self.redirect_field_name] = 'home-page' return super(HomePageView, self).dispatch(*args, **kwargs) home_page_view = HomePageView.as_view()
[ "#-*- coding: utf-8 -*-\n#\n# example_site/home/views.py\n#\n\nimport logging\n\nfrom django.views.generic import TemplateView\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom django.contrib.auth import REDIRECT_FIELD_NAME\nfrom django.urls import reverse\n\nlog = logging.getLogger('example.home.views')\n\n\n#\n# Home\n#\nclass HomePageView(TemplateView):\n template_name = \"home/home.html\"\n redirect_field_name = REDIRECT_FIELD_NAME\n\n def dispatch(self, *args, **kwargs):\n # Either way works, with or with out the reverse function.\n #kwargs[self.redirect_field_name] = reverse('home-page')\n kwargs[self.redirect_field_name] = 'home-page'\n return super(HomePageView, self).dispatch(*args, **kwargs)\n\nhome_page_view = HomePageView.as_view()\n", "import logging\nfrom django.views.generic import TemplateView\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom django.contrib.auth import REDIRECT_FIELD_NAME\nfrom django.urls import reverse\nlog = logging.getLogger('example.home.views')\n\n\nclass HomePageView(TemplateView):\n template_name = 'home/home.html'\n redirect_field_name = REDIRECT_FIELD_NAME\n\n def dispatch(self, *args, **kwargs):\n kwargs[self.redirect_field_name] = 'home-page'\n return super(HomePageView, self).dispatch(*args, **kwargs)\n\n\nhome_page_view = HomePageView.as_view()\n", "<import token>\nlog = logging.getLogger('example.home.views')\n\n\nclass HomePageView(TemplateView):\n template_name = 'home/home.html'\n redirect_field_name = REDIRECT_FIELD_NAME\n\n def dispatch(self, *args, **kwargs):\n kwargs[self.redirect_field_name] = 'home-page'\n return super(HomePageView, self).dispatch(*args, **kwargs)\n\n\nhome_page_view = HomePageView.as_view()\n", "<import token>\n<assignment token>\n\n\nclass HomePageView(TemplateView):\n template_name = 'home/home.html'\n redirect_field_name = REDIRECT_FIELD_NAME\n\n def dispatch(self, *args, **kwargs):\n kwargs[self.redirect_field_name] = 'home-page'\n return super(HomePageView, self).dispatch(*args, **kwargs)\n\n\n<assignment token>\n", "<import token>\n<assignment token>\n\n\nclass HomePageView(TemplateView):\n <assignment token>\n <assignment token>\n\n def dispatch(self, *args, **kwargs):\n kwargs[self.redirect_field_name] = 'home-page'\n return super(HomePageView, self).dispatch(*args, **kwargs)\n\n\n<assignment token>\n", "<import token>\n<assignment token>\n\n\nclass HomePageView(TemplateView):\n <assignment token>\n <assignment token>\n <function token>\n\n\n<assignment token>\n", "<import token>\n<assignment token>\n<class token>\n<assignment token>\n" ]
false
98,791
a127306ed8d303416f235c4f1a8dc462592e3f88
number = int(input(f'Ingresar un numero para saber si es par o impar ')) if number % 2 == 0: print(f'El numero {number} es par') else: print(f'El numero {number} es impar') # operador modulo % es el resto de la division si un numero es divisible por 2 entonces el resto es 0
[ "number = int(input(f'Ingresar un numero para saber si es par o impar '))\nif number % 2 == 0:\n print(f'El numero {number} es par')\nelse:\n print(f'El numero {number} es impar')\n\n # operador modulo % es el resto de la division si un numero es divisible por 2 entonces el resto es 0", "number = int(input(f'Ingresar un numero para saber si es par o impar '))\nif number % 2 == 0:\n print(f'El numero {number} es par')\nelse:\n print(f'El numero {number} es impar')\n", "<assignment token>\nif number % 2 == 0:\n print(f'El numero {number} es par')\nelse:\n print(f'El numero {number} es impar')\n", "<assignment token>\n<code token>\n" ]
false
98,792
9a8f91e5c359d9e7cda3582e816e2cdef6dce6df
Pir = input("Você possui irmãos(Sim ou não)\n:") if(Pir=="Sim")or(Pir == "sim"): int(input("Quantos irmãos você tem?\n:")) print("Ok, até mais!") elif(Pir == "Não")or(Pir == "não"): gostaria = input("Gostaria de ter?\n:") if(gostaria =="Sim")or(gostaria == "sim" ): print("Reveja suas ideias...") else: print("Ok.")
[ "Pir = input(\"Você possui irmãos(Sim ou não)\\n:\")\nif(Pir==\"Sim\")or(Pir == \"sim\"):\n int(input(\"Quantos irmãos você tem?\\n:\"))\n print(\"Ok, até mais!\")\n\nelif(Pir == \"Não\")or(Pir == \"não\"):\n gostaria = input(\"Gostaria de ter?\\n:\")\n if(gostaria ==\"Sim\")or(gostaria == \"sim\" ):\n print(\"Reveja suas ideias...\")\n else:\n print(\"Ok.\")", "Pir = input(\"\"\"Você possui irmãos(Sim ou não)\n:\"\"\")\nif Pir == 'Sim' or Pir == 'sim':\n int(input('Quantos irmãos você tem?\\n:'))\n print('Ok, até mais!')\nelif Pir == 'Não' or Pir == 'não':\n gostaria = input('Gostaria de ter?\\n:')\n if gostaria == 'Sim' or gostaria == 'sim':\n print('Reveja suas ideias...')\n else:\n print('Ok.')\n", "<assignment token>\nif Pir == 'Sim' or Pir == 'sim':\n int(input('Quantos irmãos você tem?\\n:'))\n print('Ok, até mais!')\nelif Pir == 'Não' or Pir == 'não':\n gostaria = input('Gostaria de ter?\\n:')\n if gostaria == 'Sim' or gostaria == 'sim':\n print('Reveja suas ideias...')\n else:\n print('Ok.')\n", "<assignment token>\n<code token>\n" ]
false
98,793
38b49b24db9d2ef53adb7c0233f5781aec6fb60d
# Primeiro crie 3 listas ''' * Uma lista que contem 5 frutas * Uma lista que contem 5 cores * Uma lista que contem 5 linguagens de programação ''' from mailbox import linesep import os frutas = ['Fruta1', 'Fruta2', 'Fruta3', 'Fruta4', 'Fruta5', ] cores = ['Cor1', 'Cor2', 'Cor3', 'Cor4', 'Cor5'] linguagens = ['Python', 'C#', 'Javascript', 'Java', 'PHP'] os.chdir('Dev_Aprender\\08_Automacao\\docs') """ #! Desafio 1 - Crie um novo arquivo chamado frutas.txt e insira dentro dele todos as 5 frutas que estão na lista de frutas with open ('frutas.txt','a',newline='\n') as arquivo: for f in frutas: arquivo.write(f + os.linesep) #! Desafio 2 - Imprima na tela todas as linhas que estao dentro do arquivo frutas.txt with open('frutas.txt','r') as arquivo: for f in arquivo: print(f) """ #! Desafio 3 - Sem apagar os dados que já estão dentro de frutas.txt, adicione todas as cores que estão dentro da sua lista de cores ao arquivos frutas.txt with open('frutas.txt','a',newline='') as arquivo: for f in cores: arquivo.write(f + os.linesep) #! Desafio 4 - Crie um novo arquivo chamado 'Top 5 Linguagens.txt' e popule o arquivo, de forma com que cada linguagem ocupe apenas uma linha. #! BONUS - Como você poderia criar vários arquivos vazios, usando um laço for? arquivos = ['musica.mp3','anotacoes.txt','requirements.py'] for a in arquivos: with open[a,'w']: pass
[ "# Primeiro crie 3 listas\n'''\n * Uma lista que contem 5 frutas\n * Uma lista que contem 5 cores\n * Uma lista que contem 5 linguagens de programação\n'''\nfrom mailbox import linesep\nimport os\nfrutas = ['Fruta1', 'Fruta2', 'Fruta3', 'Fruta4', 'Fruta5', ]\ncores = ['Cor1', 'Cor2', 'Cor3', 'Cor4', 'Cor5']\nlinguagens = ['Python', 'C#', 'Javascript', 'Java', 'PHP']\nos.chdir('Dev_Aprender\\\\08_Automacao\\\\docs')\n\n\"\"\" #! Desafio 1 - Crie um novo arquivo chamado frutas.txt e insira dentro dele todos as 5 frutas que estão na lista de frutas\nwith open ('frutas.txt','a',newline='\\n') as arquivo:\n for f in frutas:\n arquivo.write(f + os.linesep)\n\n#! Desafio 2 - Imprima na tela todas as linhas que estao dentro do arquivo frutas.txt\nwith open('frutas.txt','r') as arquivo:\n for f in arquivo:\n print(f) \"\"\"\n#! Desafio 3 - Sem apagar os dados que já estão dentro de frutas.txt, adicione todas as cores que estão dentro da sua lista de cores ao arquivos frutas.txt\nwith open('frutas.txt','a',newline='') as arquivo:\n for f in cores:\n arquivo.write(f + os.linesep)\n#! Desafio 4 - Crie um novo arquivo chamado 'Top 5 Linguagens.txt' e popule o arquivo, de forma com que cada linguagem ocupe apenas uma linha.\n\n#! BONUS - Como você poderia criar vários arquivos vazios, usando um laço for?\narquivos = ['musica.mp3','anotacoes.txt','requirements.py']\n\nfor a in arquivos:\n with open[a,'w']:\n pass", "<docstring token>\nfrom mailbox import linesep\nimport os\nfrutas = ['Fruta1', 'Fruta2', 'Fruta3', 'Fruta4', 'Fruta5']\ncores = ['Cor1', 'Cor2', 'Cor3', 'Cor4', 'Cor5']\nlinguagens = ['Python', 'C#', 'Javascript', 'Java', 'PHP']\nos.chdir('Dev_Aprender\\\\08_Automacao\\\\docs')\n<docstring token>\nwith open('frutas.txt', 'a', newline='') as arquivo:\n for f in cores:\n arquivo.write(f + os.linesep)\narquivos = ['musica.mp3', 'anotacoes.txt', 'requirements.py']\nfor a in arquivos:\n with open[a, 'w']:\n pass\n", "<docstring token>\n<import token>\nfrutas = ['Fruta1', 'Fruta2', 'Fruta3', 'Fruta4', 'Fruta5']\ncores = ['Cor1', 'Cor2', 'Cor3', 'Cor4', 'Cor5']\nlinguagens = ['Python', 'C#', 'Javascript', 'Java', 'PHP']\nos.chdir('Dev_Aprender\\\\08_Automacao\\\\docs')\n<docstring token>\nwith open('frutas.txt', 'a', newline='') as arquivo:\n for f in cores:\n arquivo.write(f + os.linesep)\narquivos = ['musica.mp3', 'anotacoes.txt', 'requirements.py']\nfor a in arquivos:\n with open[a, 'w']:\n pass\n", "<docstring token>\n<import token>\n<assignment token>\nos.chdir('Dev_Aprender\\\\08_Automacao\\\\docs')\n<docstring token>\nwith open('frutas.txt', 'a', newline='') as arquivo:\n for f in cores:\n arquivo.write(f + os.linesep)\n<assignment token>\nfor a in arquivos:\n with open[a, 'w']:\n pass\n", "<docstring token>\n<import token>\n<assignment token>\n<code token>\n<docstring token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
98,794
4a1ea4675dc26db05fac2ac9cb878bdd57f8de67
#!/usr/bin/python import socket import sys import os includeos_src = os.environ['INCLUDEOS_SRC'] sys.path.insert(0,includeos_src + "/test") import vmrunner # Usage: python test.py $GUEST_IP $HOST_IP GUEST = '10.0.0.44' if (len(sys.argv) < 2) else sys.argv[1] HOST = '10.0.0.1' if (len(sys.argv) < 3) else sys.argv[2] def TCP_test(): def connect(port): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = (GUEST, port) print >>sys.stderr, 'connecting to %s port %s' % server_address sock.connect(server_address) try: while True: data = sock.recv(1024) #print >>sys.stderr, '%s' % data if data: sock.sendall(data); else: break finally: print >>sys.stderr, 'closing socket' sock.close() return connect(8081) connect(8082) connect(8083) connect(8084) def listen(port): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_address = (HOST, port) print >>sys.stderr, 'starting up on %s port %s' % server_address sock.bind(server_address) sock.listen(1) while True: connection, client_address = sock.accept() try: print >>sys.stderr, 'connection from', client_address while True: data = connection.recv(1024) if data: print >>sys.stderr, 'received data, sending data back to the client' connection.sendall(data) print >>sys.stderr, 'close connection to client' connection.close() else: print >>sys.stderr, 'no more data from', client_address break finally: connection.close() break sock.close() return listen(8085) # Get an auto-created VM from the vmrunner vm = vmrunner.vms[0] # Add custom event-handler vm.on_output("IncludeOS TCP test", TCP_test) # Boot the VM, taking a timeout as parameter vm.make().boot(80)
[ "#!/usr/bin/python\n\nimport socket\nimport sys\nimport os\n\nincludeos_src = os.environ['INCLUDEOS_SRC']\nsys.path.insert(0,includeos_src + \"/test\")\n\nimport vmrunner\n\n# Usage: python test.py $GUEST_IP $HOST_IP\nGUEST = '10.0.0.44' if (len(sys.argv) < 2) else sys.argv[1]\nHOST = '10.0.0.1' if (len(sys.argv) < 3) else sys.argv[2]\n\ndef TCP_test():\n def connect(port):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server_address = (GUEST, port)\n print >>sys.stderr, 'connecting to %s port %s' % server_address\n sock.connect(server_address)\n\n try:\n while True:\n data = sock.recv(1024)\n #print >>sys.stderr, '%s' % data\n if data:\n sock.sendall(data);\n else:\n break\n finally:\n print >>sys.stderr, 'closing socket'\n sock.close()\n return\n\n connect(8081)\n connect(8082)\n connect(8083)\n connect(8084)\n\n def listen(port):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n server_address = (HOST, port)\n print >>sys.stderr, 'starting up on %s port %s' % server_address\n sock.bind(server_address)\n sock.listen(1)\n\n while True:\n connection, client_address = sock.accept()\n try:\n print >>sys.stderr, 'connection from', client_address\n while True:\n data = connection.recv(1024)\n if data:\n print >>sys.stderr, 'received data, sending data back to the client'\n connection.sendall(data)\n print >>sys.stderr, 'close connection to client'\n connection.close()\n else:\n print >>sys.stderr, 'no more data from', client_address\n break\n\n finally:\n connection.close()\n break\n sock.close()\n return\n\n listen(8085)\n\n# Get an auto-created VM from the vmrunner\nvm = vmrunner.vms[0]\n\n# Add custom event-handler\nvm.on_output(\"IncludeOS TCP test\", TCP_test)\n\n# Boot the VM, taking a timeout as parameter\nvm.make().boot(80)\n", "import socket\nimport sys\nimport os\nincludeos_src = os.environ['INCLUDEOS_SRC']\nsys.path.insert(0, includeos_src + '/test')\nimport vmrunner\nGUEST = '10.0.0.44' if len(sys.argv) < 2 else sys.argv[1]\nHOST = '10.0.0.1' if len(sys.argv) < 3 else sys.argv[2]\n\n\ndef TCP_test():\n\n def connect(port):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server_address = GUEST, port\n print >> sys.stderr, 'connecting to %s port %s' % server_address\n sock.connect(server_address)\n try:\n while True:\n data = sock.recv(1024)\n if data:\n sock.sendall(data)\n else:\n break\n finally:\n print >> sys.stderr, 'closing socket'\n sock.close()\n return\n connect(8081)\n connect(8082)\n connect(8083)\n connect(8084)\n\n def listen(port):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n server_address = HOST, port\n print >> sys.stderr, 'starting up on %s port %s' % server_address\n sock.bind(server_address)\n sock.listen(1)\n while True:\n connection, client_address = sock.accept()\n try:\n print >> sys.stderr, 'connection from', client_address\n while True:\n data = connection.recv(1024)\n if data:\n print >> sys.stderr, 'received data, sending data back to the client'\n connection.sendall(data)\n print >> sys.stderr, 'close connection to client'\n connection.close()\n else:\n print >> sys.stderr, 'no more data from', client_address\n break\n finally:\n connection.close()\n break\n sock.close()\n return\n listen(8085)\n\n\nvm = vmrunner.vms[0]\nvm.on_output('IncludeOS TCP test', TCP_test)\nvm.make().boot(80)\n", "<import token>\nincludeos_src = os.environ['INCLUDEOS_SRC']\nsys.path.insert(0, includeos_src + '/test')\n<import token>\nGUEST = '10.0.0.44' if len(sys.argv) < 2 else sys.argv[1]\nHOST = '10.0.0.1' if len(sys.argv) < 3 else sys.argv[2]\n\n\ndef TCP_test():\n\n def connect(port):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server_address = GUEST, port\n print >> sys.stderr, 'connecting to %s port %s' % server_address\n sock.connect(server_address)\n try:\n while True:\n data = sock.recv(1024)\n if data:\n sock.sendall(data)\n else:\n break\n finally:\n print >> sys.stderr, 'closing socket'\n sock.close()\n return\n connect(8081)\n connect(8082)\n connect(8083)\n connect(8084)\n\n def listen(port):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n server_address = HOST, port\n print >> sys.stderr, 'starting up on %s port %s' % server_address\n sock.bind(server_address)\n sock.listen(1)\n while True:\n connection, client_address = sock.accept()\n try:\n print >> sys.stderr, 'connection from', client_address\n while True:\n data = connection.recv(1024)\n if data:\n print >> sys.stderr, 'received data, sending data back to the client'\n connection.sendall(data)\n print >> sys.stderr, 'close connection to client'\n connection.close()\n else:\n print >> sys.stderr, 'no more data from', client_address\n break\n finally:\n connection.close()\n break\n sock.close()\n return\n listen(8085)\n\n\nvm = vmrunner.vms[0]\nvm.on_output('IncludeOS TCP test', TCP_test)\nvm.make().boot(80)\n", "<import token>\n<assignment token>\nsys.path.insert(0, includeos_src + '/test')\n<import token>\n<assignment token>\n\n\ndef TCP_test():\n\n def connect(port):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server_address = GUEST, port\n print >> sys.stderr, 'connecting to %s port %s' % server_address\n sock.connect(server_address)\n try:\n while True:\n data = sock.recv(1024)\n if data:\n sock.sendall(data)\n else:\n break\n finally:\n print >> sys.stderr, 'closing socket'\n sock.close()\n return\n connect(8081)\n connect(8082)\n connect(8083)\n connect(8084)\n\n def listen(port):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n server_address = HOST, port\n print >> sys.stderr, 'starting up on %s port %s' % server_address\n sock.bind(server_address)\n sock.listen(1)\n while True:\n connection, client_address = sock.accept()\n try:\n print >> sys.stderr, 'connection from', client_address\n while True:\n data = connection.recv(1024)\n if data:\n print >> sys.stderr, 'received data, sending data back to the client'\n connection.sendall(data)\n print >> sys.stderr, 'close connection to client'\n connection.close()\n else:\n print >> sys.stderr, 'no more data from', client_address\n break\n finally:\n connection.close()\n break\n sock.close()\n return\n listen(8085)\n\n\n<assignment token>\nvm.on_output('IncludeOS TCP test', TCP_test)\nvm.make().boot(80)\n", "<import token>\n<assignment token>\n<code token>\n<import token>\n<assignment token>\n\n\ndef TCP_test():\n\n def connect(port):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server_address = GUEST, port\n print >> sys.stderr, 'connecting to %s port %s' % server_address\n sock.connect(server_address)\n try:\n while True:\n data = sock.recv(1024)\n if data:\n sock.sendall(data)\n else:\n break\n finally:\n print >> sys.stderr, 'closing socket'\n sock.close()\n return\n connect(8081)\n connect(8082)\n connect(8083)\n connect(8084)\n\n def listen(port):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n server_address = HOST, port\n print >> sys.stderr, 'starting up on %s port %s' % server_address\n sock.bind(server_address)\n sock.listen(1)\n while True:\n connection, client_address = sock.accept()\n try:\n print >> sys.stderr, 'connection from', client_address\n while True:\n data = connection.recv(1024)\n if data:\n print >> sys.stderr, 'received data, sending data back to the client'\n connection.sendall(data)\n print >> sys.stderr, 'close connection to client'\n connection.close()\n else:\n print >> sys.stderr, 'no more data from', client_address\n break\n finally:\n connection.close()\n break\n sock.close()\n return\n listen(8085)\n\n\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<code token>\n<import token>\n<assignment token>\n<function token>\n<assignment token>\n<code token>\n" ]
false
98,795
5b52f4dbe431f774e6cdde2d0766fbfaa065a78d
# -*- coding:utf-8 -*- #中---优化---request范围PDM网站时传入账号和密码 import requests, bs4 class PdmBom(): def __init__(self, bom, cnDes, usDes, num, loc, allSon): self.bom = bom self.cnDes = cnDes self.usDes = usDes self.num = num self.loc = loc self.allSon = allSon self.needSon = [] topfather_bom_url = 'http://www.baidu.com' res = requests.get(topfather_bom_url) res.raise_for_status() print(res.text) bs_obj = bs4.BeautifulSoup(res.text) print(bs_obj.prettify()) #格式化输出 if __name__ == '__main__': topFatherBom = PdmBom('02301246', '3U', '3U Whole Machine', 1, '', ['03057769', '02351379', '35689134']) print(topFatherBom.bom) print(topFatherBom.cnDes) print(topFatherBom.usDes) print(topFatherBom.num) print(topFatherBom.loc) print(topFatherBom.allSon)
[ "# -*- coding:utf-8 -*-\n#中---优化---request范围PDM网站时传入账号和密码\nimport requests, bs4\n\nclass PdmBom():\n def __init__(self, bom, cnDes, usDes, num, loc, allSon):\n self.bom = bom\n self.cnDes = cnDes\n self.usDes = usDes\n self.num = num\n self.loc = loc\n self.allSon = allSon\n self.needSon = []\n\ntopfather_bom_url = 'http://www.baidu.com'\n\nres = requests.get(topfather_bom_url)\nres.raise_for_status()\nprint(res.text)\n\nbs_obj = bs4.BeautifulSoup(res.text)\nprint(bs_obj.prettify()) #格式化输出\n\nif __name__ == '__main__':\n topFatherBom = PdmBom('02301246', '3U', '3U Whole Machine', 1, '', ['03057769', '02351379', '35689134'])\n print(topFatherBom.bom)\n print(topFatherBom.cnDes)\n print(topFatherBom.usDes)\n print(topFatherBom.num)\n print(topFatherBom.loc)\n print(topFatherBom.allSon)", "import requests, bs4\n\n\nclass PdmBom:\n\n def __init__(self, bom, cnDes, usDes, num, loc, allSon):\n self.bom = bom\n self.cnDes = cnDes\n self.usDes = usDes\n self.num = num\n self.loc = loc\n self.allSon = allSon\n self.needSon = []\n\n\ntopfather_bom_url = 'http://www.baidu.com'\nres = requests.get(topfather_bom_url)\nres.raise_for_status()\nprint(res.text)\nbs_obj = bs4.BeautifulSoup(res.text)\nprint(bs_obj.prettify())\nif __name__ == '__main__':\n topFatherBom = PdmBom('02301246', '3U', '3U Whole Machine', 1, '', [\n '03057769', '02351379', '35689134'])\n print(topFatherBom.bom)\n print(topFatherBom.cnDes)\n print(topFatherBom.usDes)\n print(topFatherBom.num)\n print(topFatherBom.loc)\n print(topFatherBom.allSon)\n", "<import token>\n\n\nclass PdmBom:\n\n def __init__(self, bom, cnDes, usDes, num, loc, allSon):\n self.bom = bom\n self.cnDes = cnDes\n self.usDes = usDes\n self.num = num\n self.loc = loc\n self.allSon = allSon\n self.needSon = []\n\n\ntopfather_bom_url = 'http://www.baidu.com'\nres = requests.get(topfather_bom_url)\nres.raise_for_status()\nprint(res.text)\nbs_obj = bs4.BeautifulSoup(res.text)\nprint(bs_obj.prettify())\nif __name__ == '__main__':\n topFatherBom = PdmBom('02301246', '3U', '3U Whole Machine', 1, '', [\n '03057769', '02351379', '35689134'])\n print(topFatherBom.bom)\n print(topFatherBom.cnDes)\n print(topFatherBom.usDes)\n print(topFatherBom.num)\n print(topFatherBom.loc)\n print(topFatherBom.allSon)\n", "<import token>\n\n\nclass PdmBom:\n\n def __init__(self, bom, cnDes, usDes, num, loc, allSon):\n self.bom = bom\n self.cnDes = cnDes\n self.usDes = usDes\n self.num = num\n self.loc = loc\n self.allSon = allSon\n self.needSon = []\n\n\n<assignment token>\nres.raise_for_status()\nprint(res.text)\n<assignment token>\nprint(bs_obj.prettify())\nif __name__ == '__main__':\n topFatherBom = PdmBom('02301246', '3U', '3U Whole Machine', 1, '', [\n '03057769', '02351379', '35689134'])\n print(topFatherBom.bom)\n print(topFatherBom.cnDes)\n print(topFatherBom.usDes)\n print(topFatherBom.num)\n print(topFatherBom.loc)\n print(topFatherBom.allSon)\n", "<import token>\n\n\nclass PdmBom:\n\n def __init__(self, bom, cnDes, usDes, num, loc, allSon):\n self.bom = bom\n self.cnDes = cnDes\n self.usDes = usDes\n self.num = num\n self.loc = loc\n self.allSon = allSon\n self.needSon = []\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n\n\nclass PdmBom:\n <function token>\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<class token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
98,796
27f66094c8332a47c683df7e734a77f8fa0d7d9d
from skimage.transform import pyramid_gaussian import matplotlib.pyplot as plt import numpy as np def compute_gaussian_pyramid(img, level = 5): """Computes a gaussian pyramid for an input image""" image_pyramid = list(pyramid_gaussian(img, max_layer = level)) image_pyramid.reverse() return image_pyramid def remap_luminance(im_a, im_a_p, im_b): # compute luminance YIQ_tmp = colorsys.rgb_to_yiq(im_a[:,:,0],im_a[:,:,1],im_a[:,:,2]) lum_img_a = YIQ_tmp[0] YIQ_tmp = colorsys.rgb_to_yiq(im_a_p[:,:,0],im_a_p[:,:,1],im_a_p[:,:,2]) lum_img_a_p = YIQ_tmp[0] YIQ_tmp = colorsys.rgb_to_yiq(im_b[:,:,0],im_b[:,:,1],im_b[:,:,2]) lum_img_b = YIQ_tmp[0] mean_a = np.mean(lum_img_a) mean_b = np.mean(lum_img_b) std_dev_a = np.std(lum_img_a) std_dev_b = np.std(lum_img_b) img_a_remap = (std_dev_b/std_dev_a) * (lum_img_a - mean_a) + mean_b img_a_p_remap = [] for im in lum_img_a_p: img_a_p_remap.append((std_dev_b/std_dev_a) * (im - mean_a) + mean_b) return img_a_remap, img_a_p_remap def to_1d(px, w): rows, cols = px[0], px[1] return (rows * w + cols).astype(int) def to_2d(idx, w): cols = idx % w rows = (idx-cols) // w return np.array([rows, cols]) def Ap_to_2d(ixs, h, w): pxs = to_2d(ixs, w) rows, cols = pxs[0], pxs[1] img_nums = (np.floor(rows/h)).astype(int) img_ixs = ixs - img_nums * h * w return to_2d(img_ixs, w), img_nums def Ap_to_1d(pxs, img_nums, h, w): rows, cols = pxs[0], pxs[1] return (((h * img_nums) + rows) * w + cols).astype(int)
[ "from skimage.transform import pyramid_gaussian\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef compute_gaussian_pyramid(img, level = 5):\n\t\"\"\"Computes a gaussian pyramid for an input image\"\"\"\n\n\timage_pyramid = list(pyramid_gaussian(img, max_layer = level))\n\timage_pyramid.reverse()\n\n\treturn image_pyramid\n\n\ndef remap_luminance(im_a, im_a_p, im_b):\n # compute luminance\n YIQ_tmp = colorsys.rgb_to_yiq(im_a[:,:,0],im_a[:,:,1],im_a[:,:,2])\n lum_img_a = YIQ_tmp[0]\n YIQ_tmp = colorsys.rgb_to_yiq(im_a_p[:,:,0],im_a_p[:,:,1],im_a_p[:,:,2])\n lum_img_a_p = YIQ_tmp[0]\n YIQ_tmp = colorsys.rgb_to_yiq(im_b[:,:,0],im_b[:,:,1],im_b[:,:,2])\n lum_img_b = YIQ_tmp[0]\n \n mean_a = np.mean(lum_img_a)\n mean_b = np.mean(lum_img_b)\n std_dev_a = np.std(lum_img_a)\n std_dev_b = np.std(lum_img_b)\n\n img_a_remap = (std_dev_b/std_dev_a) * (lum_img_a - mean_a) + mean_b\n\n img_a_p_remap = []\n\n for im in lum_img_a_p:\n img_a_p_remap.append((std_dev_b/std_dev_a) * (im - mean_a) + mean_b)\n\n return img_a_remap, img_a_p_remap\n\ndef to_1d(px, w):\n rows, cols = px[0], px[1]\n return (rows * w + cols).astype(int)\n\ndef to_2d(idx, w):\n cols = idx % w\n rows = (idx-cols) // w\n return np.array([rows, cols])\n\ndef Ap_to_2d(ixs, h, w):\n pxs = to_2d(ixs, w)\n rows, cols = pxs[0], pxs[1]\n img_nums = (np.floor(rows/h)).astype(int)\n img_ixs = ixs - img_nums * h * w\n return to_2d(img_ixs, w), img_nums\n\ndef Ap_to_1d(pxs, img_nums, h, w):\n rows, cols = pxs[0], pxs[1]\n return (((h * img_nums) + rows) * w + cols).astype(int)\n", "from skimage.transform import pyramid_gaussian\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef compute_gaussian_pyramid(img, level=5):\n \"\"\"Computes a gaussian pyramid for an input image\"\"\"\n image_pyramid = list(pyramid_gaussian(img, max_layer=level))\n image_pyramid.reverse()\n return image_pyramid\n\n\ndef remap_luminance(im_a, im_a_p, im_b):\n YIQ_tmp = colorsys.rgb_to_yiq(im_a[:, :, 0], im_a[:, :, 1], im_a[:, :, 2])\n lum_img_a = YIQ_tmp[0]\n YIQ_tmp = colorsys.rgb_to_yiq(im_a_p[:, :, 0], im_a_p[:, :, 1], im_a_p[\n :, :, 2])\n lum_img_a_p = YIQ_tmp[0]\n YIQ_tmp = colorsys.rgb_to_yiq(im_b[:, :, 0], im_b[:, :, 1], im_b[:, :, 2])\n lum_img_b = YIQ_tmp[0]\n mean_a = np.mean(lum_img_a)\n mean_b = np.mean(lum_img_b)\n std_dev_a = np.std(lum_img_a)\n std_dev_b = np.std(lum_img_b)\n img_a_remap = std_dev_b / std_dev_a * (lum_img_a - mean_a) + mean_b\n img_a_p_remap = []\n for im in lum_img_a_p:\n img_a_p_remap.append(std_dev_b / std_dev_a * (im - mean_a) + mean_b)\n return img_a_remap, img_a_p_remap\n\n\ndef to_1d(px, w):\n rows, cols = px[0], px[1]\n return (rows * w + cols).astype(int)\n\n\ndef to_2d(idx, w):\n cols = idx % w\n rows = (idx - cols) // w\n return np.array([rows, cols])\n\n\ndef Ap_to_2d(ixs, h, w):\n pxs = to_2d(ixs, w)\n rows, cols = pxs[0], pxs[1]\n img_nums = np.floor(rows / h).astype(int)\n img_ixs = ixs - img_nums * h * w\n return to_2d(img_ixs, w), img_nums\n\n\ndef Ap_to_1d(pxs, img_nums, h, w):\n rows, cols = pxs[0], pxs[1]\n return ((h * img_nums + rows) * w + cols).astype(int)\n", "<import token>\n\n\ndef compute_gaussian_pyramid(img, level=5):\n \"\"\"Computes a gaussian pyramid for an input image\"\"\"\n image_pyramid = list(pyramid_gaussian(img, max_layer=level))\n image_pyramid.reverse()\n return image_pyramid\n\n\ndef remap_luminance(im_a, im_a_p, im_b):\n YIQ_tmp = colorsys.rgb_to_yiq(im_a[:, :, 0], im_a[:, :, 1], im_a[:, :, 2])\n lum_img_a = YIQ_tmp[0]\n YIQ_tmp = colorsys.rgb_to_yiq(im_a_p[:, :, 0], im_a_p[:, :, 1], im_a_p[\n :, :, 2])\n lum_img_a_p = YIQ_tmp[0]\n YIQ_tmp = colorsys.rgb_to_yiq(im_b[:, :, 0], im_b[:, :, 1], im_b[:, :, 2])\n lum_img_b = YIQ_tmp[0]\n mean_a = np.mean(lum_img_a)\n mean_b = np.mean(lum_img_b)\n std_dev_a = np.std(lum_img_a)\n std_dev_b = np.std(lum_img_b)\n img_a_remap = std_dev_b / std_dev_a * (lum_img_a - mean_a) + mean_b\n img_a_p_remap = []\n for im in lum_img_a_p:\n img_a_p_remap.append(std_dev_b / std_dev_a * (im - mean_a) + mean_b)\n return img_a_remap, img_a_p_remap\n\n\ndef to_1d(px, w):\n rows, cols = px[0], px[1]\n return (rows * w + cols).astype(int)\n\n\ndef to_2d(idx, w):\n cols = idx % w\n rows = (idx - cols) // w\n return np.array([rows, cols])\n\n\ndef Ap_to_2d(ixs, h, w):\n pxs = to_2d(ixs, w)\n rows, cols = pxs[0], pxs[1]\n img_nums = np.floor(rows / h).astype(int)\n img_ixs = ixs - img_nums * h * w\n return to_2d(img_ixs, w), img_nums\n\n\ndef Ap_to_1d(pxs, img_nums, h, w):\n rows, cols = pxs[0], pxs[1]\n return ((h * img_nums + rows) * w + cols).astype(int)\n", "<import token>\n\n\ndef compute_gaussian_pyramid(img, level=5):\n \"\"\"Computes a gaussian pyramid for an input image\"\"\"\n image_pyramid = list(pyramid_gaussian(img, max_layer=level))\n image_pyramid.reverse()\n return image_pyramid\n\n\ndef remap_luminance(im_a, im_a_p, im_b):\n YIQ_tmp = colorsys.rgb_to_yiq(im_a[:, :, 0], im_a[:, :, 1], im_a[:, :, 2])\n lum_img_a = YIQ_tmp[0]\n YIQ_tmp = colorsys.rgb_to_yiq(im_a_p[:, :, 0], im_a_p[:, :, 1], im_a_p[\n :, :, 2])\n lum_img_a_p = YIQ_tmp[0]\n YIQ_tmp = colorsys.rgb_to_yiq(im_b[:, :, 0], im_b[:, :, 1], im_b[:, :, 2])\n lum_img_b = YIQ_tmp[0]\n mean_a = np.mean(lum_img_a)\n mean_b = np.mean(lum_img_b)\n std_dev_a = np.std(lum_img_a)\n std_dev_b = np.std(lum_img_b)\n img_a_remap = std_dev_b / std_dev_a * (lum_img_a - mean_a) + mean_b\n img_a_p_remap = []\n for im in lum_img_a_p:\n img_a_p_remap.append(std_dev_b / std_dev_a * (im - mean_a) + mean_b)\n return img_a_remap, img_a_p_remap\n\n\ndef to_1d(px, w):\n rows, cols = px[0], px[1]\n return (rows * w + cols).astype(int)\n\n\n<function token>\n\n\ndef Ap_to_2d(ixs, h, w):\n pxs = to_2d(ixs, w)\n rows, cols = pxs[0], pxs[1]\n img_nums = np.floor(rows / h).astype(int)\n img_ixs = ixs - img_nums * h * w\n return to_2d(img_ixs, w), img_nums\n\n\ndef Ap_to_1d(pxs, img_nums, h, w):\n rows, cols = pxs[0], pxs[1]\n return ((h * img_nums + rows) * w + cols).astype(int)\n", "<import token>\n\n\ndef compute_gaussian_pyramid(img, level=5):\n \"\"\"Computes a gaussian pyramid for an input image\"\"\"\n image_pyramid = list(pyramid_gaussian(img, max_layer=level))\n image_pyramid.reverse()\n return image_pyramid\n\n\ndef remap_luminance(im_a, im_a_p, im_b):\n YIQ_tmp = colorsys.rgb_to_yiq(im_a[:, :, 0], im_a[:, :, 1], im_a[:, :, 2])\n lum_img_a = YIQ_tmp[0]\n YIQ_tmp = colorsys.rgb_to_yiq(im_a_p[:, :, 0], im_a_p[:, :, 1], im_a_p[\n :, :, 2])\n lum_img_a_p = YIQ_tmp[0]\n YIQ_tmp = colorsys.rgb_to_yiq(im_b[:, :, 0], im_b[:, :, 1], im_b[:, :, 2])\n lum_img_b = YIQ_tmp[0]\n mean_a = np.mean(lum_img_a)\n mean_b = np.mean(lum_img_b)\n std_dev_a = np.std(lum_img_a)\n std_dev_b = np.std(lum_img_b)\n img_a_remap = std_dev_b / std_dev_a * (lum_img_a - mean_a) + mean_b\n img_a_p_remap = []\n for im in lum_img_a_p:\n img_a_p_remap.append(std_dev_b / std_dev_a * (im - mean_a) + mean_b)\n return img_a_remap, img_a_p_remap\n\n\ndef to_1d(px, w):\n rows, cols = px[0], px[1]\n return (rows * w + cols).astype(int)\n\n\n<function token>\n\n\ndef Ap_to_2d(ixs, h, w):\n pxs = to_2d(ixs, w)\n rows, cols = pxs[0], pxs[1]\n img_nums = np.floor(rows / h).astype(int)\n img_ixs = ixs - img_nums * h * w\n return to_2d(img_ixs, w), img_nums\n\n\n<function token>\n", "<import token>\n\n\ndef compute_gaussian_pyramid(img, level=5):\n \"\"\"Computes a gaussian pyramid for an input image\"\"\"\n image_pyramid = list(pyramid_gaussian(img, max_layer=level))\n image_pyramid.reverse()\n return image_pyramid\n\n\ndef remap_luminance(im_a, im_a_p, im_b):\n YIQ_tmp = colorsys.rgb_to_yiq(im_a[:, :, 0], im_a[:, :, 1], im_a[:, :, 2])\n lum_img_a = YIQ_tmp[0]\n YIQ_tmp = colorsys.rgb_to_yiq(im_a_p[:, :, 0], im_a_p[:, :, 1], im_a_p[\n :, :, 2])\n lum_img_a_p = YIQ_tmp[0]\n YIQ_tmp = colorsys.rgb_to_yiq(im_b[:, :, 0], im_b[:, :, 1], im_b[:, :, 2])\n lum_img_b = YIQ_tmp[0]\n mean_a = np.mean(lum_img_a)\n mean_b = np.mean(lum_img_b)\n std_dev_a = np.std(lum_img_a)\n std_dev_b = np.std(lum_img_b)\n img_a_remap = std_dev_b / std_dev_a * (lum_img_a - mean_a) + mean_b\n img_a_p_remap = []\n for im in lum_img_a_p:\n img_a_p_remap.append(std_dev_b / std_dev_a * (im - mean_a) + mean_b)\n return img_a_remap, img_a_p_remap\n\n\n<function token>\n<function token>\n\n\ndef Ap_to_2d(ixs, h, w):\n pxs = to_2d(ixs, w)\n rows, cols = pxs[0], pxs[1]\n img_nums = np.floor(rows / h).astype(int)\n img_ixs = ixs - img_nums * h * w\n return to_2d(img_ixs, w), img_nums\n\n\n<function token>\n", "<import token>\n\n\ndef compute_gaussian_pyramid(img, level=5):\n \"\"\"Computes a gaussian pyramid for an input image\"\"\"\n image_pyramid = list(pyramid_gaussian(img, max_layer=level))\n image_pyramid.reverse()\n return image_pyramid\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef Ap_to_2d(ixs, h, w):\n pxs = to_2d(ixs, w)\n rows, cols = pxs[0], pxs[1]\n img_nums = np.floor(rows / h).astype(int)\n img_ixs = ixs - img_nums * h * w\n return to_2d(img_ixs, w), img_nums\n\n\n<function token>\n", "<import token>\n\n\ndef compute_gaussian_pyramid(img, level=5):\n \"\"\"Computes a gaussian pyramid for an input image\"\"\"\n image_pyramid = list(pyramid_gaussian(img, max_layer=level))\n image_pyramid.reverse()\n return image_pyramid\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n" ]
false
98,797
3791266a274649db4d1a25a3b20ff192451fc5c8
# <imports> from otree.api import Currency as c from otree.constants import BaseConstants # </imports> # ******************************************************************************************************************** # # *** CLASS CONSTANTS *** # # ******************************************************************************************************************** # class Constants(BaseConstants): # ---------------------------------------------------------------------------------------------------------------- # # --- Task-specific Settings --- # # ---------------------------------------------------------------------------------------------------------------- # # currency (symbol) currency = '€' # number of binary choices between "payment today" and "payment in 12 months" num_choices = 25 # include certain choice certain_choice = True # original list of payments in 12 moths used by Falk et al. (2016) original_list = [ 100.00, 103.00, 106.10, 109.20, 112.40, 115.60, 118.80, 122.10, 125.40, 128.80, 132.30, 135.70, 139.20, 142.80, 146.40, 150.10, 153.80, 157.50, 161.30, 165.10, 169.00, 172.90, 176.90, 180.90, 185.00 ] # Use original list of payments # "True" means that the for the payments in 12 months the original list by Falk et al. (2016) will be used. # "False" means that the list of payments in 12 months will be created anew, # based on the parameter "increment" and "rate" specified below. use_original_list = True # if the list is to be created anew # "payment" denotes the payment today # "payment12" denotes the initial payment in 12 months, i.e. at row 1 # "increment" determines the initial increment in the payment in 12 months (i.e. from row 1 to row 2) # "rate" denotes how much the increment changes from row to row payment = 100 payment12 = payment increment = 3 rate = 0.05 # ---------------------------------------------------------------------------------------------------------------- # # --- Overall Settings and Appearance --- # # ---------------------------------------------------------------------------------------------------------------- # # Consistency (single switching point) # --------------------------------------------------------------------------------------------------------------- # Enforce consistency, i.e. only allow for a single switching point # if <enforce_consistency = True>, all options "A" above a selected option "A" are automatically selected # similarly, all options "B" below a selected option "B" are automatically checked, implying consistent choices # note that <enforce_consistency> is only implemented if <one_choice_per_page = False> and <random_order = False> enforce_consistency = True # Single click # if <enforce_consistency = True> and <single_click = True>, when a participant selects option "B" at a certain row, # not only all options "B" below the selected option "B" are automatically checked (as in enforce_consistency), # but also all options "A" above the selected option "B" are automatically checked. # In other words, the participant is required to click only once. single_click = True # --------------------------------------------------------------------------------------------------------------- # show each lottery pair on a separate page # if <one_choice_per_page = True>, each single binary choice is shown on a separate page # if <one_choice_per_page = False>, all <num_choices> choices are displayed in a table on one page one_choice_per_page = False # order choices between lottery pairs randomly # if <random_order = True>, the ordering of binary decisions is randomized for display # if <random_order = False>, binary choices are listed in ascending order of the probability of the "high" outcome random_order = False # depict probabilities as percentage numbers # if <percentage = True>, the probability of outcome "high" will be displayed as percentage number, i.e. "50%" # if <percentage = False>, the probabilities will be displayed as fractions, i.e. "1/2" etc. percentage = True # show small pie charts for each lottery # if <small_pies = True>, a pie chart depicting the probabilities of outcomes is rendered next to each lottery # if <small_pies = False>, no graphical representation of probabilities is displayed small_pies = True # display lotteries in terms of large pie charts # if <large_pies = True>, lotteries are depicted as pie charts; if <large_pies = False> lotteries are list items # note that <large_pies = True> only affects the task's appearance if <one_choice_per_page = True> large_pies = True # show progress bar # if <progress_bar = True> and <one_choice_per_page = True>, a progress bar is rendered # if <progress_bar = False>, no information with respect to the advance within the task is displayed # the progress bar graphically depicts the advance within the task in terms of how many decision have been made # further, information in terms of "page x out of <num_choices>" (with x denoting the current choice) is provided progress_bar = True # show instructions page # if <instructions = True>, a separate template "Instructions.html" is rendered prior to the task # if <instructions = False>, the task starts immediately (e.g. in case of printed instructions) instructions = True # show results page summarizing the task's outcome including payoff information # if <results = True>, a separate page containing all relevant information is displayed after finishing the task # if <results = False>, the template "Results.html" will not be rendered results = False # null payoff (if results is false and the task is not incentive compatible) null_payoff = 0 # ---------------------------------------------------------------------------------------------------------------- # # --- oTree Settings (Don't Modify) --- # # ---------------------------------------------------------------------------------------------------------------- # name_in_url = 'patience_mpl' players_per_group = None if one_choice_per_page: if certain_choice: num_rounds = num_choices else: num_rounds = num_choices - 1 else: num_rounds = 1
[ "# <imports>\nfrom otree.api import Currency as c\nfrom otree.constants import BaseConstants\n# </imports>\n\n\n# ******************************************************************************************************************** #\n# *** CLASS CONSTANTS *** #\n# ******************************************************************************************************************** #\nclass Constants(BaseConstants):\n\n # ---------------------------------------------------------------------------------------------------------------- #\n # --- Task-specific Settings --- #\n # ---------------------------------------------------------------------------------------------------------------- #\n\n # currency (symbol)\n currency = '€'\n\n # number of binary choices between \"payment today\" and \"payment in 12 months\"\n num_choices = 25\n\n # include certain choice\n certain_choice = True\n\n # original list of payments in 12 moths used by Falk et al. (2016)\n original_list = [\n 100.00, 103.00, 106.10, 109.20, 112.40,\n 115.60, 118.80, 122.10, 125.40, 128.80,\n 132.30, 135.70, 139.20, 142.80, 146.40,\n 150.10, 153.80, 157.50, 161.30, 165.10,\n 169.00, 172.90, 176.90, 180.90, 185.00\n ]\n\n # Use original list of payments\n # \"True\" means that the for the payments in 12 months the original list by Falk et al. (2016) will be used.\n # \"False\" means that the list of payments in 12 months will be created anew,\n # based on the parameter \"increment\" and \"rate\" specified below.\n use_original_list = True\n\n # if the list is to be created anew\n # \"payment\" denotes the payment today\n # \"payment12\" denotes the initial payment in 12 months, i.e. at row 1\n # \"increment\" determines the initial increment in the payment in 12 months (i.e. from row 1 to row 2)\n # \"rate\" denotes how much the increment changes from row to row\n\n payment = 100\n payment12 = payment\n increment = 3\n rate = 0.05\n\n # ---------------------------------------------------------------------------------------------------------------- #\n # --- Overall Settings and Appearance --- #\n # ---------------------------------------------------------------------------------------------------------------- #\n\n # Consistency (single switching point)\n # ---------------------------------------------------------------------------------------------------------------\n # Enforce consistency, i.e. only allow for a single switching point\n # if <enforce_consistency = True>, all options \"A\" above a selected option \"A\" are automatically selected\n # similarly, all options \"B\" below a selected option \"B\" are automatically checked, implying consistent choices\n # note that <enforce_consistency> is only implemented if <one_choice_per_page = False> and <random_order = False>\n enforce_consistency = True\n\n # Single click\n # if <enforce_consistency = True> and <single_click = True>, when a participant selects option \"B\" at a certain row,\n # not only all options \"B\" below the selected option \"B\" are automatically checked (as in enforce_consistency),\n # but also all options \"A\" above the selected option \"B\" are automatically checked.\n # In other words, the participant is required to click only once.\n single_click = True\n\n # ---------------------------------------------------------------------------------------------------------------\n\n # show each lottery pair on a separate page\n # if <one_choice_per_page = True>, each single binary choice is shown on a separate page\n # if <one_choice_per_page = False>, all <num_choices> choices are displayed in a table on one page\n one_choice_per_page = False\n\n # order choices between lottery pairs randomly\n # if <random_order = True>, the ordering of binary decisions is randomized for display\n # if <random_order = False>, binary choices are listed in ascending order of the probability of the \"high\" outcome\n random_order = False\n\n # depict probabilities as percentage numbers\n # if <percentage = True>, the probability of outcome \"high\" will be displayed as percentage number, i.e. \"50%\"\n # if <percentage = False>, the probabilities will be displayed as fractions, i.e. \"1/2\" etc.\n percentage = True\n\n # show small pie charts for each lottery\n # if <small_pies = True>, a pie chart depicting the probabilities of outcomes is rendered next to each lottery\n # if <small_pies = False>, no graphical representation of probabilities is displayed\n small_pies = True\n\n # display lotteries in terms of large pie charts\n # if <large_pies = True>, lotteries are depicted as pie charts; if <large_pies = False> lotteries are list items\n # note that <large_pies = True> only affects the task's appearance if <one_choice_per_page = True>\n large_pies = True\n\n # show progress bar\n # if <progress_bar = True> and <one_choice_per_page = True>, a progress bar is rendered\n # if <progress_bar = False>, no information with respect to the advance within the task is displayed\n # the progress bar graphically depicts the advance within the task in terms of how many decision have been made\n # further, information in terms of \"page x out of <num_choices>\" (with x denoting the current choice) is provided\n progress_bar = True\n\n # show instructions page\n # if <instructions = True>, a separate template \"Instructions.html\" is rendered prior to the task\n # if <instructions = False>, the task starts immediately (e.g. in case of printed instructions)\n instructions = True\n\n # show results page summarizing the task's outcome including payoff information\n # if <results = True>, a separate page containing all relevant information is displayed after finishing the task\n # if <results = False>, the template \"Results.html\" will not be rendered\n results = False\n\n # null payoff (if results is false and the task is not incentive compatible)\n null_payoff = 0\n\n # ---------------------------------------------------------------------------------------------------------------- #\n # --- oTree Settings (Don't Modify) --- #\n # ---------------------------------------------------------------------------------------------------------------- #\n\n name_in_url = 'patience_mpl'\n players_per_group = None\n\n if one_choice_per_page:\n if certain_choice:\n num_rounds = num_choices\n else:\n num_rounds = num_choices - 1\n else:\n num_rounds = 1\n", "from otree.api import Currency as c\nfrom otree.constants import BaseConstants\n\n\nclass Constants(BaseConstants):\n currency = '€'\n num_choices = 25\n certain_choice = True\n original_list = [100.0, 103.0, 106.1, 109.2, 112.4, 115.6, 118.8, 122.1,\n 125.4, 128.8, 132.3, 135.7, 139.2, 142.8, 146.4, 150.1, 153.8, \n 157.5, 161.3, 165.1, 169.0, 172.9, 176.9, 180.9, 185.0]\n use_original_list = True\n payment = 100\n payment12 = payment\n increment = 3\n rate = 0.05\n enforce_consistency = True\n single_click = True\n one_choice_per_page = False\n random_order = False\n percentage = True\n small_pies = True\n large_pies = True\n progress_bar = True\n instructions = True\n results = False\n null_payoff = 0\n name_in_url = 'patience_mpl'\n players_per_group = None\n if one_choice_per_page:\n if certain_choice:\n num_rounds = num_choices\n else:\n num_rounds = num_choices - 1\n else:\n num_rounds = 1\n", "<import token>\n\n\nclass Constants(BaseConstants):\n currency = '€'\n num_choices = 25\n certain_choice = True\n original_list = [100.0, 103.0, 106.1, 109.2, 112.4, 115.6, 118.8, 122.1,\n 125.4, 128.8, 132.3, 135.7, 139.2, 142.8, 146.4, 150.1, 153.8, \n 157.5, 161.3, 165.1, 169.0, 172.9, 176.9, 180.9, 185.0]\n use_original_list = True\n payment = 100\n payment12 = payment\n increment = 3\n rate = 0.05\n enforce_consistency = True\n single_click = True\n one_choice_per_page = False\n random_order = False\n percentage = True\n small_pies = True\n large_pies = True\n progress_bar = True\n instructions = True\n results = False\n null_payoff = 0\n name_in_url = 'patience_mpl'\n players_per_group = None\n if one_choice_per_page:\n if certain_choice:\n num_rounds = num_choices\n else:\n num_rounds = num_choices - 1\n else:\n num_rounds = 1\n", "<import token>\n\n\nclass Constants(BaseConstants):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n if one_choice_per_page:\n if certain_choice:\n num_rounds = num_choices\n else:\n num_rounds = num_choices - 1\n else:\n num_rounds = 1\n", "<import token>\n<class token>\n" ]
false
98,798
1384745481ac8a8b8436bad663915374ae8a83ab
import random import numpy as np class ObstacleGrid: density = 0.1 n = 100 sparsity = 0.995 def __init__(self, t_simulation): self.t_simulation = t_simulation self.grid = [[[[] for j in range(self.n)] for i in range(self.n)] for t in range(self.t_simulation)] group = [[np.random.randint(0, self.n),np.random.randint(0, self.n)]] for _ in range(int(self.n * self.n * self.density)): if np.random.uniform(0,1) < self.sparsity: obstacleFound = True neighbours = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]] while obstacleFound: if len(neighbours) == 0: group = [[np.random.randint(0, self.n), np.random.randint(0, self.n)]] break random_group = random.choice(group) random_neighbour = random.choice(neighbours) neighbours.remove(random_neighbour) new_coord = list(np.array(random_neighbour) + np.array(random_group)) if 0 <= new_coord[0] < self.n and 0 <= new_coord[1] < self.n: if len(self.grid[0][new_coord[0]][new_coord[1]]) == 0: obstacleFound = False if not obstacleFound: for t in range(self.t_simulation): self.grid[t][new_coord[0]][new_coord[1]].append(True) group.append(new_coord) else: obstacleFound = True while obstacleFound: i = np.random.randint(0,self.n) j = np.random.randint(0,self.n) if not self.grid[0][i][j]: obstacleFound = False for t in range(self.t_simulation): self.grid[t][i][j].append(True) group = [[i,j]]
[ "import random\nimport numpy as np\nclass ObstacleGrid:\n\n density = 0.1\n n = 100\n sparsity = 0.995\n\n def __init__(self, t_simulation):\n self.t_simulation = t_simulation\n self.grid = [[[[] for j in range(self.n)] for i in range(self.n)] for t in range(self.t_simulation)]\n group = [[np.random.randint(0, self.n),np.random.randint(0, self.n)]]\n for _ in range(int(self.n * self.n * self.density)):\n if np.random.uniform(0,1) < self.sparsity:\n obstacleFound = True\n neighbours = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]\n while obstacleFound:\n if len(neighbours) == 0:\n group = [[np.random.randint(0, self.n), np.random.randint(0, self.n)]]\n break\n random_group = random.choice(group)\n random_neighbour = random.choice(neighbours)\n neighbours.remove(random_neighbour)\n\n new_coord = list(np.array(random_neighbour) + np.array(random_group))\n if 0 <= new_coord[0] < self.n and 0 <= new_coord[1] < self.n:\n if len(self.grid[0][new_coord[0]][new_coord[1]]) == 0:\n obstacleFound = False\n\n if not obstacleFound:\n for t in range(self.t_simulation):\n self.grid[t][new_coord[0]][new_coord[1]].append(True)\n group.append(new_coord)\n\n else:\n obstacleFound = True\n while obstacleFound:\n\n i = np.random.randint(0,self.n)\n j = np.random.randint(0,self.n)\n\n if not self.grid[0][i][j]:\n obstacleFound = False\n\n for t in range(self.t_simulation):\n self.grid[t][i][j].append(True)\n group = [[i,j]]", "import random\nimport numpy as np\n\n\nclass ObstacleGrid:\n density = 0.1\n n = 100\n sparsity = 0.995\n\n def __init__(self, t_simulation):\n self.t_simulation = t_simulation\n self.grid = [[[[] for j in range(self.n)] for i in range(self.n)] for\n t in range(self.t_simulation)]\n group = [[np.random.randint(0, self.n), np.random.randint(0, self.n)]]\n for _ in range(int(self.n * self.n * self.density)):\n if np.random.uniform(0, 1) < self.sparsity:\n obstacleFound = True\n neighbours = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1],\n [1, -1], [1, 0], [1, 1]]\n while obstacleFound:\n if len(neighbours) == 0:\n group = [[np.random.randint(0, self.n), np.random.\n randint(0, self.n)]]\n break\n random_group = random.choice(group)\n random_neighbour = random.choice(neighbours)\n neighbours.remove(random_neighbour)\n new_coord = list(np.array(random_neighbour) + np.array(\n random_group))\n if 0 <= new_coord[0] < self.n and 0 <= new_coord[1\n ] < self.n:\n if len(self.grid[0][new_coord[0]][new_coord[1]]) == 0:\n obstacleFound = False\n if not obstacleFound:\n for t in range(self.t_simulation):\n self.grid[t][new_coord[0]][new_coord[1]].append(True)\n group.append(new_coord)\n else:\n obstacleFound = True\n while obstacleFound:\n i = np.random.randint(0, self.n)\n j = np.random.randint(0, self.n)\n if not self.grid[0][i][j]:\n obstacleFound = False\n for t in range(self.t_simulation):\n self.grid[t][i][j].append(True)\n group = [[i, j]]\n", "<import token>\n\n\nclass ObstacleGrid:\n density = 0.1\n n = 100\n sparsity = 0.995\n\n def __init__(self, t_simulation):\n self.t_simulation = t_simulation\n self.grid = [[[[] for j in range(self.n)] for i in range(self.n)] for\n t in range(self.t_simulation)]\n group = [[np.random.randint(0, self.n), np.random.randint(0, self.n)]]\n for _ in range(int(self.n * self.n * self.density)):\n if np.random.uniform(0, 1) < self.sparsity:\n obstacleFound = True\n neighbours = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1],\n [1, -1], [1, 0], [1, 1]]\n while obstacleFound:\n if len(neighbours) == 0:\n group = [[np.random.randint(0, self.n), np.random.\n randint(0, self.n)]]\n break\n random_group = random.choice(group)\n random_neighbour = random.choice(neighbours)\n neighbours.remove(random_neighbour)\n new_coord = list(np.array(random_neighbour) + np.array(\n random_group))\n if 0 <= new_coord[0] < self.n and 0 <= new_coord[1\n ] < self.n:\n if len(self.grid[0][new_coord[0]][new_coord[1]]) == 0:\n obstacleFound = False\n if not obstacleFound:\n for t in range(self.t_simulation):\n self.grid[t][new_coord[0]][new_coord[1]].append(True)\n group.append(new_coord)\n else:\n obstacleFound = True\n while obstacleFound:\n i = np.random.randint(0, self.n)\n j = np.random.randint(0, self.n)\n if not self.grid[0][i][j]:\n obstacleFound = False\n for t in range(self.t_simulation):\n self.grid[t][i][j].append(True)\n group = [[i, j]]\n", "<import token>\n\n\nclass ObstacleGrid:\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, t_simulation):\n self.t_simulation = t_simulation\n self.grid = [[[[] for j in range(self.n)] for i in range(self.n)] for\n t in range(self.t_simulation)]\n group = [[np.random.randint(0, self.n), np.random.randint(0, self.n)]]\n for _ in range(int(self.n * self.n * self.density)):\n if np.random.uniform(0, 1) < self.sparsity:\n obstacleFound = True\n neighbours = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1],\n [1, -1], [1, 0], [1, 1]]\n while obstacleFound:\n if len(neighbours) == 0:\n group = [[np.random.randint(0, self.n), np.random.\n randint(0, self.n)]]\n break\n random_group = random.choice(group)\n random_neighbour = random.choice(neighbours)\n neighbours.remove(random_neighbour)\n new_coord = list(np.array(random_neighbour) + np.array(\n random_group))\n if 0 <= new_coord[0] < self.n and 0 <= new_coord[1\n ] < self.n:\n if len(self.grid[0][new_coord[0]][new_coord[1]]) == 0:\n obstacleFound = False\n if not obstacleFound:\n for t in range(self.t_simulation):\n self.grid[t][new_coord[0]][new_coord[1]].append(True)\n group.append(new_coord)\n else:\n obstacleFound = True\n while obstacleFound:\n i = np.random.randint(0, self.n)\n j = np.random.randint(0, self.n)\n if not self.grid[0][i][j]:\n obstacleFound = False\n for t in range(self.t_simulation):\n self.grid[t][i][j].append(True)\n group = [[i, j]]\n", "<import token>\n\n\nclass ObstacleGrid:\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n", "<import token>\n<class token>\n" ]
false
98,799
b79f99c62377722da1e197a72273581592f8f72b
#A person class. #Make a class of called Person. Make the __init__() method take firstname, #lastname, and age as parameters and add them as attributes. Make another method #called talk() which makes prints a greeting from the person containing, for #example like this: “Hello, my name is Carl Johnson and I’m 26 years old”. class Person: Name ="default" LastName ="default" Age = 0 PhoneNumber = "default" ItemsList = {} # конструктор классу def __init__(self, Name="default" ,LastName="default" ,Age = 0 ,PhoneNumber="default"): self.Name = Name self.LastName = LastName self.PhoneNumber = PhoneNumber self.Age = Age self._update_ItemsList() # Оновимо словник новими значеннями з полів классу def _update_ItemsList(self): self.ItemsList ={"Name":self.Name,"LastName":self.LastName,"Age":self.Age,"PhoneNumber":self.PhoneNumber} # метод для виводу полів классу def _get_class_items_(self): for k , m in self.ItemsList.items(): print(" %s : %s" %(k,m)) # метод для привітання def _do_introduce_(self): print(" \tHello, my name - %s %s and I’m %i years old\n \tPhone Number is %s" %(self.ItemsList["Name"],self.ItemsList["LastName"],self.ItemsList["Age"],self.ItemsList["PhoneNumber"])) Denys = Person("Denys","Zakharov", 20, "+380668645945") Denys._get_class_items_() Denys._do_introduce_()
[ "#A person class.\n\n#Make a class of called Person. Make the __init__() method take firstname,\n#lastname, and age as parameters and add them as attributes. Make another method\n#called talk() which makes prints a greeting from the person containing, for\n#example like this: “Hello, my name is Carl Johnson and I’m 26 years old”. \n\nclass Person:\n Name =\"default\"\n LastName =\"default\"\n Age = 0\n PhoneNumber = \"default\"\n ItemsList = {}\n\n # конструктор классу\n def __init__(self, Name=\"default\" ,LastName=\"default\" ,Age = 0 ,PhoneNumber=\"default\"):\n self.Name = Name\n self.LastName = LastName\n self.PhoneNumber = PhoneNumber\n self.Age = Age\n self._update_ItemsList()\n \n # Оновимо словник новими значеннями з полів классу \n def _update_ItemsList(self):\n self.ItemsList ={\"Name\":self.Name,\"LastName\":self.LastName,\"Age\":self.Age,\"PhoneNumber\":self.PhoneNumber}\n \n # метод для виводу полів классу\n def _get_class_items_(self):\n for k , m in self.ItemsList.items():\n print(\" %s : %s\" %(k,m))\n\n # метод для привітання \n def _do_introduce_(self):\n print(\" \\tHello, my name - %s %s and I’m %i years old\\n \\tPhone Number is %s\" %(self.ItemsList[\"Name\"],self.ItemsList[\"LastName\"],self.ItemsList[\"Age\"],self.ItemsList[\"PhoneNumber\"]))\n \n \nDenys = Person(\"Denys\",\"Zakharov\", 20, \"+380668645945\")\nDenys._get_class_items_()\nDenys._do_introduce_()\n\n\n\n", "class Person:\n Name = 'default'\n LastName = 'default'\n Age = 0\n PhoneNumber = 'default'\n ItemsList = {}\n\n def __init__(self, Name='default', LastName='default', Age=0,\n PhoneNumber='default'):\n self.Name = Name\n self.LastName = LastName\n self.PhoneNumber = PhoneNumber\n self.Age = Age\n self._update_ItemsList()\n\n def _update_ItemsList(self):\n self.ItemsList = {'Name': self.Name, 'LastName': self.LastName,\n 'Age': self.Age, 'PhoneNumber': self.PhoneNumber}\n\n def _get_class_items_(self):\n for k, m in self.ItemsList.items():\n print(' %s : %s' % (k, m))\n\n def _do_introduce_(self):\n print(\n ' \\tHello, my name - %s %s and I’m %i years old\\n \\tPhone Number is %s'\n % (self.ItemsList['Name'], self.ItemsList['LastName'], self.\n ItemsList['Age'], self.ItemsList['PhoneNumber']))\n\n\nDenys = Person('Denys', 'Zakharov', 20, '+380668645945')\nDenys._get_class_items_()\nDenys._do_introduce_()\n", "class Person:\n Name = 'default'\n LastName = 'default'\n Age = 0\n PhoneNumber = 'default'\n ItemsList = {}\n\n def __init__(self, Name='default', LastName='default', Age=0,\n PhoneNumber='default'):\n self.Name = Name\n self.LastName = LastName\n self.PhoneNumber = PhoneNumber\n self.Age = Age\n self._update_ItemsList()\n\n def _update_ItemsList(self):\n self.ItemsList = {'Name': self.Name, 'LastName': self.LastName,\n 'Age': self.Age, 'PhoneNumber': self.PhoneNumber}\n\n def _get_class_items_(self):\n for k, m in self.ItemsList.items():\n print(' %s : %s' % (k, m))\n\n def _do_introduce_(self):\n print(\n ' \\tHello, my name - %s %s and I’m %i years old\\n \\tPhone Number is %s'\n % (self.ItemsList['Name'], self.ItemsList['LastName'], self.\n ItemsList['Age'], self.ItemsList['PhoneNumber']))\n\n\n<assignment token>\nDenys._get_class_items_()\nDenys._do_introduce_()\n", "class Person:\n Name = 'default'\n LastName = 'default'\n Age = 0\n PhoneNumber = 'default'\n ItemsList = {}\n\n def __init__(self, Name='default', LastName='default', Age=0,\n PhoneNumber='default'):\n self.Name = Name\n self.LastName = LastName\n self.PhoneNumber = PhoneNumber\n self.Age = Age\n self._update_ItemsList()\n\n def _update_ItemsList(self):\n self.ItemsList = {'Name': self.Name, 'LastName': self.LastName,\n 'Age': self.Age, 'PhoneNumber': self.PhoneNumber}\n\n def _get_class_items_(self):\n for k, m in self.ItemsList.items():\n print(' %s : %s' % (k, m))\n\n def _do_introduce_(self):\n print(\n ' \\tHello, my name - %s %s and I’m %i years old\\n \\tPhone Number is %s'\n % (self.ItemsList['Name'], self.ItemsList['LastName'], self.\n ItemsList['Age'], self.ItemsList['PhoneNumber']))\n\n\n<assignment token>\n<code token>\n", "class Person:\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, Name='default', LastName='default', Age=0,\n PhoneNumber='default'):\n self.Name = Name\n self.LastName = LastName\n self.PhoneNumber = PhoneNumber\n self.Age = Age\n self._update_ItemsList()\n\n def _update_ItemsList(self):\n self.ItemsList = {'Name': self.Name, 'LastName': self.LastName,\n 'Age': self.Age, 'PhoneNumber': self.PhoneNumber}\n\n def _get_class_items_(self):\n for k, m in self.ItemsList.items():\n print(' %s : %s' % (k, m))\n\n def _do_introduce_(self):\n print(\n ' \\tHello, my name - %s %s and I’m %i years old\\n \\tPhone Number is %s'\n % (self.ItemsList['Name'], self.ItemsList['LastName'], self.\n ItemsList['Age'], self.ItemsList['PhoneNumber']))\n\n\n<assignment token>\n<code token>\n", "class Person:\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, Name='default', LastName='default', Age=0,\n PhoneNumber='default'):\n self.Name = Name\n self.LastName = LastName\n self.PhoneNumber = PhoneNumber\n self.Age = Age\n self._update_ItemsList()\n <function token>\n\n def _get_class_items_(self):\n for k, m in self.ItemsList.items():\n print(' %s : %s' % (k, m))\n\n def _do_introduce_(self):\n print(\n ' \\tHello, my name - %s %s and I’m %i years old\\n \\tPhone Number is %s'\n % (self.ItemsList['Name'], self.ItemsList['LastName'], self.\n ItemsList['Age'], self.ItemsList['PhoneNumber']))\n\n\n<assignment token>\n<code token>\n", "class Person:\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n\n def _get_class_items_(self):\n for k, m in self.ItemsList.items():\n print(' %s : %s' % (k, m))\n\n def _do_introduce_(self):\n print(\n ' \\tHello, my name - %s %s and I’m %i years old\\n \\tPhone Number is %s'\n % (self.ItemsList['Name'], self.ItemsList['LastName'], self.\n ItemsList['Age'], self.ItemsList['PhoneNumber']))\n\n\n<assignment token>\n<code token>\n", "class Person:\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n\n def _get_class_items_(self):\n for k, m in self.ItemsList.items():\n print(' %s : %s' % (k, m))\n <function token>\n\n\n<assignment token>\n<code token>\n", "class Person:\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<assignment token>\n<code token>\n", "<class token>\n<assignment token>\n<code token>\n" ]
false