Best Python code snippet using slash
jcov_tracer.py
Source:jcov_tracer.py  
1import os2from pom_file import PomValue3from subprocess import Popen4import socket5class JcovTracer(object):6    """7               <artifactId>maven-surefire-plugin</artifactId>8           <version>2.18.1</version>9           <configuration>10-            <argLine>-Xmx2048m</argLine>11-          </configuration>12+            <argLine>"-javaagent:C:\Users\User\Documents\GitHub\jcov\JCOV_BUILD\jcov_3.0\jcov.jar=grabber,include_list=C:\Users\User\Documents\GitHub\jcov\classes_file.txt"</argLine>13+                                 <additionalClasspathElements>14+            <additionalClasspathElement>C:\Users\User\Documents\GitHub\jcov\JCOV_BUILD\jcov_3.0\listener.jar</additionalClasspathElement>15+          </additionalClasspathElements>16+17+          <properties>18+                       <property>19+                       <name>listener</name>20+                       <value>com.sun.tdk.listener.JUnitExecutionListener</value>21+                       </property>22+                       </properties>23+                 </configuration>24         </plugin>25         <plugin>26           <groupId>org.apache.maven.plugins</groupId>27    """28    JCOV_JAR_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "externals", "jcov.jar")29    LISTENER_JAR_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "externals", "listener.jar")30    LISTENER_CLASS = "com.sun.tdk.listener.JUnitExecutionListener"31    DEBUG_CMD = ["-Xdebug", "-Xrunjdwp:transport=dt_socket,address=5000,server=y,suspend=y"]32    def __init__(self, classes_dir, path_to_out_template=None, path_to_classes_file=None, path_to_result_file=None, class_path=None, instrument_only_methods=True):33        self.classes_dir = classes_dir34        self.path_to_out_template = path_to_out_template35        self.path_to_classes_file = path_to_classes_file36        self.path_to_result_file = path_to_result_file37        self.class_path = class_path38        self.instrument_only_methods = instrument_only_methods39        self.agent_port = str(self.get_open_port())40        self.command_port = str(self.get_open_port())41        self.env = {"JcovGrabberCommandPort": self.command_port}42        assert os.environ['JAVA_HOME'], "java home is not configured"43    def get_open_port(self):44            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)45            s.bind(("", 0))46            s.listen(1)47            port = s.getsockname()[1]48            s.close()49            return port50    def check_if_grabber_is_on(self):51        import time52        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)53        try:54            time.sleep(5)55            s.connect(('127.0.0.1', int(self.command_port)))56            s.close()57            return True58        except:59            return False60        return False61    def template_creator_cmd_line(self, debug=False):62        cmd_line = [os.path.join(os.environ['JAVA_HOME'], "bin\java.exe"), '-Xms2g'] + (JcovTracer.DEBUG_CMD if debug else []) + ['-jar', JcovTracer.JCOV_JAR_PATH, 'tmplgen', '-verbose']63        if self.class_path :64            cmd_line.extend(['-cp', self.class_path])65        if self.path_to_out_template:66            cmd_line.extend(['-t', self.path_to_out_template])67        if self.path_to_classes_file:68                cmd_line.extend(['-c', self.path_to_classes_file])69        if self.instrument_only_methods:70            cmd_line.extend(['-type', 'method'])71        cmd_line.extend(self.get_classes_path())72        return cmd_line73    def grabber_cmd_line(self, debug=False):74            cmd_line = [os.path.join(os.environ['JAVA_HOME'], "bin\java.exe"), '-Xms2g'] + (JcovTracer.DEBUG_CMD if debug else []) + ['-jar', JcovTracer.JCOV_JAR_PATH, 'grabber', '-vv', '-port', self.agent_port, '-command_port', self.command_port]75            if self.path_to_out_template:76                cmd_line.extend(['-t', self.path_to_out_template])77            if self.path_to_result_file:78                    cmd_line.extend(['-o', self.path_to_result_file])79            return cmd_line80    def get_agent_arg_line(self):81        arg_line = r'-javaagent:{JCOV_JAR_PATH}=grabber,port={PORT}'.format(JCOV_JAR_PATH=JcovTracer.JCOV_JAR_PATH, PORT=self.agent_port)82        if self.path_to_classes_file:83            arg_line += r',include_list={CLASSES_FILE}'.format(CLASSES_FILE=self.path_to_classes_file)84        if self.path_to_out_template:85            arg_line += r',template={0}'.format(self.path_to_out_template)86        if self.instrument_only_methods:87            arg_line += r',type=method'88        return PomValue("maven-surefire-plugin", ["configuration", "argLine"], '"{0}"'.format(arg_line))89    def get_classes_path(self):90        all_classes = [self.classes_dir]91        for root, dirs, files in os.walk(self.classes_dir):92            if "target" in dirs:93                classes_path = os.path.join(root, "target", "classes")94                if os.path.exists(classes_path):95                    all_classes.append(classes_path)96        return all_classes97    @staticmethod98    def static_values_to_add_to_pom():99        return [PomValue("maven-surefire-plugin", ["configuration", "properties", "property", "name"], "listener"),100                PomValue("maven-surefire-plugin", ["configuration", "properties", "property", "value"], JcovTracer.LISTENER_CLASS),101                PomValue("maven-surefire-plugin", ["configuration", "additionalClasspathElements", "additionalClasspathElement"], JcovTracer.LISTENER_JAR_PATH),102                PomValue("maven-surefire-plugin", ["version"], "3.0.0", should_append=False),103                #PomValue("maven-surefire-plugin", ["configuration", "forkMode"], "once", should_append=False),104                #PomValue("maven-surefire-plugin", ["configuration", "forkedProcessTimeoutInSeconds"], "600", should_append=False),105                PomValue("maven-surefire-plugin", ["configuration", "forkCount"], "1", should_append=False),106                PomValue("maven-surefire-plugin", ["configuration", "reuseForks"], "false", should_append=False)]107    def get_enviroment_variables_values(self):108        return [#PomValue("maven-surefire-plugin", ["configuration", "forkMode"], "once", should_append=False),109                #PomValue("maven-surefire-plugin", ["configuration", "forkedProcessTimeoutInSeconds"], "600", should_append=False),110                PomValue("maven-surefire-plugin", ["configuration", "forkCount"], "1", should_append=False),111                PomValue("maven-surefire-plugin", ["configuration", "reuseForks"], "false", should_append=False),112                PomValue("maven-surefire-plugin", ["configuration", "environmentVariables", "JcovGrabberCommandPort"], self.command_port)]113    def get_values_to_add(self):114        return JcovTracer.static_values_to_add_to_pom() + [self.get_agent_arg_line()] + self.get_enviroment_variables_values()115    def stop_grabber(self):116        Popen(["java", "-jar", JcovTracer.JCOV_JAR_PATH, "grabberManager", "-save", '-command_port', self.command_port]).communicate()117        Popen(["java", "-jar", JcovTracer.JCOV_JAR_PATH, "grabberManager", "-stop", '-command_port', self.command_port]).communicate()118    def execute_jcov_process(self, debug=False):119        Popen(self.template_creator_cmd_line(debug=debug)).communicate()120        for path in [self.path_to_classes_file, self.path_to_out_template]:121            if path:122                with open(path) as f:123                    assert f.read(), "{0} is empty".format(path)124        p = Popen(self.grabber_cmd_line(debug=debug))125        assert p.poll() is None...wrestler.py
Source:wrestler.py  
1import argparse2from collections import deque3class Wrestler(object):4    def __init__(self, name):5        self._name = name6        self._rivals = deque()7        self._parent = None8        self.depth = 09    def __repr__(self):10        return "{}: {}".format(self._name, [rival.name for rival in self._rivals])11    @property12    def name(self):13        return self._name14    @property15    def rivals(self):16        return self._rivals17    def add_rival(self, rival):18        self._rivals.append(rival)19def wrestler_bfs(wrestlers):20    seen = set()21    bfs_babyfaces = []22    bfs_heels = []23    for wrestler in wrestlers:24        current_wrestlers = deque([wrestler])25        while current_wrestlers:26            current_wrestler = current_wrestlers.popleft()27            if current_wrestler.name not in seen:28                seen.add(current_wrestler.name)29                wrestlers_to_expand = deque(current_wrestler.rivals)30                if current_wrestler.depth % 2 == 0:31                    should_append = True32                    for rival_wrestler in wrestlers_to_expand:33                        if rival_wrestler.name in bfs_babyfaces:34                            should_append = False35                            break36                    if should_append:37                        bfs_babyfaces.append(current_wrestler.name)38                else:39                    should_append = True40                    for rival_wrestler in wrestlers_to_expand:41                        if rival_wrestler.name in bfs_heels:42                            should_append = False43                            break44                    if should_append:45                        bfs_heels.append(current_wrestler.name)46                for rival_wrestler in wrestlers_to_expand:47                    rival_wrestler.depth = current_wrestler.depth + 148                current_wrestlers += wrestlers_to_expand49    return bfs_babyfaces, bfs_heels50def get_wrestler_info_from_file(filename):51    found_wrestlers = deque()52    found_wrestler_indexes = {}53    with open(filename, "r") as input_file:54        lines = input_file.readlines()55        current_line = 056        file_num_wrestlers = int(lines[current_line])57        for i in range(file_num_wrestlers):58            current_line += 159            wrestler_name = lines[current_line].strip("\n")60            found_wrestlers.append(Wrestler(wrestler_name))61            found_wrestler_indexes[wrestler_name] = len(found_wrestlers) - 162        current_line += 163        num_rivalries = int(lines[current_line])64        for _ in range(num_rivalries):65            current_line += 166            rival_1_name, rival_2_name = lines[current_line].strip("\n").split(" ")67            rival_1_index = found_wrestler_indexes[rival_1_name]68            rival_2_index = found_wrestler_indexes[rival_2_name]69            found_wrestlers[rival_1_index].add_rival(found_wrestlers[rival_2_index])70            found_wrestlers[rival_2_index].add_rival(found_wrestlers[rival_1_index])71        return found_wrestlers72if __name__ == "__main__":73    parser = argparse.ArgumentParser(description="Tool to determine which wrestlers are babyfaces or heels")74    parser.add_argument("input_filename", help="Filename of wrestler information to use")75    args = parser.parse_args()76    all_wrestlers = get_wrestler_info_from_file(args.input_filename)77    babyfaces, heels = wrestler_bfs(all_wrestlers)78    num_wrestlers = len(all_wrestlers)79    num_assigned = len(babyfaces) + len(heels)80    if num_wrestlers == num_assigned:81        print("Yes")82        print("Babyfaces: {}".format(" ".join(babyfaces)))83        print("Heels: {}".format(" ".join(heels)))84    else:...filter_releases.py
Source:filter_releases.py  
1"""Helper Functions to be used for sorting and filtering."""2from datetime import datetime3def filter_releases(releases, filter_options):4  """Filters by all of the criteria.5  Args:6    releases: dictionary of release objects7    state: int representation of a state8    branch: string branch9    release_type: string release_type10    start_date: unix datetime of the beginning of a time period11    end_date: unix datetime of the end of a time period12    datetype: string determing which date (creation or last_modified) is13              filtered by the time period14  Returns:15    Array of releases that is filtered by the arguments.16  """17  # convert and validate inputs18  state = int(filter_options.state)19  if state < 0 or state > 6:20    state = 021  now = datetime.now()22  start_date = datetime.fromtimestamp(int(filter_options.start_date))23  if start_date < datetime.fromtimestamp(0) or start_date > now:24    start_date = datetime.fromtimestamp(0)25  end_date = datetime.fromtimestamp(int(filter_options.end_date))26  if end_date <= datetime.fromtimestamp(0):27    end_date = now28  branch = str(filter_options.branch)29  if branch == 'null':30    branch = None31  release_type = str(filter_options.release_type)32  if release_type == 'null':33    release_type = None34  filtered = []35  for release in releases.values():36    # If invalid datetype will default to started37    if filter_options.datetype == 'last_modified':38      check_date = release.last_modified39    else:40      check_date = release.started41    if check_date >= start_date and check_date <= end_date:42      should_append = False43      if release.state == state or state == 0:44        should_append = True45      if branch and should_append:46        should_append = (release.branch == branch)47      if release_type and should_append:48        should_append = (release.release_type == release_type)49      if should_append:50        filtered.append(release)51  return filtered52class Sorting(object):53  BY_NAME = 154  BY_CREATION = 255  BY_LAST_MODIFIED = 356  BY_LAST_ACTIVE = 457def sort(releases, filter_options):58  """Sorts 'releases' according to 'sort_method'.59  Args:60    releases: array of release objects61    sort_method: int representation of a sort_method62    reverse: int representing bool63  Returns:64    Array 'releases' in a sorted order.65  """66  sort_method = int(filter_options.sort_method)67  reverse = bool(int(filter_options.reverse))68  if sort_method == Sorting.BY_NAME:69    result = sorted(releases, key=lambda k: k.name, reverse=reverse)70  elif sort_method == Sorting.BY_CREATION:71    result = sorted(releases, key=lambda k: k.started, reverse=reverse)72  elif sort_method == Sorting.BY_LAST_MODIFIED:73    result = sorted(releases, key=lambda k: k.last_modified, reverse=reverse)74  elif sort_method == Sorting.BY_LAST_ACTIVE:75    result = sorted(releases, key=lambda k: k.last_active_task, reverse=reverse)...toggle_breakpoint_command.py
Source:toggle_breakpoint_command.py  
1import sublime, sublime_plugin2try:3    from .debugger import *4except:5    from debugger import *6class EraseAllCommand(sublime_plugin.TextCommand):7	def run(self, edit):8		self.view.erase(edit, sublime.Region(0, self.view.size()))9class ReplaceContentCommand(sublime_plugin.TextCommand):10	def run(self, edit, new_content, line_to_show, should_append):11		sublime.set_timeout(lambda view=self.view, new_content=new_content, line_to_show=line_to_show, should_append=should_append: ViewHelper.replace_content(view, new_content, line_to_show, should_append), 0)12class ToggleBreakpointCommand(sublime_plugin.TextCommand):13	def run(self, edit, mode, **args):14		if mode == "clear_all":15			for view in self.view.window().views():16				view.erase_regions("breakpoint")17				DebuggerModel.BREAKPOINTS = []18				self.view.window().run_command("debug", {"command" : "set_breakpoint"})19		elif mode == "normal":20			self.update_breakpoints()21		elif mode == "conditional":22			self.view.window().show_input_panel("Enter condition", '', lambda condition : self.update_breakpoints(condition), None, None)23		elif mode == "refresh":24			self.view.erase_regions("breakpoint")25			self.update_regions(self.view.file_name(), [], "")26	def update_breakpoints(self, condition=None):27		self.view.erase_regions("breakpoint")28		selected_lines = ViewHelper.get_lines(self.view, self.view.sel())29		self.update_regions(self.view.file_name(), selected_lines, condition)30		self.view.window().run_command("debug", {"command" : "set_breakpoint"})31	def update_regions(self, selected_file, selcted_line_numbers, condition):32		current_breakpoints = DebuggerModel.BREAKPOINTS33		unchanged = []34		unchanged_in_selected_file = []35		added = []36		for breakpoint in current_breakpoints:37			was_found = False38			for line_number in selcted_line_numbers:39				if breakpoint.line_number-1 == line_number:40					was_found = True41					break42			if not was_found and breakpoint.file_name == selected_file:43				unchanged_in_selected_file += [breakpoint]44			if not was_found :45				unchanged += [breakpoint]46		for line_number in selcted_line_numbers:47			was_found = False48			for breakpoint in current_breakpoints:49				if breakpoint.line_number-1 == line_number:50					was_found = True51					break52			if not was_found:53				added += [self.create_breakpoint(line_number, condition)]54		self.view.add_regions("breakpoint", self.to_regions(added+unchanged_in_selected_file), "string", "circle", sublime.PERSISTENT)55		DebuggerModel.BREAKPOINTS = added+unchanged56	def create_breakpoint(self, line_number, condition):57		return Breakpoint(self.view.file_name(), line_number+1, condition)58	def create_region(self, breakpoint):59		point = self.view.text_point(breakpoint.line_number-1, 0)60		region = sublime.Region(point, point)61		return region62	def to_regions(self, breakpoints):...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!!
