Best JavaScript code snippet using fast-check-monorepo
arbiter.py
Source:arbiter.py
1from pc.models.world import WorldUpdater, World2from pc.vision import tools, camera, vision3from pc.planning.planner import Planner4from pc.robot import Robot5import time6from pc.vision import calibrationgui, visiongui7from Tkinter import *8from pc.vision.vision import split_into_rgb_channels9import cv210CONTROLS = ["LH", "UH", "LS", "US", "LV", "UV", "LR",11 "UR", "LG", "UG", "LB", "UB", "BR", "BL",12 "C1", "C2"]13MAX_BAR = {"LH": 360,14 "UH": 360,15 "LS": 255,16 "US": 255,17 "LV": 255,18 "UV": 255,19 "LR": 255,20 "UR": 255,21 "LG": 255,22 "UG": 255,23 "LB": 255,24 "UB": 255,25 "BR": 100,26 "BL": 100,27 "C1": 100,28 "C2": 100}29class Arbiter(object):30 """31 Ties vision/state to planning/communication.32 """33 def __init__(self, pitch, colour, our_side, profile="None",34 video_src=0, comm_port='/dev/ttyACM0', comms=False):35 """36 Entry point for the SDP system. Initialises all components37 and runs the polling loop.38 :param pitch: Pitch number: 0 (main) 1 (secondary)39 :param colour: Our team's plate colour (blue, yellow)40 :param our_side: Our defender's side as on video feed41 :param profile: Planning profile - 'attacker', 'defender', 'dog'42 :param video_src: Source of feed - 0 default for DICE cameras43 :param comm_port: Robot serial port44 :param comms: Enable serial communication45 :return:46 """47 assert pitch in [0, 1]48 assert colour in ['yellow', 'blue']49 assert our_side in ['left', 'right']50 assert profile in ['ms3', 'attacker', 'penalty', 'None']51 self.pitch = pitch52 self.colour = colour53 self.side = our_side54 self.profile = profile55 self.calibration = tools.get_colors(pitch)56 self.comms = comms57 self.contrast_toggle = False58 self.vision_filter_toggle = False59 # Set up capture device60 self.camera = camera.Camera(pitch, video_src=video_src)61 # Set up robotController62 self.robot_controller = Robot(port=comm_port, comms=comms)63 # Set up vision64 self.vision = None65 self.start_vision()66 # Set up world model; updater67 self.world = None68 self.world_updater = None69 self.start_world()70 # Set up the planner71 self.planner = None72 self.start_planner()73 # Initialize the main GUI74 self.root = Tk()75 self.root.resizable(width=FALSE, height=FALSE)76 self.root.wm_title("Vision Wrapper")77 self.root.bind('<Key>', self.key_press)78 # Overwrite the "any key" bind with other, more specific binds79 self.root.bind('<Escape>', lambda e: self.root.quit()) # Escape to quit80 self.root.bind('<q>', lambda e: self.root.quit()) # Q to |q|uit81 self.root.bind('<c>', lambda e: self.switch_colours()) # C to switch |c|olours82 self.root.bind('<s>', lambda e: self.switch_sides()) # S to switch |s|ides83 self.root.bind('<l>', lambda e: self.toggle_planning()) # L to toggle p|l|anning84 self.root.bind('<a>', lambda e: self.clear_calibrations()) # A to reset current c|a|libration85 self.root.bind('<e>', lambda e: self.take_penalty()) # E to take a p|e|nalty86 # GUI Layout87 # [Title ]88 # [Vision Frame (+fps etc)][Buttons ]89 # [Calibration Label ][Slider Labels]90 # [Calibration Frame ][Sliders ]91 # Our glorious -leader- logo92 logo = PhotoImage(file="minilogo.ppm")93 tk_logo = Label(image=logo)94 tk_logo.grid(row=0, column=14, rowspan=2, columnspan=100)95 tk_logo.image = logo96 vision_height = 16 # The height of the vision frame in TKinter grid terms - allows for button spacing97 # Labels98 self.title = Label(self.root, text="Group 7 - SDP - Vision GUI",99 height=2)100 self.title.grid(row=0, column=0, columnspan=100)101 self.calibration_label = \102 Label(self.root, text="Calibrating: plate mask", height=2)103 self.calibration_label.grid(row=(vision_height+2), column=0)104 # Frames105 self.vision_frame = Label(self.root)106 self.vision_frame.grid(row=1, column=0, rowspan=vision_height)107 self.calibration_frame = Label(self.root)108 self.calibration_frame.grid(row=(vision_height+3), column=0)109 # Sliders110 self.sliders = {}111 self.slider_labels = {}112 for index, setting in enumerate(CONTROLS):113 self.sliders[setting] = Scale(self.root, from_=0,114 to=MAX_BAR[setting],115 length=300, width=10)116 self.sliders[setting].grid(row=(vision_height+3), column=(index+1))117 self.slider_labels[setting] = Label(self.root, text=setting)118 self.slider_labels[setting].grid(row=(vision_height+2), column=(index+1))119 # Buttons120 # Planning pause/resume toggle121 self.planner_paused = False # Flag for pausing/resuming the planning122 planning_toggle = Button(self.root)123 planning_toggle["text"] = "P[l]anning Toggle"124 planning_toggle["command"] = self.toggle_planning125 planning_toggle.grid(row=1, column=1, columnspan=5)126 # Calibration reset127 calib_reset = Button(self.root)128 calib_reset["text"] = "Reset Current\nC[a]libration"129 calib_reset["command"] = self.clear_calibrations130 calib_reset.grid(row=2, column=1, columnspan=5)131 # Side switch132 side_switch = Button(self.root)133 side_switch["text"] = "Switch [S]ides"134 side_switch["command"] = self.switch_sides135 side_switch.grid(row=3, column=1, columnspan=5)136 # Colour switch137 colour_switch = Button(self.root)138 colour_switch["text"] = "Switch [C]olours"139 colour_switch["command"] = self.switch_colours140 colour_switch.grid(row=4, column=1, columnspan=5)141 # Penalty mode142 penalty_mode = Button(self.root)143 penalty_mode["text"] = "Take P[e]nalty"144 penalty_mode["command"] = self.take_penalty145 penalty_mode.grid(row=5, column=1, columnspan=5)146 # Vision filter toggle147 vision_filter_toggle = Button(self.root)148 vision_filter_toggle["text"] = "Toggle Vision\nFilters (-FPS)"149 vision_filter_toggle["command"] = self.toggle_vision_filters150 vision_filter_toggle.grid(row=7, column=1, columnspan=5)151 # Contrast toggle152 contrast_toggle = Button(self.root)153 contrast_toggle["text"] = "Toggle Contrast\nEXPERIMENTAL (-FPS)"154 contrast_toggle["command"] = self.toggle_contrast155 contrast_toggle.grid(row=8, column=1, columnspan=5)156 # Used by the calibration GUI to know157 # which mode to calibrate (plate/dot/red etc)158 self.key_event = False159 self.key = 'p'160 # The OpenCV-based calibration and vision GUIs, which get wrapped161 self.calibration_gui = calibrationgui.CalibrationGUI(self, self.calibration)162 self.gui = visiongui.VisionGUI(self, self.pitch, self.contrast_toggle)163 # FPS counter init164 self.counter = 1L165 self.timer = time.clock()166 def start_planner(self):167 """168 Starts a new planner depending on our current world state, robot controller, and profile.169 """170 if self.profile != "None":171 self.planner = Planner(self.world, self.robot_controller, self.profile)172 else:173 self.planner = None174 def start_vision(self):175 """176 Start a new vision system - note that this discards the colour-corrupt first frame.177 """178 frame_shape = self.camera.get_frame().shape179 frame_center = self.camera.get_adjusted_center()180 self.vision = vision.Vision(self.pitch, self.colour, self.side, frame_shape,181 frame_center, self.calibration,182 perspective_correction=True)183 def start_world(self):184 """185 Starts a new world model and world updater.186 """187 self.world = World(self.side, self.pitch)188 self.world_updater = WorldUpdater(self.pitch, self.colour, self.side,189 self.world, self.vision)190 def key_press(self, event):191 """192 Sets the value of self.key upon a keypress.193 """194 # Raise a flag that a key_event has occurred (used by195 # calibration to change colour mode when needed)196 self.key_event = True197 self.key = event.char198 def toggle_planning(self):199 """200 Toggles planning to prevent updates.201 """202 self.planner.robot_ctl.stop()203 self.planner_paused = not self.planner_paused204 def clear_calibrations(self):205 """206 Resets the calibration sliders.207 If the slider is a "lower" slider, sets the value to 0;208 if the slider is an "upper" slider, sets the value to max;209 if the slider is brightness/blur, sets the value to 0.210 """211 # Hue212 self.sliders['LH'].set(0)213 self.sliders['UH'].set(MAX_BAR['UH'])214 # Saturation215 self.sliders['LS'].set(0)216 self.sliders['US'].set(MAX_BAR['US'])217 # Value218 self.sliders['LV'].set(0)219 self.sliders['UV'].set(MAX_BAR['UV'])220 # Red221 self.sliders['LR'].set(0)222 self.sliders['UR'].set(MAX_BAR['UR'])223 # Green224 self.sliders['LG'].set(0)225 self.sliders['UG'].set(MAX_BAR['UG'])226 # Blue227 self.sliders['LB'].set(0)228 self.sliders['UB'].set(MAX_BAR['UB'])229 # Brightness/blur230 self.sliders['BR'].set(0)231 self.sliders['BL'].set(0)232 def switch_sides(self):233 """234 Switch which side we're on.235 """236 our_new_side = ""237 if self.side == "left":238 our_new_side = "right"239 elif self.side == "right":240 our_new_side = "left"241 self.side = our_new_side242 # Restart the vision system, world model + updater, and planner243 self.start_vision()244 self.start_world()245 self.start_planner()246 def switch_colours(self):247 """248 Switch which colour we are.249 """250 our_new_colour = ""251 if self.colour == "blue":252 our_new_colour = "yellow"253 elif self.colour == "yellow":254 our_new_colour = "blue"255 self.colour = our_new_colour256 # Restart the vision system, world model + updater, and planner257 self.start_vision()258 self.start_world()259 self.start_planner()260 def take_penalty(self):261 """262 Set the profile to penalty, and restart the planner263 Planning automatically resumes to "attacker" when the penalty has been taken.264 """265 self.profile = 'penalty'266 self.start_planner()267 def toggle_contrast(self):268 """269 Toggle the contrast filtering on vision.270 Restarts the vision system, and the vision GUI.271 """272 self.contrast_toggle = not self.contrast_toggle273 self.start_vision()274 self.gui = visiongui.VisionGUI(self, self.pitch, self.vision_filter_toggle)275 def toggle_vision_filters(self):276 """277 Toggle whether or not the "misc" sliders are affecting the GUI view of the pitch.278 Restarts the vision GUI.279 """280 self.vision_filter_toggle = not self.vision_filter_toggle281 self.gui = visiongui.VisionGUI(self, self.pitch, self.vision_filter_toggle)282 def run(self):283 """284 Ticks the whole system, cleanly exits saving calibrations and resetting the robot.285 """286 try:287 self.tick()288 self.root.mainloop()289 except:290 raise291 finally:292 if self.comms:293 self.robot_controller.teardown()294 self.camera.release()295 tools.save_colors(self.pitch, self.calibration)296 def tick(self):297 """298 Main loop of the system. Grabs frames and passes them to the GUIs and299 the world state.300 """301 # Get frame302 frame = self.camera.get_frame()303 ct_clipLimit = self.sliders['C1'].get()304 ct_tileGridSize = self.sliders['C2'].get()305 if self.contrast_toggle:306 # Apply contrast changes first307 r, g, b = split_into_rgb_channels(frame)308 if ct_clipLimit == 0:309 ct_clipLimit += 1310 if ct_tileGridSize == 0:311 ct_tileGridSize += 1312 clahe = cv2.createCLAHE(clipLimit=1.0*ct_clipLimit,313 tileGridSize=(1.0*ct_tileGridSize, 1.0*ct_tileGridSize))314 r_c = clahe.apply(r)315 g_c = clahe.apply(g)316 b_c = clahe.apply(b)317 frame = cv2.merge((r_c, g_c, b_c))318 # Find object positions, update world model319 model_positions, regular_positions, grabbers = \320 self.world_updater.update_world(frame)321 # Act on the updated world model322 p_state = s_state = None323 if self.planner is not None:324 if not self.planner_paused:325 self.planner.plan()326 p_state = self.planner.planner_state_string327 s_state = self.planner.strategy_state_string328 fps = float(self.counter) / (time.clock() - self.timer)329 # Draw GUIs330 self.calibration_gui.show(frame, self.key_event, key=self.key)331 self.gui.draw(frame, model_positions, regular_positions,332 grabbers, fps, self.colour, self.side, p_state,333 s_state, self.sliders['BR'].get(), self.sliders['BL'].get())334 self.counter += 1335 # Reset the key_event flag336 self.key_event = False337 self.root.after(1, self.tick) # TODO Oh wow.338if __name__ == '__main__':339 # Set capture card settings340 import subprocess341 subprocess.call(['./v4lctl.sh'])342 # Create a launcher343 from pc.gui import launcher344 app = launcher.Launcher()345 app.mainloop()346 # Checks if the launcher flag was set to "launch", and if so, runs Arbiter347 if app.launching:348 arb = Arbiter(int(app.pitch.get()), app.colour.get(), app.side.get(),349 profile=app.profile.get(), comms=app.comms.get())...
statistics.py
Source:statistics.py
1#/usr/bin/python32# -*- coding: UTF-8 -*-3#***************************************************************************************4# Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences5# Copyright (c) 2020-2021 Peng Cheng Laboratory6#7# XiangShan is licensed under Mulan PSL v2.8# You can use this software according to the terms and conditions of the Mulan PSL v2.9# You may obtain a copy of Mulan PSL v2 at:10# http://license.coscl.org.cn/MulanPSL211#12# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,13# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,14# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.15#16# See the Mulan PSL v2 for more details.17#***************************************************************************************18import sys19import re20import copy21import pprint22LINE_COVERRED = "LINE_COVERRED"23NOT_LINE_COVERRED = "NOT_LINE_COVERRED"24TOGGLE_COVERRED = "TOGGLE_COVERRED"25NOT_TOGGLE_COVERRED = "NOT_TOGGLE_COVERRED"26DONTCARE = "DONTCARE"27BEGIN = "BEGIN"28END = "END"29CHILDREN = "CHILDREN"30MODULE = "MODULE"31INSTANCE = "INSTANCE"32TYPE = "TYPE"33ROOT = "ROOT"34NODE = "NODE"35SELFCOVERAGE = "SELFCOVERAGE"36TREECOVERAGE = "TREECOVERAGE"37LINECOVERAGE = 038TOGGLECOVERAGE = 139def check_one_hot(l):40 cnt = 041 for e in l:42 if e:43 cnt += 144 return cnt <= 145def get_lines(input_file):46 lines = []47 with open(input_file) as f:48 for line in f:49 lines.append(line)50 return lines51def get_line_annotation(lines):52 line_annotations = []53 # pattern_1: 040192 if(array_0_MPORT_en & array_0_MPORT_mask) begin54 # pattern_2: 2218110 end else if (_T_30) begin // @[Conditional.scala 40:58]55 # pattern_2: 000417 end else begin56 line_coverred_pattern_1 = re.compile('^\s*(\d+)\s+if')57 line_coverred_pattern_2 = re.compile('^\s*(\d+)\s+end else')58 not_line_coverred_pattern_1 = re.compile('^\s*(%0+)\s+if')59 not_line_coverred_pattern_2 = re.compile('^\s*(%0+)\s+end else')60 toggle_coverred_pattern_1 = re.compile('^\s*(\d+)\s+reg')61 toggle_coverred_pattern_2 = re.compile('^\s*(\d+)\s+wire')62 toggle_coverred_pattern_3 = re.compile('^\s*(\d+)\s+input')63 toggle_coverred_pattern_4 = re.compile('^\s*(\d+)\s+output')64 not_toggle_coverred_pattern_1 = re.compile('^\s*(%0+)\s+reg')65 not_toggle_coverred_pattern_2 = re.compile('^\s*(%0+)\s+wire')66 not_toggle_coverred_pattern_3 = re.compile('^\s*(%0+)\s+input')67 not_toggle_coverred_pattern_4 = re.compile('^\s*(%0+)\s+output')68 line_cnt = 069 for line in lines:70 line_coverred_match = line_coverred_pattern_1.search(line) or line_coverred_pattern_2.search(line)71 not_line_coverred_match = not_line_coverred_pattern_1.search(line) or not_line_coverred_pattern_2.search(line)72 assert not (line_coverred_match and not_line_coverred_match)73 toggle_coverred_match = toggle_coverred_pattern_1.search(line) or toggle_coverred_pattern_2.search(line) or \74 toggle_coverred_pattern_3.search(line) or toggle_coverred_pattern_4.search(line)75 not_toggle_coverred_match = not_toggle_coverred_pattern_1.search(line) or not_toggle_coverred_pattern_2.search(line) or \76 not_toggle_coverred_pattern_3.search(line) or not_toggle_coverred_pattern_4.search(line)77 assert not (toggle_coverred_match and not_toggle_coverred_match)78 all_match = (line_coverred_match, not_line_coverred_match,79 toggle_coverred_match, not_toggle_coverred_match)80 if not check_one_hot(all_match):81 print("not_one_hot")82 print(line_cnt)83 print(all_match)84 assert False, "This line matches multiple patterns"85 if line_coverred_match:86 line_annotations.append(LINE_COVERRED)87 elif not_line_coverred_match:88 line_annotations.append(NOT_LINE_COVERRED)89 elif toggle_coverred_match:90 line_annotations.append(TOGGLE_COVERRED)91 elif not_toggle_coverred_match:92 line_annotations.append(NOT_TOGGLE_COVERRED)93 else:94 line_annotations.append(DONTCARE)95 line_cnt += 196 return line_annotations97# get the line coverage statistics in line range [start, end)98def get_coverage_statistics(line_annotations, start, end):99 line_coverred = 0100 not_line_coverred = 0101 toggle_coverred = 0102 not_toggle_coverred = 0103 for i in range(start, end):104 if line_annotations[i] == LINE_COVERRED:105 line_coverred += 1106 if line_annotations[i] == NOT_LINE_COVERRED:107 not_line_coverred += 1108 if line_annotations[i] == TOGGLE_COVERRED:109 toggle_coverred += 1110 if line_annotations[i] == NOT_TOGGLE_COVERRED:111 not_toggle_coverred += 1112 # deal with divide by zero113 line_coverage = 1.0114 if line_coverred + not_line_coverred != 0:115 line_coverage = float(line_coverred) / (line_coverred + not_line_coverred)116 toggle_coverage = 1.0117 if toggle_coverred + not_toggle_coverred != 0:118 toggle_coverage = float(toggle_coverred) / (toggle_coverred + not_toggle_coverred)119 return ((line_coverred, not_line_coverred, line_coverage),120 (toggle_coverred, not_toggle_coverred, toggle_coverage))121# get modules and all it's submodules122def get_modules(lines):123 modules = {}124 module_pattern = re.compile("module (\w+)\(")125 endmodule_pattern = re.compile("endmodule")126 submodule_pattern = re.compile("(\w+) (\w+) \( // @\[\w+.scala \d+:\d+\]")127 line_count = 0128 name = "ModuleName"129 for line in lines:130 module_match = module_pattern.search(line)131 endmodule_match = endmodule_pattern.search(line)132 submodule_match = submodule_pattern.search(line)133 assert not (module_match and endmodule_match)134 if module_match:135 name = module_match.group(1)136 # print("module_match: module: %s" % name)137 assert name not in modules138 # [begin139 modules[name] = {}140 modules[name][BEGIN] = line_count141 # the first time we see a module, we treat as a root node142 modules[name][TYPE] = ROOT143 if endmodule_match:144 # print("endmodule_match: module: %s" % name)145 assert name in modules146 assert END not in modules[name]147 # end)148 modules[name][END] = line_count + 1149 # reset module name to invalid150 name = "ModuleName"151 if submodule_match:152 # submodule must be inside hierarchy153 assert name != "ModuleName"154 submodule_type = submodule_match.group(1)155 submodule_instance = submodule_match.group(2)156 # print("submodule_match: type: %s instance: %s" % (submodule_type, submodule_instance))157 # submodules should be defined first158 # if we can not find it's definition159 # we consider it a black block module160 if submodule_type not in modules:161 print("Module %s is a Blackbox" % submodule_type)162 else:163 # mark submodule as a tree node164 # it's no longer root any more165 modules[submodule_type][TYPE] = NODE166 if CHILDREN not in modules[name]:167 modules[name][CHILDREN] = []168 submodule = {MODULE: submodule_type, INSTANCE: submodule_instance}169 modules[name][CHILDREN].append(submodule)170 line_count += 1171 return modules172# we define two coverage metrics:173# self coverage: coverage results of this module(excluding submodules)174# tree coverage: coverage results of this module(including submodules)175def get_tree_coverage(modules, coverage):176 def dfs(module):177 if TREECOVERAGE not in modules[module]:178 self_coverage = modules[module][SELFCOVERAGE]179 if CHILDREN not in modules[module]:180 modules[module][TREECOVERAGE] = self_coverage181 else:182 line_coverred = self_coverage[LINECOVERAGE][0]183 not_line_coverred = self_coverage[LINECOVERAGE][1]184 toggle_coverred = self_coverage[TOGGLECOVERAGE][0]185 not_toggle_coverred = self_coverage[TOGGLECOVERAGE][1]186 # the dfs part187 for child in modules[module][CHILDREN]:188 child_coverage = dfs(child[MODULE])189 line_coverred += child_coverage[LINECOVERAGE][0]190 not_line_coverred += child_coverage[LINECOVERAGE][1]191 toggle_coverred += child_coverage[TOGGLECOVERAGE][0]192 not_toggle_coverred += child_coverage[TOGGLECOVERAGE][1]193 # deal with divide by zero194 line_coverage = 1.0195 if line_coverred + not_line_coverred != 0:196 line_coverage = float(line_coverred) / (line_coverred + not_line_coverred)197 toggle_coverage = 1.0198 if toggle_coverred + not_toggle_coverred != 0:199 toggle_coverage = float(toggle_coverred) / (toggle_coverred + not_toggle_coverred)200 modules[module][TREECOVERAGE] = ((line_coverred, not_line_coverred, line_coverage),201 (toggle_coverred, not_toggle_coverred, toggle_coverage))202 return modules[module][TREECOVERAGE]203 for module in modules:204 modules[module][SELFCOVERAGE] = coverage[module]205 for module in modules:206 modules[module][TREECOVERAGE] = dfs(module)207 return modules208# arg1: tree coverage results209# arg2: coverage type210def sort_coverage(coverage, self_or_tree, coverage_type):211 l = [(module, coverage[module][self_or_tree][coverage_type])for module in coverage]212 l.sort(key=lambda x:x[1][2])213 return l214def print_tree_coverage(tree_coverage):215 def dfs(module, level):216 # print current node217 tree = tree_coverage[module][TREECOVERAGE]218 self = tree_coverage[module][SELFCOVERAGE]219 print(" " * level + "- " + module)220 print(" " * level + " tree_line", end="")221 print("(%d, %d, %.2f)" % (tree[LINECOVERAGE][0], tree[LINECOVERAGE][1], tree[LINECOVERAGE][2] * 100.0))222 print(" " * level + " self_line", end="")223 print("(%d, %d, %.2f)" % (self[LINECOVERAGE][0], self[LINECOVERAGE][1], self[LINECOVERAGE][2] * 100.0))224 print(" " * level + " tree_toggle", end="")225 print("(%d, %d, %.2f)" % (tree[TOGGLECOVERAGE][0], tree[TOGGLECOVERAGE][1], tree[TOGGLECOVERAGE][2] * 100.0))226 print(" " * level + " self_toggle", end="")227 print("(%d, %d, %.2f)" % (self[TOGGLECOVERAGE][0], self[TOGGLECOVERAGE][1], self[TOGGLECOVERAGE][2] * 100.0))228 # print children nodes229 if CHILDREN in modules[module]:230 # the dfs part231 for child in modules[module][CHILDREN]:232 dfs(child[MODULE], level + 1)233 for module in tree_coverage:234 if tree_coverage[module][TYPE] == ROOT:235 dfs(module, 0)236if __name__ == "__main__":237 assert len(sys.argv) == 2, "Expect input_file"238 input_file = sys.argv[1]239 pp = pprint.PrettyPrinter(indent=4)240 lines = get_lines(input_file)241 # print("lines:")242 # pp.pprint(lines)243 annotations = get_line_annotation(lines)244 # print("annotations:")245 # pp.pprint(annotations)246 modules = get_modules(lines)247 # print("modules:")248 # pp.pprint(modules)249 self_coverage = {module: get_coverage_statistics(annotations, modules[module][BEGIN], modules[module][END])250 for module in modules}251 # print("self_coverage:")252 # pp.pprint(self_coverage)253 tree_coverage = get_tree_coverage(modules, self_coverage)254 # print("tree_coverage:")255 # pp.pprint(tree_coverage)256 print("LineSelfCoverage:")257 pp.pprint(sort_coverage(tree_coverage, SELFCOVERAGE, LINECOVERAGE))258 print("LineTreeCoverage:")259 pp.pprint(sort_coverage(tree_coverage, TREECOVERAGE, LINECOVERAGE))260 print("ToggleSelfCoverage:")261 pp.pprint(sort_coverage(tree_coverage, SELFCOVERAGE, TOGGLECOVERAGE))262 print("ToggleTreeCoverage:")263 pp.pprint(sort_coverage(tree_coverage, TREECOVERAGE, TOGGLECOVERAGE))264 print("AllCoverage:")...
controls-toggle.js
Source:controls-toggle.js
1'use strict';2require('jsdom-global')();3const chai = require('chai');4const dom = require('../mock/dom');5const mixitup = require('../../dist/mixitup.js');6chai.use(require('chai-shallow-deep-equal'));7chai.use(require('chai-as-promised'));8describe('Controls', () => {9 describe('Toggle', () => {10 describe('OR', () => {11 let frag = document.createDocumentFragment();12 let container = dom.getContainer();13 let controls = dom.getFilterControls();14 container.insertBefore(controls, container.children[0]);15 frag.appendChild(container);16 let mixer = mixitup(container, {17 controls: {18 scope: 'local'19 }20 });21 after(() => mixer.destroy());22 it('should accept toggle controls with a selector value', () => {23 return mixer.hide()24 .then(() => {25 let toggle = controls.querySelector('[data-toggle=".category-a"]');26 let totalMatching = container.querySelectorAll('.category-a').length;27 toggle.click();28 let state = mixer.getState();29 chai.assert.equal(state.activeFilter.selector, '.category-a');30 chai.assert.equal(state.totalShow, totalMatching);31 chai.assert.isOk(toggle.matches('.mixitup-control-active'));32 });33 });34 it('should build up a compound selector as toggles are activated', () => {35 let toggleA = controls.querySelector('[data-toggle=".category-a"]');36 let toggleB = controls.querySelector('[data-toggle=".category-b"]');37 let totalMatching = container.querySelectorAll('.category-a, .category-b').length;38 toggleB.click();39 let state = mixer.getState();40 chai.assert.equal(state.activeFilter.selector, '.category-a, .category-b');41 chai.assert.equal(state.totalShow, totalMatching);42 chai.assert.isOk(toggleA.matches('.mixitup-control-active'));43 chai.assert.isOk(toggleB.matches('.mixitup-control-active'));44 });45 it('should break down a compound selector as toggles are deactivated', () => {46 let toggle = controls.querySelector('[data-toggle=".category-a"]');47 let totalMatching = container.querySelectorAll('.category-b').length;48 toggle.click();49 let state = mixer.getState();50 chai.assert.equal(state.activeFilter.selector, '.category-b');51 chai.assert.equal(state.totalShow, totalMatching);52 chai.assert.isNotOk(toggle.matches('.mixitup-control-active'));53 });54 it('should return to "all" when all toggles are deactivated', () => {55 let toggle = controls.querySelector('[data-toggle=".category-b"]');56 toggle.click();57 let state = mixer.getState();58 chai.assert.equal(state.activeFilter.selector, '.mix');59 chai.assert.equal(state.totalHide, 0);60 chai.assert.isNotOk(toggle.matches('.mixitup-control-active'));61 });62 it ('should activate the appropriate toggle controls on load for an OR compound selector', () => {63 const frag = document.createDocumentFragment();64 const container = dom.getContainer();65 const controls = dom.getFilterControls();66 frag.appendChild(controls);67 frag.appendChild(container);68 const mixer = mixitup(container, {69 load: {70 filter: '.category-a, .category-c'71 }72 }, frag);73 after(() => mixer.destroy());74 const toggleA = controls.querySelector('[data-toggle=".category-a"]');75 const toggleC = controls.querySelector('[data-toggle=".category-c"]');76 chai.assert.isTrue(toggleA.classList.contains('mixitup-control-active'));77 chai.assert.isTrue(toggleC.classList.contains('mixitup-control-active'));78 });79 });80 describe('AND', () => {81 let frag = document.createDocumentFragment();82 let container = dom.getContainer();83 let controls = dom.getFilterControls();84 container.insertBefore(controls, container.children[0]);85 frag.appendChild(container);86 let mixer = mixitup(container, {87 controls: {88 scope: 'local',89 toggleLogic: 'AND'90 }91 });92 after(() => mixer.destroy());93 it('should accept toggle controls with a selector value', () => {94 return mixer.hide()95 .then(() => {96 let toggle = controls.querySelector('[data-toggle=".category-a"]');97 let totalMatching = container.querySelectorAll('.category-a').length;98 toggle.click();99 let state = mixer.getState();100 chai.assert.equal(state.activeFilter.selector, '.category-a');101 chai.assert.equal(state.totalShow, totalMatching);102 chai.assert.isOk(toggle.matches('.mixitup-control-active'));103 });104 });105 it('should build up a compound selector as toggles are activated', () => {106 let toggleA = controls.querySelector('[data-toggle=".category-a"]');107 let toggleB = controls.querySelector('[data-toggle=".category-c"]');108 let totalMatching = container.querySelectorAll('.category-a.category-c').length;109 toggleB.click();110 let state = mixer.getState();111 chai.assert.equal(state.activeFilter.selector, '.category-a.category-c');112 chai.assert.equal(state.totalShow, totalMatching);113 chai.assert.isOk(toggleA.matches('.mixitup-control-active'));114 chai.assert.isOk(toggleB.matches('.mixitup-control-active'));115 });116 it('should break down a compound selector as toggles are deactivated', () => {117 let toggle = controls.querySelector('[data-toggle=".category-a"]');118 let totalMatching = container.querySelectorAll('.category-c').length;119 toggle.click();120 let state = mixer.getState();121 chai.assert.equal(state.activeFilter.selector, '.category-c');122 chai.assert.equal(state.totalShow, totalMatching);123 chai.assert.isNotOk(toggle.matches('.mixitup-control-active'));124 });125 it('should return to "all" when all toggles are deactivated', () => {126 let toggle = controls.querySelector('[data-toggle=".category-c"]');127 toggle.click();128 let state = mixer.getState();129 chai.assert.equal(state.activeFilter.selector, '.mix');130 chai.assert.equal(state.totalHide, 0);131 chai.assert.isNotOk(toggle.matches('.mixitup-control-active'));132 });133 it('should allow toggles to activated via the API', () => {134 let totalMatching = container.querySelectorAll('.category-a.category-c').length;135 mixer.toggleOn('.category-a');136 mixer.toggleOn('.category-c');137 let state = mixer.getState();138 chai.assert.equal(state.activeFilter.selector, '.category-a.category-c');139 chai.assert.equal(state.totalShow, totalMatching);140 });141 it ('should activate the appropriate toggle controls on load for an AND compound selector', () => {142 const frag = document.createDocumentFragment();143 const container = dom.getContainer();144 const controls = dom.getFilterControls();145 frag.appendChild(controls);146 frag.appendChild(container);147 const mixer = mixitup(container, {148 controls: {149 toggleLogic: 'and'150 },151 load: {152 filter: '.category-a.category-c'153 }154 }, frag);155 after(() => mixer.destroy());156 const toggleA = controls.querySelector('[data-toggle=".category-a"]');157 const toggleC = controls.querySelector('[data-toggle=".category-c"]');158 chai.assert.isTrue(toggleA.classList.contains('mixitup-control-active'));159 chai.assert.isTrue(toggleC.classList.contains('mixitup-control-active'));160 });161 });162 describe('Defaults', () => {163 it('should default to "none" when all toggles are deactivated and toggleDefault is set to "none"', () => {164 let frag = document.createDocumentFragment();165 let container = dom.getContainer();166 let controls = dom.getFilterControls();167 container.insertBefore(controls, container.children[0]);168 frag.appendChild(container);169 let mixer = mixitup(container, {170 controls: {171 scope: 'local',172 toggleDefault: 'none'173 }174 });175 return mixer.hide()176 .then(() => {177 let toggle = controls.querySelector('[data-toggle=".category-a"]');178 // on179 toggle.click();180 // off181 toggle.click();182 let state = mixer.getState();183 chai.assert.equal(state.activeFilter.selector, '');184 chai.assert.equal(state.totalShow, 0);185 chai.assert.isNotOk(toggle.matches('.mixitup-control-active'));186 mixer.destroy();187 });188 });189 it('should default to "all" when all toggles are deactivated', () => {190 let container = dom.getContainer();191 let controls = dom.getFilterControls();192 container.insertBefore(controls, container.children[0]);193 document.body.appendChild(container);194 let mixer = mixitup(container, {195 controls: {196 scope: 'local',197 toggleDefault: 'all'198 }199 });200 return mixer.hide()201 .then(() => {202 let toggle = controls.querySelector('[data-toggle=".category-a"]');203 // on204 toggle.click();205 // off206 toggle.click();207 let state = mixer.getState();208 chai.assert.equal(state.activeFilter.selector, '.mix');209 chai.assert.equal(state.totalHide, 0);210 chai.assert.isNotOk(toggle.matches('.mixitup-control-active'));211 });212 });213 });214 });...
protractor.js
Source:protractor.js
...41};42it('should toggle the outer toggle', function() {43 var outerToggle = new OuterToggle();44 expect(outerToggle.isOpen()).toEqual('outerToggle.isOpen(): false');45 outerToggle.toggle();46 expect(outerToggle.isOpen()).toEqual('outerToggle.isOpen(): true');47});48it('should toggle all outer toggles', function() {49 var outerToggle = new OuterToggle();50 var repeatToggles = new NgRepeatToggles();51 var ifToggle = new NgIfToggle();52 expect(outerToggle.isOpen()).toEqual('outerToggle.isOpen(): false');53 expect(repeatToggles.isOuterOpen(1)).toEqual('outerToggle.isOpen(): false');54 expect(repeatToggles.isOuterOpen(2)).toEqual('outerToggle.isOpen(): false');55 expect(repeatToggles.isOuterOpen(3)).toEqual('outerToggle.isOpen(): false');56 expect(ifToggle.isOuterOpen()).toEqual('outerToggle.isOpen(): false');57 outerToggle.toggle();58 expect(outerToggle.isOpen()).toEqual('outerToggle.isOpen(): true');59 expect(repeatToggles.isOuterOpen(1)).toEqual('outerToggle.isOpen(): true');60 expect(repeatToggles.isOuterOpen(2)).toEqual('outerToggle.isOpen(): true');61 expect(repeatToggles.isOuterOpen(3)).toEqual('outerToggle.isOpen(): true');62 expect(ifToggle.isOuterOpen()).toEqual('outerToggle.isOpen(): true');63});64it('should toggle each repeat iteration separately', function() {65 var repeatToggles = new NgRepeatToggles();66 repeatToggles.forEach(function(repeatToggle) {67 expect(repeatToggle.isOpen()).toEqual('ngRepeatToggle.isOpen(): false');68 expect(repeatToggle.isOuterOpen()).toEqual('outerToggle.isOpen(): false');69 repeatToggle.toggle();70 expect(repeatToggle.isOpen()).toEqual('ngRepeatToggle.isOpen(): true');71 expect(repeatToggle.isOuterOpen()).toEqual('outerToggle.isOpen(): false');72 });...
toggle_3Buttons.py
Source:toggle_3Buttons.py
1import os2from msvcrt import getch3import time456def toggle_button():7 toggle_A = toggle_S = toggle_D = 08 while True:910 inp = ord(getch())11 os.system('cls')12 if inp in [ord("A".lower()), ord("S".lower()), ord("D".lower())]:1314 if inp == ord("A".lower()) and toggle_A == 0:15 print("ON")16 toggle_A = 11718 elif inp == ord("A".lower()) and toggle_A == 1:19 print('OFF')20 toggle_A = 02122 # ---------------------------------------------------------------------2324 elif inp == ord("S".lower()) and toggle_S == 0:25 print("ON")26 toggle_S = 12728 elif inp == ord("S".lower()) and toggle_S == 1:29 print('OFF')30 toggle_S = 03132 # ---------------------------------------------------------------------3334 elif inp == ord("D".lower()) and toggle_D == 0:35 print("ON")36 toggle_D = 13738 elif inp == ord("D".lower()) and toggle_D == 1:39 print('OFF')40 toggle_D = 04142 # ---------------------------------------------------------------------4344 else:45 print('Thanx for playing !!\n')46 exit()474849print('\nLets start the game........')50time.sleep(1)51print('\nA - OFF', 'S - OFF', 'D - OFF')52time.sleep(1)53print('\nPress any key from " A S D" key to start the game and press another key to end the game\n')54
...
09-button-styles.py
Source:09-button-styles.py
1'''2Button styles3You can also get really creative with your Button widgets.4In this exercise, you'll practice using CheckboxGroup, RadioGroup, and Toggle to add multiple Button widgets with different styles.5curdoc and widgetbox have already been imported for you.6INSTRUCTIONS7100XP8INSTRUCTIONS9100XP10Import CheckboxGroup, RadioGroup, Toggle from bokeh.models.11Add a Toggle called toggle using the Toggle() function with button_type 'success' and label 'Toggle button'.12Add a CheckboxGroup called checkbox using the CheckboxGroup() function with labels=['Option 1', 'Option 2', 'Option 3'].13Add a RadioGroup called radio using the RadioGroup() function with labels=['Option 1', 'Option 2', 'Option 3'].14Add the widgetbox containing the Toggle toggle, CheckboxGroup checkbox, and RadioGroup radio to the current document.15'''16# Import CheckboxGroup, RadioGroup, Toggle from bokeh.models17from bokeh.models import CheckboxGroup, RadioGroup, Toggle18# Add a Toggle: toggle19toggle = Toggle(label='Toggle button',button_type='success')20# Add a CheckboxGroup: checkbox21checkbox = CheckboxGroup(labels=['Option 1', 'Option 2', 'Option 3'])22# Add a RadioGroup: radio23radio = RadioGroup(labels=['Option 1', 'Option 2', 'Option 3'])24# Add widgetbox(toggle, checkbox, radio) to the current document...
toggle.js
Source:toggle.js
...32 toggle.bindEvents = function bindEvents() {33 toggle.el.addEventListener('click', toggle.toggleClass);34 };35 toggle.toggleClass = function toggleClass() {36 toggle.el.classList.toggle(toggle.toggleButtonClass);37 };38 return {39 initialize: toggle.initialize,40 };...
app_button_styles.py
Source:app_button_styles.py
1# Import CheckboxGroup, RadioGroup, Toggle from bokeh.models2from bokeh.layouts import widgetbox3from bokeh.io import output_file, curdoc4from bokeh.models import CheckboxGroup, RadioGroup, Toggle5# Add a Toggle: toggle6toggle = Toggle(7 label = 'Toggle button',8 button_type = 'success')9# Add a CheckboxGroup: checkbox10checkbox = CheckboxGroup(11 labels = ['Option 1','Option 2','Option 3'])12# Add a RadioGroup: radio13radio = RadioGroup(14 labels = ['Option 1','Option 2','Option 3'])15# Add widgetbox(toggle, checkbox, radio) to the current document16layout = widgetbox(toggle, checkbox, radio)...
Using AI Code Generation
1const { toggle } = require('fast-check-monorepo');2const { toggle } = require('fast-check-monorepo');3const { toggle } = require('fast-check-monorepo');4const { toggle } = require('fast-check-monorepo');5const { toggle } = require('fast-check-monorepo');6const { toggle } = require('fast-check-monorepo');7const { toggle } = require('fast-check-monorepo');
Using AI Code Generation
1const fc = require('fast-check');2const { toggle } = require('fast-check-monorepo');3console.log(toggle(true));4console.log(toggle(false));5const fc = require('fast-check');6const { toggle } = require('fast-check-monorepo');7console.log(toggle(true));8console.log(toggle(false));9const fc = require('fast-check');10const { toggle } = require('fast-check-monorepo');11console.log(toggle(true));12console.log(toggle(false));13const fc = require('fast-check');14const { toggle } = require('fast-check-monorepo');15console.log(toggle(true));16console.log(toggle(false));17const fc = require('fast-check');18const { toggle } = require('fast-check-monorepo');19console.log(toggle(true));20console.log(toggle(false));21const fc = require('fast-check');22const { toggle } = require('fast-check-monorepo');23console.log(toggle(true));24console.log(toggle(false));25const fc = require('fast-check');26const { toggle } = require('fast-check-monorepo');27console.log(toggle(true));28console.log(toggle(false));29const fc = require('fast-check');30const { toggle } = require('fast-check-monorepo');31console.log(toggle(true));32console.log(toggle(false));
Using AI Code Generation
1const { toggle } = require('@myorg/fast-check-monorepo');2toggle('test3');3const { toggle } = require('@myorg/fast-check-monorepo');4toggle('test1');5const { toggle } = require('@myorg/fast-check-monorepo');6toggle('test2');7const { toggle } = require('@myorg/fast-check-monorepo');8toggle('test4');9const { toggle } = require('@myorg/fast-check-monorepo');10toggle('test5');11const { toggle } = require('@myorg/fast-check-monorepo');12toggle('test6');13const { toggle } = require('@myorg/fast-check-monorepo');14toggle('test7');15const { toggle } = require('@myorg/fast-check-monorepo');16toggle('test8');17const { toggle } = require('@myorg/fast-check-monorepo');18toggle('test9');19const { toggle } = require('@myorg/fast-check-monorepo');20toggle('test10');21const { toggle } = require('@myorg/fast-check-monorepo');22toggle('test11');23const { toggle } = require('@myorg/fast-check-monorepo');24toggle('test12');25const { toggle } = require('@myorg/fast-check-monorepo');26toggle('test
Using AI Code Generation
1var fc = require('fast-check');2var assert = require('assert');3var toggle = function (a) {4 return a ? false : true;5};6assert(toggle(true) === false);7assert(toggle(false) === true);8assert(typeof toggle
Using AI Code Generation
1const assert = require('assert');2const fc = require('fast-check');3const genString = fc.string({ minLength: 1 });4const genString1 = fc.string({ minLength: 1, maxLength: 1 });5const genString2 = fc.string({ minLength: 2, maxLength: 2 });6const genString3 = fc.string({ minLength: 3, maxLength: 3 });7const genString4 = fc.string({ minLength: 4, maxLength: 4 });8const genString5 = fc.string({ minLength: 5, maxLength: 5 });9const genString6 = fc.string({ minLength: 6, maxLength: 6 });10const genString7 = fc.string({ minLength: 7, maxLength: 7 });11const genString8 = fc.string({ minLength: 8, maxLength: 8 });12const genString9 = fc.string({ minLength: 9, maxLength: 9 });13const genString10 = fc.string({ minLength: 10, maxLength: 10 });14const genString11 = fc.string({ minLength: 11, maxLength: 11 });15const genString12 = fc.string({ minLength: 12, maxLength: 12 });16const genString13 = fc.string({ minLength: 13, maxLength: 13 });17const genString14 = fc.string({ minLength: 14, maxLength: 14 });18const genString15 = fc.string({ minLength: 15, maxLength: 15 });
Using AI Code Generation
1const { check, property } = require("fast-check");2const { myFunction } = require("./myFunction");3const myArb = (min, max) => {4 return {5 generate: () => {6 return {7 x: Math.floor(Math.random() * (max - min + 1)) + min,8 y: Math.floor(Math.random() * (max - min + 1)) + min,9 };10 },11 shrink: () => [],12 };13};14const myProperty = (x, y) => {15 return myFunction(x, y).x === x;16};17check(18 property(myArb(1, 100), (m) => {19 return myProperty(m.x, m.y);20 }),21 { verbose: true }22);23const myFunction = (x, y) => {24 return { x: x, y: y };25};26module.exports = { myFunction };27const { check, property } = require("fast-check");28const { myFunction } = require("./myFunction");29const myArb = (min, max) => {30 return {31 generate: () => {32 return {33 x: Math.floor(Math.random() * (max - min + 1)) + min,34 y: Math.floor(Math.random() * (max - min + 1)) + min,35 };36 },37 shrink: () => [],38 };39};40const myProperty = (m) => {41 return myFunction(m.x, m.y).x === m.x;42};43check(44 property(myArb(1, 100), myProperty),45 { verbose: true }46);47const myFunction = (x, y) => {48 return { x: x, y: y };49};50module.exports = { myFunction };
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!