def test() : cl = CommandLine(['poide','KUUU','-fhw','88888','45','1','7']) cl.parse() print cl.get_usage() configuration = Configuration() configuration.show()
def __init__(self, interface=None, channel=None, encryption=None,\ wps=False, target_bssid=None, output_file_prefix='airodump',\ ivs_only=False, skip_wash=False): ''' Sets up airodump arguments, doesn't start process yet ''' Configuration.initialize() if interface == None: interface = Configuration.interface if interface == None: raise Exception("Wireless interface must be defined (-i)") self.interface = interface self.targets = [] if channel == None: channel = Configuration.target_channel self.channel = channel self.five_ghz = Configuration.five_ghz self.encryption = encryption self.wps = wps self.target_bssid = target_bssid self.output_file_prefix = output_file_prefix self.ivs_only = ivs_only self.skip_wash = skip_wash # For tracking decloaked APs (previously were hidden) self.decloaking = False self.decloaked_targets = [] self.decloaked_times = {} # Map of BSSID(str) -> epoch(int) of last deauth
def test_setAttr_wrongType(self): c = Configuration(self.stringParametersConfig()) try: c.ConfigParam1 = 1 self.fail("Exception expected") except TypeError, e: self.assertEquals("str value expected, got int", e.args[0])
def __init__(self, interface=None, channel=None, encryption=None,\ wps=False, target_bssid=None, output_file_prefix='airodump',\ ivs_only=False): ''' Sets up airodump arguments, doesn't start process yet ''' Configuration.initialize() if interface == None: interface = Configuration.interface if interface == None: raise Exception("Wireless interface must be defined (-i)") self.interface = interface self.targets = [] if channel == None: channel = Configuration.target_channel self.channel = channel self.encryption = encryption self.wps = wps self.target_bssid = target_bssid self.output_file_prefix = output_file_prefix self.ivs_only = ivs_only
def test_setAttr_wrongName(self): c = Configuration(self.stringParametersConfig()) try: c.WrongParam1 = "ParamValue" self.fail("Exception expected") except AttributeError, e: self.assertEquals("WrongParam1", e.args[0])
def setUp(self): """ Check for at least one active Celery worker else skip the test. @param self Object reference. """ self.__inspection = inspect() try: active_nodes = self.__inspection.active() except Exception: # pylint:disable = W0703 unittest.TestCase.skipTest(self, "Skip - RabbitMQ seems to be down") if (active_nodes == None): unittest.TestCase.skipTest(self, "Skip - No active Celery workers") # Get the current MAUS version. configuration = Configuration() self.config_doc = configuration.getConfigJSON() config_dictionary = json.loads(self.config_doc) self.__version = config_dictionary["maus_version"] # Reset the worker. Invoke twice in case the first attempt # fails due to mess left by previous test. self.reset_worker() self.reset_worker() if maus_cpp.globals.has_instance(): maus_cpp.globals.death() maus_cpp.globals.birth(self.config_doc)
def main(): configuration = Configuration(); configuration.mRobotArm.move( math.pi/3, -math.pi/5 ); # initialize the pygame module pygame.init() # load and set the logo #logo = pygame.image.load("logo32x32.png") #pygame.display.set_icon(logo) pygame.display.set_caption("minimal program") # create a surface on screen that has the size of 240 x 180 screen = pygame.display.set_mode((1366,768)) white = (255,255,255) # define a variable to control the main loop running = True screen.fill(white) # main loop while running: # event handling, gets all event from the eventqueue for event in pygame.event.get(): # only do something if the event is of type QUIT if event.type == pygame.QUIT: # change the value to False, to exit the main loop running = False elif event.type == pygame.KEYDOWN: pass configuration.render( screen ); pygame.display.flip()
def __init__(self,inifile,ini_section,ini_options): self.ini_section = ini_section self.inifile = inifile self.ini_options = ini_options Configuration.__init__(self,inifile) self.validate_section(self.ini_section,self.ini_options) self.use_gridmanager = False self.userjob_classads_required = False self.daemon_list = None self.schedd_name_suffix = "jobs" self.client_only_install = False # VOFrontend is only one which will reset self.condor_version = None self.condor_first_dir = None #--- secondary schedd files -- ## self.schedd_setup_file = "new_schedd_setup.sh" ## self.schedd_init_file = "init_schedd.sh" ## self.schedd_startup_file = "start_master_schedd.sh" self.schedd_initd_function = "return # no secondary schedds" #--- condor config data -- self.condor_config_data = { "00_gwms_general" : "", "01_gwms_collectors" : "", "02_gwms_schedds" : "", "03_gwms_local" : "", "11_gwms_secondary_collectors" : "", } #-- classes used --- self.certs = None self.get_certs()
def test_defaults(self): """Check that we load configuration defaults correctly""" a_config = Configuration() maus_config = json.loads(a_config.getConfigJSON()) ## test setup maus_root_dir = os.environ.get('MAUS_ROOT_DIR') self.assertNotEqual(maus_root_dir, None) config_dict = {} default_filename = \ '%s/src/common_py/ConfigurationDefaults.py' % maus_root_dir exec(open(default_filename,'r').read(), globals(), #pylint:disable=W0122 config_dict) #pylint:disable=W0122 # compare; note we are allowed additional entries in maus_config that # are hard coded (e.g. version number) exclusions = [ "maus_version", # changed at runtime, tested below "reconstruction_geometry_filename", # changed at runtime, tested below "os", # module needed to use environment variables "__doc__", # docstring from ConfigurationDefaults ] for key in config_dict.keys(): if key not in exclusions: self.assertEqual(config_dict[key], maus_config[key])
def test_new_value(self): """Test that we can create a configuration value from an input file""" string_file = io.StringIO(u"test = 4") config = Configuration() value = config.getConfigJSON(string_file) json_value = json.loads(value) self.assertEqual(json_value["test"], 4)
def test_code_full(self): c = Configuration(self.stringParametersConfig()) c['ConfigParam1'] = 'newvalue' self.assertEquals( "network.Processing1['ConfigParam3'] = 'Param3'\n" "network.Processing1['ConfigParam2'] = 'Param2'\n" "network.Processing1['ConfigParam1'] = 'newvalue'\n" , c.code("Processing1", fullConfig = True))
def uiconf(key): conf = confs.get(key, None) if conf is None: from Configuration import Configuration conf = Configuration() conf.CONF_FILE = __default_ui_config__ confs[key] = conf return conf
def find_files(self, endswith=None): ''' Finds all files in the temp directory that start with the output_file_prefix ''' result = [] for fil in os.listdir(Configuration.temp()): if fil.startswith(self.output_file_prefix): if not endswith or fil.endswith(endswith): result.append(Configuration.temp() + fil) return result
def __init__(self): try: configuration = Configuration() self.session = configuration.getConfig() print 'hello' maxHotelId = self.session.query(func.max(TaHotelReview1.id)).first() print maxHotelId except Exception as ex: print ex
def edit_racestart(cls, previous_file): """ Updates the race start parameters in the configuration file and builds a test video. """ try: print( "Editing configuration file {}".format( previous_file)) config = Configuration(previous_file) config.modify_racestart() print( "Creating low-quality video as {}".format( config.output_video)) print( "If video trimming needs to be adjusted, run the ", "Project CARS Replay Enhancer with the `-t` option.") print("\n") print( "To synchronize telemetry with video, run the ", "Project CARS Replay Enhancer with the `-r` option.") print( "Set the synchronization offset to the value shown ", "on the Timer when the viewed car crosses the start ", "finish line to begin lap 2.") try: replay = cls(config.config_file) except ValueError as error: print("Invalid JSON in configuration file: {}".format( error)) else: start_video = replay.build_default_video(False) end_video = replay.build_default_video(False) start_video = start_video.set_duration( start_video.duration).subclip(0, 185) if replay.show_champion: end_video = end_video.set_duration( end_video.duration).subclip( end_video.duration-120) else: end_video = end_video.set_duration( end_video.duration).subclip( end_video.duration-100) output = mpy.concatenate_videoclips( [start_video, end_video]) output.write_videofile( replay.output_video, fps=10, preset='superfast') except KeyboardInterrupt: raise
def test_overwrite_value(self): """Test that we can overwrite configuration value from an input file""" string_file = io.StringIO\ (u"simulation_geometry_filename = 'Stage4Something.dat'") conf = Configuration() value = conf.getConfigJSON(string_file) json_value = json.loads(value) self.assertEqual(json_value["simulation_geometry_filename"], 'Stage4Something.dat')
def new_configuration(cls): """ Creates a new configuration file and builds a test video. """ try: print("No configuration file provided.") print("Creating new configuration file.") config = Configuration() config.new_configuration() print("Creating low-quality video as {}".format( config.output_video)) print( "If video trimming needs to be adjusted, run the ", "Project CARS Replay Enhancer with the `-t` option.") print("\n") print( "To synchronize telemetry with video, run the ", "Project CARS Replay Enhancer with the `-r` option.") print( "Set the synchronization offset to the value shown " "on the Timer when the viewed car crosses the start ", "finish line to begin lap 2.") print( "Please wait. Telemetry being processed and ", "rendered. If this is the first time this data has ", "been used, it make take longer.") try: replay = cls(config.config_file) except ValueError as error: print("Invalid JSON in configuration file: {}".format( error)) else: start_video = replay.build_default_video(False) end_video = replay.build_default_video(False) start_video = start_video.set_duration( start_video.duration).subclip(0, 185) if replay.show_champion: end_video = end_video.set_duration( end_video.duration).subclip( end_video.duration-120) else: end_video = end_video.set_duration( end_video.duration).subclip( end_video.duration-100) output = mpy.concatenate_videoclips( [start_video, end_video]) output.write_videofile( replay.output_video, fps=10, preset='superfast') except KeyboardInterrupt: raise
def __init__(self,inifile,ini_section,ini_options): self.ini_section = ini_section self.inifile = inifile Configuration.__init__(self,self.inifile) self.validate_section(self.ini_section,ini_options) self.vdt = None self.javascriptrrd_dir = None self.flot_dir = None self.jquery_dir = None
def __init__(self,section,inifile): self.section = section Configuration.__init__(self,inifile) self.validate_section(self.section,valid_options) self.vdt_services = ["fetch-crl", "vdt-rotate-logs", "vdt-update-certs",] self.messagesDict = { "pacman_url" : self.pacman_url(), "pacman_urlfile" : self.pacman_urlfile(), "pacman_location" : self.pacman_location(), "pacman_parent" : self.pacman_parent(), "pacman_tarball" : self.pacman_tarball(), "vdt_location" : self.vdt_location(), }
def test_get_cabling(self): #pylint: disable = R0201 """Test we can download cabling for proper device, date, run""" # load the configuration and get the daq cabling date parameter config = Configuration() lconfig = json.loads(config.getConfigJSON()) cablingdate = lconfig['DAQ_cabling_date'] # get cabling for default config date # check we can get cabling for valid detector dev = "DAQ" gdc_.GetCabling().get_cabling_for_date(dev, cablingdate) # check we can get cabling for valid det and specified date cablingdate = '2012-05-27 12:00:00.0' gdc_.GetCabling().get_cabling_for_date(dev, cablingdate)
def parse_sentence(self, gold): self.current_sent = gold self.correct_ras = gold.rightarcs self.correct_las = gold.leftarcs self.found_rarcs = set() self.found_larcs = set() # Start configuration: Root on stack, all tokens on buffer, empty arc set c = Configuration([gold.tokenlist[0]], gold.tokenlist[1:]) # While buffer is not empty while len(c.buffer) > 0: # If it's possible to form a leftarc with the current configuration and the goldstandard # Then build this leftarc and extract the features if len(c.stack) > 0 and self.canleftarc(c): new_feat = self.extract_feats(c, self.current_sent) self.extracted_feats.append(("LA", new_feat)) c = self.doleftarc(c) # Else if it's possible to form a rightarc with the current configuration and the goldstandard # Then build this rightarc and extract the features elif len(c.stack) > 0 and self.canrightarc(c, gold): new_feat = self.extract_feats(c, self.current_sent) self.extracted_feats.append(("RA", new_feat)) c = self.dorightarc(c) # Else perform a shift and extract the features else: new_feat = self.extract_feats(c, self.current_sent) self.extracted_feats.append(("SH", new_feat)) c = self.shift(c) return 1
def __init__(self,parent,title): wx.Frame.__init__(self,parent,title=title,size=(1024, 800), style = wx.DEFAULT_FRAME_STYLE | wx.MAXIMIZE) #style=wx.MINIMIZE_BOX|wx.SYSTEM_MENU| wx.CAPTION|wx.CLOSE_BOX|wx.CLIP_CHILDREN) self.spMain = wx.SplitterWindow(self) self.spSTL = wx.SplitterWindow(self.spMain) self.renderPanel = RenderPanel(self.spSTL) self.infoPanel = InfoPanel(self.spSTL, "green") self.spSTL.SplitHorizontally(self.renderPanel, self.infoPanel) # percent ocupation of SLT preview self.spSTL.SetSashGravity(0.7) self.filePanel = wx.Panel(self.spMain,style=wx.SUNKEN_BORDER) self.spMain.SplitVertically(self.filePanel,self.spSTL, 400) self.AddStatusBar() self.AddToolBar() self.AddFileTree() self.infogrid = InfoGrid(self.infoPanel) # open config file if exist self.conf = Configuration() self.conf.load() self.conf.wxParent = self lastPath = self.conf.GetlastSelPath() if lastPath: self.fileTree.DirExplorer(lastPath) self.slic3r = Slic3r() self.lastGCodeGen = ""
def forge_packet(xor_file, bssid, station_mac): ''' Forges packet from .xor file ''' forged_file = 'forged.cap' cmd = [ 'packetforge-ng', '-0', '-a', bssid, # Target MAC '-h', station_mac, # Client MAC '-k', '192.168.1.2', # Dest IP '-l', '192.168.1.100', # Source IP '-y', xor_file, # Read PRNG from .xor file '-w', forged_file, # Write to Configuration.interface ] cmd = '"%s"' % '" "'.join(cmd) (out, err) = Process.call(cmd, cwd=Configuration.temp(), shell=True) if out.strip() == 'Wrote packet to: %s' % forged_file: return forged_file else: from Color import Color Color.pl('{!} {R}failed to forge packet from .xor file{W}') Color.pl('output:\n"%s"' % out) return None
def main(): # Parse arguments. from optparse import OptionParser usagestring = "usage: %prog configFile outputPrefix webIDLFile" o = OptionParser(usage=usagestring) o.add_option("--verbose-errors", action='store_true', default=False, help="When an error happens, display the Python traceback.") (options, args) = o.parse_args() if len(args) != 3: o.error(usagestring) configFile = os.path.normpath(args[0]) outputPrefix = args[1] webIDLFile = os.path.normpath(args[2]) # Load the parsing results f = open('ParserResults.pkl', 'rb') parserData = cPickle.load(f) f.close() # Create the configuration data. config = Configuration(configFile, parserData) # Generate the prototype classes. generate_binding_rs(config, outputPrefix, webIDLFile)
def __init__(self, target, attack_type, client_mac=None, replay_file=None): ''' Starts aireplay process. Args: target - Instance of Target object, AP to attack. attack_type - int, str, or WEPAttackType instance. client_mac - MAC address of an associated client. ''' cmd = Aireplay.get_aireplay_command(target, attack_type, client_mac=client_mac, replay_file=replay_file) # TODO: set 'stdout' when creating process to store output to file. # AttackWEP will read file to get status of attack. # E.g., chopchop will regex "(\d+)% done" to get percent complete. ''' from subprocess import PIPE sout = PIPE if '--chopchop' in cmd: sout = open(Configuration.temp('chopchop'), 'w') ''' self.pid = Process(cmd, devnull=False, cwd=Configuration.temp())
def test_override_shallow_var(self): config = Configuration.load(self.target_config) config.setPath("a", 2) self.assertTrue( config.config == { "a": 2, "b": { "c": 2 }, "d": "iets" }, 'shallow int assignment must result in correct configuration') config.setPath("d", "nogiets") self.assertTrue( config.config == { "a": 2, "b": { "c": 2 }, "d": "nogiets" }, 'shallow string assignment must result in correct configuration')
def test_getAttr_wrongName(self): c = Configuration(self.stringParametersConfig()) try: param = c.WrongParam1 self.fail("Exception expected") except AttributeError, e: self.assertEquals("WrongParam1", e.args[0])
def solve(self, initial_configuration: Configuration) -> int: """Find the best solution for the configuration <initial_configuration> and return the cost of the solution.""" # configs contains all seen configuration. (hash_code: config) configs = dict() # PriorityQueue of configurations to analyse (cost, config) open_list = PriorityQueue() open_list.put( (initial_configuration.get_cost(), initial_configuration)) while not open_list.empty(): (cost, configuration) = open_list.get() print(cost) # if the configuration <configuration> has already been seen if configs.get(configuration.get_hash_code(), None) != None: continue configs[configuration.get_hash_code()] = configuration if configuration.is_final(): return cost for config in self.__get_possible_next_configurations( configuration): open_list.put((config.get_cost(), config)) return -1
def test_setItem_wrongType(self): c = Configuration(self.stringParametersConfig()) try: c["ConfigParam1"] = 1 self.fail("Exception expected") except TypeError, e: self.assertEquals("str value expected, got int", e.args[0])
def test_setitem_wrongName(self): c = Configuration(self.stringParametersConfig()) try: c["WrongParam1"] = "value" self.fail("Exception expected") except KeyError, e: self.assertEquals("WrongParam1", e.args[0])
def update(self, jsn: dict = None, originator: str = None) -> Tuple[bool, int, str]: if jsn is not None: if self.tpe not in jsn: Logging.logWarn("Update types don't match") return False, C.rcContentsUnacceptable, 'resource types mismatch' # validate the attributes if not (result := CSE.validator.validateAttributes( jsn, self.tpe, self.attributePolicies, create=False))[0]: return result j = jsn[ self.tpe] # get structure under the resource type specifier for key in j: # Leave out some attributes if key in ['ct', 'lt', 'pi', 'ri', 'rn', 'st', 'ty']: continue value = j[key] # Special handling for et when deleted: set a new et if key == 'et' and value is None: self['et'] = Utils.getResourceDate( Configuration.get('cse.expirationDelta')) continue self[key] = value # copy new value
def perform_action(self, action, rule): if action == True: config = Configuration() folder = config.actionDir #get action from rule for x in rule: match = re.findall('ACTION', x) if match: rule_action = rule.get(x) print 'Attack Detected!' actions = rule_action.split(',') for action in actions: action = action.replace("'", "").replace(" ", '') action_target = folder + action action_target = action_target.replace(" ", "").replace("'", '') if os.path.exists(action_target) is True: #print 'The action rule is : ', action_target subprocess.call( [sys.executable, action_target, rule['DESCRIPTION =']]) else: print 'The action rule is not valid. Please use the correct path of the file.' else: print 'No Attack detected...'
def startApps() -> None: global appsStarted, aeStatistics, aeCSENode if not Configuration.get('cse.enableApplications'): return time.sleep(Configuration.get('cse.applicationsStartupDelay')) Logging.log('Starting Apps') appsStarted = True if Configuration.get('app.csenode.enable'): aeCSENode = CSENode() if not appsStarted: # shutdown? return if Configuration.get('app.statistics.enable'): aeStatistics = AEStatistics()
def __createSectors(self, sectorsData): cfg = Configuration() self.sectorsP = [] self.sectorNames = [] #@todo: comprobar que no se incumplen las restricciones de emisiones i = 0 depentedSectors = [] for sectorID in sectorsData: self.sectorNames.append(sectorID) if sectorID in sectorsData: if (sectorsData[sectorID]["type"] == "Dependent"): depentedSectors.append(i) self.sectorsP.append( self.__newSector(sectorID, sectorsData[sectorID])) #else: # self.sectorsP.append(self.__newNoneDataSector(self.ef[i], sectorID)) i += 1 for i in depentedSectors: assSectorsStr = sectorsData[ self.sectorsP[i].name]['data']['assSector'] assSectorsList = assSectorsStr.split('/') print(assSectorsList) for assSector in assSectorsList: assSectorN = self.sectorNames.index(assSector) self.sectorsP[i].assSectorObjs.append( self.sectorsP[assSectorN])
def __init__(self, date): try: self._date = date self._data_file_base_path = Configuration.get_option( 'global', 'DataFileBasePath') except: raise
def get_xor(): ''' Finds the last .xor file in the directory ''' xor = None for fil in os.listdir(Configuration.temp()): if fil.startswith('replay_') and fil.endswith('.xor'): xor = fil return xor
def instance(cls, client_address, hostname, port): key = "%s:%s:%d" % (client_address, hostname, port) if not key in cls.__singleton_dict: with cls.__singleton_lock: if not key in cls.__singleton_dict: cls.__singleton_dict[key] = cls(client_address, hostname, port, Configuration().testcase_list) return cls.__singleton_dict[key]
def get_usage(self) : """Return a usage string created from configuration.""" configuration = Configuration() usage = '%s [OPTION]...' % (os.path.basename(self._commandline[0]),) for key in schema_default : if key in schema : if 'cmdlinename' in schema[key] : usage += ' [%s]' % (schema[key]['cmdlinename'] ,) else : # strange error pass else : # strange error pass usage += '\n' usage += 'Get informations about a directory.\n' usage += '\n' usage += 'Options may be :\n' for key in configuration : if ('minialias' in schema[key]) and (schema[key]['minialias']!='') : minialiasstring = '-%s,' % schema[key]['minialias'] else : minialiasstring = ' ' if schema[key]['needvalue'] : partline = ' %s --%s=%s' % (minialiasstring,key,schema[key]['cmdlinename']) else : partline = ' %s --%s' % (minialiasstring,key,) partline += ' '*(30-len(partline)) partline += '%s\n' % (schema[key]['doc']['en'],) usage += partline str # usage += '\n' return usage
def generate_random_individual( num_variables, full, initial_level=1, max_tree_level=Configuration.get_max_tree_level()): root = Tree_Operations.get_random_node(num_variables, initial_level) max_depht = 0 stack = [root] while len(stack) > 0: node = stack.pop() if node.level > max_depht: max_depht = node.level if node.type == NodeTypes.OPERATION_NODE_TYPE: if full: node.left = Tree_Operations.get_random_full_node( num_variables, node.level + 1) else: node.left = Tree_Operations.get_random_node( num_variables, node.level + 1) stack.append(node.left) if node.operation.get_num_op() == 2: if full: node.right = Tree_Operations.get_random_full_node( num_variables, node.level + 1) else: node.right = Tree_Operations.get_random_node( num_variables, node.level + 1) stack.append(node.right) if node.level + 1 > max_tree_level: continue root.max_depht = max_depht return root
def main(): # Parse arguments. from optparse import OptionParser usagestring = "usage: %prog [header|cpp] configFile outputPrefix srcPrefix webIDLFile" o = OptionParser(usage=usagestring) o.add_option("--verbose-errors", action='store_true', default=False, help="When an error happens, display the Python traceback.") (options, args) = o.parse_args() if len(args) != 5 or (args[0] != "header" and args[0] != "cpp"): o.error(usagestring) buildTarget = args[0] configFile = os.path.normpath(args[1]) outputPrefix = args[2] srcPrefix = os.path.normpath(args[3]) webIDLFile = os.path.normpath(args[4]) # Load the parsing results f = open('ParserResults.pkl', 'rb') parserData = cPickle.load(f) f.close() # Create the configuration data. config = Configuration(configFile, parserData) # Generate the prototype classes. if buildTarget == "header": generate_binding_header(config, outputPrefix, srcPrefix, webIDLFile) elif buildTarget == "cpp": generate_binding_cpp(config, outputPrefix, srcPrefix, webIDLFile) else: assert False # not reached
def __enter__(self): ''' Setting things up for this context. Called at start of 'with Airodump(...) as x:' Actually starts the airodump process. ''' self.delete_airodump_temp_files() self.csv_file_prefix = Configuration.temp() + self.output_file_prefix # Build the command command = [ 'airodump-ng', self.interface, '-a', # Only show associated clients '-w', self.csv_file_prefix # Output file prefix ] if self.channel: command.extend(['-c', str(self.channel)]) if self.encryption: command.extend(['--enc', self.encryption]) if self.wps: command.extend(['--wps']) if self.target_bssid: command.extend(['--bssid', self.target_bssid]) if self.ivs_only: command.extend(['--output-format', 'ivs,csv']) else: command.extend(['--output-format', 'pcap,csv']) # Start the process self.pid = Process(command, devnull=True) return self
def addFlexContainerInstance(self, originator: str) -> None: Logging.logDebug('Adding flexContainerInstance') dct: JSON = { 'rn': f'{self.rn}_{self.st:d}', } if self.lbl is not None: dct['lbl'] = self.lbl for attr in self.dict: if attr not in self.ignoreAttributes: dct[attr] = self[attr] continue # special for at attribute. It might contain additional id's when it # is announced. Those we don't want to copy. if attr == 'at': dct['at'] = [x for x in self['at'] if x.count('/') == 1 ] # Only copy single csi in at resource = Factory.resourceFromDict(resDict={ self.tpe: dct }, pi=self.ri, ty=T.FCI).resource CSE.dispatcher.createResource(resource, originator=originator) resource['cs'] = self.cs # Check for mia handling if self.mia is not None: # Take either mia or the maxExpirationDelta, whatever is smaller maxEt = Utils.getResourceDate(self.mia if self.mia <= ( med := Configuration.get('cse.maxExpirationDelta')) else med) # Only replace the childresource's et if it is greater than the calculated maxEt if resource.et > maxEt: resource.setAttribute('et', maxEt)
def main(): # disclaimer.print_disclaimer() # get the full path of the config file provided as system argument iniFileName = os.path.abspath(sys.argv[1]) debug_mode = False if len(sys.argv) > 2: if (sys.argv[2] == "debug"): debug_mode = True configuration = Configuration(iniFileName=iniFileName, debug_mode=debug_mode) currTimeStep = ModelTime() initial_state = None currTimeStep.getStartEndTimeSteps(configuration.globalOptions['startTime'], configuration.globalOptions['endTime']) currTimeStep.update(1) logger.info('Transient simulation run has started') deterministic_runner = DeterministicRunner( # FAO66_behaviour, WaterBalanceModel, configuration, currTimeStep, variable_list, initial_state) dynamic_framework = DynamicFramework(deterministic_runner, currTimeStep.nrOfTimeSteps) dynamic_framework.setQuiet(True) dynamic_framework.run()
class InputCppDAQDataTestCase(unittest.TestCase): # pylint: disable = R0904 """Tests for InputCppDAQData""" @classmethod def setUpClass(self): # pylint: disable = C0103, C0202 """Sets a mapper and configuration""" if not os.environ.get("MAUS_ROOT_DIR"): raise Exception('InitializeFail', 'MAUS_ROOT_DIR unset!') # Set our data path & filename # It would be nicer to test with a smaller data file! self._datapath = '%s/src/input/InputCppDAQData' % \ os.environ.get("MAUS_ROOT_DIR") self._datafile = '05466' self._c = Configuration() self._mapper = InputCppDAQData() def test_init(self): # pylint: disable = W0201 """Check birth with default configuration""" self._mapper.birth( self._c.getConfigJSON() ) self._mapper.death() return @classmethod def tearDownClass(self): # pylint: disable = C0103,C0202 """Check that we can death() MapCppTOFDigits""" pass
def setUpClass(self): # pylint: disable = C0103, C0202 """Sets a mapper and configuration""" print "SETUPCLASS" if not os.environ.get("MAUS_ROOT_DIR"): raise Exception('InitializeFail', 'MAUS_ROOT_DIR unset!') # Set our data path & filename # It would be nicer to test with a smaller data file! self._datapath = '%s/src/input/InputCppDAQData' % \ os.environ.get("MAUS_ROOT_DIR") # setup data files for StepI and StepIV # set the checksum and event count accordingly self._datafile = '05466' self._numevents = 12 self._checksum = 'f226ea9b823996f653a73fd9e969b2f2' # self._checksum = 'f699f0d81aee1f64a2f1cec7968b9289' # note that the StepIV file is garbage data as of now # this will have to be updated - DR, March 13, 2015 if os.environ['MAUS_UNPACKER_VERSION'] == "StepIV": self._datafile = '06008' self._numevents = 22 self._checksum = '155b3b02e36ea80c0b0dcfad3be7027d' config = Configuration().getConfigJSON() config_json = json.loads(config) config_json["daq_data_path"] = self._datapath config_json["daq_data_file"] = self._datafile config_json["DAQ_cabling_by"] = "date" self._config = json.dumps(config_json) self.mapper = None
def main(): # Parse arguments. from optparse import OptionParser usagestring = "usage: %prog configFile interfaceName" o = OptionParser(usage=usagestring) o.add_option("--verbose-errors", action='store_true', default=False, help="When an error happens, display the Python traceback.") (options, args) = o.parse_args() if len(args) != 2: o.error(usagestring) configFile = os.path.normpath(args[0]) interfaceName = args[1] # Load the parsing results f = open('ParserResults.pkl', 'rb') parserData = cPickle.load(f) f.close() # Create the configuration data. config = Configuration(configFile, parserData) # Generate the example class. generate_interface_example(config, interfaceName)
def set_locked(self): for i, label in enumerate(self.locked): self.locked[i].setPixmap( QtGui.QPixmap( os.path.join(Configuration().ICONS, "lock_icon_closed_64.png"))) self.locked[i].setGeometry(0, 0, 64, 64)
def fakeauth(target, timeout=5, num_attempts=3): ''' Tries a one-time fake-authenticate with a target AP. Params: target (py.Target): Instance of py.Target timeout (int): Time to wait for fakeuth to succeed. num_attempts (int): Number of fakeauth attempts to make. Returns: (bool): True if fakeauth succeeds, otherwise False ''' cmd = [ 'aireplay-ng', '-1', '0', # Fake auth, no delay '-a', target.bssid, '-T', str(num_attempts) ] if target.essid_known: cmd.extend(['-e', target.essid]) cmd.append(Configuration.interface) fakeauth_proc = Process(cmd, devnull=False, cwd=Configuration.temp()) timer = Timer(timeout) while fakeauth_proc.poll() is None and not timer.ended(): time.sleep(0.1) if fakeauth_proc.poll() is None or timer.ended(): fakeauth_proc.interrupt() return False output = fakeauth_proc.stdout() return 'association successful' in output.lower()
def openDB(self) -> None: # All databases/tables will use the smart query cache # TODO not compatible with TinyDB 4 yet? # TinyDB.table_class = SmartCacheTable if Configuration.get('db.inMemory'): Logging.log('DB in memory') self.dbResources = TinyDB(storage=MemoryStorage) self.dbIdentifiers = TinyDB(storage=MemoryStorage) self.dbSubscriptions = TinyDB(storage=MemoryStorage) self.dbStatistics = TinyDB(storage=MemoryStorage) self.dbAppData = TinyDB(storage=MemoryStorage) else: Logging.log('DB in file system') self.dbResources = TinyDB(self.path + '/resources.json') self.dbIdentifiers = TinyDB(self.path + '/identifiers.json') self.dbSubscriptions = TinyDB(self.path + '/subscriptions.json') self.dbStatistics = TinyDB(self.path + '/statistics.json') self.dbAppData = TinyDB(self.path + '/appdata.json') self.tabResources = self.dbResources.table('resources', cache_size=self.cacheSize) self.tabIdentifiers = self.dbIdentifiers.table( 'identifiers', cache_size=self.cacheSize) self.tabSubscriptions = self.dbSubscriptions.table( 'subsriptions', cache_size=self.cacheSize) self.tabStatistics = self.dbStatistics.table('statistics', cache_size=self.cacheSize) self.tabAppData = self.dbAppData.table('appdata', cache_size=self.cacheSize)
def main(conf_file): config = Configuration(conf_file) a = ActiveMonitor(config) a.do_probe() logger.info('Probing ended...') cli = JSONClient(config) cli.prepare_and_send()
def __init__(self, parent_win): GUILibraries.QDialog.__init__(self, parent_win) self.configuration = Configuration() self.setWindowTitle('About ' + self.configuration.application_name) self.parent_win = parent_win self.setWindowModality(GUILibraries.Qt.WindowModal) self.parent_win.setWindowTitle('About ' + self.configuration.application_name) singleMessage.version = self.configuration.getApplicationVersion() self.setWindowIcon(GUILibraries.QIcon(self.configuration.getLogoSignSmall())) self.AboutFixityLayout =GUILibraries.QVBoxLayout() self.widget = GUILibraries.QWidget(self) self.pgroup = GUILibraries.QGroupBox() self.detail_layout = GUILibraries.QVBoxLayout() self.description_btn = GUILibraries.QPushButton('Description') self.author_and_license_btn = GUILibraries.QPushButton('Author and License') self.contact_btn = GUILibraries.QPushButton('Contact') self.close_btn = GUILibraries.QPushButton('Close') self.about_layout =GUILibraries.QGroupBox() self.heading = GUILibraries.QTextEdit() self.content = GUILibraries.QTextEdit() self.heading.setReadOnly(True) self.content.setReadOnly(True) self.main = GUILibraries.QHBoxLayout()
def __init__(self): self._config = Configuration() self.players = PlayerConfiguration() self.burrows = BurrowsConfiguration() self.matrix = [[' ' for x in range(self._config.size_jungle)] for x in range(self._config.size_jungle)] self.children = [] self.update()
def setUp(self): """ Initialiser. setUp is called before each test function is called.""" self._reducer = ReducePyScalers() conf = Configuration() config_doc = json.loads(conf.getConfigJSON()) key = 'output_scalers_file_name' if ( key in config_doc ): self._output_file_name = config_doc[key] else: self._output_file_name = 'scalers.dat' # Test whether the configuration files were loaded correctly at birth success = self._reducer.birth(conf.getConfigJSON()) if not success: raise Exception('InitializeFail', 'Could not start worker')
def __init__(self, rootpath=None, outputfile=None, size=None, tree=None, configuration=None): self._configuration = configuration if self._configuration == None: self._configuration = Configuration() if rootpath == None and self._configuration.get_value("path") != "": rootpath = self._configuration.get_value("path") # Gruik Gruik : C:" -> C:\ Thanks Windows ! if rootpath and (len(rootpath) == 3) and (rootpath[2]) == '"': rootpath = rootpath[0:2] + "\\" if (rootpath == None) and (tree == None): rootpath = "." if rootpath != None: if os.path.supports_unicode_filenames: rootpath = unicode(rootpath) else: rootpath = str(rootpath) tree = FileTree(rootpath) tree.scan() self._rootpath = rootpath self._tree = tree filename = outputfile if filename == None: filename = self._configuration.get_value("outputfile") if filename == "": if os.path.isdir(rootpath): filename = os.path.join(rootpath, self._configuration.get_value("basename") + self.EXT) else: name = os.path.split(rootpath)[1] filename = name + "." + self._configuration.get_value("basename") + self.EXT self._filename = filename self._size = size
class Email: #This function sends an e-mail with the given message. config = Configuration() fromaddr = config.fromaddr toaddr = config.toaddr subject = 'WARNING: Error Detected!!' headers = [ "From: " + fromaddr, "Subject: " + subject, "To: " + toaddr, "MIME-Version: 1.0", "Content-Type: text/html" ] headers = "\r\n".join(headers) username = config.username password = config.password server = smtplib.SMTP(config.server) if username != "" and password != "": pass server.starttls() server.ehlo() server.login(username, password) else: pass server.sendmail(fromaddr, toaddr, headers + "\r\n\r\n" + sys.argv[1]) server.quit()
def simulator(): conf = Configuration('confjava.rmto') pools = dict() pools[0] = MotorUnitPool(conf, 'SOL') pools[1] = InterneuronPool(conf, 'RC', 'ext') Syn = SynapsesFactory(conf, pools) t = np.arange(0.0, conf.simDuration_ms, conf.timeStep_ms) tic = time.clock() for i in xrange(0, len(t)): # Corrent injected at the some of MNs for j in xrange(1, len(pools[0].iInjected), 2): pools[0].iInjected[j] = 10 pools[0].atualizeMotorUnitPool(t[i]) # MN pool pools[2].atualizePool(t[i]) # RC synaptic Noise pools[1].atualizeInterneuronPool(t[i]) # RC pool toc = time.clock() print str(toc - tic) + ' seconds' pools[0].listSpikes() plt.figure() plt.plot(pools[0].poolSomaSpikes[:, 0], pools[0].poolSomaSpikes[:, 1] + 1, '.') plt.figure() plt.plot(t, pools[0].Muscle.force, '-') plt.xlabel('t (ms)') plt.ylabel('Muscle Force (N)')
def config() : configuration = Configuration() for key in configuration : if configuration.need_configure(key) : doc = configuration.get_doc(key) strvalue = configuration.get_strvalue(key) print "%s ?[%s]" % (doc,strvalue) line = sys.stdin.readline().replace('\r','').replace('\n','') if line != '' : configuration.set_strvalue(key,line) configuration.save() print "The file %s has been updated. Press RETURN to continue." % (configuration.get_filename(),) sys.stdin.readline()
def test_recon_filename(self): """Check that the version is defined correctly""" # default should have them equal if reconstruction_geometry_filename is # empty string config = json.loads(Configuration().getConfigJSON()) string_file = io.StringIO\ (u"reconstruction_geometry_filename = ''\n"+\ u"simulation_geometry_filename = 'Test.dat'\n") self.assertEqual(config['simulation_geometry_filename'], config['reconstruction_geometry_filename']) # else should be different string_file = io.StringIO\ (u"reconstruction_geometry_filename = 'Test.dat'") conf = Configuration() value = json.loads(conf.getConfigJSON(string_file)) self.assertEqual(value['reconstruction_geometry_filename'], 'Test.dat')