How to use _add_line method in tappy

Best Python code snippet using tappy_python

parser_generator.py

Source:parser_generator.py Github

copy

Full Screen

...48 logging.debug(grammar)49 # Add standard generated warning at the top50 self._output_str = (51 '# NOTE: THIS FILE IS AUTOMATICALLY GENERATED BY ebnf_cc')52 self._add_line('# ONLY CHANGE THIS FILE IF YOU DO NOT MIND '53 'LOSING ALL YOUR CHANGES')54 self._add_description()55 # Import files56 self._add_line('import _symbol')57 self._add_line('import _token_stream')58 # Create parser of language by traversing the Grammar object59 self._add_grammar(grammar)60 # Import custom definitions61 self._add_line('# Import any user-provided parser classes')62 self._add_line('# Necessary if the EBNF specification is incomplete')63 self._add_line('try:')64 self._push_depth()65 self._add_line('from _custom_definitions import *')66 self._pop_depth()67 self._add_line('except ImportError:')68 self._push_depth()69 self._add_line('pass')70 self._pop_depth()71 self._add_line('')72 with open(output_filename, 'w') as f:73 f.write(self._output_str)74 # Copy token_stream and symbol modules over75 for module in (token_stream, symbol):76 src_name = inspect.getfile(module)77 if src_name[-1] == 'c':78 src_name = src_name[:-1]79 shutil.copyfile(src_name, '_%s' % os.path.basename(src_name))80 def _add_description(self):81 """Add description to top of the file."""82 self._add_line('')83 self._add_line('# Description')84 self._add_line('# ###########')85 # TODO(akhouderchah) add full description + usage86 self._add_line('')87 def _add_grammar(self, grammar):88 """Add parser for the specified EBNF grammar."""89 for rule in grammar._children:90 self._add_rule(rule)91 def _add_rule(self, rule):92 """Add parser class for a single EBNF rule."""93 rule_name = rule.get_next()94 self._add_line('class %s(_symbol.BaseSymbol):' % rule_name)95 self._push_depth()96 self._add_line('def __init__(self):')97 self._push_depth()98 self._add_line('super(%s, self).__init__()' % rule_name)99 rhs = rule.get_next(ebnf_parser.Rhs)100 if rhs is None:101 raise Exception('Expected RHS in rule:\n%s' % rule)102 intermediate_repr = intermediate_language.ILGenerator().generate(rhs)103 self._add_intermediate(intermediate_repr)104 self._pop_depth()105 self._pop_depth()106 self._add_line('')107 self._add_line('')108 def _add_intermediate(self, intermediate, optional_mode=None):109 """Generates parser class body of a rule given its IL representation.110 Params:111 intermediate: intermediate_language._ILObject representing the112 rule to generate a parser class for.113 optional_mode: an _OPTIONAL_* value representing if the generated114 code currently resides in an if or elif statement.115 """116 if isinstance(intermediate, ebnf_parser.Terminal):117 self._add_terminal(intermediate, optional_mode)118 elif isinstance(intermediate, ebnf_parser.Identifier):119 self._add_identifier(intermediate, optional_mode)120 elif isinstance(intermediate, intermediate_language.Choice):121 self._add_choice(intermediate, optional_mode)122 elif isinstance(intermediate, intermediate_language.Sequence):123 self._add_sequence(intermediate, optional_mode)124 elif isinstance(intermediate, intermediate_language.Repetition):125 self._add_repetition(intermediate, optional_mode)126 elif isinstance(intermediate, intermediate_language.Optional):127 self._add_optional(intermediate, optional_mode)128 else:129 raise ValueError('Unexpected object type in IL representation')130 def _add_terminal(self, terminal, optional_mode):131 """Generate code to parse the given ebnf_parser.Terminal object.132 Params:133 terminal: ebnf_parser.Terminal representing the EBNF terminal.134 optional_mode: an _OPTIONAL_* value representing if the generated135 code currently resides in an if or elif statement.136 """137 terminal.get_next() # Skip over ' token138 term = terminal.get_next()139 if not optional_mode:140 self._add_line("self.add_token('%s')" % term)141 elif optional_mode == self._OPTIONAL_IF:142 self._add_line("if self.add_token_optional('%s'):" % term)143 self._push_depth()144 elif optional_mode == self._OPTIONAL_ELIF:145 self._add_line("elif self.add_token_optional('%s'):" % term)146 self._push_depth()147 def _add_identifier(self, identifier, optional_mode):148 """Generate code to parse the given ebnf_parser.Identifier object.149 Params:150 identifier: ebnf_parser.Identnifier representing the EBNF identifier.151 optional_mode: an _OPTIONAL_* value representing if the generated152 code currently resides in an if or elif statement.153 """154 term = identifier.get_next()155 if not optional_mode:156 self._add_line('self.add(%s)' % term)157 elif optional_mode == self._OPTIONAL_IF:158 self._add_line('if self.add_optional(%s):' % term)159 self._push_depth()160 elif optional_mode == self._OPTIONAL_ELIF:161 self._add_line('elif self.add_optional(%s):' % term)162 self._push_depth()163 def _add_choice(self, il_choice, optional_mode):164 """Generate code to parse the given Choice object.165 Params:166 il_choice: intermediate_language.Choice representing the167 EBNF rule choice.168 optional_mode: an _OPTIONAL_* value representing if the generated169 code currently resides in an if or elif statement.170 """171 self._add_intermediate(il_choice._objs[0], self._OPTIONAL_IF)172 self._add_line('pass')173 self._pop_depth()174 for i in range(1, len(il_choice._objs)):175 self._add_intermediate(il_choice._objs[i],176 self._OPTIONAL_ELIF)177 self._add_line('pass')178 self._pop_depth()179 if optional_mode:180 self._push_depth()181 else:182 self._add_line('else:')183 self._push_depth()184 # TODO(akhouderchah) add error message185 self._add_line('raise _symbol.SymbolException(\'\')')186 self._pop_depth()187 def _add_sequence(self, il_sequence, optional_mode):188 """Generate code to parse the given Sequence object.189 Params:190 il_sequence: intermediate_language.Sequence representing the191 EBNF rule sequence.192 optional_mode: an _OPTIONAL_* value representing if the generated193 code currently resides in an if or elif statement.194 """195 self._add_intermediate(il_sequence._objs[0], optional_mode)196 for i in range(1, len(il_sequence._objs)):197 obj = il_sequence._objs[i]198 self._add_intermediate(obj)199 def _add_repetition(self, il_repetition, optional_mode):200 """Generate code to parse the given Repetition object.201 Params:202 il_optional: intermediate_language.Repetition representing the203 repeating EBNF rule sequence.204 optional_mode: an _OPTIONAL_* value representing if the generated205 code currently resides in an if or elif statement.206 """207 self._add_line('while True:')208 self._push_depth()209 self._add_intermediate(il_repetition._objs[0], self._OPTIONAL_IF)210 self._add_line('pass')211 self._pop_depth()212 self._add_line('else:')213 self._push_depth()214 self._add_line('break')215 self._pop_depth()216 self._pop_depth()217 def _add_optional(self, il_optional, optional_mode):218 """Generate code to parse the given Optional object.219 Params:220 il_optional: intermediate_language.Optional representing the221 optional EBNF rule sequence.222 optional_mode: an _OPTIONAL_* value representing if the generated223 code currently resides in an if or elif statement.224 """225 self._add_intermediate(il_optional._objs[0], self._OPTIONAL_IF)226 # Special casing optional terminals227 if not isinstance(il_optional._objs[0],228 intermediate_language._ILObject):229 self._add_line('pass')230 self._pop_depth()231 def _add_line(self, line):232 """Adds line to file."""233 self._output_str += '\n%s%s' % (self.TAB * self._depth, line)234 def _push_depth(self):235 """Decrements indentation level for subsequent _add_line calls."""236 self._depth += 1237 def _pop_depth(self):238 """Increments indentation level for subsequent _add_line calls."""...

Full Screen

Full Screen

script_generator.py

Source:script_generator.py Github

copy

Full Screen

...9 self._build_script()10 @abstractmethod11 def _build_script(self) -> None:12 pass13 def _add_line(self, line: str, indent_level: int = 0) -> None:14 for i in range(indent_level):15 self._output += "\t"16 # add the line17 self._output += line18 # close the line19 self._end_line()20 @property21 def file_name(self) -> str:22 return self._file_name23 def _end_line(self):24 self._output += "\n"25 def write(self, directory: str = ".") -> None:26 out_file: Path = Path(directory) / self._file_name27 with out_file.open("w") as f:28 f.write(self._output)29class PythonGenerator(ScriptGenerator):30 def __init__(31 self,32 file_name: str,33 database_file: str,34 parameter_file: str,35 base_dir: str,36 import_line: str,37 n_procs: int,38 n_nodes: Optional[int] = None,39 linear_exceution: bool = False,40 ) -> None:41 """42 Generate the python script that will be run43 :param file_name:44 :type file_name: str45 :param database_file:46 :type database_file: str47 :param parameter_file:48 :type parameter_file: str49 :param base_dir:50 :type base_dir: str51 :param import_line:52 :type import_line: str53 :param n_procs:54 :type n_procs: int55 :param n_nodes:56 :type n_nodes: Optional[int]57 :param linear_exceution:58 :type linear_exceution: bool59 :returns:60 """61 self._import_line = import_line62 self._n_procs: int = n_procs63 self._n_nodes: Optional[int] = n_nodes64 self._parameter_file: str = parameter_file65 self._database_file: str = Path(database_file).absolute()66 self._base_dir: str = base_dir67 self._linear_execution: bool = linear_exceution68 super().__init__(file_name)69 def _build_script(self) -> None:70 self._add_line(self._import_line)71 self._add_line("from joblib import Parallel, delayed")72 self._add_line("from tqdm.auto import tqdm")73 self._add_line("from ronswanson import ParameterGrid")74 if self._n_nodes is not None:75 self._add_line("import sys")76 self._end_line()77 self._add_line("key_num = int(sys.argv[-1])")78 self._end_line()79 self._add_line(80 f"pg = ParameterGrid.from_yaml('{self._parameter_file}')"81 )82 self._add_line("def func(i):")83 self._add_line("params = pg.at_index(i)", indent_level=1)84 self._add_line(85 f"simulation = Simulation(i, params, pg.energy_grid,'{self._database_file}')",86 indent_level=1,87 )88 self._add_line("simulation.run()", indent_level=1)89 if self._n_nodes is None:90 self._add_line("iteration = [i for i in range(0, pg.n_points)]")91 else:92 self._add_line(93 f"with open(f'{self._base_dir}/key_file{{key_num}}.txt') as f:"94 )95 self._add_line("iteration = f.readlines()")96 pass97 if self._linear_execution:98 # just do a straight for loop99 self._add_line("for i in tqdm(iteration):")100 self._add_line("func(i)", indent_level=1)101 else:102 # use joblib103 if self._n_nodes is not None:104 self._add_line(105 f"Parallel(n_jobs={self._n_procs})(delayed(func)(i) for i in iteration)"106 )107 else:108 self._add_line(109 f"Parallel(n_jobs={self._n_procs})(delayed(func)(i) for i in tqdm(iteration, colour='#FC0A5A'))"110 )111class SLURMGenerator(ScriptGenerator):112 def __init__(113 self,114 file_name: str,115 n_procs: int,116 n_nodes: int,117 hrs: int,118 min: int,119 sec: int,120 ) -> None:121 self._n_procs: int = n_procs122 self._n_nodes: int = n_nodes123 self._hrs: int = hrs124 self._min: int = min125 self._sec: int = sec126 super().__init__(file_name)127 def _build_script(self) -> None:128 self._add_line("#!/bin/bash")129 self._add_line("")130 self._add_line(f"#SBATCH --array=0-{self._n_nodes} #generate array")131 self._add_line("#SBATCH -o ./output/%A_%a.out #output file")132 self._add_line("#SBATCH -e ./output/%A_%a.err #error file")133 self._add_line("#SBATCH -D ./ #working directory")134 self._add_line("#SBATCH -J grid_mp #job name")135 self._add_line("#SBATCH -N 1 ")136 self._add_line("#SBATCH --ntasks-per-node=1")137 self._add_line(f"#SBATCH --cpus-per-task={self._n_procs}")138 self._add_line(f"#SBATCH --time={self._hrs}:{self._min}:{self._sec}")139 self._add_line("#SBATCH --mail-type=ALL ")140 self._add_line(141 f"#SBATCH --mail-user={ronswanson_config.slurm.user_email}"142 )143 self._add_line("")144 if ronswanson_config.slurm.modules is not None:145 for m in ronswanson_config.slurm.modules:146 self._add_line(f"module load {m}")147 self._add_line("")148 # self._add_line("module load gcc/11")149 # self._add_line("module load openmpi/4")150 # self._add_line("module load hdf5-serial/1.10.6")151 # self._add_line("module load anaconda/3/2021.05")152 self._add_line("")153 self._add_line("#add HDF5 library path to ld path")154 self._add_line("export LD_LIBRARY_PATH=$HDF5_HOME/lib:$LD_LIBRARY_PATH")155 self._add_line("")156 self._add_line(157 "srun /u/eschoe/conda-envs/py_env/bin/python3 run_sim_mp_rav.py ${SLURM_ARRAY_TASK_ID}"...

Full Screen

Full Screen

qc_plots.py

Source:qc_plots.py Github

copy

Full Screen

...23 "pct_counts_mito",24 )25 fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(12, 10))26 axs = {k: ax for k, ax in zip(KEYS, axs.flatten())}27 def _add_line(ax, val):28 if val is not None:29 if cumulative:30 ax.hlines(31 y=val, color="red", linewidth=1, xmin=0, xmax=ax.get_xlim()[1]32 )33 else:34 ax.vlines(35 x=val, color="red", linewidth=1, ymin=0, ymax=ax.get_ylim()[1]36 )37 for key, ax in axs.items():38 if key == "total_counts (< 5000)":39 values = adata.obs["total_counts"][adata.obs["total_counts"] < 5000]40 else:41 values = adata.obs[key]42 if not cumulative:43 sns.histplot(values, bins=100, ax=ax)44 else:45 ranks = values.rank(ascending=True, method="first")46 ax.scatter(x=ranks, y=values, marker=".", s=2)47 ax.set_xlabel(key)48 if cumulative:49 axs["total_counts"].set_yscale("log")50 axs["total_counts (< 5000)"].set_yscale("log")51 _add_line(axs["total_counts"], min_counts)52 _add_line(axs["total_counts (< 5000)"], min_counts)53 _add_line(axs["total_counts"], max_counts)54 _add_line(axs["n_genes_by_counts"], min_genes)55 _add_line(axs["pct_counts_mito"], max_pct_mito)56 if show:57 plt.show()58 else:...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run tappy automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful