def __init__(self): self.user = User() self.account = Account() self.employee = Employee() self.service = Service() self.utilities = Utilities() self.initAmt = 0
def __start__(self): function = self.function name = self.name inbox = self.inbox outbox = self.outbox copies = self.copies verbose = self.verbose # report if verbose: print '%s: Starting %i Copies' % (name, copies) sys.stdout.flush() # initialize services nodes = [] for i in range(copies): this_name = '%s - Node %i' % (name, i) service = Service(function, inbox, outbox, this_name, verbose) service.start() nodes.append(service) #: for each node # store self.nodes = nodes
def __init__(self): self._service = Service() self._sleepTime = 0.5 pygame.init() logo = pygame.image.load("Resources/logo32x32.png") pygame.display.set_icon(logo) pygame.display.set_caption("GA") screen = pygame.display.set_mode( (SQUARE_WIDTH * WIDTH, SQUARE_HEIGHT * HEIGHT)) screen.fill(WHITE) running = True path = [] while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.KEYDOWN: if pygame.key.get_pressed()[pygame.K_SPACE]: start = time.time() path = self._service.solver() print(time.time() - start) print(len(path)) print(len(set(path))) image = self._service.mapWithPath(path) image = self._service.mapWithDrone(image) image = self._service.mapWithSensors(image) screen.blit(image, (0, 0)) pygame.display.flip() pygame.quit()
def get(self): try: service = session.query(ServiceModel, Client, Product).join( Client, Product).filter(ServiceModel.id == self._service._id).first() if service is None: return None else: c = ClientClass(service.Client.name, service.Client.cpf, service.Client.segment) c._id = service.Client.id p = ProductClass(service.Product.name, service.Product.description, service.Product.image) p._id = service.Product.id s = ServiceClass(service.Service.request_date, service.Service.cancel_date) s._id = service.Service.id s._client = c s._product = p return s except Exception as e: print "Erro: ", e
def emptyServices(self, drivers, vehicles): """Creates an accessory ServicesList to be used in the first working period, after attribution of vehicles to the available drivers. Requires: drivers and vehicles are collections of drivers and vehicles, respectively. Ensures: A ServicesList regarding the working period prior to the first of the day (ie 0709). This will be useful if one considers the first working period of the day (0911), where vehicles are not attributed to drivers and no service List is available. Thus, vehicles, lexicographic sorted by plate, are attributed to drivers according to their entry hour (and name, in case of tie). All the service-related information is set as a "no service" (_no_client_, _no_circuit_, service kms = 0), Arrival and Departure hours are set as the Driver's entry hour and being ready to work, drivers' status is standby, of course! """ # sort drivers for the 1st period (0911) according to Drivers' EntryHour # and in case of tie, Drivers' name d = sorted(drivers.values()) v = sorted(vehicles.keys()) j = 0 for i in d: driverName = i.getDriverName() vehiclePlate = v[j] serv = Service(driverName, vehiclePlate, "", i.getDriverEntryHour(), i.getDriverEntryHour(), "", "", "") serv.noService() self.append(serv) j += 1
def restart(self): """Restart the LogicMonitor collector""" logging.debug("Running Collector.restart...") if self.platform == "Linux": logging.debug("Platform is Linux") logging.debug("Restarting logicmonitor-agent service") (output, err) = Service.doAction("logicmonitor-agent", "restart") if output != 0: self.fail( msg="Error: Failed starting logicmonitor-agent " + "service. " + err) logging.debug("Restarting logicmonitor-watchdog service") (output, err) = Service.doAction("logicmonitor-watchdog", "restart") if output != 0: self.fail( msg="Error: Failed starting logicmonitor-watchdog " + "service. " + err) else: (self.fail( msg="Error: LogicMonitor Collector must be installed " + "on a Linux device."))
def run_process(self): service = Service() # Load siti from excel (LoadResources class) #TODO: qunado si leggerà la tabella bisogna prendere sia l'url del sito che il nome del negozio che andrà nel report # al posto dell'url nella variabile sito #lista_siti = ["https://www.lubecreostorepratolapeligna.it/", ] lista_siti = [ "https://www.lubestoresenigallia.it/", ] #lista_siti = ["https://lubecreomilano.it/", ] #lista_siti = ["https://www.cucineluberoma.it/", ] for sito in lista_siti: report = service.valuta_sito_web(sito) print(report.toJSON()) # self.db_manager.insert(self.cl,report) # TODO: for social in lista social facebook e valuta # for sito in lista_fcebook: # report = service.valuta_facebook_profile(sito) # print(report.toJSON()) # TODO:self.db_manager.insert(self.cl,report) # TODO: for social in lista social instagram e valuta # for sito in lista_instagram: # report = service.valuta_instagram_profile(sito) # print(report.toJSON()) # TODO: self.db_manager.insert(self.cl,report) self.logger.info("FINISH")
def process_sheet(sheet, workbook): services = [] sheet_ranges = workbook[sheet] columnDict = get_columns_index(sheet_ranges) max_col = sheet_ranges.rows.gi_frame.f_locals['max_col'] max_row = sheet_ranges.rows.gi_frame.f_locals['max_row'] STARTING_SERVICE_ROW = 2 for row in sheet_ranges.iter_rows(min_row=STARTING_SERVICE_ROW, max_col=max_col, max_row=max_row): fields = {} for cell in row: if hasattr(cell,'column') and cell.column in columnDict.keys(): fields[columnDict[cell.column]] = cell.value else: continue if len(fields) == 0: continue service = Service(fields) if service.is_valid_service(): services.append(service) print('Services for ' + sheet + ' has been processed') return services
def test_request(self): persistence = Persistence('test.db') now = datetime.utcnow().replace(microsecond=0) dt0 = now - timedelta(seconds=30) persistence.store(dt0, 100.0, 100.0, 100.0, 100.0) service = Service(persistence) response = service.request(self.start_response) self.assertEqual( response.next(), 'data: {"dest": "archive", "items": [], "type": "preload"}\n\n') self.assertEqual( response.next(), 'data: {"dest": "recent", "items": [{"dt": "%sZ", "humidity": 100.0, "temperature": 100.0, "moisture": 100.0, "luminence": 100.0}], "type": "preload"}\n\n' % dt0.isoformat()) dt1 = now service.enqueue('recent', 'realtime', [{ 'dt': dt1, 'moisture': 200.0, 'luminence': 200.0, 'temperature': 200.0, 'humidity': 200.0 }]) self.assertEqual( response.next(), 'data: {"dest": "recent", "items": [{"dt": "%sZ", "humidity": 200.0, "temperature": 200.0, "moisture": 200.0, "luminence": 200.0}], "type": "realtime"}\n\n' % dt1.isoformat())
def replanning(self): print "Recovery Workflow started" data = cherrypy.request.json response = RESTInterface(self.params.pmaddress, self.params.pmport, "/pm/v0.0/rest/get_services_involved", json.dumps(data)).run() print response affected = json.loads(response) #for service in affected -> delete (PM) for service in affected['services']: print "Service " + json.dumps(service) request = self.generateRequest("", 0, service['id'], 2, "", "") RESTInterface(self.params.pmaddress, self.params.pmport, "/pm/v0.0/rest/dispatch", request).run() #for service in affected -> path (PCE) # -> configure (PM) for service in affected['services']: r = self.generatePCErequest(service['source'], service['sport'], service['dest'], service['dport']) req = json.loads(r) xro = {'dpid': data['body']['dpid'], 'port': data['body']['port']} req['xro'] = xro r = json.dumps(req) response = RESTInterface(self.params.pceaddress, self.params.pceport, "/pce/v0.0/rest/request", r).run() jsonret = json.loads(response) #check error status print response id = self.getID(service['id']) nwsrc = "unset" nwdst = "unset" if "nwDst" in service.keys(): nwdst = service['nwDst'] if "nwSrc" in service.keys(): nwsrc = service['nwSrc'] request = self.generateRequest(response[:-1], 100000000, id, 1, nwsrc, nwdst) if ("Error" in jsonret) | ("Error" in jsonret['path'][0]): return '{"Error":"NOPATH found"}' #trik for faster recovery #recuest=json.loads(request) #first=recuest['path'].pop(0) #recuest['path'].append(first) #request=json.dumps(recuest) ### ri2 = RESTInterface(self.params.pmaddress, self.params.pmport, "/pm/v0.0/rest/dispatch", request) ret = ri2.run() jsonret = json.loads(ret) if "OK" in jsonret['Status']: serv = Service(id, cherrypy.request.remote.ip, "E2EProvisioning", "PM", jsonret['id'], service['source'], service['dest'], service['sport'], service['dport'], request, nwsrc, nwdst) self.services[id] = serv print serv.toString()
def main(self): while 1==1: files=input("Fisier:" ) ngen=int(input("Generations:")) popsize=int(input("Popsize:")) r=repo(files,"1")m s=Service(r) print(str(s.solve(popsize,ngen)))
def setUp(self) -> None: self.service = Service() self.request_parameters = { "keywords": ["openstack", "nova", "css"], "proxies": ["93.152.176.225:54136", "185.189.211.70:8080"], "type": "Repositories" } self.test_url = "https://github.com/search?utf8=✓&q=openstack+nova+css&type=Repositories"
def test_nine_digits_format(self, ): server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) service = Service(20, server_socket, True) num = '12345' expected = '000012345' actual = service.nine_digits_format(num) server_socket.close() self.assertEqual(expected, actual)
def __init__(self,obj,name='Object'): Service.__init__(self) self.name = name self._object = obj self.start()
def InstallService(self): service = ServiceClass() service._id = self._id sd = ServiceDao(service) service = sd.get() print "Sera instalado o Produto ( %s ) para o Client ( %s )" % ( service._product._name, service._client._name) docker = DockerOps() res = docker.createContainer(service._id, service._product._image)
def E2Eprovisioning(self): data = cherrypy.request.json source = data['source'] sport = data['sport'] dest = data['dest'] dport = data['dport'] bandwidth = data['bandwidth'] nwDst = "unset" nwSrc = "unset" wavelength = "unset" if 'nwSrc' in data.keys(): nwSrc = data['nwSrc'] if 'nwDst' in data.keys(): nwDst = data['nwDst'] print "Test- Added wavelength to retrieve it from json" if 'wavelength' in data.keys(): wavelength = data['wavelength'] #first of all: PCE request (via REsT APi) print json.dumps(data) ri = RESTInterface(self.params.pceaddress, self.params.pceport, "/pce/v0.0/rest/request", json.dumps(data)) ret = ri.run() jsonret = json.loads(ret) #check error status id = self.generateID() request = self.generateRequest(ret[:-1], bandwidth, id, 1, nwSrc, nwDst, wavelength) print "::::::::::::::::::::::::::::::::::::::::::::" print ret[:-1] print "-----------------------" print request print "::::::::::::::::::::::::::::::::::::::::::::" if "vlan" in data.keys(): request = request[:-1] + ',"vlan":' + data['vlan'] + '}' if ("Error" in ret): return '{"Error":"NOPATH found"}' print request ri2 = RESTInterface(self.params.pmaddress, self.params.pmport, "/pm/v0.0/rest/dispatch", request) ret = ri2.run() jsonret = json.loads(ret) if "OK" in jsonret['Status']: # Test- Added wavelength o service serv = Service(id, cherrypy.request.remote.ip, "E2EProvisioning", "PM", jsonret['id'], source, dest, sport, dport, request, nwSrc, nwDst, wavelength) #serv=Service(id,cherrypy.request.remote.ip,"E2EProvisioning", "PM", jsonret['id'],source,dest, sport, dport, request, nwSrc, nwDst) self.services[id] = serv print serv.toString() return '{"Workflow":"' + serv.workflow + '","ID":"' + str( serv.id ) + '","from":"' + serv.ip + '","Status":"E2EProvisioning successfully finished"}'
def __init__(self, driver, vehicle, service): """Creates a DetailedService object, subclass of Service. Requires: driver is a Driver object, vehicle is a Vehicle object and service is a Service object. Ensures: a DetailedService object - a Service object enriched with three attributes: drivers' accumulated time and vehicles' Autonomy and Kms done. """ Service.__init__(self, service.getServiceDriver(), service.getServicePlate(), service.getServiceClient(), \ service.getServiceDepartHour(), service.getServiceArrivalHour(), service.getServiceCircuit(), \ service.getServiceCircuitKms(), service.getServiceDriverStatus()) self._accumTime = driver.getDriverAccumTime() self._vehicleKmsDone = vehicle.getVehicleKmsDone() self._vehicleAutonomy = vehicle.getVehicleAutonomy()
class UI: def __init__(self): self.service = Service() # self.service.loadEnvironment("Resources/test2.map") def run(self): pygame.init() logo = pygame.image.load("Resources/logo32x32.png") pygame.display.set_icon(logo) pygame.display.set_caption("Resources/drone exploration") screen = pygame.display.set_mode((800, 400)) screen.fill(WHITE) screen.blit(self.service.environmentImage, (0, 0)) running = True self.service.markDetectableWalls() while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == KEYDOWN: if pygame.key.get_pressed()[K_LEFT]: self.service.slow_down() if pygame.key.get_pressed()[K_RIGHT]: self.service.speed_up() self.service.moveDFS() screen.blit(self.service.detectedMapImage, (400, 0)) pygame.display.flip() pygame.quit()
def __init__(self): self.total_addresses = 0 self.address_accuracy = 0 self.total_addresses_by_type = 0 self.address_accuracy_by_type = 0 self.accuracy_list = [] self.path_resources = Constants.path_resources self.file_test_img = Constants.file_test_img self.path_test_addresses = Constants.path_test_addresses self.path_test_address_file = Constants.path_test_address_file self.service = Service()
def run(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) port = 4397 sock.bind(('0.0.0.0', 4397)) sock.listen(5) cons = {} # 所有客户端连接存储 ready = {} # 对话准备 logger.debug("启动websock,端口是:" + str(4397)) while True: con, addr = sock.accept() key = str(uuid.uuid1()).replace("-", "") cons[key] = {"con": con, "handshake": False, "name": None} service = Service(key, cons, ready) service.start()
def main(): # file = input("Introduceti nume fisierului:") # pop = input("Introduceti populatia initiala:") # gen = input("Introduceti numarul de generatii:") file = "mediumF.txt" pop = "100" gen = "500" start = 3 file = "data/" + file r = Repo(file) s = Service(r) net = parseberlin("data/hardE.txt") runGA(int(pop), int(gen), costofpath, s.getNet(), start)
def recovery(self): print "Recovery Workflow started" data = cherrypy.request.json response = RESTInterface(self.params.pmaddress, self.params.pmport, "/pm/v0.0/rest/get_services_involved", json.dumps(data)).run() affected = json.loads(response) #for service in affected -> delete (PM) #if "MOBILITY" not in data['']: #we dont delete when mobility (just in case) for service in affected['services']: print "Service " + json.dumps(service) request = self.generateRequest("", 0, service['id'], 2, "", "") RESTInterface(self.params.pmaddress, self.params.pmport, "/pm/v0.0/rest/dispatch", request).run() #for service in affected -> path (PCE) # -> configure (PM) for service in affected['services']: response = RESTInterface( self.params.pceaddress, self.params.pceport, "/pce/v0.0/rest/request", self.generatePCErequest(service['source'], service['sport'], service['dest'], service['dport'])).run() jsonret = json.loads(response) #check error status print response id = self.getID(service['id']) nwsrc = "unset" nwdst = "unset" if "nwDst" in service.keys(): nwdst = service['nwDst'] if "nwSrc" in service.keys(): nwsrc = service['nwSrc'] request = self.generateRequest(response[:-1], 100000000, id, 1, nwsrc, nwdst) if ("Error" in jsonret) | ("Error" in jsonret['path'][0]): return '{"Error":"NOPATH found"}' ri2 = RESTInterface(self.params.pmaddress, self.params.pmport, "/pm/v0.0/rest/dispatch", request) ret = ri2.run() jsonret = json.loads(ret) if "OK" in jsonret['Status']: serv = Service(id, cherrypy.request.remote.ip, "E2EProvisioning", "PM", jsonret['id'], service['source'], service['dest'], service['sport'], service['dport'], request, nwsrc, nwdst) self.services[id] = serv print serv.toString()
def diseasePredictionController(): data = request.get_json() if 'symptoms' not in data.keys(): response = {'statusCode': 400, 'message': 'Please send symptoms'} return Response(response=json.dumps(response)) symptoms = data['symptoms'] service = Service() predicted_diseases = service.get_predicted_disease(symptoms) response = {'statusCode': 200, 'diseases': predicted_diseases} return Response(response=json.dumps(response))
def getStatus(self, statClass=None): """ Return the status number for this WinService """ if self.startMode not in self.getMonitoredStartModes(): return -1 return Service.getStatus(self, statClass)
def test_check_9_digits(self, ): server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) service = Service(20, server_socket, True) patterns = [ '0', '159263487', '0123456789', '01asd', 'asd01', 'abc', '', 'asdfghjklñ' ] expected = [True, True, False, False, False, False, False, False] actual = [] for p in patterns: if service.check_9_digits(p): actual.append(True) else: actual.append(False) server_socket.close() self.assertEqual(expected, actual)
def monitored(self): """Should this Windows Service be monitored """ startMode = getattr(self, "startMode", None) #don't monitor Disabled services if startMode and startMode == "Disabled": return False return Service.monitored(self)
def test_with_fake(self): validator: FakeValidator = FakeValidator() subject: Service = Service(validator) subject.dowork() self.assertEquals(1, subject.work_count)
def add_service(self, port, proto, value, uri=None, content=None, \ username=None, password=None): service_name = "%s/%s" % (port, proto) if self.services.has_key(service_name): pass self.services[service_name] = Service(port, proto, value, \ self.logger, uri, content, username, password)
class mainBankingApp: def __init__(self): self.user = User() self.account = Account() self.employee = Employee() self.service = Service() self.utilities = Utilities() self.initAmt = 0 def runProg(self): self.user.creatingNewUser() while True: # os.system("cls") print( "************************************************************") print( "Choose 'a' to create new account and deposit some initial amount" ) print("Choose 'b' to deposit amount:") print("Choose 'c' to withdraw amount") print("Choose 'd' to apply for a loan") print("Choose 'e' to know your application decision") print( "************************************************************") optionChosen = input("\nPlease enter one of the options above\n") # print(optionChosen) if optionChosen == 'a': self.initAmt = eval( input("Please insert a amount to start an Account:\n ")) # print(self.initAmt) self.account.initial_deposit(self.initAmt) elif optionChosen == 'b': print("Your current account balance is :", self.initAmt) depositAmt = input("\nPlease enter the amount to deposit:") self.account.deposit(depositAmt) elif optionChosen == 'c': wamount = input("Enter amount to withdraw: ") self.account.withdraw(wamount) elif optionChosen == 'd': inputData = self.service.newLoanApplication() self.service.savingToJsonFile(inputData) elif optionChosen == 'e': self.employee.verifyApplicationForApproval() break
def stop(self): """Stop the LogicMonitor collector""" logging.debug("Running Collector.stop...") if self.platform == "Linux": logging.debug("Platform is Linux") output = Service.getStatus("logicmonitor-agent") if "is running" in output: logging.debug("Service logicmonitor-agent is running") logging.debug("System changed") self.change = True if self.check_mode: self.exit(changed=True) logging.debug("Stopping service logicmonitor-agent") (output, err) = Service.doAction("logicmonitor-agent", "stop") if output != 0: self.fail( msg="Error: Failed stopping logicmonitor-agent " + "service. " + err) output = Service.getStatus("logicmonitor-watchdog") if "is running" in output: logging.debug("Service logicmonitor-watchdog is running") logging.debug("System changed") self.change = True if self.check_mode: self.exit(changed=True) logging.debug("Stopping service logicmonitor-watchdog") (output, err) = Service.doAction("logicmonitor-watchdog", "stop") if output != 0: self.fail( msg="Error: Failed stopping logicmonitor-watchdog " + "service. " + err) else: self.fail( msg="Error: LogicMonitor Collector must be " + "installed on a Linux device.")
def __str__(self): """A str representation of a DetailedService""" return Service.__str__(self) + \ "\nAccum Time: " + self._accumTime + \ "\nvehiclePlate: " + self._vehiclePlate + \ "\nvehicleKmsLeft: " + self._vehicleKmsLeft + \ "\nvehicleAutonomy: " + self._vehicleAutonomy
def handleGetServices(document): print 'starting get service handler' document = removeIlegalCharacters(document) try: dom = xml.dom.minidom.parseString(document) servicesXml = dom.getElementsByTagName("Service") services = {} print 'starting get service handler' for servicexml in servicesXml: service = Service() print 'starting get service handler' service.setFromXmlNode(servicexml) print 'starting get service handler' services[service.getId()] = service return services except Exception as e: raise FoundationException(str(e))
def main (): if not OptionParser: raise Exception("TileCache seeding requires optparse/OptionParser. Your Python may be too old.\nSend email to the mailing list \n(http://openlayers.org/mailman/listinfo/tilecache) about this problem for help.") usage = "usage: %prog <layer> [<zoom start> <zoom stop>]" parser = OptionParser(usage=usage, version="%prog $Id: Client.py 406 2010-10-15 11:00:18Z crschmidt $") parser.add_option("-f","--force", action="store_true", dest="force", default = False, help="force recreation of tiles even if they are already in cache") parser.add_option("-b","--bbox",action="store", type="string", dest="bbox", default = None, help="restrict to specified bounding box") parser.add_option("-c", "--config", action="store", type="string", dest="tilecacheconfig", default=None, help="path to configuration file") parser.add_option("-d","--delay",action="store", type="int", dest="delay", default = 0, help="Delay time between requests.") parser.add_option("-p","--padding",action="store", type="int", dest="padding", default = 0, help="extra margin tiles to seed around target area. Defaults to 0 "+ "(some edge tiles might be missing). A value of 1 ensures all tiles "+ "will be created, but some tiles may be wholly outside your bbox") parser.add_option("-r","--reverse", action="store_true", dest="reverse", default = False, help="Reverse order of seeding tiles") (options, args) = parser.parse_args() if len(args)>3: parser.error("Incorrect number of arguments. bbox and padding are now options (-b and -p)") from Service import Service, cfgfiles from Layer import Layer cfgs = cfgfiles if options.tilecacheconfig: configFile = options.tilecacheconfig print "Config file set to %s" % (configFile) cfgs = cfgs + (configFile,) svc = Service.load(*cfgs) layer = svc.layers[args[0]] if options.bbox: bboxlist = map(float,options.bbox.split(",")) else: bboxlist=None if len(args)>1: seed(svc, layer, map(int, args[1:3]), bboxlist , padding=options.padding, force = options.force, reverse = options.reverse, delay=options.delay) else: for line in sys.stdin.readlines(): lat, lon, delta = map(float, line.split(",")) bbox = (lon - delta, lat - delta, lon + delta, lat + delta) print "===> %s <===" % (bbox,) seed(svc, layer, (5, 17), bbox , force = options.force )
def newInstance(self, instance="main", args={}, path='', parent=None, consume="", originator=None, model=None): """ """ if parent is not None and instance == "main": instance = parent.instance instance = instance.lower() service = self.aysrepo.getService(role=self.role, instance=instance, die=False) if service is not None: # print("NEWINSTANCE: Service instance %s!%s exists." % (self.name, instance)) service._recipe = self service.init(args=args) if model is not None: service.model = model else: key = "%s!%s" % (self.role, instance) if path: fullpath = path elif parent is not None: fullpath = j.sal.fs.joinPaths(parent.path, key) else: ppath = j.sal.fs.joinPaths(self.aysrepo.basepath, "services") fullpath = j.sal.fs.joinPaths(ppath, key) if j.sal.fs.isDir(fullpath): j.events.opserror_critical(msg='Service with same role ("%s") and of same instance ("%s") is already installed.\nPlease remove dir:%s it could be this is broken install.' % (self.role, instance, fullpath)) service = Service(aysrepo=self.aysrepo,servicerecipe=self, instance=instance, args=args, path="", parent=parent, originator=originator, model=model) self.aysrepo._services[service.key] = service # service.init(args=args) service.consume(consume) return service
def __start__(self): function = self.function name = self.name inbox = self.inbox outbox = self.outbox copies = self.copies verbose = self.verbose # report if verbose: print '%s: Starting %i Copies' % (name,copies); sys.stdout.flush() # initialize services nodes = [] for i in range(copies): this_name = '%s - Node %i'%(name,i) service = Service( function, inbox, outbox, this_name, verbose ) service.start() nodes.append(service) #: for each node # store self.nodes = nodes
def main(): from Service import Service, cfgfiles from Layer import Layer base = sys.argv[1] svc = Service.load(*cfgfiles) layer = svc.layers[sys.argv[2]] if len(sys.argv) == 5: seed(svc, base, layer, map(int, sys.argv[3:])) elif len(sys.argv) == 6: seed(svc, base, layer, map(int, sys.argv[3:5]), map(float, sys.argv[5].split(","))) else: for line in sys.stdin.readlines(): lat, lon, delta = map(float, line.split(",")) bbox = (lon - delta, lat - delta, lon + delta, lat + delta) print "===> %s <===" % (bbox,) seed(svc, base, layer, (5, 17), bbox)
def parseServices(self,filename): serviceFile = open(filename) serviceReader = csv.reader(serviceFile) for row in serviceReader: service = Service(row[0]) service.event = row[1] service.guys = int(row[2]) service.girls = int(row[3]) service.either = int(row[4]) service.trusted = int(row[5]) service.experienced = row[6] == "yes" self.services.append(service)
def main (): if not OptionParser: raise Exception("TileCache cleaner requires optparse/OptionParser. Your Python may be too old.\nSend email to the mailing list \n(http://openlayers.org/mailman/listinfo/tilecache) about this problem for help.") usage = "usage: %prog <layer> [<zoom start> <zoom stop>]" parser = OptionParser(usage=usage, version="%prog $Id: Cleaner.py 406 2010-10-15 11:00:18Z sbeorchia inspired by Client.py $") parser.add_option("-b","--bbox",action="store", type="string", dest="bbox", default = None, help="restrict to specified bounding box") parser.add_option("-c", "--config", action="store", type="string", dest="tilecacheconfig", default=None, help="path to configuration file") parser.add_option("-z","--zone", action="store", type="string", dest="zone", default = False, help="define the filter zone") parser.add_option("-d","--delete", action="store_true", dest="delete", default = False, help="define if the tile are to be deleted") (options, args) = parser.parse_args() if len(args) > 4: parser.error("Incorrect number of arguments. bbox and padding are now options (-b and -p)") from Service import Service, cfgfiles from Layer import Layer cfgs = cfgfiles if options.tilecacheconfig: configFile = options.tilecacheconfig print "Config file set to %s" % (configFile) cfgs = cfgs + (configFile,) svc = Service.load(*cfgs) layer = svc.layers[args[0]] if options.bbox: bboxlist = map(float,options.bbox.split(",")) else: bboxlist=None if len(args)>1: seed(layer, map(int, args[1:3]), bboxlist , zone = options.zone, path_to_tiles = layer.cache.basedir, delete = options.delete)
def __init__(self, name=None): Service.__init__(self, name) return
sender.publish(sendCh, JSON.encode(sendData)) isSending = True timer = threading.Timer(5, checkSend) timer.start() def process(channel, data): global isSending isSending = False if data['err'] > 0: return if data['err'] == -1: # 网络不通 srv.stop() return data = data['data'] if data['direction'] == 'buy': pos[data['iid']]['buy'] += data['pos'] elif data['direction'] == 'sell': pos[data['iid']]['sell'] += data['pos'] if data['isLast']: print pos key = 'POSITION_%s' % (data['iid']) rds.set(key, JSON.encode(pos[data['iid']])) time.sleep(1) send() listenCh = C.get('channel_trade_rsp') + str(appKey) srv = Service([listenCh], process) send() srv.run()
''' Created on 2013. 11. 25. @author: devsik ''' from Service import Service aaa = Service(); aaa.setname("김윤식"); aaa.sum("가", "나"); bbb = Service(); bbb.setname("임성연"); bbb.sum("다", "나"); print(type(bbb));
def __init__(self, parent): Service.__init__(self, self.serviceID, parent) self.initData()
def search(self, policy_tuples): policies = [] for policy_tuple in policy_tuples: src = [] dest = [] services = [] action = None description = None src_zone = policy_tuple[0] dest_zone = policy_tuple[1] policy_name = policy_tuple[2] if src_zone == dest_zone == "global": match_line = "global policy " + self.rpad(policy_name) else: match_line = "from-zone" + self.pad(src_zone) + "to-zone" + self.pad(dest_zone) + "policy" + self.pad(policy_name) for policy_line in self.config.get_filtered_lines("policy", [match_line], []): for address_type in ["source-address", "destination-address"]: if address_type in policy_line: target_address = re.search(address_type + ' (.*)', policy_line) if target_address: target_address = target_address.group(1) if address_type == "source-address": if target_address == "any": src.append(Address("any", "any", "any")) else: src.append(self.parse_address(target_address)) else: if target_address == "any": dest.append(Address("any", "any", "any")) else: dest.append(self.parse_address(target_address)) # services if "match application " in policy_line: service = re.search('match application (.*)', policy_line) service = service.group(1) if service == "any": service_objcet = Service("any", "any", "any") elif "junos-" in service: protocol, destination_port = self.get_junos_default_service(service) service_objcet = Service(service, protocol, destination_port) else: stdout = self.config.get_filtered_lines("service", ["application-set", self.pad(service)], ["description"]) if len(stdout) != 0: # services in the set service_objcet = ServiceGroup(service) for service_set_line in stdout: if " application " in service_set_line: service_set_service = re.search('application (.*)', service_set_line) service_set_service = service_set_service.group(1) if "junos-" in service_set_service: protocol, destination_port = self.get_junos_default_service(service_set_service) service_objcet.add_service(Service(service_set_service, protocol, destination_port)) else: stdout = self.config.get_filtered_lines("service", [self.pad(service_set_service)], ["application-set", "description"]) if " term " not in service_set_line[0]: # found the actual service protocol, destination_port = self.get_generic_service(stdout) service_objcet.add_service(Service(service_set_service, protocol, destination_port)) else: # termed service object terms = set() for lines in stdout: group_term = re.search(' term (.+?) ', service_set_line) group_term = group_term.group(1) terms.add(group_term) for term in terms: protocol, destination_port = self.get_generic_service(self.config.get_filtered_lines("service", [self.pad(service_set_service), self.pad(term)], ["application-set", "description"])) service_objcet.add_service(Service(term, protocol, destination_port)) else: protocol, destination_port = self.get_generic_service(self.config.get_filtered_lines("service", [self.pad(service)], ["application-set", "description"])) service_objcet = Service(service, protocol, destination_port) services.append(service_objcet) # action if action is None: if " then " in policy_line and " log " not in policy_line: action = re.search('then (permit|deny|reject)', policy_line) action = action.group(1) # description if " description " in policy_line: description = re.search('description (.*)', policy_line) description = description.group(1) description = description.strip('"') if description is None: description = "" policies.append(Policy(policy_name, description, src, dest, action, services, src_zone, dest_zone)) return policies