def testFile(fname): lex = Scanner() lex.build() readFile(fname, lex.Lexer)
def test_parse_assignment_fails_on_word(self): '''Fail on an invalid range: invalid word.''' with self.assertRaises(ParseError) as context: s = Scanner('1 = 15') p = Parser(s) fb_range = p.parse_assignment()
def test_parse_assignment_fails_on_equal_sign(self): '''Fail on an invalid range.: missing the equal sign.''' with self.assertRaises(ParseError) as context: s = Scanner('buzz...15') p = Parser(s) fb_range = p.parse_assignment()
def __init__(self, report_filename = ""): self.report_filename = report_filename self.scanner = Scanner(self, self.report_filename) self.tokeniser = Tokeniser(self) self.token_num = 0
def test_parse_range_fails_on_ellipsis(self): '''Fail on an invalid range.: missing the ellipsis.''' with self.assertRaises(ParseError) as context: s = Scanner('1=15') p = Parser(s) fb_range = p.parse_range()
import textwrap import sys import re from scanner import Scanner from astparsing import Parser from ast_visual import NodeVisitor, ASTVisualizer from asmgeneration import AssemblyGenerator from subprocess import check_output scanner = Scanner() parser = Parser(scanner) # ast parser rm visualize = ASTVisualizer(parser) # create ASTVisualizer object visualize.gendot() # get the content of dot file ro parser = Parser(scanner) # ast parser rm asm = AssemblyGenerator(parser) # ASM GEN OBJECT _ = asm.gens() # get the content of .s file ro content = ''.join(asm.dot_body) # print(content) cfg_header = [ textwrap.dedent("""\ digraph astgraph { node [shape=box, style = filled, fillcolor=\"white\", fontsize=10, fontname="Courier", height=.09]; ranksep=.3; edge [arrowsize=.5] """) ]
def format(self, sourceStr): normalizedStr = "" scanner = Scanner(sourceStr) while scanner.hasNext(): normalizedStr += str(scanner.next()) + " " return normalizedStr
from parser import Parser from medium_level_ir import MediumLevelIRCreator from pseudo_assembler import PseudoAssembler from scanner import Scanner from scope_analyser import ScopeAnalyser from real_assembler import RealAssembler from util import * from variable import Function, FunctionVariable import sys if __name__ == "__main__": input_file = open(sys.argv[1], 'r') source = input_file.read() grammar = GrammarDriver(rules) scanner = Scanner(source) p = Parser(scanner, grammar) p.parse() if not p.success: raise p.error main_variable = FunctionVariable(MAIN_NAME, MAIN_NAME, None, None) p.program.main_function = Function(main_variable) p.program.main_function.name = MAIN_NAME p.program.main_function.unique_name = MAIN_NAME sa = ScopeAnalyser(p.program) sa.builtins.add("print") sa.builtins.add("Array") sa.builtins.add("test_do_gc")
# LD features are pre-specified. We are basically just building the NB model. LDfeats = read_features(args.ld_feats) else: # LD features not pre-specified, so we compute them. # Tokenize DFfeats = None print "will tokenize %d files" % len(items) # TODO: Custom tokenizer if doing custom first-pass features if args.df_feats: print "reading custom features from:", args.df_feats DFfeats = read_features(args.df_feats) print "building tokenizer for custom list of {0} features".format( len(DFfeats)) tk = Scanner(DFfeats) elif args.word: print "using word tokenizer" tk = str.split else: print "using byte NGram tokenizer, max_order: {0}".format( args.max_order) tk = NGramTokenizer(1, args.max_order) # First-pass tokenization, used to determine DF of features b_dirs = build_index(items, tk, buckets_dir, args.buckets, args.jobs, args.chunksize, args.sample_count, args.sample_size) if args.debug: # output the paths to the buckets
def main(): parser = argparse.ArgumentParser( "Runs a set of tests against the set of provided URLs") parser.add_argument("-u", "--url", action="append", dest="targets", help="Add a target to test") parser.add_argument("-f", "--target-file", action="append", dest="target_files", help="File with URLs to test") parser.add_argument("-m", "--module", action="append", default=["corechecks"], dest="modules", help="Load an extension module") parser.add_argument("-p", "--force-passive", action="store_true", default=False, dest="force_passives", help="Force passives to be run for each active test") parser.add_argument("-d", "--dns", action="store_false", default=True, dest="resolve_target", help="Skip DNS resolution when registering a target") parser.add_argument("-r", "--report", action="store", default="reporter.AntXmlReporter", dest="report", help="Load a reporter e.g. -r reporter.AntXmlReporter") parser.add_argument("-o", "--output", action="store", default="garmr-results.xml", dest="output", help="Default output is garmr-results.xml") parser.add_argument("-c", "--check", action="append", dest="opts", help="Set a parameter for a check (check:opt=value)") parser.add_argument("-e", "--exclude", action="append", dest="exclusions", help="Prevent a check from being run/processed") parser.add_argument( "--save", action="store", dest="dump_path", help= "Write out a configuration file based on parameters (won't run scan)") args = parser.parse_args() scanner = Scanner() scanner.force_passives = args.force_passives scanner.resolve_target = args.resolve_target scanner.output = args.output # Start building target list. if args.targets != None: for target in args.targets: scanner.register_target(target) # Add targets from files to the list. if args.target_files != None: for targets in args.target_files: try: f = open(targets, "r") for target in f: t = target.strip() if len(t) > 0: scanner.register_target(t) except: Scanner.logger.error( "Unable to process the target list in: %s", targets) # Configure modules. # TODO: change the module loading to scan the list of classes in a module and automagically # detect any tests defined. if args.modules != None: for module in args.modules: try: __import__(module) m = sys.modules[module] m.configure(scanner) except Exception, e: Scanner.logger.fatal( "Unable to load the requested module [%s]: %s", module, e) quit()
def __init__(self, iface): self.scanner = Scanner(iface) fn = '%s/spectral_scan0' % self.scanner.get_debugfs_dir() self.file_reader = SpectrumFileReader(fn) self.interface = iface
return result if __name__ == '__main__': grammar1 = Grammar("g1.txt") parser1 = Parser(grammar1) string = 'a * ( a # a )' sequence1 = string.split(" ") se1 = string.split(" ") print("Grammar 1:") finish = parser1.parseSequence(se1) print(finish) print(parser1.derivationString(finish)) print(' ') scanner2 = Scanner("pb1.txt") scanner2.scan() sequence2 = [] pif = scanner2.programInternalForm for elem in pif: sequence2.append(pif[elem][0]) grammar2 = Grammar("g2.txt") parser2 = Parser(grammar2) parser2.fillParsingTable() print('Grammar 2:') finish2 = parser2.parseSequence(sequence2) print(finish2) print(parser2.derivationString(finish2))
def execute(self, command_manager): """Execute load command Return NO_ERROR, None if successful. """ self.command_manager = command_manager self.gui = command_manager.gui if self.path.split('.')[-1] == "defb": # File is an already built network with open(self.path, 'rb') as fp: try: monitors, devices, network, names, completed_cycles = \ pickle.load(fp) except pickle.UnpicklingError: return self.command_manager.INVALID_DEFINITION_FILE, None else: # File is a definition file names = Names() devices = Devices(names) network = Network(names, devices) monitors = Monitors(names, devices, network) scanner = Scanner(self.path, names) parser = Parser(names, devices, network, monitors, scanner) completed_cycles = 0 if not parser.parse_network(): errors = parser.error_to_gui self.gui.log_text('\n'.join(errors)) error_message = errors[0] return self.command_manager.INVALID_DEFINITION_FILE, \ error_message # Set new instances self.command_manager.monitors = monitors self.command_manager.devices = devices self.command_manager.network = network self.command_manager.names = names self.command_manager.undo_stack.clear() self.command_manager.redo_stack.clear() self.gui.monitors = self.command_manager.monitors self.gui.devices = self.command_manager.devices self.gui.network = self.command_manager.network self.gui.names = self.command_manager.names self.gui.switches = self.gui.devices.find_devices(devices.SWITCH) swithces_names = [ names.get_name_string(switch_id) for switch_id in self.gui.switches ] self.gui.switches_select.Clear() for switch_name in swithces_names: self.gui.switches_select.Append(switch_name) self.gui.canvas_2D.monitors = self.command_manager.monitors self.gui.canvas_3D.monitors = self.command_manager.monitors self.gui.monitors_select.Clear() for monitor_name in self.gui.monitors.get_signal_names()[0] + \ self.gui.monitors.get_signal_names()[1]: self.gui.monitors_select.Append(monitor_name) self.gui.canvas_2D.devices = self.command_manager.devices self.gui.canvas_3D.devices = self.command_manager.devices self.gui.update_cycles(completed_cycles) self.gui.switches_select.SetValue("") self.gui.switches_update_toggle() self.gui.monitors_select.SetValue("") self.gui.monitors_update_toggle() self.gui.log_text(_("Load file ") + self.path) self.gui.path = self.path self.gui.load_file_text_box.SetValue(self.path.split('/')[-1]) self.gui.canvas.render() return self.command_manager.NO_ERROR, None
for name in dir(): if not name.startswith('_'): del globals()[name] from pygame import mixer from time import sleep from scanner import Scanner mixer.init() mixer.music.load('F:\car_alarm_short.mp3') sample_rate = 2.048e6 gain = 49.6 scn = Scanner(sample_rate, gain) center_freq = 433.9e6 thresh = 7.0 print("100") #while True: # scn.start_monitor_psd_until(center_freq,thresh,monit="MEAN") # print('apertado!') while True: scn.start_monitor_psd(center_freq, 256, 10, monit="MEAN") print('apertado!') #mixer.music.play() sleep(1) print("END")
def __init__(self, fileName): self.scanner = Scanner(fileName) self.tk = self.scanner.GetNextToken()
import sys from scanner import Scanner from parser import Parser from simulator import Simulator def usage(): sys.stderr.write('Usage: Pascal filename\n') sys.exit(1) if __name__ == '__main__': if len(sys.argv) != 2: usage() filename = sys.argv[1] # Initialize scanner scanner = Scanner(1, 1, '', '', [], [], False, False, False, False) # Pass in file name, return list of tokens tokens = scanner.scan(filename) tokens.append(('EOF', 0, 0, 0)) # Initialize parser parser = Parser(tokens, 0) # Return the AST using tokens ast = parser.parse() simulator = Simulator(ast['decorated_nodes'], ast['symtable'] ) instructions = [] for inst in ast['decorated_nodes']: instructions.append( [inst['instruction'], inst['value']] ) print "\n" print "[Simulator]: Generated instructions for stack machine" print "\n"
def __init__(self): self.scanner = Scanner() self.scanner.build() self.errors = False
def __init__(self): self.lexer = Scanner() self.parser = yacc.yacc(module=self)
def evaluate(self, sourceStr): self._evaluator = PFEvaluator(Scanner(sourceStr)) value = self._evaluator.evaluate() return value
'detection yields high rate of false positives ' '(nearly 20% for scans performed with SSF<2); results should be ' 'interpreted with caution.') LIFE_DESCRIPTION = ( 'Lower sensitivity scans detects thermal activity patterns consistent with ' 'Chifoilisk\'s "Universal Guidelines For the Detection of "Animal" Life" ' '(X972). Higher sensitivity scans (exceeding SSF=2) apply the more ' 'resource-intensive approach outlined by Mitis (X974), yielding a 65% ' 'increase in the detection of non-"animal" life.') SCANNERS = [ Scanner('Water', WATER_DESCRIPTION, [ [ 'non-sensitive item 1', 'non-sensitive item 2', 'non-sensitive item 3' ], ['sensitive item 1', 'sensitive item 2', 'sensitive item 3'], ], SCAN_SECONDS), Scanner('Fuel', FUEL_DESCRIPTION, [ [ 'non-sensitive item 1', 'non-sensitive item 2', 'non-sensitive item 3' ], ['sensitive item 1', 'sensitive item 2', 'sensitive item 3'], ], SCAN_SECONDS), Scanner('Life', LIFE_DESCRIPTION, [ [ 'non-sensitive item 1', 'non-sensitive item 2', 'non-sensitive item 3' ],
def validate(self, input_file): scanner = Scanner(input_file) scanner.print_file() parser = Parser(scanner) parser.start()
def Scan(self, filename): result = Scanner(filename, self.ruleBuilder, self.sgrep_helper).Scan() return result
def test_peek_past_whitespace(self): '''Find literal past whitespace.''' s = Scanner(' ...= ') self.assertTrue(s.peek().is_ellipsis(), 'whitespace before ...')
""" "OR" print function remaining in type_checker """ import sys import os from flr_token import Token, TokenType from scanner import Scanner from error import LexicalError, ParseError, SemanticError from flr_parser import Parser from type_checker import TypeChecker program = """ program factors( n : integer ); begin return if n < 1 then if n < 5 then 5 else 10 else 1 end. """ scanner = Scanner(program) parser = Parser(scanner) ast = parser.parse() print("AST\n", ast, "\n\n\n") t_checker = TypeChecker(ast) t_checker.type_check() t_checker.pretty_print()
def test_parse_range_fails_on_upper_bound(self): '''Fail on an invalid range: bad upper bound.''' with self.assertRaises(ParseError) as context: s = Scanner('1...Fizz') p = Parser(s) fb_range = p.parse_range()
def test_fulladder_semantic(request, names, devices, network, monitors): """Testing error-less file doesn't throw errors""" sc = Scanner(fulladderpath, names) parser = Parser(names, devices, network, monitors, sc) assert parser.parse_network() == True
def test_literal_tokens_with_whitespace(self): '''Find two literals inside whitespace.''' s = Scanner(' ...= ') self.assertTrue(s.next_token().is_ellipsis()) self.assertTrue(s.next_token().is_equals()) self.assertTrue(s.next_token().is_eof())
import pytest from scanner import Scanner, tokens s = Scanner() def test_clean(): s.sentence = 'A and B' s.buffer = 'and' s.tokens = [['A', tokens.ID]] s.clean() assert s.buffer == '' assert s.sentence == '' assert s.tokens == [] def test_add_buffer_to_tokens(): s.clean() s.buffer = 'and' s._Scanner__add_buffer_to_tokens(tokens.OPERATOR) assert s.tokens == [['and', tokens.OPERATOR]] def test_add_to_tokens(): s.clean() token = ['A1', tokens.OPERATOR]
def test_parse_assignment_fails_on_value(self): '''Fail on an invalid range: bad upper bound.''' with self.assertRaises(ParseError) as context: s = Scanner('buzz=...') p = Parser(s) fb_range = p.parse_assignment()
def __init__(self): super().__init__() self.version = '1.0.2' self.icon = self.processIcon(app_icon) # Add window icon self.setWindowIcon(self.icon) self.setupUi(self) self.setStyleSheet(load_stylesheet()) # Main Props self.scanner = Scanner() self.killer = Killer() # Settings props self.minimize = True self.remember = False self.from_tray = False # We send elmocut to the settings window self.settings_window = Settings(self, self.icon) self.about_window = About(self, self.icon) self.applySettings() # Threading self.scan_thread = ScanThread() self.scan_thread.thread_finished.connect(self.ScanThread_Reciever) self.scan_thread.progress.connect(self.pgbar.setValue) # Connect buttons self.buttons = [ (self.btnScanEasy, self.scanEasy, scan_easy_icon, 'Arping Scan'), (self.btnScanHard, self.scanHard, scan_hard_icon, 'Pinging Scan'), (self.btnKill, self.kill, kill_icon, 'Kill selected device'), (self.btnUnkill, self.unkill, unkill_icon, 'Un-kill selected device'), (self.btnKillAll, self.killAll, killall_icon, 'Kill all devices'), (self.btnUnkillAll, self.unkillAll, unkillall_icon, 'Un-kill all devices'), (self.btnSettings, self.openSettings, settings_icon, 'View elmoCut settings'), (self.btnAbout, self.openAbout, about_icon, 'About elmoCut') ] for btn, btn_func, btn_icon, btn_tip in self.buttons: btn.setToolTip(btn_tip) btn.clicked.connect(btn_func) btn.setIcon(self.processIcon(btn_icon)) self.pgbar.setVisible(False) # Table Widget self.tableScan.itemClicked.connect(self.deviceClicked) self.tableScan.cellClicked.connect(self.cellClicked) self.tableScan.setColumnCount(4) self.tableScan.verticalHeader().setVisible(False) self.tableScan.setHorizontalHeaderLabels( ['IP Address', 'MAC Address', 'Vendor', 'Type']) ''' System tray icon and it's tray menu ''' show_option = QAction('Show', self) hide_option = QAction('Hide', self) quit_option = QAction('Quit', self) kill_option = QAction(self.processIcon(kill_icon), '&Kill All', self) unkill_option = QAction(self.processIcon(unkill_icon), '&Unkill All', self) show_option.triggered.connect(self.show) hide_option.triggered.connect(self.hide_all) quit_option.triggered.connect(self.quit_all) kill_option.triggered.connect(self.killAll) unkill_option.triggered.connect(self.unkillAll) tray_menu = QMenu() tray_menu.addAction(show_option) tray_menu.addAction(hide_option) tray_menu.addSeparator() tray_menu.addAction(kill_option) tray_menu.addAction(unkill_option) tray_menu.addSeparator() tray_menu.addAction(quit_option) self.tray_icon = QSystemTrayIcon(self) self.tray_icon.setIcon(self.icon) self.tray_icon.setToolTip('elmoCut') self.tray_icon.setContextMenu(tray_menu) self.tray_icon.show() self.tray_icon.activated.connect(self.tray_clicked)