class Opera(RemoteWebDriver): def __init__(self): self.service = Service(logging_level, port) self.service.start() RemoteWebDriver.__init__(self, command_executor=self.service.service_url, desired_capabilities=DesiredCapabilities.OPERA) def quit(self): """ Closes the browser and shuts down the ChromeDriver executable that is started when starting the ChromeDriver """ try: RemoteWebDriver.quit(self) except httplib.BadStatusLine: pass finally: self.service.stop() def save_screenshot(self, filename): """ Gets the screenshot of the current window. Returns False if there is any IOError, else returns True. Use full paths in your filename. """ png = self._execute(Command.SCREENSHOT)['value'] try: f = open(filename, 'wb') f.write(base64.decodestring(png)) f.close() except IOError: return False finally: del png return True
def test_abs_plus(): serviceTest = Service() testValue = serviceTest.abs_plus(-5) assert(testValue == 6) testValue = serviceTest.abs_plus(0) assert(testValue == 1)
def process_event(): try: svc = Service() svc.process_event(request.data) return SvcUtils.handle_response(status.HTTP_200_OK) except Exception as ex: return SvcError.handle_error(ex)
def ping(): try: svc = Service() svc_response = svc.ping() return SvcUtils.handle_response(svc_response, status.HTTP_200_OK) except Exception as ex: return SvcError.handle_error(ex)
def get_message_by_username(username): try: svc = Service() svc_response = svc.get_message_by_username(username) return SvcUtils.handle_response(svc_response, status.HTTP_200_OK) except Exception as ex: return SvcError.handle_error(ex)
def save_message(): try: svc = Service() svc_response = svc.save_message(request.data) return SvcUtils.handle_response(svc_response, status.HTTP_201_CREATED) except Exception as ex: return SvcError.handle_error(ex)
def service_create(image, name, start, target_num_instances, instance_size, run_command, env, ports, exposes, volumes, links, namespace, scaling_info, custom_domain_name, region_name): image_name, image_tag = util.parse_image_name_tag(image) instance_ports, port_list = util.parse_instance_ports(ports) expose_list = util.merge_internal_external_ports(port_list, exposes) instance_ports.extend(expose_list) instance_envvars = util.parse_envvars(env) links = util.parse_links(links) volumes = util.parse_volumes(volumes) scaling_mode, scaling_cfg = util.parse_autoscale_info(scaling_info) if scaling_mode is None: scaling_mode = 'MANUAL' service = Service(name=name, image_name=image_name, image_tag=image_tag, target_num_instances=target_num_instances, instance_size=instance_size, run_command=run_command, instance_ports=instance_ports, instance_envvars=instance_envvars, volumes=volumes, links=links, namespace=namespace, scaling_mode=scaling_mode, autoscaling_config=scaling_cfg, custom_domain_name=custom_domain_name, region_name=region_name) if start: service.run() else: service.create()
def __init__(self, start="<", end=">", close="/"): """Service constructor.""" Service.__init__(self) self.markup_delimiter_start = start self.markup_delimiter_end = end self.markup_delimiter_close = close self.expressions = [] self.exceptions = [] # Add the exceptions self.add_except_expression("@", "@") self.add_except_markup("pre") # Add the expressions and markups self.add_expression("italic", "/(.*?)/", "<em>\\1</em>") self.add_expression("bold", r"\*(.*?)\*", "<strong>\\1</strong>") self.add_expression( "header1", r"^(\s*)h1\.\s+(.*?)\s*$", r"\1<h1>\2</h1>", re.MULTILINE ) # Test (o delete) text = """
def test_complicated_function(self): ser = Service() ser.bad_random = mock.Mock(return_value=15) re = ser.complicated_function(3) assert re == (5, 1) ser.bad_random = mock.Mock(return_value=15) self.assertRaises(ZeroDivisionError, ser.complicated_function,0)
def strict_up(self, ignore): started_list = [] for i in range(len(self.services) - 1): for service in self.services[i]: try: service.run() except AlaudaServerError as ex: if str(ex).find('App {} already exists'.format(service.name)) > -1 and ignore: continue else: print 'error: {}'.format(ex.message) raise ex started_list.extend(self.services[i]) ret = self._wait_services_ready(self.services[i]) if ret is not None: for service in started_list: Service.remove(service.name) raise AlaudaServerError(500, ret) for service in self.services[len(self.services) - 1]: try: service.run() except AlaudaServerError as ex: if str(ex).find('App {} already exists'.format(service.name)) > -1 and ignore: print 'Ignore exist service -> {}'.format(service.name) continue else: raise ex
class WebDriver(RemoteWebDriver): def __init__(self, executable_path='IEDriverServer.exe', port=DEFAULT_PORT, timeout=DEFAULT_TIMEOUT): self.port = port if self.port == 0: self.port = utils.free_port() self.iedriver = Service(executable_path, port=self.port) self.iedriver.start() RemoteWebDriver.__init__( self, command_executor='http://localhost:%d' % self.port, desired_capabilities=DesiredCapabilities.INTERNETEXPLORER) def quit(self): RemoteWebDriver.quit(self) self.iedriver.stop() def save_screenshot(self, filename): """ Gets the screenshot of the current window. Returns False if there is any IOError, else returns True. Use full paths in your filename. """ png = RemoteWebDriver.execute(self, Command.SCREENSHOT)['value'] try: f = open(filename, 'wb') f.write(base64.decodestring(png)) f.close() except IOError: return False finally: del png return True
def test_abs_plus(): newService = Service() assert newService.abs_plus(-10) == (abs(-10) + 1) assert newService.abs_plus(10) == (abs(10) + 1) assert newService.abs_plus(0) == (abs(0) + 1) assert newService.abs_plus(3.14) == (abs(3.14) + 1)
def index(self): platform_id = int(self.get_argument('platform_id',6)) run_id = int(self.get_argument('run_id',0)) plan_id = int(self.get_argument('plan_id',0)) partner_id = int(self.get_argument('partner_id',0)) version_name = self.get_argument('version_name','').replace('__','.') product_name = self.get_argument('product_name','') #perm run_list=self.run_list() run_list = self.filter_run_id_perms(run_list=run_list) run_id_list = [run['run_id'] for run in run_list] if run_id == 0 and run_id_list: # has perm and doesn't select a run_id if len(run_id_list) == len(Run.mgr().Q().extra("status<>'hide'").data()): run_id = 0 # user has all run_id perms else: run_id = run_id_list[0] if run_id not in run_id_list and run_id != 0: # don't has perm and selete a run_id scope = None # scope else: scope = Scope.mgr().Q().filter(platform_id=platform_id,run_id=run_id,plan_id=plan_id, partner_id=partner_id,version_name=version_name,product_name=product_name)[0] tody = self.get_date() yest = tody - datetime.timedelta(days=1) last = yest - datetime.timedelta(days=1) start = tody - datetime.timedelta(days=30) basics,topn_sch,topn_hw,b_books,c_books = [],[],[],[],[] visit_y = dict([(i,{'pv':0,'uv':0}) for i in PAGE_TYPE]) visit_l = dict([(i,{'pv':0,'uv':0}) for i in PAGE_TYPE]) if scope: # basic stat dft = dict([(i,0) for i in BasicStatv3._fields]) basic_y = BasicStatv3.mgr().Q(time=yest).filter(scope_id=scope.id,mode='day',time=yest)[0] basic_l = BasicStatv3.mgr().Q(time=last).filter(scope_id=scope.id,mode='day',time=last)[0] basic_m = BasicStatv3.mgr().get_data(scope.id,'day',start,tody,ismean=True) basic_p = BasicStatv3.mgr().get_peak(scope.id,'day',start,tody) basic_y,basic_l = basic_y or dft,basic_l or dft basic_y['title'],basic_l['title'] = '昨日统计','前日统计' basic_m['title'],basic_p['title'] = '每日平均','历史峰值' basics = [basic_y,basic_l,basic_m,basic_p] # page visit for i in VisitStat.mgr().Q().filter(scope_id=scope.id,mode='day',time=yest): visit_y[i['type']] = i for i in VisitStat.mgr().Q().filter(scope_id=scope.id,mode='day',time=last): visit_l[i['type']] = i # topN search & hotword q = TopNStat.mgr().Q().filter(scope_id=scope.id,mode='day',time=yest) topn_sch = q.filter(type='search').orderby('no')[:10] topn_hw = q.filter(type='hotword').orderby('no')[:10] # books of by-book & by-chapter q = BookStat.mgr().Q(time=yest).filter(scope_id=scope.id,mode='day',time=yest) b_books = Service.inst().fill_book_info(q.filter(charge_type='book').orderby('fee','DESC')[:10]) c_books = Service.inst().fill_book_info(q.filter(charge_type='chapter').orderby('fee','DESC')[:10]) self.render('data/basic.html', platform_id=platform_id,run_id=run_id,plan_id=plan_id, partner_id=partner_id,version_name=version_name,product_name=product_name, run_list=self.run_list(),plan_list=self.plan_list(),date=tody.strftime('%Y-%m-%d'), basics = basics,visit_y=visit_y,visit_l=visit_l,topn_sch = topn_sch, topn_hw=topn_hw,b_books=b_books,c_books=c_books )
def test_bad_random(self, randintMock, mockOpen): # integers mockOpen.return_value = MockFile([1, 4, 7]) randintMock.return_value = 2 assert Service.bad_random() == 2 randintMock.assert_called_once_with(0, 2) randintMock.reset_mock() # empty mockOpen.return_value = MockFile([]) randintMock.return_value = -1 assert Service.bad_random() == -1 randintMock.assert_called_once_with(0, -1) randintMock.reset_mock() # float mockOpen.return_value = MockFile([5.2]) randintMock.return_value = 0 assert Service.bad_random() == 0 randintMock.assert_called_once_with(0, 0) randintMock.reset_mock() # non-numeric values mockOpen.return_value = MockFile([1, "a", 7]) self.assertRaises(ValueError, Service.bad_random) mockOpen.reset_mock()
def cmsGetCurrentConnectionIDs(event): if not event: return False Service.upnpAddResponse(event, CMSService.SERVICE_CMS_ARG_CONNECTION_IDS, '') return event['status']
class WebDriver(RemoteWebDriver): def __init__(self, executable_path='IEDriverServer.exe', port=DEFAULT_PORT, timeout=DEFAULT_TIMEOUT, host=DEFAULT_HOST, log_level=DEFAULT_LOG_LEVEL, log_file=DEFAULT_LOG_FILE): self.port = port if self.port == 0: self.port = utils.free_port() self.host = host self.log_level = log_level self.log_file = log_file self.iedriver = Service(executable_path, port=self.port, host=self.host, log_level=self.log_level, log_file=self.log_file) self.iedriver.start() RemoteWebDriver.__init__( self, command_executor='http://localhost:%d' % self.port, desired_capabilities=DesiredCapabilities.INTERNETEXPLORER) def quit(self): RemoteWebDriver.quit(self) self.iedriver.stop()
def testDivide(self, mockAbsPlus): mockAbsPlus.return_value = 10 assert(Service.abs_plus(-9) == 10) mockAbsPlus.return_value = 1 assert(Service.abs_plus(0) == 1) mockAbsPlus.return_value = 11 assert(Service.abs_plus(10) == 11)
class WebDriver(RemoteWebDriver): """ Controls the OperaDriver and allows you to drive the browser. """ def __init__(self, executable_path=None, port=0, desired_capabilities=DesiredCapabilities.OPERA): """ Creates a new instance of the Opera driver. Starts the service and then creates new instance of Opera Driver. :Args: - executable_path - path to the executable. If the default is used it assumes the executable is in the Environment Variable SELENIUM_SERVER_JAR - port - port you would like the service to run, if left as 0, a free port will be found. - desired_capabilities: Dictionary object with desired capabilities (Can be used to provide various Opera switches). """ if executable_path is None: try: executable_path = os.environ["SELENIUM_SERVER_JAR"] except: raise Exception( "No executable path given, please add one to Environment Variable \ 'SELENIUM_SERVER_JAR'" ) self.service = Service(executable_path, port=port) self.service.start() RemoteWebDriver.__init__( self, command_executor=self.service.service_url, desired_capabilities=desired_capabilities ) def quit(self): """ Closes the browser and shuts down the OperaDriver executable that is started when starting the OperaDriver """ try: RemoteWebDriver.quit(self) except httplib.BadStatusLine: pass finally: self.service.stop() def save_screenshot(self, filename): """ Gets the screenshot of the current window. Returns False if there is any IOError, else returns True. Use full paths in your filename. """ png = RemoteWebDriver.execute(self, Command.SCREENSHOT)["value"] try: f = open(filename, "wb") f.write(base64.decodestring(png)) f.close() except IOError: return False finally: del png return True
def request(self, uri): """Build the request to run against drupal request(project uri) Values and structure returned: {username: {uid:int, repo_id:int, access:boolean, branch_create:boolean, branch_update:boolean, branch_delete:boolean, tag_create:boolean, tag_update:boolean, tag_delete:boolean, per_label:list, name:str, pass:md5, ssh_keys: { key_name:fingerprint } } }""" service = Service(AuthProtocol('vcs-auth-data')) service.request_json({"project_uri":self.projectname(uri)}) def NoDataHandler(fail): fail.trap(ConchError) message = fail.value.value log.err(message) # Return a stub auth_service object return {"users":{}, "repo_id":None} service.addErrback(NoDataHandler) return service.deferred
def msrIsValidated(event): if not event: return False # Sends a fake authorization. Service.upnpAddResponse(event, MSRService.SERVICE_MSR_ARG_RESULT, MSRService.SERVICE_MSR_STATUS_OK) return event.status
def test_complicated_function(self, bad_random): service = Service() assert service.complicated_function(5) == (3, 1) #assert service.complicated_function(0) == (11, 1) with self.assertRaises(ZeroDivisionError): service.complicated_function(0) assert service.complicated_function(-5) == (-3, 1)
def test_divide(self, bad_random): service = Service() assert service.divide(1) == 10 #assert service.divide(0) == "Division by zero" with self.assertRaises(ZeroDivisionError): service.divide(0) assert service.divide(-1) == -10
def test_abs_plus(self): s = Service() #s.bad_random = mock.Mock(return_value=10) r_val = s.abs_plus(-100) assert r_val == 101 r_val1 = s.abs_plus(1e-9) assert r_val1 == 1e-9+1
def test_complicated_function(self): s = Service() s.bad_random = mock.Mock(return_value=10) #s.divide = mock.Mock(return_value=2) r_val = s.complicated_function(5) assert r_val == (2,0) self.assertRaises(ZeroDivisionError,s.complicated_function,0)
def test_complicated_function(self): service = Service() service.bad_random = mock.Mock(return_value=42) assert service.complicated_function(3) == (42/3, 0) service.bad_random = mock.Mock(return_value=43) assert service.complicated_function(3) == (43/3, 1)
def test_divide(self): service = Service() service.bad_random = mock.Mock(return_value=9) return_val = service.divide(2) assert return_val == 4.5 # trying to divide 0 self.assertRaises(ZeroDivisionError,service.divide,0)
def create_app(data_config): currPath = path.dirname(__file__) template_path = path.join(currPath, '../templates') app = Service(template_path, data_config) app.wsgi_app = SharedDataMiddleware(app.wsgi_app, { '/global': path.join(path.dirname(__file__), '../global') }) return app
class WebDriver(RemoteWebDriver): """ Controls the ChromeDriver and allows you to drive the browser. You will need to download the ChromeDriver executable from http://code.google.com/p/chromedriver/downloads/list """ def __init__(self, executable_path="chromedriver", port=0, chrome_options=None, service_args=None, desired_capabilities=None, service_log_path=None): """ Creates a new instance of the chrome driver. Starts the service and then creates new instance of chrome driver. :Args: - executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH - port - port you would like the service to run, if left as 0, a free port will be found. - desired_capabilities: Dictionary object with non-browser specific capabilities only, such as "proxy" or "loggingPref". - chrome_options: this takes an instance of ChromeOptions """ if chrome_options is None: options = Options() else: options = chrome_options if desired_capabilities is not None: desired_capabilities.update(options.to_capabilities()) else: desired_capabilities = options.to_capabilities() self.service = Service(executable_path, port=port, service_args=service_args, log_path=service_log_path) self.service.start() try: RemoteWebDriver.__init__(self, command_executor=self.service.service_url, desired_capabilities=desired_capabilities) except: self.quit() raise self._is_remote = False def quit(self): """ Closes the browser and shuts down the ChromeDriver executable that is started when starting the ChromeDriver """ try: RemoteWebDriver.quit(self) except: # We don't care about the message because something probably has gone wrong pass finally: self.service.stop()
def __init__(self): Service.__init__(self) self.shell = None self.reentrancyGaurd = 0 self.processingBulkData = False self.clocksynchronizing = 0 self.clocklastsynchronized = None self.lastLongCallTimestamp = 0 blue.pyos.synchro.timesyncs.append(self.OnTimerResync)
def testDivide(self, mockDivide): mockDivide.return_value = 10 assert(Service.divide(2) == 10) mockDivide.return_value = -10 assert(Service.divide(-2) == -10) mockDivide.return_value = 20 assert(Service.divide(1) == 20) mockDivide.return_value = -20 assert(Service.divide(-1) == -20)
def instance_logs(name, uuid, namespace, start_time=None, end_time=None): service = Service.fetch(name, namespace) instance = service.get_instance(uuid) result = instance.logs(start_time, end_time) util.print_logs(result, 'instance')
def Run(self, *args): Service.Run(self, *args) uthread.worker('ConnectionService::LongCallTimer', self.__LongCallTimer)
def service_enable_autoscaling(name, namespace, autoscaling_config): _, scaling_cfg = util.parse_autoscale_info(('AUTO', autoscaling_config)) service = Service.fetch(name, namespace) service.enable_autoscaling(scaling_cfg)
def addService(self, content): service = Service(content) self.services[content['service_id']] = service return service.__dict__
def service_ports(name, namespace): service = Service.fetch(name, namespace) util.print_ports(service)
return render_template('msg.html', msg=("%s has been created!" % s.name)) @app.route('/delete/<service_id>', methods=('GET', )) def delete_yo(service_id): if not login.current_user.is_authenticated(): return redirect(url_for('admin.login_view')) oid = None try: oid = ObjectId(service_id) except Exception, e: return redirect('/sry/poorly%20formed%20url') cursor = db.services.find({'_id': oid}) if cursor.count() == 0: return redirect('/sry/no%20such%20service%20exists') s = Service(cursor.next()) if ObjectId(login.current_user._id) != s.owner: return redirect('/sry/no%20such%20service%20exists') db.services.remove({'_id': s._id}) db.user_data.remove({'service': s._id}) return render_template('msg.html', msg=('%s has been deleted.' % s.name)) @app.route('/edit/<service_id>', methods=('GET', )) def edit_yo(service_id): if not login.current_user.is_authenticated(): return redirect(url_for('admin.login_view')) oid = None try: oid = ObjectId(service_id) except Exception, e:
def __init__(self): Service.__init__(self)
def __init__(self): Service.__init__(self) self.descriptionIndex = cfg.evegraphics.Get(1).header.index('description')
def setUp(self): self.service = Service()
def service_stop(name, namespace): service = Service.fetch(name, namespace) service.stop()
def service_start(name, namespace): service = Service.fetch(name, namespace) service.start()
def compute_graph(stock): if stock: container = [] for interval in prediction_interval: result = Service.getInstance().getGraph( stock, interval, "Scatter") x = result["x"] y = result["y"] all_point = go.Scatter(x=x, y=y, mode="lines", showlegend=False) last_ten = go.Scatter(x=x[-10:], y=y[-10:], mode=result["mode"], name="last 10 point") container.append( html.H3("Prediction " + stock + " for " + interval)) buttons = [] data = [] number = 0 active = 0 active_name = "" active_value = None active_color = None # for example output = Service.getInstance().getPrediction("stock", y[-10:]) possible_value = max(output) for index in range(13): show = False if index == 0: name = "original" button_name = "original" data = [all_point, last_ten] else: name = "pattern " + str( index) + " " + pattern_name[index] + " " + str( round(output[number])) + "%" button_name = "pattern " + str(index) + " " + str( round(output[number])) + "%" if number < len( output) and output[number] == possible_value: active_name = name active = number + 1 if round(output[number]) > 90: if active_name in predict_trend["up"]: active_value = "This stock tend to be up" active_color = "success" else: active_value = "This stock tend to be down" active_color = "danger" else: active_value = "The similarity of pattern is less than 90%, this stock is currently in unknown trend" active_color = "dark" show = True label_name = "pattern " + str(index) normalized_value = normalize(max(y[-10:]), min(y[-10:]), standard_pattern[number]) data.append( go.Scatter( x=x[-10:], y=normalized_value, mode="lines+markers", name=label_name, visible=show, )) number += 1 buttons.append( dict(label=button_name, method="update", args=[{ "visible": show_prediction[index], "title": name, "annotations": [] }]), ) fig = go.Figure( data=data, layout=go.Layout( title=active_name, height=600, width=1050, yaxis={'range': [min(y[-20:]) - 5, max(y[-20:]) + 5]}, xaxis={ 'range': [ datetime.fromisoformat(min(x[-15:])[:-1]) - timedelta(days=focus_range[interval]), datetime.fromisoformat(max(x[-15:])[:-1]) + timedelta(days=focus_range[interval]) ], }, ), ) fig.update_layout(updatemenus=[ dict( type="buttons", direction="down", active=active, x=1.4, y=1.1, buttons=list(buttons), ) ]) container.append( dbc.Row([ dbc.Alert( id="alert", children= "From the most percentage of similar pattern: " + active_value, color=active_color, style={"width": "100%"}) ])) container.append( dbc.Row([ dbc.Col([dcc.Graph(figure=fig)]), ], ), ) return container, stock
class WebDriver(RemoteWebDriver): """ Controls the ChromeDriver and allows you to drive the browser. You will need to download the ChromeDriver executable from http://code.google.com/p/chromedriver/downloads/list """ def __init__(self, executable_path="chromedriver", port=0, chrome_options=None): """ Creates a new instance of the chrome driver. Starts the service and then creates new instance of chrome driver. :Args: - executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH - port - port you would like the service to run, if left as 0, a free port will be found. - desired_capabilities: Dictionary object with desired capabilities (Can be used to provide various chrome switches). This is being deprecated, please use chrome_options - chrome_options: this takes an instance of ChromeOptions """ if chrome_options is None: options = Options() else: options = chrome_options desired_capabilities = options.to_capabilities() self.service = Service(executable_path, port=port) self.service.start() try: RemoteWebDriver.__init__(self, command_executor=self.service.service_url, desired_capabilities=desired_capabilities) except: self.quit() raise def quit(self): """ Closes the browser and shuts down the ChromeDriver executable that is started when starting the ChromeDriver """ try: RemoteWebDriver.quit(self) except: # We don't care about the message because something probably has gone wrong pass finally: self.service.stop() def save_screenshot(self, filename): """ Gets the screenshot of the current window. Returns False if there is any IOError, else returns True. Use full paths in your filename. """ png = RemoteWebDriver.execute(self, Command.SCREENSHOT)['value'] try: f = open(filename, 'wb') f.write(base64.decodestring(png)) f.close() except IOError: return False finally: del png return True
def getSortCapabilities(event): Service.upnpAddResponse(event, CDSService.SERVICE_CDS_ARG_SORT_CAPS, "") return event['status']
def service(self): self.serv = Service(self) self.serv.place(x=600, y=400)
def instance_ps(name, namespace): service = Service.fetch(name, namespace) instance_list = service.list_instances() util.print_instance_ps_output(instance_list)
def basic(self): platform_id = int(self.get_argument('platform_id',6)) run_id = int(self.get_argument('run_id',0)) plan_id = int(self.get_argument('plan_id',0)) partner_id = int(self.get_argument('partner_id',0)) version_name = self.get_argument('version_name','').replace('__','.') product_name = self.get_argument('product_name','') tody = self.get_date() yest = tody - datetime.timedelta(days=1) last = yest - datetime.timedelta(days=1) run_list = [i for i in self.run_list() if i['run_id'] in IOS_RUN_ID_LIST] basics = [] if run_id == 0: #不限 if partner_id: scope = Scope.mgr().Q().filter(platform_id=platform_id,run_id=run_id,plan_id=plan_id, partner_id=partner_id,version_name=version_name,product_name=product_name)[0] if scope: scope_id_list = str(scope['id']) dft = dict([(i,0) for i in BasicStatv3._fields]) basic_y = BasicStatv3.mgr().get_sum_data_by_multi_scope(scope_id_list,yest)[0] basic_l = BasicStatv3.mgr().get_sum_data_by_multi_scope(scope_id_list,last)[0] basic_y,basic_l = basic_y or dft,basic_l or dft basic_y['title'],basic_l['title'] = '昨日统计','前日统计' basics = [basic_y,basic_l] for basic in basics: basic['cfee'] = long(basic['cfee']) basic['bfee'] = long(basic['bfee']) basic['batch_fee'] = long(basic['batch_fee']) else: scope = Scope.mgr().get_ios_scope_id_list() if scope: scope_id_list = ','.join([str(i['id']) for i in scope]) dft = dict([(i,0) for i in BasicStatv3._fields]) basic_y = BasicStatv3.mgr().get_sum_data_by_multi_scope(scope_id_list,yest)[0] basic_l = BasicStatv3.mgr().get_sum_data_by_multi_scope(scope_id_list,last)[0] basic_y,basic_l = basic_y or dft,basic_l or dft basic_y['title'],basic_l['title'] = '昨日统计','前日统计' basics = [basic_y,basic_l] for basic in basics: basic['cfee'] = long(basic['cfee']) basic['bfee'] = long(basic['bfee']) basic['batch_fee'] = long(basic['batch_fee']) else: # scope scope = Scope.mgr().Q().filter(platform_id=platform_id,run_id=run_id,plan_id=plan_id, partner_id=partner_id,version_name=version_name,product_name=product_name)[0] tody = self.get_date() yest = tody - datetime.timedelta(days=1) last = yest - datetime.timedelta(days=1) start = tody - datetime.timedelta(days=30) basics,topn_sch,topn_hw,b_books,c_books = [],[],[],[],[] visit_y = dict([(i,{'pv':0,'uv':0}) for i in PAGE_TYPE]) visit_l = dict([(i,{'pv':0,'uv':0}) for i in PAGE_TYPE]) if scope: # basic stat dft = dict([(i,0) for i in BasicStatv3._fields]) basic_y = BasicStatv3.mgr().Q(time=yest).filter(scope_id=scope.id,mode='day',time=yest)[0] basic_l = BasicStatv3.mgr().Q(time=last).filter(scope_id=scope.id,mode='day',time=last)[0] basic_m = BasicStatv3.mgr().get_data(scope.id,'day',start,tody,ismean=True) basic_p = BasicStatv3.mgr().get_peak(scope.id,'day',start,tody) basic_y,basic_l = basic_y or dft,basic_l or dft basic_y['title'],basic_l['title'] = '昨日统计','前日统计' basic_m['title'],basic_p['title'] = '每日平均','历史峰值' basics = [basic_y,basic_l,basic_m,basic_p] for basic in basics: basic['cfee'] = long(basic['cfee']) basic['bfee'] = long(basic['bfee']) basic['batch_fee'] = long(basic['batch_fee']) # page visit for i in VisitStat.mgr().Q().filter(scope_id=scope.id,mode='day',time=yest): visit_y[i['type']] = i for i in VisitStat.mgr().Q().filter(scope_id=scope.id,mode='day',time=last): visit_l[i['type']] = i # topN search & hotword q = TopNStat.mgr().Q().filter(scope_id=scope.id,mode='day',time=yest) topn_sch = q.filter(type='search').orderby('no')[:10] topn_hw = q.filter(type='hotword').orderby('no')[:10] # books of by-book & by-chapter q = BookStat.mgr().Q(time=yest).filter(scope_id=scope.id,mode='day',time=yest) b_books = Service.inst().fill_book_info(q.filter(charge_type='book').orderby('fee','DESC')[:10]) c_books = Service.inst().fill_book_info(q.filter(charge_type='chapter').orderby('fee','DESC')[:10]) self.render('data/ios_basic.html', run_id=run_id, partner_id=partner_id, run_list=run_list,date=tody.strftime('%Y-%m-%d'), basics = basics )
def __init__(self): self.__initPygame() self.__screen = pygame.display.set_mode((400,400)) self.__screen.fill(Constants.WHITE) self.__service = Service()
def service_logs(name, namespace, start_time, end_time): service = Service.fetch(name, namespace) result = service.logs(start_time, end_time) util.print_logs(result, 'service')
from snakesist.exist_client import ExistClient from starlette.responses import Response, JSONResponse, PlainTextResponse from starlette.requests import Request from random import choice from string import ascii_letters from pathlib import Path from multiprocessing import Manager from service import Service, beacon_service from models import EntityMeta from .config import CFG, ROOT_COLLECTION, XSLT_FLAG, ENTITY_NAMES, STAGE db = ExistClient(host="db") #db = ExistClient(host="localhost") db.root_collection = ROOT_COLLECTION service = Service(db, CFG, watch_updates=True) app = FastAPI() meta = {} class XMLResponse(Response): media_type = "application/xml" @app.on_event('startup') async def on_startup(): try: db_version_file = Path(__file__).parent / "../.db-version" with db_version_file.open('r') as version: db_version_hash = version.read().strip("\n")
def service_disable_autoscaling(name, namespace, target_num_instances): service = Service.fetch(name, namespace) service.disable_autoscaling(target_num_instances)
class GUI: def __init__(self): self.__initPygame() self.__screen = pygame.display.set_mode((400,400)) self.__screen.fill(Constants.WHITE) self.__service = Service() def __initPygame(self): pygame.init() logo = pygame.image.load("logo32x32.png") pygame.display.set_icon(logo) pygame.display.set_caption("Doru Exploratoru revine") def __getMapImage(self, colour = Constants.BLUE, background = Constants.WHITE): image = pygame.Surface((400,400)) brick = pygame.Surface((20,20)) brick.fill(colour) image.fill(background) mapSurface = self.__service.getMapSurface() for i in range(Constants.MAP_HEIGHT): for j in range(Constants.MAP_WIDTH): if (mapSurface[i][j] == 1): image.blit(brick, (j * 20, i * 20)) return image def __moveDroneAlongPath(self, droneImage, pathImage, actualPath): pathTile = pygame.Surface((20,20)) pathTile.fill(Constants.GREEN) for position in actualPath: pathImage.blit(pathTile, (position[1] * 20, position[0] * 20)) pathImageCopy = pathImage.copy() pathImageCopy.blit(droneImage, (position[1] * 20, position[0] * 20)) self.__screen.blit(pathImageCopy, (0, 0)) pygame.display.update() pygame.time.wait(Constants.TIME_BETWEEN_MOVES) def __displayWithPath(self, visitedPositions, actualPath): droneImage = pygame.image.load("minune.jpg") visitedTile = pygame.Surface((20,20)) visitedTile.fill(Constants.RED) pathImage = self.__getMapImage() # show all the visited positions for position in visitedPositions: pathImage.blit(visitedTile, (position[1] * 20, position[0] * 20)) pathImage.blit(droneImage, (self.__service.getDroneYCoord() * 20, self.__service.getDroneXCoord() * 20)) self.__screen.blit(pathImage, (0, 0)) pygame.display.update() # then progressively show the actual path of the drone self.__moveDroneAlongPath(droneImage, pathImage, actualPath) def __waitForKeyboardInput(self): while True: for event in pygame.event.get(): if event.type == KEYDOWN: return pygame.time.wait(1) def __runAlgorithm(self, searchAlgorithm, initialX, initialY, finalX, finalY): visitedPositions, actualPath, searchType, searchTime = searchAlgorithm(initialX, initialY, finalX, finalY) print (searchType) print (searchTime) print ("Visited: ", len(visitedPositions)) print ("Path length: ", len(actualPath)) print() self.__displayWithPath(visitedPositions, actualPath) self.__waitForKeyboardInput() def start(self): self.__runAlgorithm(self.__service.searchDFS, 2, 3, 19, 19) self.__runAlgorithm(self.__service.searchAStar, 2, 3, 19, 19) self.__runAlgorithm(self.__service.searchGreedy, 2, 3, 19, 19) pygame.quit()
def onnet_CC(A,B,**kwargs): print(f"!\n!!\n************** Test {A}{B} type EP *************\n!!!") dict1 = yaml.load(open(file_path + '/../Topology/inputfile_CC.yml'),Loader=yaml.Loader) qos_dict = yaml.load(open(file_path + '/../Topology/qos_class.yml'),Loader=yaml.Loader) dict1.update(qos_dict) pprint(kwargs) dict1['site_list'][0]['port_type'],dict1['site_list'][1]['port_type'] = '{}-type'.format(A),'{}-type'.format(B) if kwargs: dict1.update(kwargs) my_config = Service(**dict1) ## create the object for service class. my_config.connect_nodes() ## connect the nodes. my_config.gather_facts() ## Update the dictionary with info from Nodes. my_config.SRTE_Config() ## do SRTE config via H-policy tool & attach the PW class to the Service. my_config.Command_Creation() ## create the commands to create and Delete service my_config.push_config() ## send the configs to the node. test_result,input_dict = {},{} ## create a empty dictionary to hold results. # test_result['XC_status'] = my_config.get_netconf_XC_status() # use netconf to see XC status # test_result['mtu_mod_test'] = mtu_modification_test(my_config) # set Random MTU at Both End and then Revert back to 9186 MTU test_result['ccm_status'] = my_config.Validate_ccm() ## store CCM Test results. test_result['SR_ping'] = my_config.test_SR_OAM_PING() ## perform SR MPLS ping from NCS to NCS test_result['SR_trace'] = my_config.test_SR_OAM_trace() ## perform SR MPLS Trace from NCS to NCS test_result['CCM_ping'] = my_config.test_CCM_PING() ## perform CCM ping over the service test_result['CCM_trace'] = my_config.test_CCM_trace() ## perform CCM trace over the service # test_result['Y1564'] = my_config.Y1564_test() ## perform Y1564 test on Cisco(7.1.2) to Cisco, Acc to Acc, or Acc to Cisco # my_config.disconnect_nodes() ## release netmiko connection from NCS and Accedian. input_dict = my_config.create_spirent_input_dict() # create the required dictionary for spirent Traffic. Spirent_L2_Gen = Spirent_L2_Traffic_Gen() ## create the spirent object. Spirent_L2_Gen.Port_Init() # reserve the port. # test_result['ccm_transparency'] = ccm_transparency_test(A,B,my_config,Spirent_L2_Gen,**input_dict) # perform ccm transparency test(same level and lower should not pass) test_result['l2CP'] = l2CP_transparency_test(A,B,my_config,Spirent_L2_Gen,**input_dict) # perform L2CP test for P,PL EP's # test_result['UC_traffic'] = UC_BC_MC_test(A,B,'UC',my_config,Spirent_L2_Gen,**input_dict) # test Known Unicast Traffic. # test_result['BC_traffic'] = UC_BC_MC_test(A,B,'BC',my_config,Spirent_L2_Gen,**input_dict) # test Broadcast Traffic. # test_result['MC_traffic'] = UC_BC_MC_test(A,B,'MC',my_config,Spirent_L2_Gen,**input_dict) # test Multicast Traffic. # test_result['LLF_Spi_test'] = LLF_test(my_config,Spirent_L2_Gen,A,B,3) # do LLF test by breaking from spirent side. # test_result['LLF_UNI_test'] = LLF_UNI_Test(my_config,A,B,1) # do LLF test by shutting UNI # test_result['lag_test'] = lag_test(my_config,Spirent_L2_Gen,A,B,1) # perfrom LAG test with UNI LAG and NNI LAG with Accedian. # test_result['frr_test'] = fast_reroute_test(my_config,Spirent_L2_Gen,A,B,1) # perform FRR test ( Local shut) # rfc_stream_handle = get_rfc_stream_handle(A,B,Spirent_L2_Gen,**input_dict) # Create the RFC stream handles # test_result['rfc_fl_test'] = Spirent_L2_Gen.rfc_2544_frameloss_test(rfc_stream_handle[0],rfc_stream_handle[1]) # perform rfc Framelost Test. # test_result['rfc_tput_test'] = Spirent_L2_Gen.rfc_2544_throughput_test(rfc_stream_handle[0],rfc_stream_handle[1]) # my_config.connect_nodes() ## connect the nodes. test_result['ELAN_MAC_test'] = ELAN_MAC_test(A,B,my_config,Spirent_L2_Gen,**input_dict) Spirent_L2_Gen.Clean_Up_Spirent() ## Clean UP Spirent. # test_result['CFM_Stats_cisco'] = my_config.mep_statistic_cisco() # Check CCM,DM,SL statistics on NCS test_result['Polier_drop'] = my_config.check_QOS_drops() # Check drops on the input & output Policy. # test_result['Polier_CIR'] = my_config.check_QOS_configured_CIR() test_result['voq_stat'] = my_config.check_voq_stats() my_config.delete_config() # delete the config from NCS and Accedian. my_config.disconnect_nodes() # release netmiko connection from NCS and Accedian. # print(f"{'test_name':<15}{'result':<15}") # for k,v in test_result['ELAN_MAC_test'].items(): # print(f"{k:<15}{v:<15}") # pprint(test_result) return test_result
def __init__(self): self.entity = Entity() self.service = Service()
def browse(event): if not event: return False if not event['status']: return False metadata = False index = Service.upnpGetUI4(event['request'], CDSService.SERVICE_CDS_ARG_START_INDEX) count = Service.upnpGetUI4(event['request'], CDSService.SERVICE_CDS_ARG_REQUEST_COUNT) _id = Service.upnpGetUI4(event['request'], CDSService.SERVICE_CDS_ARG_OBJECT_ID) flag = Service.upnpGetString(event['request'], CDSService.SERVICE_CDS_ARG_BROWSE_FLAG) _filter = Service.upnpGetString(event['request'], CDSService.SERVICE_CDS_ARG_FILTER) sort_criteria = Service.upnpGetUI4( event['request'], CDSService.SERVICE_CDS_ARG_SORT_CRIT) manager = OneServerManager() manager.log.debug( "index=%s, count=%s, _id=%s, flag=%s, _filter=%s, sort_criteria=%s" % (index, count, _id, flag, _filter, sort_criteria)) if not flag or not _filter: return False # Validation checking. if flag == CDSService.SERVICE_CDS_BROWSE_METADATA: if index != 0: return False metadata = True elif flag == CDSService.SERVICE_CDS_BROWSE_CHILDREN: metadata = False else: return False entry = manager.rootEntry.getChild(_id) if not entry and _id < 0: manager.error("Invalid id {0}, defaulting to root".format(_id)) entry = manager.rootEntry if not entry: return False out = "" result_count = 0 if metadata: result_count, out = CDSService.cdsBrowseMetadata( event, out, index, count, entry, _filter) else: result_count, out = CDSService.cdsBrowseDirectChildren( event, out, index, count, entry, _filter) if result_count < 0: return False Service.upnpAddResponse(event, CDSService.SERVICE_CDS_DIDL_UPDATE_ID, CDSService.SERVICE_CDS_ROOT_OBJECT_ID) return event['status']
def getSystemUpdateId(event): Service.upnpAddResponse(event, CDSService.SERVICE_CDS_ARG_UPDATE_ID, CDSService.SERVICE_CDS_ROOT_OBJECT_ID) return event['status']
from flask import Flask, jsonify, request from models import * from service import Service app = Flask(__name__) service = Service() @app.route('/') def index(): return jsonify(name='FQueue REST API Service', version='1.0'), 200 @app.route('/claims', methods=["POST"]) def add_new_claim(): data = request.get_json() if data is None: return make_bad_request('it is not json') if ('flag' in data) & ('team' in data): claim = Claim(data['flag'], data['team']) try: cipher_claim = service.add_new_claim(claim) response = jsonify({'id': cipher_claim.id, 'cipher_text': cipher_claim.cipher_text, 'key': cipher_claim.key}) response.status_code = 201 return response except Exception: return make_bad_request('error in add claim') else:
def instance_inspect(name, uuid, namespace): service = Service.fetch(name, namespace) instance = service.get_instance(uuid) result = instance.inspect() util.print_json_result(result)
def backup_create(name, service_name, mounted_dir, namespace): service = Service.fetch(service_name, namespace) backup = Backup(service=service, name=name, mounted_dir=mounted_dir) backup.create()
def service_inspect(name, namespace): service = Service.fetch(name, namespace) result = service.inspect() util.print_json_result(result)