text
stringlengths
8
6.05M
# t9.py from collections import deque class DigitTree(): key_mapping = { "a": 2, "b": 2, "c": 2, "d": 3, "e": 3, "f": 3, "g": 4, "h": 4, "i": 4, "j": 5, "k": 5, "l": 5, "m": 6, "n": 6, "o": 6, "p": 7, "q": 7, "r": 7, "s": 7, "t": 8, "u": 8, "v": 8, "w": 9, "x": 9, "y": 9, "z": 9, } class DigitTreeNode(): def __init__(self): self.words = [] self.children = {} def __init__(self): self.root = self.DigitTreeNode() def digits(self, word): return ''.join([str(key_mapping[c]) for c in word]) def insert(self, word): node = self.root for digit in self.digits(word): if digit not in node.children: node.children[digit] = self.DigitTreeNode() node = node.children[digit] node.words.append(word) def search(self, digits): node = self.root for digit in digits: try: node = node.children[digit] except KeyError: return [] result = [] agenda = deque([node]) while len(agenda) > 0: node = agenda.popleft() result.extend(node.words) agenda.extend(node.children.values()) return result tree = DigitTree() words = [ "roach", "roaches", "poach", "poachers", "reach", "hello", "world" ] for word in words: tree.insert(word) print tree.search("76224") print tree.search("73")
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-04-12 21:36:40 # @Author : Fallen (xdd043@qq.com) # @Link : https://github.com/fallencrasher/python-learning # @Version : $Id$ #内置函数 #print(self,*args,sep=' ',end='\n',file=None) print(1,2,3,4,sep='|') print(1,2,3,4,end='\t') #list() 转换为列表 l1 = list('sjfoiwjfosj') print(l1) #dict() 转换为字典 #创建字典 dict1 = dict([(1,"one"),(2,"two")]) dict2 = dict(one=1,two=2) l2 = [1,2,3,4] dict3 = dict.fromkeys(l2,10) print(dict1) print(dict2) print(dict3) #abs() 求绝对值 *** print(abs(-6)) #sum() 求一个可迭代对象的和 l3 = [i for i in range(10)] print(sum(l3)) #sum() 可以设置初始值 print(sum(l3,100)) #就是,把100加到 l3 的加和里 #reverse() #列表的 list.reverse()方法是直接对原列表进行翻转 #reversed() 函数 , 是把对传入列表进行处理,产生一个新的翻转的迭代器 l4 = [i for i in range(10)] obj = reversed(l4) print(list(obj)) #zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组, #然后返回由这些元祖组成的内容,如果各个迭代器的元素个数不一致,则按照长度最短的返回 l5 = [1,2,3,4,5] tu1 = ('太白','b哥','degang') s1 = 'abcd' obj = zip(l5,tu1,s1) for i in obj: print(i) #(1, '太白', 'a') #(2, 'b哥', 'b') #(3, 'degang', 'c') print(list(obj)) #[(1, '太白', 'a'), (2, 'b哥', 'b'), (3, 'degang', 'c')] #*********以下方法超级重要*********** #min() max() l6 = [33,2,1,54,7,-1,-9] print(min(l6)) ##以绝对值的方式取最小值,min()和max() 函数,有参数 key=参数名,可以 ##对传入的可第二代对象中的每一个量传入 key 指定函数后,再求函数结果的 ##最小值,函数名可以直接用匿名函数替代 print(min(l6,key=abs)) print(max(l6,key=abs)) #求出值最小的键 dic = {'a':3,'b':2,'c':1} #如果直接用min,min()函数会取比较dic的键,而不是值 print(min(dic)) #要这么写,dict类型也是可迭代的,只是迭代的是键,没有值 print(min(dic,key = lambda a:dic[a] )) #求出年龄最小的那个人的元组 l7 = [('太白',18),('alex',73),('wusir',35),('口天吴',42)] print(min(l7,key=lambda a:a[1])) #sorted() 排序,他也有个 key 参数 l8 = [22,33,1,2,8,7,6,5] print(sorted(l8)) # l7列表中,让列表按年龄从小到大排序 print(sorted(l7,key=lambda a:a[1])) # l7列表中,让列表按年龄从大到小 print(sorted(l7,key=lambda a:a[1],reverse=True)) #filter() 筛选,可用于列表推导式的筛选模式,返回值是个迭代器 print([i for i in l8 if i>3]) print(list(filter(lambda a:a>3,l8))) #因为filter()返回迭代器,所以打印要加 list() #map() 函数,有俩参数,第一个参数是个函数名,第二个参数是个可迭代对象,把第二个参数书传入第一个参数的函数,并执行 #map() 返回值是个迭代器 l9 = [1,4,9,16,25] print([i**2 for i in range(1,6)]) print(list(map(lambda a:a**2,range(1,6)))) ##普遍一点,这样 def func3(a): return a**2 print(list(map(func3,l9))) #reduce() 函数 # reduce 的使用方式: # reduce(函数名,可迭代对象) # 这两个参数必须都要有,缺一个不行 #reduce() 函数是 functools 包里边的一个函数 #reduce的作用是先把列表中的前俩个元素取出计算出一个值然后临时保存着, #接下来用这个临时保存的值和列表中第三个元素进行计算,求出一个新的值将最开始 #临时保存的值覆盖掉,然后在用这个新的临时值和列表中第四个元素计算.依次类 from functools import reduce def func4(x,y): return x*10+y # # 第一次的时候 x是1 y是2 x乘以10就是10,然后加上y也就是2最终结果是12然后临时存储起来了 # # 第二次的时候x是临时存储的值12 x乘以10就是 120 然后加上y也就是3最终结果是123临时存储起来了 # # 第三次的时候x是临时存储的值123 x乘以10就是 1230 然后加上y也就是4最终结果是1234然后返回了 # ​ ret = reduce(func4,[1,2,3,4]) print(ret) #lambda print(reduce(lambda x,y:x*10+y,[1,2,3,4]))
df3 = df3[~df3.index.duplicated()]
#!/usr/bin/env python from setuptools import setup setup( name='mschap', version='1.0.6', author='bit0rez', author_email='b1t0r3z@gmail.com', description='Copy of mschap library for python. Library copied from IBS project (http://sourceforge.net/projects/ibs/).', long_description=open('README.md').read(), url='https://github.com/xjaner/mschap-python', packages=['mschap'], license='GNU General Public License', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.4', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
import pandas as pd import sqlalchemy as alc #import petl as etl __author__ = 'Meraz' dw_config = { "user": "root", "password": "claire", "host": "localhost", "database": 'diploma' } #DataFrame.to_sql(name, con, flavor='sqlite', schema=None, if_exists='fail', index=True, index_label=None, chunksize=None, dtype=None) #connection eng = alc.create_engine('mysql+pymysql://{user}:{password}@{host}/{database}'.format(**dw_config), echo=True) grad = pd.read_csv("GRADUATION_WITH_CENSUS_cleansed.csv") #table = etl.fromdataframe(grad) #print table grad.to_sql('grad', eng, if_exists='replace', index=True, chunksize=100)
from account.models import MyUser, MyUserProfile, RateReader from rate.models import Rate from countrycity.models import Location, Liner from rest_framework import serializers, status from django.contrib.auth.password_validation import validate_password class ProfileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = MyUserProfile fields = ('id', 'profile_name', 'job_boolean', 'company', 'image') class RateReaderSerializer(serializers.ModelSerializer): class Meta: model = RateReader fields = ('id', 'shower', 'reader') class RateUserSerializer(serializers.HyperlinkedModelSerializer): profile = ProfileSerializer(many=False) who_reads = RateReaderSerializer(many=True) class Meta: model = MyUser fields = ('id', 'email', 'nickname', 'profile', 'who_reads') class UserSerializer(serializers.HyperlinkedModelSerializer): profile = ProfileSerializer(many=False) class Meta: model = MyUser fields = ('id', 'email', 'nickname', 'profile') class UserCreateSerializer(serializers.ModelSerializer): profile = ProfileSerializer(many=False) class Meta: model = MyUser fields = ('id', 'email', 'nickname', 'password', 'profile') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): profile_data = validated_data.pop('profile') password = validated_data.pop('password') myuser = MyUser.objects.create(**validated_data) myuser.set_password(password) myuser.save() MyUserProfile.objects.create(owner=myuser, **profile_data) return myuser class UserUpdateSerializer(serializers.ModelSerializer): profile = ProfileSerializer(many=False) class Meta: model = MyUser fields = ('id', 'profile') def update(self, instance, validated_data): profile_data = validated_data.pop('profile') profile = instance.profile instance.email = validated_data.get('email', instance.email) instance.nickname = validated_data.get('nickname', instance.nickname) instance.save() profile.profile_name = profile_data.get( 'profile_name', profile.profile_name ) profile.company = profile_data.get( 'company', profile.company ) profile.job_boolean = profile_data.get( 'job_boolean', profile.job_boolean ) profile.save() return instance class ChangeProfileImageSerializer(serializers.Serializer): new_profile_image = serializers.ImageField(use_url=True) class ChangePasswordSerializer(serializers.Serializer): old_password = serializers.CharField(required=True) new_password = serializers.CharField(required=True) def validate_new_password(self, value): validate_password(value) return value class RateSerializer(serializers.ModelSerializer): inputperson = UserSerializer(read_only=True) class Meta: model = Rate fields = ( 'id', 'inputperson', 'account', 'liner', 'pol', 'pod', 'buying20', 'selling20', 'buying40', 'selling40', 'buying4H', 'selling4H', 'loadingFT', 'dischargingFT', 'effectiveDate', 'offeredDate', 'recordedDate', 'remark', 'deleted', ) class RateInputpersonSerializer(serializers.ModelSerializer): inputperson = serializers.CharField(source='inputperson.profile.profile_name') class Meta: model = Rate fields = ( 'inputperson', ) class RateAccountSerializer(serializers.ModelSerializer): class Meta: model = Rate fields = ( 'account', ) class RateLinerSerializer(serializers.ModelSerializer): class Meta: model = Liner fields = ( 'label', ) class RatePolSerializer(serializers.ModelSerializer): class Meta: model = Rate fields = ( 'pol', ) class RatePodSerializer(serializers.ModelSerializer): class Meta: model = Rate fields = ( 'pod', ) class LinerSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Liner fields = ('id', 'name', 'label') class LocationSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Location fields = ('id', 'name', 'country', 'label')
from . import analysis, config, io, pipeline, postprocess, segment
import requests import csv import json from bs4 import BeautifulSoup from pprint import pprint import yfinance as yf import threading def get_stock_list(): stocks = [] with open('stock_data.txt') as stock_string: stocks = stock_string.read() stocks = stocks.split(',') clean_data = [] for stock in stocks: if "^" in stock: stock = stock.replace("^", "-") clean_data.append(stock) elif "." in stocks: stock = stock.replace(".", "-") clean_data.append(stock) else: clean_data.append(stock) clean_data = clean_data[:10] print("Will work with ", len(clean_data), "stocks\n") return(clean_data) def grow_measurement(stock, percetage): interesting_data = {} try: info = yf.Ticker(stock) oney_hist = info.history(period="1y") oney_hist_string = str(oney_hist) oney_hist_list1 = oney_hist_string.split('\n') oney_hist_list2 = oney_hist_list1[2].split(' ') last_year = float(oney_hist_list2[4]) stock_last_close = info.info['previousClose'] anual_grow = ((stock_last_close*100)/last_year) - 100 anual_grow = round(anual_grow, 2) if anual_grow >= float(percetage): interesting_data.update({stock:{'anual_grow':anual_grow}}) interesting_data[stock].update({'actual':stock_last_close}) except IndexError: # print('valio pito') pass except ValueError: # print('valio mas pito') pass except ImportError: # print('valio mucho mas pito') pass except urllib.error.HTTPError: # print('valio mucho mas pito') pass with open("stock_data.json", "r+") as file: data = json.load(file) data.update(interesting_data) file.seek(0) json.dump(data, file) def grow_threaths(all_stocks, percetage, function): threaths = [] for stock in all_stocks: try: th = threading.Thread(target=function, args=(stock, percetage)) th.start() finally: threaths.append(th) for tr in threaths: tr.join() def one_y_premonition_yahoo(): interesting_data = {} with open("stock_data.json", 'r') as outfile: interesting_data = json.loads(outfile.read()) for key,value in interesting_data.items(): url = 'https://finance.yahoo.com/quote/' + key res = requests.get( url ) html = res.text soup = BeautifulSoup( html, 'html.parser' ) test = str(soup) if "ONE_YEAR_TARGET_PRICE-value" in test: market_cap_elem = soup.find( 'td', { 'data-test' : 'ONE_YEAR_TARGET_PRICE-value' } ) market_cap = market_cap_elem.text market_cap = market_cap.replace(',','') market_cap = market_cap.replace('$','') interesting_data[key].update({'premo':market_cap}) with open("stock_data.json", "r+") as file: data = json.load(file) data.update(interesting_data) file.seek(0) json.dump(data, file) def main(): all_stocks = get_stock_list() percetage = input("Give me the percentage for one year grow accepted: ") print('\n') grow_threaths(all_stocks, percetage, grow_measurement) one_y_premonition_yahoo() with open("stock_data.json", 'r') as outfile: interesting_data = json.loads(outfile.read()) pprint(interesting_data) # for stock in top20_list: # """ # Ver # Cuanto tiempo tiene la empresa # Cuanta es su ganancia en el ultimo anio y mes # Entender lo de el volumen para cuantificarlo # Ver los stackeholders # obtener el website # Numero de empleados # numero de shares 'floatShares" # 'fiftyDayAverage': 173.32559, # 'fiftyTwoWeekHigh': 190.7, # 'fiftyTwoWeekLow': 108.8, # 'enterpriseValue' # 'enterpriseToEbitda': 19.345, # 'enterpriseToRevenue': 8.828, # 'earningsQuarterlyGrowth': 0.383, # 'averageDailyVolume10Day': 75622200, # 'averageVolume': 31802203, # 'averageVolume10days': 75622200, # """ # append values in an ordered way to top20_table # # print(top20_table) """ As a pretty table """ if __name__ == '__main__': main()
import numpy as np n, q = [int(x) for x in input().split()] ans = np.zeros(n, dtype = int) for i in range(q): l,r,t = [int(x) for x in input().split()] ans[l-1:r] = t for i in range(n): print(ans[i])
from django.urls import path from . import views urlpatterns = [ path('', views.DeputiesList.as_view()), path('parties/', views.PartiesList.as_view()) ]
"""Define automations for plants.""" # pylint: disable=attribute-defined-outside-init,unused-argument from typing import Union from automation import Automation, Feature # type: ignore class PlantAutomation(Automation): """Define an automation for plants.""" class LowMoisture(Feature): """Define a feature to notify us of low moisture.""" @property def current_moisture(self) -> int: """Define a property to get the current moisture.""" return int(self.hass.get_state(self.entities['current_moisture'])) def initialize(self) -> None: """Initialize.""" self._low_moisture = False self.hass.listen_state( self.low_moisture_detected, self.entities['current_moisture'], constrain_input_boolean=self.enabled_toggle) def low_moisture_detected( # pylint: disable=too-many-arguments self, entity: Union[str, dict], attribute: str, old: str, new: str, kwargs: dict) -> None: """Notify when the plant's moisture is low.""" if (not (self._low_moisture) and int(new) < int(self.properties['moisture_threshold'])): self.hass.log( 'Notifying people at home that plant is low on moisture') self._low_moisture = True self.handles[ self.hass. friendly_name] = self.hass.notification_manager.repeat( '{0} is Dry 💧'.format(self.hass.friendly_name), '{0} is at {1}% moisture and needs water.'.format( self.hass.friendly_name, self.current_moisture), self.properties['notification_interval'], target='home') else: self._low_moisture = False if self.hass.friendly_name in self.handles: self.handles.pop(self.hass.friendly_name)()
import vcf import sys import time MOTHER_SAMPLE = 9 FATHER_SAMPLE = 10 def de_novo_one_parent(progeny, parent): for n in progeny: if n in parent: return False return True def de_novo_both_parents(progeny, parents): possible_progeny = [[parents[0][0], parents[1][0]], [parents[0][0], parents[1][1]], [parents[0][1], parents[1][0]], [parents[0][1], parents[1][1]]] if (progeny in possible_progeny) or (progeny[::-1] in possible_progeny): return False return True def run(filepath): # speed testing t0 = time.time() n_records = 0 # opens file with PyVCF vcf_reader = vcf.Reader(open(filepath, 'rb')) vcf_writer = vcf.Writer(open('output_de_novo_no_filter.vcf', 'w'), vcf_reader) SAMPLES = ['701-1-1', '701-1-3', '701-1-6', '701-1-7', '701-2-1', '701-2-2', '701-2-3', '701-2-4', '701-3-2', '701-Female', '701-Male'] de_novo_counts = {sample: 0 for sample in SAMPLES} # none_y_calls = {sample: 0 for sample in SAMPLES} # none_x_calls = {sample: 0 for sample in SAMPLES} # het_x_calls = {sample: 0 for sample in SAMPLES} # none_all = {sample: 0 for sample in SAMPLES} # num_x = 0 # num_y = 0 for record in vcf_reader: n_records += 1 match_type = 0 de_novo = False mother = record.samples[MOTHER_SAMPLE] father = record.samples[FATHER_SAMPLE] if mother['GT'] is None: if father['GT'] is None: match_type = 0 else: one_parent = [father['GT'][0], father['GT'][2]] # print 'father:', one_parent match_type = 1 else: if father['GT'] is None: one_parent = [mother['GT'][0], mother['GT'][2]] # print 'mother:', one_parent match_type = 1 else: both_parents = [[mother['GT'][0], mother['GT'][2]], [father['GT'][0], father['GT'][2]]] # print 'both:', both_parents match_type = 2 # try: # if (sum(mother['AD']) < 10) or (sum(father['AD']) < 10): # match_type = 0 # except: # pass if match_type != 0: for sample in range(0, 9): progeny = record.samples[sample] if progeny['GT'] is not None: progeny_gt = [progeny['GT'][0], progeny['GT'][2]] if match_type == 1: if de_novo_one_parent(progeny_gt, one_parent): # print record.INFO # record.INFO = progeny.sample de_novo_counts[progeny.sample] += 1 # print 'de novo!!!', record, progeny_gt, 'p:', one_parent de_novo = True elif match_type == 2: if de_novo_both_parents(progeny_gt, both_parents): de_novo = True de_novo_counts[progeny.sample] += 1 # print 'de novo!!!', record, progeny_gt, 'p:', both_parents else: pass if de_novo: vcf_writer.write_record(record) if n_records % 10000 == 0: print 'Processed', n_records, 'records...' # break # print 'X chr none calls:', none_x_calls, num_x # print 'X chr het calls:', het_x_calls, num_x # print 'Y chr none calls:', none_y_calls, num_y print de_novo_counts, 'total records:', n_records t1 = time.time() print 'Buona notte!', t1-t0, 'seconds have passed.' if __name__ == '__main__': run(sys.argv[1])
from django.http import HttpResponse from rest_framework.views import APIView from rest_framework import status from rest_framework.response import Response from .models import Article from .serializerModel import ArticlesSerializer from rest_framework import status class ArticleApiView(APIView): def get(self, request): article = Article.objects.all() serializer = ArticlesSerializer(article,many=True) return Response(serializer.data) def post(self, request): serializer = ArticlesSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data,status.HTTP_202_ACCEPTED) return Response(serializer.errors,status.HTTP_400_BAD_REQUEST) class ArticleDetailApiView(APIView): def get_object(self,id): try: article = Article.objects.get(pk=id) return article except: return HttpResponse(status=status.HTTP_404_NOT_FOUND) def get(self,request, id): article = self.get_object(id) serializer = ArticlesSerializer(article) return Response(serializer.data,status.HTTP_202_ACCEPTED) def put(self,request, id): serializer = ArticlesSerializer(self.get_object(id),request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data,status.HTTP_202_ACCEPTED) else: return Response(serializer.errors,status.HTTP_400_BAD_REQUEST) def delete(self,request,id): self.get_object(id).delete() return Response(status=status.HTTP_204_NO_CONTENT)
import urllib3 from PIL import Image import numpy as np import boto3 import io import os def lambda_handler(event, context): from_number = event['fromNumber'] pic_url = event['image'] num_media = event['numMedia'] if num_media != '0': http = urllib3.PoolManager() response = http.request('GET', pic_url) scaled_image = Image.open(io.BytesIO(response.data)).convert('L').resize((200,200)) payload = '' for i in np.asarray(scaled_image.convert('L')).flatten(): payload += f'{i},' payload = payload[:-1] client = boto3.client('runtime.sagemaker') response = client.invoke_endpoint(EndpointName=os.environ.get('SGM_ARN'), ContentType='text/csv', Body=payload) prediction = response['Body'].read().decode() twilio_resp = prediction else: twilio_resp = 'There was an error' return '<?xml version=\"1.0\" encoding=\"UTF-8\"?>'\ f'<Response><Message><Body>{twilio_resp}</Body></Message></Response>'
from utils import * from tqdm import tqdm import os if __name__ == '__main__': train_text_data_path = os.path.abspath('..') + '/gen_data/data/train_text_data.pkl' train_text_data = load_pkl_data(train_text_data_path) question_ids = {} pos_ans_ids = {} neg_ans_ids = {} corpus = [] corpus_sentence = [] corpus_path = os.path.abspath('.') + '/data/corpus.txt' corpus_sentence_path = os.path.abspath('.') + '/data/corpus_sentence.pkl' with tqdm(total=len(train_text_data)) as pbar: for item in train_text_data: question_id = item.question_id pos_ans_id = item.pos_ans_id neg_ans_id = item.neg_ans_id if question_ids.get(question_id, 'N') == 'N': question_ids[question_id] = 'Y' corpus.append(item.q_content) if pos_ans_ids.get(pos_ans_id, 'N') == 'N': pos_ans_ids[pos_ans_id] = 'Y' corpus.append(item.p_ans_content) if neg_ans_ids.get(neg_ans_id, 'N') == 'N': neg_ans_ids[neg_ans_id] = 'Y' corpus.append(item.n_ans_content) pbar.update(1) with open(corpus_path, 'w', encoding='utf-8') as fp: for item in corpus: text = ''.join([token+' ' for token in item]) fp.write(text) with tqdm(total=len(corpus)) as pbar: for item in corpus: sentence = [token for token in item] corpus_sentence.append(sentence) pbar.update(1) save_pkl_data(corpus_sentence, corpus_sentence_path) print('end')
#!/usr/bin/env python # -*- coding: utf-8 -*- from NaoCreator.setting import Setting Setting(nao_connected=False, debug=True, bypass_wait_for=False, nao_quest_v="2.1", load_cpt_data=False, ip="169.254.88.3", USE_MIC=False) from NaoQuest.questor import Questor from PlayerManager.player_manager import Player from NaoSimulator.get_mic_input import record Player("swan").save() q = Questor('PlanterBulbe', "swan") q.launch() q.player.save()
from django.contrib import admin from.models import Product, Comment, Order class CommentInLine(admin.TabularInline): model = Comment extra = 0 @admin.register(Order) class Admin(admin.ModelAdmin): fields = ('product_fk', 'user_fk', 'product_count', 'cost', 'order_code', 'date_order',) list_display = ('product_fk', 'user_fk', 'product_count', 'cost', 'order_code', 'date_order',) list_filter = ('order_code', 'date_order', 'accepted',) @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ('name', 'price', 'count', 'description') fields = ('name', 'price', 'count', 'description', 'image') inlines = [CommentInLine,] class CommentAdmin(admin.ModelAdmin): list_display = ('comment', 'author', 'time_stamp') fields = (('fk_product', 'author'), 'comment') admin.site.register(Comment, CommentAdmin)
from math import cos,pi,radians import time def dcos(a): return cos(radians(a)) def motor1(value): if value<0 and value >=-255: motor1r = 0 motor1l = 1 motor1speed = abs(value) print('Motor1 is rotating CCW') elif value>0 and value<=255: motor1r = 1 motor1l = 0 motor1speed = abs(value) print('Motor1 is rotating CW') elif value == 0: motor1r = 0 motor1l = 0 motor1speed = 0 print('Motor1 is not rotating') elif value<-255 or value>255: print('error') #come back and do changes here def motor2(value): if value<0 and value >=-255: motor2r = 0 motor2l = 1 motor2speed = abs(value) print('Motor2 is rotating CCW') if value>0 and value <=255: motor2r = 1 motor2l = 0 motor2speed = abs(value) print('Motor2 is rotating CW') if value == 0: motor2r = 0 motor2l = 0 motor2speed = 0 print('Motor2 is not rotating') if value<-255 or value>255: print('error') #come back and do changes here def motor3(value): if value<0 and value >=-255: motor3r = 0 motor3l = 1 motor3speed = abs(value) print('Motor3 is rotating CCW') if value>0 and value <=255: motor3r = 1 motor3l = 0 motor3speed = abs(value) print('Motor3 is rotating CW') if value == 0: motor3r = 0 motor3l = 0 motor3speed = 0 print('Motor3 is not rotating') if value<-255 or value>255: print('error') #come back and do changes here def move(DesiredDirection,velocity): #velocity from 0 to 255 Fa = velocity*dcos(150 - DesiredDirection) #motor 1 Fb = velocity*dcos(30 - DesiredDirection) #motor 2 Fc = velocity*dcos(270 - DesiredDirection) #motor 3 print('Motor 1 Speed is',round(Fa)) print('Motor 2 Speed is',round(Fb)) print('Motor 3 Speed is',round(Fc)) motor1(round(Fa)) motor2(round(Fb)) motor3(round(Fc)) return def turn(DesiredAngle,velocity): R
class Point: def __init__(self, x, y): self.x = x self.y = y class BarycentricLagrange: # initialize the class with data points def __init__(self, data_points): # data_points is an array of Point objects self.data_points = data_points self.weights = [] # calculate the weight of initial data points for i in range(len(self.data_points)): self.calculate_weight(i) # calculate the weight of data_points[point_index] def calculate_weight(self, point_index): result = 1 for i in range(len(self.data_points)): if point_index != i : result *= self.data_points[point_index].x - self.data_points[i].x self.weights.insert(point_index, 1/result) def interpolation(self, x): numerator = 0 denominator = 0 for i in range(len(self.data_points)): if (x-self.data_points[i].x) == 0: # if x exists in data points. return self.data_points[i].y temp = self.weights[i] / (x-self.data_points[i].x) denominator += temp numerator += temp * self.data_points[i].y return numerator/denominator # add a single point to data points def add_point(self, new_point): for i in range(len(self.data_points)): # check to see if the x attribute of the new point already exists. if new_point.x == self.data_points[i].x: # if so, only update the y attribute self.data_points[i].y = new_point.y return # update weights for i in range(len(self.data_points)): self.weights[i] *= 1/(self.data_points[i].x - new_point.x) self.data_points.append(new_point) # calculate the weight of the new point self.calculate_weight(len(self.data_points)-1) if __name__ == "__main__": point1 = Point(4, 21/5) point2 = Point(3/4, 11.7) point3 = Point(2.5, 531/5) point5 = Point(1.5, 10) point6 = Point(2.5, 5.5) point7 = Point(4.5, 80) new_points = [point5, point6, point7] dp = [point1, point2, point3] bl = BarycentricLagrange(dp) print("interpolation with initial data points:") print(bl.interpolation(1.7)) print(bl.interpolation(2.3)) print(bl.interpolation(3.2)) print(bl.interpolation(3.5)) print(bl.interpolation(4.2)) for i in range(3): print("after adding new data point #",i+1) bl.add_point(new_points[i]) print(bl.interpolation(1.7)) print(bl.interpolation(2.3)) print(bl.interpolation(3.2)) print(bl.interpolation(3.5)) print(bl.interpolation(4.2))
import time import webbrowser from pywin.tools import browser from selenium.webdriver.firefox.options import Options as FirefoxOptions from selenium import webdriver from selenium import * from selenium.webdriver.common.keys import Keys options = webdriver.FirefoxOptions() options.add_argument("-headless") driver = webdriver.Firefox(options=options) siteOpt = [ "1) LinkedIn", "2) Indeed", "3) Other" ] jobUrl = { "1": "https://www.linkedin.com/jobs/", "2": "https://www.indeed.com/" } ################## ################## print("WELCOME TO AUTO JOB SEARCH!\n" + "=" * 30) print("WHICH JOB SITE WOULD YOU LIKE TO USE TODAY?") print(*siteOpt, sep="\n") jobSite = input() while int(jobSite) > 2: print("ERROR: PLEASE ENTER A CONSOLE NUMBER!") jobSite = input() sel_jobSite = jobSite print("WHAT JOB TITLE DO YOU WANT TO APPLY FOR?") jobTitle = input() print("HOW MANY JOB LISTINGS WOULD YOU LIKE TO APPLY FOR? \n *LIMIT 50*") hmt = int(input()) # LIMIT CHECK while hmt > 51: print("PLEASE ENTER A NUMBER LESS THAN 50") hmt = int(input()) if hmt < 51: break ################## # init job srch def main_fcs(): if jobSite in jobUrl: webbrowser.open(jobUrl[sel_jobSite]) time.sleep(10) jobTitle_fill = driver.find_element_by_xpath('//input[@id="text-input-what"]') jobTitle_fill.send_keys(jobTitle) driver.close() else: print("NOTHING!") ########## # INIT DEF ######### main_fcs()
#!/usr/bin/python """ This is the code to accompany the Lesson 3 (decision tree) mini-project. Use a Decision Tree to identify emails from the Enron corpus by author: Sara has label 0 Chris has label 1 """ import sys from time import time sys.path.append("../tools/") from email_preprocess import preprocess from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import accuracy_score import numpy ### features_train and features_test are the features for the training ### and testing datasets, respectively ### labels_train and labels_test are the corresponding item labels features_train, features_test, labels_train, labels_test = preprocess() ######################################################### ### your code goes here ### ######################################################### def ex1(): #create the classifier object classifier = DecisionTreeClassifier(min_samples_split=40) #fit with the training data and labels classifier.fit(features_train, labels_train) #do the prediction for test data predicted = classifier.predict(features_test) print str(accuracy_score(predicted, labels_test)) def ex2(): #get the number of features from the training data # its the number of columns per row print str(numpy.shape(features_train)[1]) if __name__ == "__main__": ex1()
import unittest from katas.kyu_8.opposite_number import opposite class OppositeNumberTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(opposite(1), -1) def test_equals_2(self): self.assertEqual(opposite(25.6), -25.6) def test_equals_3(self): self.assertEqual(opposite(0), 0) def test_equals_4(self): self.assertEqual(opposite(1425.2222), -1425.2222) def test_equals_5(self): self.assertEqual(opposite(-3.1458), 3.1458) def test_equals_6(self): self.assertEqual(opposite(-95858588225), 95858588225)
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 # Copyright (c) 2012 dput authors # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. import sys import argparse # A little temporary hack for those of us not using virtualenv import os sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) import dput.core import dput.changes import dput.exceptions from dput import upload_package from dput.profile import parse_overrides parser = argparse.ArgumentParser(description='Debian package upload tool') parser.add_argument('-d', '--debug', action='count', default=False, help="Enable debug messages. Repeat twice to increase the " "verbosity level") parser.add_argument('-c', '--config', metavar="FILE", action='store', default=None, help='Configuration file to parse') parser.add_argument('-D', '--dinstall', action='store_true', help='(silently ignored)') parser.add_argument('-e', '--delayed', action='store', metavar="DAYS", help='Upload to a delayed queue. Takes an argument from 0 to 15', type=int, choices=range(0, 16)) parser.add_argument('-F', '--full-upload-log', action='store_true', help='Write more verbose .upload logs') parser.add_argument('-f', '--force', action='store_true', help='Force an upload') parser.add_argument('-l', '--lintian', action='store_true', help='Run lintian before upload (deprecated)') parser.add_argument('-U', '--no-upload-log', action='store_true', help='Do not write an .upload log after uploading') parser.add_argument('-o', '--check-only', action='store_true', help='Only check the package') parser.add_argument('-O', '--override', action='append', help='override profile key') parser.add_argument('-S', '--unset', action='append', help='override profile key by unsetting its value') parser.add_argument('-P', '--passive', action='store_true', help='Use passive mode for ftp uploads') parser.add_argument('-s', '--simulate', action='count', default=False, help="Simulate the upload only. Repeat twice to increase " "the level of simulation. Provided once runs pre-upload " "checks, provided twice runs pre-upload checks and network" " set-up without actually uploading files") parser.add_argument('-u', '--unchecked', action='store_true', help='Don\'t check GnuPG signature') parser.add_argument('-v', '--version', action='store_true', help='(silently ignored)') parser.add_argument('-V', '--check-version', action='store_true', help='(ignored)') parser.add_argument('host', metavar="HOST", action='store', default=None, help="Target host to upload a package", nargs="?") parser.add_argument('changes', metavar="CHANGES-FILE", action='store', default=None, nargs='+', help="A Debian .changes file") args = parser.parse_args() if args.host and args.host.endswith(".changes") and os.path.isfile(args.host): args.changes.insert(0, args.host) args.host = None if args.config: dput.core.DPUT_CONFIG_LOCATIONS[args.config] = 1 if args.debug: dput.core._enable_debugging(args.debug) try: overrides = [] if args.unset: for arg in args.unset: overrides.append("-%s" % (arg)) if args.override: for arg in args.override: overrides.append(arg) args.override = parse_overrides(overrides) for changes in args.changes: changes = dput.changes.parse_changes_file( changes, os.path.dirname(changes) ) upload_package(changes, args) # XXX: avoid only uploading one and breaking due to an UploadException? except dput.exceptions.DputConfigurationError as e: dput.core.logger.critical(str(e)) dput.core.maybe_print_traceback(args.debug, sys.exc_info()) sys.exit(2) except dput.exceptions.UploadException as e: dput.core.logger.critical(str(e)) dput.core.maybe_print_traceback(args.debug, sys.exc_info()) sys.exit(3) except dput.exceptions.HookException as e: dput.core.logger.critical(str(e)) dput.core.maybe_print_traceback(args.debug, sys.exc_info()) sys.exit(1) except EnvironmentError as e: dput.core.logger.critical(str(e)) dput.core.maybe_print_traceback(args.debug, sys.exc_info()) sys.exit(2) except KeyboardInterrupt: sys.exit(0)
class Solution: def closedIsland(self, grid: List[List[int]]) -> int: """ https://leetcode.com/problems/number-of-closed-islands well flags were not declared as it should be. loops needed more strict range. my bad. """ m, n = len(grid), len(grid[0]) island = 0 def dfs(i:int, j:int) -> bool: if grid[i][j] == 1: return True if (i == 0 or i == m-1 or j == 0 or j == n-1): return False grid[i][j] = 1 a = dfs(i-1, j) b = dfs(i, j-1) c = dfs(i+1, j) d = dfs(i, j+1) return a and b and c and d for i in range(1, m-1): for j in range(1, n-1): if grid[i][j] == 0 and dfs(i,j): island += 1 return island
__author__ = 'Sebastian Bernasek' from copy import deepcopy import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from scipy.stats import ttest_ind, ks_2samp from .base import Base from .settings import * from .palettes import Palette from flyeye.processing.alignment import MultiExperimentAlignment class HorizontalBoxplot(Base): """ Object for constructing horizontal boxplot comparisons. Attributes: orientation (str) - indicates whether figure is horizontal/vertical Inherited attributes: data (pd.DataFrame) - data fig (matplotlib.figure.Figure) """ # set class path and name path = 'graphics/comparison' @classmethod def from_experiment(cls, experiment, **kwargs): """ Instantiate from Experiment instance. Cells concurrent with early R-cells are selected by default. Args: experiment (data.experiments.Experiment) kwargs: keyword arguments for cell selection Returns: figure_obj (figures.base.Base derivative) """ # determine which channel corresponds to yan yan_channel = cls.get_yan_channel(experiment) # get early neuron data and delineate metrics data = experiment.get_early_neuron_data(**kwargs) data = cls._delineate_metrics(data, yan_channel=yan_channel) # instantiate figure object figure_obj = cls(data=data) return figure_obj def render(self, height=1.5, aspect=1.25, width=.75, lw=0.75, cell_types=None): """ Render boxplot. Args: height (float) - figure height passed to seaborn.FacetGrid aspect (float) - figure aspect ratio passed to seaborn.FacetGrid width (float) - artist patch width lw (float) - artist line width cell_types (list of lists) - early R cell types to be included """ # get neuron classes and corresponding labels if cell_types is None: cell_types = [['r8'],['r2','r5'],['r3', 'r4'],['r1','r6'],['r7']] r_cell_types = ['/'.join(types).upper() for types in cell_types] # get data data = self.data[self.data['ReferenceType'].isin(r_cell_types)] # create facetgrid and plot data fig = self.plot(data, height=height, aspect=aspect, width=width, lw=lw) self.set_patch_colors(fig, cell_types=cell_types) # format axes self.format_axes(fig) self.format_ticklabels(fig, cell_types, self.orientation) # store output self.fig = fig def plot(self, data, height=1.5, aspect=1.25, width=0.75, lw=0.75): """ Create facetgrid and plot data using seaborn.boxplot method. Data must contain Metric, Score, ReferenceType, and Population keys as these are used to categorically partition data within the figure. Args: data (pd.DataFrame) - data height (float) - figure height passed to seaborn.FacetGrid aspect (float) - figure aspect ratio passed to seaborn.FacetGrid width (float) - artist patch width lw (float) - artist line width Returns: fig (matplotlib.figure.Figure) """ order = ['R8', 'R2/R5', 'R3/R4', 'R1/R6', 'R7'] hue_order = ['Multipotent', 'Differentiated'] grid = sns.FacetGrid(data, col="Metric", height=height, aspect=aspect, sharey=False) fig = grid.map(sns.boxplot, "ReferenceType", "Score", "Population", order=order, hue_order=hue_order, orient='v', fliersize=0, linewidth=lw, notch=True, width=width) fig.despine(left=False, right=False, top=False) self.orientation = 'v' return fig @staticmethod def _delineate_metrics(data0, yan_channel='ch2_normalized'): """ Delineate early neuron data with Metric/Score attributes. """ data0['Metric'] = 'Pnt' data0['Score'] = data0.ch1_normalized data1 = deepcopy(data0) data1['Metric'] = 'Yan' data1['Score'] = data1[yan_channel] data2 = deepcopy(data0) data2['Metric'] = 'Ratio' data2['Score'] = data2.logratio delineated_data = pd.concat((data0, data1, data2)) return delineated_data @staticmethod def set_patch_colors(fig, cell_types, lw=1): """ Set colors for patch objects (boxes). Args: fig (matplotlib.figure.Figure) cell_types (list of lists) - cell types used to define colors colorer (figures.palettes.Palette) - colormap for cell types lw (float) - patch line width """ colorer = Palette() for ax in fig.axes.ravel(): for i, artist in enumerate(ax.artists): # get color from colorer neuron = cell_types[i // 2][0] if i % 2 == 0: color = colorer(neuron) greys = Palette({'grey': 'grey'}) artist.set_facecolor(greys('grey', 'light', shade=1)) artist.set_edgecolor(color) artist.set_linewidth(lw) else: color = colorer(neuron) artist.set_facecolor(color) @staticmethod def format_ticklabels(fig, cell_types, orientation='v'): """ Set neuron type labels and label colors. """ colorer = Palette() # get axes iterable if type(fig.axes) == list: axes = fig.axes else: axes = fig.axes.ravel() # format each axis for ax in axes: # set axis label labels = ['{:s}'.format('/'.join(types).upper()) for types in cell_types] if orientation == 'v': ax.set_xticklabels(labels) ticks = ax.xaxis.get_ticklabels() else: ax.set_yticklabels(labels) ticks = ax.yaxis.get_ticklabels() for i, label in enumerate(ticks): # get color from colorer types = cell_types[i] cell_type = types[0] color = colorer(cell_type) # set text and color label.set_color(color) @staticmethod def format_axes(fig): """ Format figure axes. """ # get axes objects axes = fig.axes[0] ax0, ax1, ax2 = axes # set axis limits for ax in axes[0:2]: ax.set_ylim(0, 2) ax.set_yticks(np.arange(0, 2.5, 0.5)) axes[-1].set_ylim(-2, 2) axes[-1].set_yticks(np.arange(-2, 2.5, 1)) # set axis labels ax0.set_ylabel('Pnt Expression (a.u.)') ax1.set_ylabel('Yan Expression, (a.u.)') ax2.set_ylabel('log2 Ratio') fig.set_xlabels('') fig.set_titles('') # set spacing betwee subplots plt.subplots_adjust(wspace=0.5) # format ticks for ax in axes: ax.tick_params(axis='both', direction='in', length=3) def get_statistics(self, test='ks_2samp', rounding=1): """ Perform statistical test to determine whether or not expression levels differ between cell types. Args: test (str) - statistical test used rounding (int) - rounding applied to log10(pvalues) Returns: pvalues (dict) - nested {metric: {cell_type: {test: pvalue}}} pairs where metric is the quantity being compared, cell type indicates the concurrent population of early R cells, test denotes the type of statistical test, and pvalue is the resultant pvalue. """ channel_names = dict(ch1_normalized='PntGFP', ch2_normalized='Yan', logratio='P:Y ratio') # determine unique populations cell_types = self.data['ReferenceType'].unique() # get test if test == 'ks_2samp': test = lambda x, y: ks_2samp(x, y) elif test == 'welch': test = lambda x, y: ttest_ind(x, y, equal_var=False) elif test == 't': test = lambda x, y: ttest_ind(x, y, equal_var=True) # iterate across channels to be compared stats = {} for channel in ('ch1_normalized', 'ch2_normalized', 'logratio'): stats[channel_names[channel]] = {} # iterate across neuron types for types in cell_types: # get early neurons and concurrent progenitors current = self.data[self.data['ReferenceType']==types] multipotent = current[current.Population=='Multipotent'][channel].values differentiated = current[current.Population=='Differentiated'][channel].values # apply test and store log10 pval ks, pval = test(multipotent, differentiated) stats[channel_names[channel]][types] = np.log10(pval) # compile and sort dataframe data = pd.DataFrame.from_dict(stats) columns = ['PntGFP', 'Yan', 'P:Y ratio'] return data.loc[cell_types][columns].round(rounding) class VerticalBoxplot(HorizontalBoxplot): """ Object for constructing horizontal boxplot comparisons. Inherited attributes: data (pd.DataFrame) - data fig (matplotlib.figure.Figure) orientation (str) - indicates whether figure is horizontal/vertical """ def plot(self, data, height=1.5, aspect=1.25, width=.75, lw=0.75): """ Create facetgrid and plot data using seaborn.boxplot method. Data must contain Metric, Score, ReferenceType, and Population keys as these are used to categorically partition data within the figure. Args: data (pd.DataFrame) - data containing Metric, Score, ReferenceType, and Population keys. height (float) - figure height passed to seaborn.FacetGrid aspect (float) - figure aspect ratio passed to seaborn.FacetGrid width (float) - artist patch width lw (float) - artist line width Returns: fig (matplotlib.figure.Figure) """ order = ['R8', 'R2/R5', 'R3/R4', 'R1/R6', 'R7'] hue_order = ['Multipotent', 'Differentiated'] grid = sns.FacetGrid(data, row="Metric", height=height, aspect=aspect, sharex=False) fig = grid.map(sns.boxplot, "Score", "ReferenceType", "Population", order=order, hue_order=hue_order, orient='h', fliersize=0, linewidth=lw, notch=True, width=width) fig.despine(left=False, right=False, top=False, bottom=False) self.orientation = 'h' return fig @staticmethod def format_axes(fig): # get axes objects axes = fig.axes.ravel() ax0, ax1, ax2 = axes # set axis limits for ax in axes[0:2]: ax.set_xlim(-0, 2) ax.set_xticks(np.arange(0., 2.5, 0.5)) axes[-1].set_xlim(-2, 2) axes[-1].set_xticks(np.arange(-2, 3, 1)) # set axis labels ax0.set_xlabel('Pnt Expression (a.u.)') ax1.set_xlabel('Yan Expression (a.u.)') ax2.set_xlabel('log2 Ratio') fig.set_ylabels('') fig.set_titles('') # set spacing between subplots plt.subplots_adjust(hspace=0.5) # format axes for ax in axes: ax.xaxis.set_ticks_position('bottom') ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['left'].set_position(('outward', 5)) ax.spines['bottom'].set_position(('outward', 5)) yticks = ax.get_yticks() ax.spines['left'].set_bounds(yticks[0], yticks[-1]) class ViolinPlot(VerticalBoxplot): """ Object for constructing vertical violinplot comparisons. Creates facetgrid and plot data using seaborn.boxplot method. Data must contain Metric, Score, ReferenceType, and Population keys as these are used to categorically partition data within the figure. Inherited attributes: data (pd.DataFrame) - data fig (matplotlib.figure.Figure) orientation (str) - indicates whether figure is horizontal/vertical """ def plot(self, data, height=4, aspect=1, lw=1, **kwargs): """ Create facetgrid and plot data using seaborn.violin method. Data must contain Metric, Score, ReferenceType, and Population keys as these are used to categorically partition data within the figure. Args: data (pd.DataFrame) - data height (float) - figure height passed to seaborn.FacetGrid aspect (float) - figure aspect ratio passed to seaborn.FacetGrid lw (float) - artist line width Returns: fig (matplotlib.figure.Figure) """ grid = sns.FacetGrid(data, row="Metric", height=height, aspect=aspect, sharex=False) fig = (grid.map(sns.violinplot, "Score", "ReferenceType", "Population", orient='h', split=True, scale="area", inner='quartile', linewidth=lw, bw=.25, scale_hue=False)) fig.despine(left=False, right=False, top=False, bottom=False) self.orientation = 'h' return fig class DosingComparison(VerticalBoxplot): """ Object for constructing boxplot comparison of expression levels between two experiments with different PntGFP dosages. Creates facetgrid and plot data using seaborn.boxplot method. Data must contain Metric, Score, ReferenceType, and Population keys as these are used to categorically partition data within the figure. Attributes: pvalues (dict) - comparison statistics Inherited attributes: data (pd.DataFrame) - data fig (matplotlib.figure.Figure) orientation (str) - indicates whether figure is horizontal/vertical """ def __init__(self, data, orientation='v'): """ Instantiate gene dosage comparison figure. Args: data (pd.DataFrame) - data for figure orientation (str) - indicates whether figure is horizontal/vertical """ super().__init__(data) self.orientation = orientation @classmethod def from_experiment(cls, pnt1x, pnt2x, orientation='v', **kwargs): """ Instantiate from data.experiments.Experiment instances. Cells concurrent with early R-cells are selected by default. Args: pnt1x (data.experiments.Experiment) - first PntGFP dosage condition pnt2x (data.experiments.Experiment) - second PntGFP dosage condition orientation (str) - indicates whether figure is horizontal/vertical kwargs: keyword arguments for early R cell selection Returns: figure_obj (figures.base.Base) """ # align experiments alignment = MultiExperimentAlignment(pnt1x, pnt2x) pnt1x_aligned, pnt2x_aligned = alignment.get_aligned_experiments() # get early neuron data data_1x = pnt1x_aligned.get_early_neuron_data(**kwargs) data_2x = pnt2x_aligned.get_early_neuron_data(**kwargs) # assign gene dosage labels data_1x['Dosing'] = '1X PntGFP' data_2x['Dosing'] = '2X PntGFP' dosing_data = pd.concat((data_1x, data_2x)) # only use progenitors data = dosing_data[dosing_data.Population=='Multipotent'] # instantiate DosingComparisonFigure object return cls(data=data, orientation=orientation) def render(self, channel='logratio', figsize=(2, 1.5), width=.75, lw=0.75, cell_types=None): """ Render boxplot comparing gene dosage conditions. Args: channel (str) - expressional channel to be compared figsize (tuple) - figure size width (float) - artist patch width lw (float) - artist line width cell_types (list of lists) - early R cell types to be included """ # select data concurrent with specified cell types if cell_types is None: cell_types = [['r8'],['r2','r5'],['r3', 'r4'],['r1','r6'],['r7']] r_cell_types = ['/'.join(types).upper() for types in cell_types] data = self.data[self.data['ReferenceType'].isin(r_cell_types)] # create figure self.fig = self.create_figure(figsize=figsize) # plot data self.plot(data, channel=channel, width=width, lw=lw) self.set_patch_colors(self.fig.axes[0], cell_types=cell_types) # format axes self._format_ax(self.fig.axes[0], channel, self.orientation) self.format_ticklabels(self.fig, cell_types, self.orientation) def plot(self, data, channel='logratio', width=0.75, lw=1): """ Create facetgrid and plot data using seaborn.boxplot method. Data must contain Metric, Score, ReferenceType, and Population keys as these are used to categorically partition data within the figure. Args: data (pd.DataFrame) - data containing ReferenceType and Dosing keys. channel (str) - expressional channel to be compared width (float) - artist patch width lw (float) - artist line width """ # define colors for 1x and 2x dosing greys = Palette({'grey': 'grey'}) pal = [greys('grey', 'light', shade=2), greys('grey', 'dark', shade=2)] # assemble formatting arguments kw = dict(palette=pal, notch=True, fliersize=0, width=width, linewidth=lw) # plot distributions if self.orientation == 'v': sns.boxplot(data=data, x='ReferenceType', y=channel, hue='Dosing', orient='v', ax=self.fig.axes[0], **kw) else: sns.boxplot(data=data, x=channel, y='ReferenceType', hue='Dosing', orient='h', ax=self.fig.axes[0], **kw) # remove legend self.fig.axes[0].legend_.remove() @staticmethod def _format_ax(ax, channel='ch1_normalized', orientation='v'): """ Format figure axes. Args: fig (matplotlib.axes.AxesSubplot) channel (str) - expression channel orientation (str) - box orientation """ # format axis # get axis limits if channel == 'ch1_normalized': lim = (0, 6) ticks = np.arange(7) label = 'Pnt (a.u.)' elif channel == 'ch2_normalized': lim = (0, 6) ticks = np.arange(7) label = 'Yan (a.u.)' else: lim = (-3, 3.5) ticks = np.arange(-3, 4) label = 'log2 Ratio' # horizontal formatting if orientation == 'h': ax.set_ylabel('') ax.set_xlim(*lim) ax.set_xticks(ticks) ax.set_xlabel(label) ax.spines['left'].set_position(('outward', 5)) ax.spines['bottom'].set_position(('outward', 1)) ax.plot([0, 0], [-5, 5], '-', color='pink', linewidth=2, zorder=0) # vertical formatting else: ax.set_xlabel('') ax.set_ylim(*lim) ax.set_yticks(ticks) ax.set_ylabel(label) ax.spines['left'].set_position(('outward', 1)) ax.spines['bottom'].set_position(('outward', -5)) ax.plot([-5, 5], [0, 0], '-', color='pink', linewidth=2, zorder=0) # format spines xticks = ax.get_xticks() yticks = ax.get_yticks() ax.spines['left'].set_bounds(yticks[0], yticks[-1]) ax.spines['bottom'].set_bounds(xticks[0], xticks[-1]) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) @staticmethod def set_patch_colors(ax, cell_types, lw=1): """ Set colors for patch objects (boxes). Args: ax (matplotlib.axes.AxesSubplot) cell_types (list of lists) - cell types used to define colors lw (float) - patch line width """ # instantiate cell type colormaps colorer = Palette() greys = Palette({'grey': 'grey'}) # iterate across patch artists for i, artist in enumerate(ax.artists): # set facecolor if i % 2 == 0: artist.set_facecolor(greys('grey', 'light', shade=2)) else: artist.set_facecolor(greys('grey', 'dark', shade=2)) # set linecolor types = cell_types[i // 2][0] color = colorer(types) artist.set_edgecolor(color) artist.set_linewidth(lw) def get_statistics(self, channel='logratio', test='ks_2samp', rounding=2): """ Perform statistical test to determine whether or not expression levels differ between PntGFP dosages. Args: channel (str) - expression channel test (str) - statistical test used rounding (int) - rounding applied to log10(pvalues) Returns: data (pd.DataFrame) - dataframe summarizing comparison statistics """ # get test if test == 'ks_2samp': test = lambda x, y: ks_2samp(x, y) elif test == 'welch': test = lambda x, y: ttest_ind(x, y, equal_var=False) elif test == 't': test = lambda x, y: ttest_ind(x, y, equal_var=True) # determine unique reference populations cell_types = self.data['ReferenceType'].unique() # split data by PntGFP dosage pnt1x_data = self.data[self.data.Dosing=='1X PntGFP'] pnt2x_data = self.data[self.data.Dosing=='2X PntGFP'] # iterate across metrics and cell types to be compared stats = {} # iterate across reference cell types for types in cell_types: # select concurrent progenitors p1 = pnt1x_data[pnt1x_data['ReferenceType']==types] p2 = pnt2x_data[pnt2x_data['ReferenceType']==types] # get scores p1scores = p1[channel].values p2scores = p2[channel].values # apply test and store log10 pval _, pval = test(p1scores, p2scores) stats[types] = {'log10 pval': np.round(np.log10(pval), rounding)} return pd.DataFrame.from_dict(stats, orient='index') class PerturbationComparison(Base): """ Object for constructing boxplot comparison between control and perturbation experiments. Attributes: reference_types (list) - reference cell types pre (pd.DataFrame) - data for progenitors concurrent with reference reference (pd.DataFrame) - data for reference cells Inherited attributes: data (pd.DataFrame) - data fig (matplotlib.figure.Figure) """ def __init__(self, data, reference, **kwargs): """ Instantiate perturbation comparison figure. Args: data (pd.DataFrame) - data containing Control/Perturbation labels reference (list) - reference cell types kwargs: keyword arguments for concurrent cell selection """ # define measurement data cells = self.select_concurrent(data, reference, **kwargs) self.reference_types = reference self.pre = cells[cells.label=='pre'] self.reference = cells[cells.label.isin(reference)] # initialize figure self.fig = None @classmethod def from_experiments(cls, control, perturbation, reference, **kwargs): """ Instantiate from Experiment instances. Cells concurrent with early R-cells are selected by default. Args: control (data.experiments.Experiment) - control data perturbation (data.experiments.Experiment) - perturbation data reference (list) - reference cell types kwargs: keyword arguments for concurrent cell selection Returns: figure_obj (figures.base.Base derivative) """ # compile control data control = pd.concat([d.data for d in control.discs.values()]) control['experiment'] = 'Control' # compile perturbation data perturbation = pd.concat([d.data for d in perturbation.discs.values()]) perturbation['experiment'] = 'Perturbation' # concatenate data data = pd.concat((control, perturbation)) return cls(data, reference, **kwargs) @staticmethod def select_concurrent(data, reference, offset=1, n=25): """ Select all cells concurrent with early cells of a reference cell type. Args: data (pd.DataFrame) - cell measurement data reference (list) - reference cell types offset (int) - index of first early reference cell (excludes outliers) n (int) - number of early reference cells included Returns: concurrent (pd.DataFrame) - concurrent cell measurement data """ selected = data[data.label.isin(reference)] selected.sort_values(by='t', inplace=True) tmin = selected.iloc[offset:n].t.min() tmax = selected.iloc[offset:n].t.max() concurrent = data[data.t.between(tmin, tmax)] return concurrent def render(self, channel='logratio', figsize=(1., 1.5), **kwargs): """ Create formatted figure and plot data. Args: channel (str) - expression channel figsize (tuple) - figure size kwargs: keyword arguments for plotting """ self.fig = self.create_figure(figsize=figsize) # determine marker color palette = Palette() marker_color = palette(self.reference_types[0]) # plot boxplots and markers self.plot(channel=channel, color=marker_color, **kwargs) self._format_ax(self.fig.axes[0]) def plot(self, channel='logratio', color='k', size=2): """ Plot data using seaborn.boxplot method. Data must contain "experiment" keys as these are used to categorically partition data. Progenitors are shown as boxes, overlayed by reference cell markers. Args: channel (str) - expression channel color (str) - marker color size (float) - marker size """ # get axis ax = self.fig.axes[0] # define box order order = ('Control', 'Perturbation') # plot progenitors ax = sns.boxplot(x="experiment", y=channel, data=self.pre, color=".8", order=order, width=0.5, ax=ax, linewidth=1, fliersize=2) # overlay reference cells ax = sns.stripplot(x="experiment", y=channel, data=self.reference, size=size, jitter=.25, order=order, color=color, edgecolor='w', linewidth=0.) @staticmethod def _format_ax(ax): """ Format figure axes. Args: ax (matplotlib.axes.AxesSubplot) """ # set axis limits ax.set_ylim(-2, 2) ax.set_yticks(np.arange(-2, 2.25, 1)) # labels ax.tick_params(pad=0, labelsize=6, length=2) ax.set_ylabel('') ax.set_xticklabels(['WT', 'Sev>RasV12']) ax.set_xlabel('') # hide the right and top spines ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.yaxis.set_ticks_position('left') ax.xaxis.set_ticks_position('bottom')
a = int(input("enter")) b = int(input("enter")) c = int(input("enter")) d = int(input("enter")) e = int(input("enter")) if(a>=b) and (a>=c) and (a>=d) and (a>=e): print(a) elif(b>=c) and (b>=d) and (b>=e): print(b) elif(c>=d) and (c>=e): print(c) elif(d>=e): print(d) else: print(e)
# -*- coding: utf-8 -*- from django.db import models from tipo_questao import TipoQuestao from questao import Questao #from libs.uniqifiers_benchmark import f11 as uniqifier class FiltroQuestao(models.Model): """ Classe que ira gerar uma questao(QuestaoDeAvaliacao) com base em alguns criterios/filtros(TipoQuestao). """ #vou fazer que um filtro de questao pode ser usado apenas num template de Avaliacao por vez, acho q fica mais #logico a ideia. templateAvaliacao = models.ForeignKey('Avaliacao.TemplateAvaliacao', related_name='filtrosQuestoes') #representa a nota que o aluno receberá se conseguir 100% da questão notaBase = models.DecimalField(u"Nota Base",max_digits=10, decimal_places=2,default="0.00") #representa o limite inferior que a nota dessa questao pode chegar. notaLimMinimo = models.DecimalField(u"Limite Mínimo da Nota",max_digits=10, decimal_places=2,default="0.00") #representa o limite superior que a nota dessa questao pode chegar. notaLimMaximo = models.DecimalField(u"Limite Máximo da Nota",max_digits=10, decimal_places=2,default="0.00") #tipo que da questao, usado para filtragem tipo = models.ManyToManyField(TipoQuestao, related_name="filtrosQuestoes") #caso seja de uma questao expecifica. questaoExata = models.ForeignKey(Questao, related_name='filtrosQuestoes', blank=True, null=True,limit_choices_to = {'verificada':True}) class Meta: verbose_name = u'Filtro de Questão' app_label = 'Questao' def verifica_autor(self,autor): "verifica se um dado autor(usuario) corresponde ao autor do templateAvaliacao desse filtro" return self.templateAvaliacao.autor.pk == autor.pk def _prepara_tipos_requeridos(self): """ Metodo usado por filtrarQuestao. prepara os tipos requeridos, juntando n elementos de num_descendentes cada um dos tipos retorna um vetor com um vetor de listas de todos os tipos e seus descententes Ex: Tipos: * C -> Ponteiro -> Malloc * Facil * Estruturas de Dados -> Pilha Isso resultaria no seguinte vetor: [[C,Ponteiro,Malloc], [Facil,], [Estruturas de Dados, Pilha]] """ tiposRequeridos = [] for tipoFiltro in self.tipo.all(): listaTiposFilho_e_proprio = tipoFiltro.get_descendants(include_self=True) tiposRequeridos.append(listaTiposFilho_e_proprio) return tiposRequeridos def _questoes_selecionadas(self,tiposRequeridos): """ Recupera todas as questoes selecionadas usando os filtros(sem serem exatas) dos tiposRequeridos. """ #recupera todas as questoes tdsQuestoes = Questao.objects.filter(verificada=True) questoesSelecionadas = [] for questaoATestar in tdsQuestoes: questao_valida = True for grupoDeTiposRequeridos in tiposRequeridos: tipo_valido = False for tipoQuestao_da_questaoATestar in questaoATestar.tipo.all(): if tipoQuestao_da_questaoATestar in grupoDeTiposRequeridos: tipo_valido=True break if not tipo_valido: questao_valida = False break if questao_valida: questoesSelecionadas.append(questaoATestar) return questoesSelecionadas def filtrarQuestao(self): """ Retorna uma questao utilizando criterios de busca baseado no campo 'tipo', ou retorna questaoExata se esta for != None Passando como parametro uma lista de questoes previamente selecionadas, para evitar a selecao de uma destas. se for uma questão exata e simulado=True então nao pega a propria questão mas uma qualquer que seja do mesmo tipo que esta. """ ###################### #: se tiver questão exata, retorna a mesma(uma lista com apenas ela) #caso contrario, tenta recuperar uma questão aleatoria, seguindo os tipos do filtro if self.questaoExata: # print "(EXATA) " + self.questaoExata.slug return [self.questaoExata,] #prepara os tipos requeridos, juntando n elementos de num_descendentes cada um dos tipos tiposRequeridos = self._prepara_tipos_requeridos() # print "====================================" # print ">>>tiposFiltro:" # print self.tipo.all() # print ">>>tiposRequeridos:" # print tiposRequeridos # print ">>>>>>>>>>>>>>>>>>>" questoesSelecionadas = self._questoes_selecionadas(tiposRequeridos) if questoesSelecionadas == []: raise Exception("Nenhuma questao encontrada para os seguintes filtro:%s"%str(self.pk)) # #randamiza uma dessas questoes para ser a resposta. # import random # rand = random.randint(0, questoesSelecionadas.__len__()-1) # questao = questoesSelecionadas[rand] # print str(rand) + " " + questao.slug return questoesSelecionadas #Ver qual o unicode que vou por para esse model # def __unicode__(self): # return self.arquivo.name
#!/usr/bin/python # Copyright 2015 Jason Edelman <jason@networktocode.com> # Network to Code, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = r""" --- module: ntc_file_copy short_description: Copy a file to a remote network device over SCP description: - Copy a file to the flash (or bootflash) remote network device on supported platforms over SCP. - Supported platforms include Cisco Nexus switches with NX-API, Cisco IOS switches or routers, Arista switches with eAPI. notes: - On NXOS, the feature must be enabled with feature scp-server. - On IOS and Arista EOS, the user must be at privelege 15. - If the file is already present (md5 sums match), no transfer will take place. - Check mode will tell you if the file would be copied. - The same user credentials are used on the API/SSH channel and the SCP file transfer channel. author: Jason Edelman (@jedelman8) version_added: 1.9.2 requirements: - pyntc extends_documentation_fragment: - networktocode.netauto.netauto options: local_file: description: - Path to local file. Local directory must exist. required: false type: str remote_file: description: - Remote file path of the copy. Remote directories must exist. If omitted, the name of the local file will be used. required: false default: null type: str file_system: description: - The remote file system of the device. If omitted, devices that support a file_system parameter will use their default values. required: false default: null type: str global_delay_factor: description: - Sets delay between operations. required: false default: 1 type: int delay_factor: description: - Multiplication factor for timing delays required: false default: 1 type: int """ EXAMPLES = r""" - hosts: all vars: nxos_provider: host: "{{ inventory_hostname }}" username: "ntc-ansible" password: "ntc-ansible" platform: "cisco_nxos_nxapi" - name: copy file to network device networktocode.netauto.ntc_file_copy: platform: cisco_nxos_nxapi local_file: /path/to/file host: "{{ inventory_hostname }}" username: "{{ username }}" password: "{{ password }}" transport: http - name: copy file to network device networktocode.netauto.ntc_file_copy: ntc_host: n9k1 ntc_conf_file: .ntc.conf local_file: /path/to/file - name: copy file to network device networktocode.netauto.ntc_file_copy: ntc_host: eos_leaf local_file: /path/to/file - name: copy file to network device networktocode.netauto.ntc_file_copy: platform: arista_eos_eapi local_file: /path/to/file remote_file: /path/to/remote_file host: "{{ inventory_hostname }}" username: "{{ username }}" password: "{{ password }}" - name: copy file to network device networktocode.netauto.ntc_file_copy: platform: cisco_ios local_file: "{{ local_file_1 }}" provider: "{{ nxos_provider }}" """ RETURN = r""" transfer_status: description: Whether a file was transfered. "No Transfer" or "Sent". returned: success type: str sample: 'Sent' local_file: description: The path of the local file. returned: success type: str sample: '/path/to/local/file' remote_file: description: The path of the remote file. returned: success type: str sample: '/path/to/remote/file' atomic: description: Whether the module has atomically completed all steps, including closing connection after file delivering. returned: always type: bool sample: true """ import os from ansible.module_utils.basic import AnsibleModule from ansible_collections.networktocode.netauto.plugins.module_utils.args_common import ( CONNECTION_ARGUMENT_SPEC, MUTUALLY_EXCLUSIVE, REQUIRED_ONE_OF, ) try: HAS_PYNTC = True from pyntc import ntc_device, ntc_device_by_name except ImportError: HAS_PYNTC = False def main(): # pylint: disable=too-many-locals,too-many-branches,too-many-statements """Main execution.""" base_argument_spec = dict( global_delay_factor=dict(default=1, required=False, type="int"), delay_factor=dict(default=1, required=False, type="int"), local_file=dict(required=False), remote_file=dict(required=False), file_system=dict(required=False), ) argument_spec = base_argument_spec argument_spec.update(CONNECTION_ARGUMENT_SPEC) argument_spec["provider"] = dict(required=False, type="dict", options=CONNECTION_ARGUMENT_SPEC) module = AnsibleModule( argument_spec=argument_spec, mutually_exclusive=MUTUALLY_EXCLUSIVE, required_one_of=[REQUIRED_ONE_OF], supports_check_mode=True, ) provider = module.params["provider"] or {} # allow local params to override provider for param, pvalue in provider.items(): if module.params.get(param) is not False: module.params[param] = module.params.get(param) or pvalue if not HAS_PYNTC: module.fail_json(msg="pyntc is required for this module.") platform = module.params["platform"] host = module.params["host"] username = module.params["username"] password = module.params["password"] ntc_host = module.params["ntc_host"] ntc_conf_file = module.params["ntc_conf_file"] transport = module.params["transport"] port = module.params["port"] global_delay_factor = int(module.params["global_delay_factor"]) delay_factor = int(module.params["delay_factor"]) secret = module.params["secret"] if ntc_host is not None: device = ntc_device_by_name(ntc_host, ntc_conf_file) else: kwargs = {} if transport is not None: kwargs["transport"] = transport if port is not None: kwargs["port"] = port if secret is not None: kwargs["secret"] = secret if global_delay_factor is not None: kwargs["global_delay_factor"] = global_delay_factor if delay_factor is not None: kwargs["delay_factor"] = delay_factor device_type = platform device = ntc_device(device_type, host, username, password, **kwargs) local_file = module.params["local_file"] remote_file = module.params["remote_file"] file_system = module.params["file_system"] argument_check = { "host": host, "username": username, "platform": platform, "password": password, "local_file": local_file, } for key, val in argument_check.items(): if val is None: module.fail_json(msg=str(key) + " is required") device.open() changed = False transfer_status = "No Transfer" file_exists = True if not os.path.isfile(local_file): module.fail_json(msg="Local file {0} not found".format(local_file)) if file_system: remote_exists = device.file_copy_remote_exists(local_file, remote_file, file_system=file_system) else: remote_exists = device.file_copy_remote_exists(local_file, remote_file) if not remote_exists: changed = True file_exists = False if not module.check_mode and not file_exists: try: if file_system: device.file_copy(local_file, remote_file, file_system=file_system) else: device.file_copy(local_file, remote_file) transfer_status = "Sent" except Exception as err: # pylint: disable=broad-except module.fail_json(msg=str(err)) try: device.close() atomic = True except: # noqa atomic = False if remote_file is None: remote_file = os.path.basename(local_file) module.exit_json( changed=changed, transfer_status=transfer_status, local_file=local_file, remote_file=remote_file, file_system=file_system, atomic=atomic, ) if __name__ == "__main__": main()
count_days = int(input()) count_cooks = int(input()) count_cake = int(input()) count_waffles = int(input()) count_pancakes = int(input()) price_cake = 45 price_waffles = 5.8 price_pancakes = 3.20 daily_wage = (count_cake * price_cake + count_waffles * price_waffles + count_pancakes * price_pancakes) *count_cooks total_sum = daily_wage * count_days charlty_money = total_sum - 1/8 * total_sum print(charlty_money)
from math import trunc def two_decimal_places(number): factor = float(10 ** 2) return trunc(number * factor) / factor
# Create Node # Create Linkedlist # Add nodes to Linkedlist # Print Linkedlist class Node: def __init__(self,data=None): self.data = data self.next = None class Linkedlist: def __init__(self): self.root = None def InsertNode(self,newNode): if self.root is None: self.root = newNode else: lastNode = self.root while True: if lastNode.next is None: break lastNode = lastNode.next lastNode.next = newNode def PrintList(self): currentNode = self.root while True: if currentNode is None: break print(currentNode.data) currentNode = currentNode.next nodeOne = Node("Jamiul") listOne = Linkedlist() listOne.InsertNode(nodeOne) nodeTwo = Node("Jahir") listOne.InsertNode(nodeTwo) nodeThree = Node("Rifat") listOne.InsertNode(nodeThree) listOne.PrintList()
from mlmicrophysics.models import DenseNeuralNetwork from mlmicrophysics.data import subset_data_files_by_date, assemble_data_files import numpy as np import pandas as pd from sklearn.preprocessing import StandardScaler, MinMaxScaler, MaxAbsScaler, RobustScaler, OneHotEncoder from sklearn.metrics import confusion_matrix, accuracy_score, mean_absolute_error, mean_squared_error from mlmicrophysics.metrics import heidke_skill_score, peirce_skill_score, hellinger_distance, root_mean_squared_error, r2_corr import argparse import yaml from os.path import join, exists import os from datetime import datetime import logging import optuna from aimlutils.hyper_opt.utils import trial_suggest_loader from aimlutils.hyper_opt.base_objective import * from aimlutils.hyper_opt.utils import KerasPruningCallback logger = logging.getLogger(__name__) scalers = {"MinMaxScaler": MinMaxScaler, "MaxAbsScaler": MaxAbsScaler, "StandardScaler": StandardScaler, "RobustScaler": RobustScaler} class_metrics = {"accuracy": accuracy_score, "heidke": heidke_skill_score, "peirce": peirce_skill_score} reg_metrics = {"rmse": root_mean_squared_error, "mae": mean_absolute_error, "r2": r2_corr, "hellinger": hellinger_distance, "mse": mean_squared_error} def leaky(x): return tf.nn.leaky_relu(x, alpha=0.01) def ranked_probability_score(y_true_discrete, y_pred_discrete): y_pred_cumulative = np.cumsum(y_pred_discrete) y_true_cumulative = np.cumsum(y_true_discrete) return np.mean((y_pred_cumulative - y_true_cumulative) ** 2) / float(y_pred_discrete.shape[1] - 1) def objective(trial, config): # Get list of hyperparameters from the config hyperparameters = config["optuna"]["parameters"] # Now update some hyperparameters via custom rules class_activation = trial_suggest_loader(trial, hyperparameters["class_activation"]) class_hidden_layers = trial_suggest_loader(trial, hyperparameters["class_hidden_layers"]) class_hidden_neurons = trial_suggest_loader(trial, hyperparameters["class_hidden_neurons"]) class_lr = trial_suggest_loader(trial, hyperparameters["class_lr"]) class_l2_weight = trial_suggest_loader(trial, hyperparameters["class_l2_weight"]) reg_activation = trial_suggest_loader(trial, hyperparameters["reg_activation"]) reg_hidden_layers = trial_suggest_loader(trial, hyperparameters["reg_hidden_layers"]) reg_hidden_neurons = trial_suggest_loader(trial, hyperparameters["reg_hidden_neurons"]) reg_lr = trial_suggest_loader(trial, hyperparameters["reg_lr"]) reg_l2_weight = trial_suggest_loader(trial, hyperparameters["reg_l2_weight"]) data_path = config["data_path"] out_path = config["out_path"] input_cols = config["input_cols"] output_cols = config["output_cols"] input_transforms = config["input_transforms"] output_transforms = config["output_transforms"] np.random.seed(config["random_seed"]) input_scaler = scalers[config["input_scaler"]]() subsample = config["subsample"] if not exists(out_path): os.makedirs(out_path) train_files, val_files, test_files = subset_data_files_by_date(data_path, **config["subset_data"]) print("Loading training data") scaled_input_train, \ labels_train, \ transformed_out_train, \ scaled_out_train, \ output_scalers, \ meta_train = assemble_data_files(train_files, input_cols, output_cols, input_transforms, output_transforms, input_scaler, subsample=subsample) print("Loading testing data") scaled_input_test, \ labels_test, \ transformed_out_test, \ scaled_out_test, \ output_scalers_test, \ meta_test = assemble_data_files(test_files, input_cols, output_cols, input_transforms, output_transforms, input_scaler, output_scalers=output_scalers, train=False, subsample=subsample) input_scaler_df = pd.DataFrame({"mean": input_scaler.mean_, "scale": input_scaler.scale_}, index=input_cols) out_scales_list = [] for var in output_scalers.keys(): for out_class in output_scalers[var].keys(): print(var, out_class) if output_scalers[var][out_class] is not None: out_scales_list.append(pd.DataFrame({"mean": output_scalers[var][out_class].mean_, "scale": output_scalers[var][out_class].scale_}, index=[var + "_" + str(out_class)])) out_scales_df = pd.concat(out_scales_list) out_scales_df.to_csv(join(out_path, "output_scale_values.csv"), index_label="output") beginning = datetime.now() print(f"BEGINNING: {beginning}") classifiers = dict() regressors = dict() reg_index = [] for output_col in output_cols: for label in list(output_transforms[output_col].keys()): if label != 0: reg_index.append(output_col + f"_{label:d}") test_prediction_values = np.zeros((scaled_out_test.shape[0], len(reg_index))) test_prediction_labels = np.zeros(scaled_out_test.shape) l = 0 score = 0 for o, output_col in enumerate(output_cols): print("Train Classifer ", output_col) classifiers[output_col] = DenseNeuralNetwork(hidden_layers=class_hidden_layers, hidden_neurons=class_hidden_neurons, lr=class_lr, l2_weight=class_l2_weight, activation=class_activation, **config["classifier_networks"]) hist = classifiers[output_col].fit(scaled_input_train, labels_train[output_col], scaled_input_test, labels_test[output_col], callbacks=[KerasPruningCallback(trial, "val_loss")]) logger.info(f"finished with classifier {output_col}") regressors[output_col] = dict() print("Evaluate Classifier", output_col) test_prediction_labels[:, o] = classifiers[output_col].predict(scaled_input_test) true = OneHotEncoder(sparse=False).fit_transform(labels_test[output_col].to_numpy().reshape(-1, 1)) pred = OneHotEncoder(sparse=False).fit_transform(pd.DataFrame(test_prediction_labels[:, o])) score += ranked_probability_score(true, pred) for label in list(output_transforms[output_col].keys()): if label != 0: print("Train Regressor ", output_col, label) regressors[output_col][label] = DenseNeuralNetwork(hidden_layers=reg_hidden_layers, hidden_neurons=reg_hidden_neurons, lr=reg_lr, l2_weight=reg_l2_weight, activation = reg_activation, **config["regressor_networks"]) hist = regressors[output_col][label].fit(scaled_input_train.loc[labels_train[output_col] == label], scaled_out_train.loc[labels_train[output_col] == label, output_col], scaled_input_test.loc[labels_test[output_col] == label], scaled_out_test.loc[labels_test[output_col] == label, output_col], callbacks=[KerasPruningCallback(trial, "val_loss")]) logger.info(f"finished with regressor {output_col}") if label > 0: out_label = "pos" else: out_label = "neg" print("Test Regressor", output_col, label) test_prediction_values[:, l] = output_scalers[output_col][label].inverse_transform(regressors[output_col][label].predict(scaled_input_test)) score += mean_squared_error(transformed_out_test.loc[labels_test[output_col] == label, output_col], test_prediction_values[labels_test[output_col] == label, l]) l += 1 print(f"Running the model took: {datetime.now() - beginning}") return score class Objective(BaseObjective): def __init__(self, study, config, metric = "val_loss", device = "cpu"): # Initialize the base class BaseObjective.__init__(self, study, config, metric, device) def train(self, trial, conf): result = objective(trial, conf) results_dictionary = { "val_loss": result } return results_dictionary if __name__ == "__main__": main() print("Starting script...") # parse arguments from config/yaml file parser = argparse.ArgumentParser() parser.add_argument("config", help="Path to config file") args = parser.parse_args() with open(args.config) as config_file: config = yaml.load(config_file, Loader=yaml.FullLoader) study = optuna.create_study(direction=config["direction"], pruner=optuna.pruners.MedianPruner()) study.optimize(objective, config, n_trials=config["n_trials"]) pruned_trials = [t for t in study.trials if t.state == optuna.trial.TrialState.PRUNED] complete_trials = [t for t in study.trials if t.state == optuna.trial.TrialState.COMPLETE] print("Study statistics: ") print(" Number of finished trials: ", len(study.trials)) print(" Number of pruned trials: ", len(pruned_trials)) print(" Number of complete trials: ", len(complete_trials)) print("Best trial:") trial = study.best_trial print(" Value: ", trial.value) print(" Params: ") for key, value in trial.params.items(): print(" {}: {}".format(key, value))
import subprocess import os """ There are many cases in which you want to call an external command in python and you can do this with the built-in library called subprocess. And if you need to, you can also capture the output of that command or even pipe the output from one command into another. """ # running an external command is pretty simple with the subprocess module # in this case, we run the command line command "ls" subprocess.run("pwd") print(type(subprocess.run("pwd"))) # returns a subprocess.CompletedProcess class print(subprocess.run("pwd")) print(os.getcwd()) print(type(os.getcwd())) # returns a string subprocess.run("ls -alt", shell=True) # you can use shell=True # one downside to using shell=True is that it can be a security hazard, as you are passing in the arguments yourself # So only use this if you are passing in the arguments yourself, and be sure you're not running it with user input or anything like that. # but, if we don't want to specify using shell=True, you will need to pass in everything as a list of arguments and we get the same thing subprocess.run(["ls", "-alt"]) # we can get the arguments that were passed in as part of the original command with the .args function a = subprocess.run(["ls", "-alt"], capture_output=True) print(a.args) # we can also see if we get any errors from the function by looking at the return code. 0 means exited without any issues. print(a.returncode) # you can also grab the standard output of the function # the reason we are getting back none as a result is that is is just sending the standard out to the console print(a.stdout) # we get back None as a result print(a.stdout.decode()) # if we want to capture the output of this function, we will have to pass into the function, a special argument to indicate # that we want to capture the output of this function # z = subprocess.run(["ls", "-alt"], stdout="PIPE") # for some reason, I am getting expected argument error # print(z)
''' Created on Oct 12, 2010 Decision Tree Source Code for Machine Learning in Action Ch. 3 @author: Peter Harrington Things to note: Entropy is a measurement of "chaos in a set" Example high entropy set: high_entropy_set = set("dog", "cat", "bird", "fish", "lizard") Example low entropy set: low_entropy_set = set("dog", "cat", "dog", "dog", "cat") Example 0 entropy set: zero_entropy_set = set("dog", "dog", "dog", "dog", "dog") Each set has the same number of values, but the low entropy set has less "chaos". The last set is uniform (all values are the same) so it has an entropy of 0. ''' from math import log import operator from collections import Counter def createDataSet(): labels = [ 'no surfacing', 'flippers'] # is fish dataSet = [ [ 1, 1, 'yes' ], [ 1, 1, 'yes' ], [ 1, 0, 'no' ], [ 0, 1, 'no' ], [ 0, 1, 'no' ], ] #change to discrete values return dataSet, labels def calcShannonEnt(dataSet): numEntries = len(dataSet) labelCounts = Counter(featVec[-1] for featVec in dataSet) logBase2 = lambda n: log(n, 2) def entropy(labelCount): prob = float(labelCount) / numEntries return -1 * prob * logBase2(prob) return sum(entropy(labelCount) for labelCount in labelCounts.values()) def splitDataSet(dataSet, axis, value): return [ # chop out axis used for splitting: featVec[:axis] + featVec[axis+1:] for featVec in dataSet if featVec[axis] == value ] def chooseBestFeatureToSplit(dataSet): # The last column is used for the labels numFeatures = len(dataSet[0]) - 1 baseEntropy = calcShannonEnt(dataSet) def infoGain(featureToSplitOn): # get a set of unique values for this feature uniqueVals = set(example[i] for example in dataSet) newEntropy = 0.0 for value in uniqueVals: subDataSet = splitDataSet(dataSet, i, value) prob = len(subDataSet) / float(len(dataSet)) newEntropy += prob * calcShannonEnt(subDataSet) # calculate the info gain; ie reduction in entropy return baseEntropy - newEntropy features = range(numFeatures) return max(features, key=infoGain) def majorityCnt(classList): classCount = Counter(classList) return max(classCount, key=lambda key: classCount[key]) def createTree(dataSet,labels): classList = [example[-1] for example in dataSet] if classList.count(classList[0]) == len(classList): return classList[0]#stop splitting when all of the classes are equal if len(dataSet[0]) == 1: #stop splitting when there are no more features in dataSet return majorityCnt(classList) bestFeat = chooseBestFeatureToSplit(dataSet) bestFeatLabel = labels[bestFeat] myTree = {bestFeatLabel:{}} del(labels[bestFeat]) featValues = [example[bestFeat] for example in dataSet] uniqueVals = set(featValues) for value in uniqueVals: subLabels = labels[:] #copy all of labels, so trees don't mess up existing labels myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value),subLabels) return myTree def classify(inputTree,featLabels,testVec): firstStr = inputTree.keys()[0] secondDict = inputTree[firstStr] featIndex = featLabels.index(firstStr) key = testVec[featIndex] valueOfFeat = secondDict[key] if isinstance(valueOfFeat, dict): classLabel = classify(valueOfFeat, featLabels, testVec) else: classLabel = valueOfFeat return classLabel def storeTree(inputTree,filename): import pickle fw = open(filename,'w') pickle.dump(inputTree,fw) fw.close() def grabTree(filename): import pickle fr = open(filename) return pickle.load(fr)
#!/usr/bin/python # coding=utf-8 # 作者:李发富 # 邮箱:fafu_li@live.com & 348926676@qq.com # 时间:2018.07.05 from kafka import KafkaConsumer from kafka import TopicPartition import time import datetime import sys #reload(sys) #sys.setdefaultencoding('utf-8') class KafkaC: """ 消费模块: 通过不同groupid消费topic里面的消息 """ def __init__(self, bootstrap_servers, topic, group, action=None, offset=None, enable_auto_commit=True): self.bootstrap_servers = bootstrap_servers self.topic = topic self.group_id = group self.action = action self.offset = offset # self.enable_auto_commit = True self.enable_auto_commit = enable_auto_commit self.auto_commit_interval_ms = 1000 self.consumer = KafkaConsumer( # self.kafka_topic, # auto_offset_reset默认latest,如果是第一次使用一个新的消费者组,不管前面数据是否消费 # 都不会消费,使用earliest参数就可以消费前面没有消费的数据 auto_offset_reset='earliest', group_id=self.group_id, bootstrap_servers=self.bootstrap_servers, enable_auto_commit=self.enable_auto_commit, auto_commit_interval_ms=self.auto_commit_interval_ms ) # 获取所有topics def get_all_topics(self): return self.consumer.topics() # 获取最开始offset def get_beginning_offsets(self): _ps = [TopicPartition(self.topic, p) for p in self.consumer.partitions_for_topic(self.topic)] return _ps, self.consumer.beginning_offsets(_ps) # 获取最新的offset,比最新数据的offset大1,因为kafkaoffset从0开始 def get_end_offsets(self): _ps = [TopicPartition(self.topic, p) for p in self.consumer.partitions_for_topic(self.topic)] return _ps, self.consumer.end_offsets(_ps) # 获取当前消费者开始消费的offset def get_last_position(self, partition=None): _ps = [TopicPartition(self.topic, p) for p in self.consumer.partitions_for_topic(self.topic)] self.consumer.assign(_ps) return self.consumer.position(partition=_ps[0]) # 以时间戳(微秒)方式获取offset,消息必须带有timestamp字段,即kafka版本大于0.10.0才支持 def get_offset_by_timestamp(self, timestamp): _ps = [TopicPartition(self.topic, p) for p in self.consumer.partitions_for_topic(self.topic)] return _ps, self.consumer.offsets_for_times({_ps[0]: timestamp}) def consume_data(self, offset=None): """ :param action: none 从 kafka 正常的 `CURRENT-OFFSET` 开始消费 custom 从指定offset开始 begin 从 kafka 从这个topic最开始消费 end 从 kafka 从这个topic从最新生成的数据库开始,会跳过未消费数据,慎用 :param offset: 数字 int>=0 type为custom时有效从当前数字 offset 开始,包括当前数字, 如果数字大于当前topic总offset,从最新生成的数据库开始 :return: """ # 获取topic所有分区并分配给当前消费者, 需要使用 assign 的话, 在 KafkaConsumer 初始化时就不能指定 topic _ps = [TopicPartition(self.topic, p) for p in self.consumer.partitions_for_topic(self.topic)] if offset is None: offset = self.get_last_position() self.consumer.assign(_ps) for p in self.consumer.partitions_for_topic(self.topic): # 也可以只指定一个分区的 offset self.consumer.seek(TopicPartition(self.topic, p), offset) # try: # for message in self.consumer: # yield message # except KeyboardInterrupt as e: # print(e) for message in self.consumer: yield message def consume_daesta_stop(self): """ 获取到最新的offset自动停止 :param action: none 从 kafka 正常的 `CURRENT-OFFSET` 开始消费 custom 从指定offset开始 begin 从 kafka 从这个topic最开始消费 end 从 kafka 从这个topic从最新生成的数据库开始,会跳过未消费数据,慎用 :param offset: 数字 int>=0 type为custom时有效从当前数字 offset 开始,包括当前数字, 如果数字大于当前topic总offset,从最新生成的数据库开始 :return: """ # 获取topic所有分区并分配给当前消费者, 需要使用 assign 的话, 在 KafkaConsumer 初始化时就不能指定 topic _ps = [TopicPartition(self.topic, p) for p in self.consumer.partitions_for_topic(self.topic)] self.consumer.assign(_ps) if self.action is None: pass elif self.action == 'begin': self.consumer.seek_to_beginning() elif self.action == 'end': self.consumer.seek_to_end() elif self.action == 'custom': for p in self.consumer.partitions_for_topic(self.topic): # 也可以只指定一个分区的 offset self.consumer.seek(TopicPartition(self.topic, p), self.offset) else: print('action values is not support! Plesase input "begin|end|custom"') sys.exit(1) for message in self.consumer: yield message def commit_consumer(self): # self.consumer.commit() self.consumer.commit_async() # 异步提交 def close_consumer(self): self.consumer.close(autocommit=self.enable_auto_commit) if __name__ == '__main__': BOOTSTRAP_SERVERS = "pycdhnode2:9092,pycdhnode3:9092,pycdhnode4:9092" KAFKA_TOPIC = "py_etl.py_etl_active_stock_fund_evaluate_2_1" GROUP = 'py_group' ACTION = 'custom' OFFSET = 887931 # CONSUMER = KafkaC(BOOTSTRAP_SERVERS, KAFKA_TOPIC, GROUP, ACTION, OFFSET) CONSUMER = KafkaC(BOOTSTRAP_SERVERS, KAFKA_TOPIC, GROUP) ALL_TOPICS = CONSUMER.get_all_topics() if len(ALL_TOPICS) == 0: print('topic: {0} is not exist'.format(KAFKA_TOPIC)) CONSUMER.close_consumer() elif len(ALL_TOPICS) != 0 and KAFKA_TOPIC not in ALL_TOPICS: print('topic: {0} is not exist'.format(KAFKA_TOPIC)) CONSUMER.close_consumer() else: # MESSAGE = CONSUMER.consume_data() # # MESSAGE = CONSUMER.consume_data() # for MSG in MESSAGE: # print(MSG) # # time.sleep(1) # # value = msg.value # # print(value.decode('utf8')) PS, STARTOFFSETS = CONSUMER.get_beginning_offsets() PS, ENDOFFSETS = CONSUMER.get_end_offsets() STARTOFFSET = int(STARTOFFSETS[PS[0]]) ENDOFFSET = int(ENDOFFSETS[PS[0]]) # 获取topic第一个0分区的最新的offset POSITION = CONSUMER.get_last_position(PS[0]) # 获取topic第一个0分区最新的开始消费的offset print("startoffset: {0}".format(STARTOFFSET)) print("endoffset: {0}".format(ENDOFFSET)) print("position: {0}".format(POSITION)) print("total not consume log: {0}".format(ENDOFFSET - POSITION)) print('---------------------------------------------') if CONSUMER.action is not None and CONSUMER.offset is not None: if CONSUMER.offset > ENDOFFSET - 1: CONSUMER.offset = ENDOFFSET POSITION = CONSUMER.offset MESSAGE = CONSUMER.consume_data_stop() print("startoffset: {0}".format(STARTOFFSET)) print("endoffset: {0}".format(ENDOFFSET)) print("position: {0}".format(POSITION)) print("total not consume log: {0}".format(ENDOFFSET - POSITION)) # dt = '2018-07-26 10:45:29' # ts = int(time.mktime(time.strptime(dt, "%Y-%m-%d %H:%M:%S"))) # # print int(ts) # 获取毫秒 # # print int(round(ts*1000)) # 获取微秒 # PS, TIMEOFFSETS = CONSUMER.get_offset_by_timestamp(int(round(ts*1000))) # TIMEOFFSET = TIMEOFFSETS[PS[0]] # if TIMEOFFSET is not None: # print 'message @timestamp: {0} offset: {1}'.format(TIMEOFFSET[1], TIMEOFFSET[0]) # else: # print 'message @timestamp: {0} offset: None'.format(int(round(ts*1000))) sys.exit(0) start_time = datetime.datetime.now() i = 0 if ENDOFFSET > POSITION: for MSG in MESSAGE: # print MSG # print( # 'topic:{0} partition:{1} offset:{2} key:{3} value:{4}' # .format(MSG.topic, MSG.partition, MSG.offset, MSG.key, MSG.value.decode('utf-8')) # ) i += 1 if MSG.offset == ENDOFFSET - 1: CONSUMER.close_consumer() break else: print('no message to consumption') CONSUMER.close_consumer() print('total consumption: {0}'.format(i)) end_time = datetime.datetime.now() exec_time = 'exec_time:{0}'.format(end_time - start_time) print(exec_time)
import mysvg def variations(filter_key): filter_key = mysvg.get_filter_key(filter_key) iterables = mysvg.get_iterables(filter_key) print(f"iterables : {iterables }") if __name__ == '__main__': variations("Cross-smooth")
from django import forms from .models import Post,UserProfile import os class PostForm(forms.ModelForm): content=forms.CharField(widget=forms.Textarea(attrs={'class':'mdl-textfield__input','rows':4})) # media=forms.FileField(widget=forms.FileInput(attrs={'class':"mdl-button mdl-js-button mdl-button--raised mdl-button--colored"})) class Meta: model = Post fields = [ "content", "media" ] def clean_media(self): media=self.cleaned_data.get("media") if media: name, extension = os.path.splitext(media.name) if extension in [".3gp",".3GP",".avi",".AVI",".mkv",".MKV"]: raise forms.ValidationError("Only mp4 and WebM video formats are supported :(") return media class CommentForm(forms.Form): content=forms.CharField(label='', widget=forms.Textarea(attrs={'class':'mdl-textfield__input','rows':2})) class UserProfileForm(forms.ModelForm): class Meta: model=UserProfile fields=['profile_pic','gender','phone','dob','address','relationship_status'] widgets={ 'profile_pic':forms.FileInput(attrs={'class':"mdl-button mdl-js-button mdl-button--raised mdl-button--colored"}), 'gender':forms.TextInput(attrs={'class':'mdl-textfield__input'}), 'phone':forms.TextInput(attrs={'class':'mdl-textfield__input'}), 'dob':forms.TextInput(attrs={'class':'mdl-textfield__input'}), 'address':forms.TextInput(attrs={'class':'mdl-textfield__input', 'rows':4}), 'relationship_status':forms.TextInput(attrs={'class':'mdl-textfield__input'}), }
class Solution: def asteroidCollision(self, asteroids: List[int]) -> List[int]: stack = [] for ast in asteroids: if not stack or stack[-1] < 0 or ast > 0: stack.append(ast) continue while stack and stack[-1] > 0: if abs(stack[-1]) == abs(ast): stack.pop() break elif abs(stack[-1] < abs(ast)): stack.pop() if not stack or stack[-1] < 0: stack.append(ast) break elif abs(stack[-1] > abs(ast)): break return stack
import numpy as np import scipy.sparse as sp import numba from numba import njit from ..base_transforms import SparseTransform from ..transform import Transform from ..sparse import add_selfloops, eliminate_selfloops @Transform.register() class NeighborSampler(SparseTransform): def __init__(self, max_degree: int = 25, selfloop: bool = True, add_dummy: bool = True): super().__init__() self.collect(locals()) def __call__(self, adj_matrix: sp.csr_matrix): return neighbor_sampler(adj_matrix, max_degree=self.max_degree, selfloop=self.selfloop, add_dummy=self.add_dummy) @njit def sample(indices, indptr, max_degree=25, add_dummy=True): N = len(indptr) - 1 if add_dummy: M = numba.int32(N) + np.zeros((N+1, max_degree), dtype=np.int32) else: M = np.zeros((N, max_degree), dtype=np.int32) for n in range(N): neighbors = indices[indptr[n]:indptr[n + 1]] size = neighbors.size if size > max_degree: neighbors = np.random.choice(neighbors, max_degree, replace=False) elif size < max_degree: neighbors = np.random.choice(neighbors, max_degree, replace=True) M[n] = neighbors return M def neighbor_sampler(adj_matrix: sp.csr_matrix, max_degree: int = 25, selfloop: bool=True, add_dummy=True): if selfloop: adj_matrix = add_selfloops(adj_matrix) else: adj_matrix = eliminate_selfloops(adj_matrix) M = sample(adj_matrix.indices, adj_matrix.indptr, max_degree=max_degree, add_dummy=add_dummy) np.random.shuffle(M.T) return M
#!bin/python # For simplicity of the implementation this assumes square matrix with size being a power of 2 def matrixAdd(A, B, sub = False): assert len(A) == len(B) assert len(A[0]) == len(B[0]) C = [] for i in range(len(A)): C.append([]) for j in range(len(A[i])): if not sub: C[i].append(A[i][j] + B[i][j]) else: C[i].append(A[i][j] - B[i][j]) return C def strassen(X, Y): if len(X) == 1: return [[X[0][0] * Y[0][0]]] m = len(X) // 2 # under assumption this is fine only. A = [] B = [] C = [] D = [] E = [] F = [] G = [] H = [] for i in range(m): A.append([]) B.append([]) C.append([]) D.append([]) E.append([]) F.append([]) G.append([]) H.append([]) for j in range(m): A[i].append(X[i][j]) C[i].append(X[i + m][j]) B[i].append(X[i][j + m]) D[i].append(X[i + m][j + m]) E[i].append(Y[i][j]) G[i].append(Y[i + m][j]) F[i].append(Y[i][j + m]) H[i].append(Y[i + m][j + m]) M1 = strassen(matrixAdd(A, C), matrixAdd(E, F)) M2 = strassen(matrixAdd(B, D), matrixAdd(G, H)) M3 = strassen(matrixAdd(A, D, True), matrixAdd(E, H)) M4 = strassen(A, matrixAdd(F, H, True)) M5 = strassen(matrixAdd(C, D), E) M6 = strassen(matrixAdd(A, B), H) M7 = strassen(D, matrixAdd(G, E, True)) I = matrixAdd(M2, matrixAdd(M3, matrixAdd(M6, M7), True)) J = matrixAdd(M4, M6) K = matrixAdd(M5, M7) L = matrixAdd(M1, matrixAdd(M3, matrixAdd(M4, M5)), True) Z = [] for i in range(len(I)): Z.append([]) Z[i].extend(I[i]) Z[i].extend(J[i]) for i in range(len(K)): Z.append([]) Z[i + len(I)].extend(K[i]) Z[i + len(I)].extend(L[i]) return Z A = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ] B = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ] C = [ [1, 2], [3, 4] ] D = [ [1, 2], [3, 4] ] print(strassen(A, B))
p, n = map(int, input().split(' ')) l = list(map(int, input().split())) s = '' for i in range(n-1): if l[i+1] - l[i] > p or l[i] - l[i+1] > p: s = 'GAME OVER' break else: s = 'YOU WIN' print(s)
# -*- coding: utf-8 -*- # !/usr/bin/env python """ ------------------------------------------------- File Name: message.py Description: 对外输出的log,显示及统计信息处理 Author: Dexter Chen Date:2017-09-19 ------------------------------------------------- """ import mongodb_handler as mh import screen import stats import utilities as ut import config def msg(who, identifier, action, result, info_type, *args): '''*args可以为log, display, stat一个或多个''' for fn in args: fn(ut.time_str("full"), who, identifier, action, result, info_type) def log(when, who, identifier, action, result, info_type): # 用于日志的信息 if config.log_protocol == 9: mh.add_new_log(when, who, identifier, action, result, info_type) elif config.log_protocol == 5 and info_type in ["important", "error", "notice", "debug", "info"]: mh.add_new_log(when, who, identifier, action, result, info_type) elif config.log_protocol == 4 and info_type in ["important", "error", "notice", "info"]: mh.add_new_log(when, who, identifier, action, result, info_type) elif config.log_protocol == 3 and info_type in ["important", "error", "notice"]: mh.add_new_log(when, who, identifier, action, result, info_type) elif config.log_protocol == 2 and info_type in ["important", "error"]: mh.add_new_log(when, who, identifier, action, result, info_type) elif config.log_protocol == 1 and info_type == "important": mh.add_new_log(when, who, identifier, action, result, info_type) else: pass def display(when, who, identifier, action, result, info_type): # 用于显示的信息 if config.display_protocol == 9: screen.add_new_display(when, who, identifier, action, result, info_type) elif config.display_protocol == 5 and info_type in ["important", "error", "notice", "debug", "info"]: screen.add_new_display(when, who, identifier, action, result, info_type) elif config.display_protocol == 4 and info_type in ["important", "error", "notice", "info"]: screen.add_new_display(when, who, identifier, action, result, info_type) elif config.display_protocol == 3 and info_type in ["important", "error", "notice"]: screen.add_new_display(when, who, identifier, action, result, info_type) # 只记录错误 elif config.display_protocol == 2 and info_type in ["important", "error"]: screen.add_new_display(when, who, identifier, action, result, info_type) elif config.display_protocol == 1 and info_type == "important": screen.add_new_display(when, who, identifier, action, result, info_type) else: pass def stat(when, who, identifier, action, result, info_type): # 用于统计的信息 if result == "succ": if who == "sum page": stats.success_sum_page += 1 elif who == "record": stats.success_record += 1 elif who == "pmid": stats.success_pmid += 1 stats.c_skipped_pmid = 0 elif who == "crawl pmid": if result == "started": stats.crawl_pmid_start = ut.time_str("full") elif result == "finished": stats.crawl_pmid_finish = ut.time_str("full") elif who == "crawl detail": if result == "started": stats.crawl_detail_start = ut.time_str("full") if result == "finished": stats.crawl_detail_finish = ut.time_str("full") elif result == "fail": if who == "sum page": stats.failed_sum_page += 1 elif who == "record": stats.failed_record += 1 elif who == "pmid": stats.failed_pmid += 1 elif result == "proc": if who == "sum page": stats.processed_sum_page += 1 elif who == "record": stats.processed_record += 1 elif who == "pmid": stats.processed_pmid += 1 elif result == "skip": if who == "sum page": stats.skipped_sum_page += 1 elif who == "record": stats.skipped_record += 1 elif who == "pmid": stats.skipped_pmid += 1 stats.c_skipped_pmid += 1 if __name__ == '__main__': msg("sp", '4', 'loaded in phantomjs', 'info', log, display)
import datetime import logging from storm.monitoring.sensor.api import sensor from storm.monitoring.sensor.api import metrics from storm.monitoring.sensor.api import services from storm.monitoring.sensor.api import measure from storm.monitoring.sensor.host.mem import mem_check from storm.monitoring.sensor.api import measures class MemSensor(sensor.Sensor): def __init__(self, hostname, service_types): self.logger = logging.getLogger("storm_sensor.mem_sensor") self.logger.info("creating an instance of MemSensor") self.hostname = hostname self.metric_type = metrics.Metrics().mem for val in service_types: if val not in services.Services().get_services(): msg = 'The specified servive type %s does not exist' % str(val) raise services.ServicesError(msg) self.service_types = service_types self.timestamp = '' self.measures = measures.Measures() def get_hostname(self): """Return hostname information""" self.logger.info("getting hostname") return self.hostname def run(self): """Run sensor and save data""" self.logger.info("doing run") self.timestamp = datetime.datetime.now() output = mem_check.Free() self.measures.add_measure(output.get_used()) self.measures.add_measure(output.get_free()) self.get_measures() def get_measures(self): """Return measures""" self.logger.info("getting measures") return self.measures def get_timestamp(self): """Return timestamp""" self.logger.info("getting timestamp") return self.timestamp def get_metric_type(self): """Return metric type""" self.logger.info("getting measures") return self.metric_type def get_storm_service_types(self): """Return storm service types""" self.logger.info("getting storm service types") return self.service_types
#-*-coding:utf-8-*- # Author : Zhang Zhichaung # Date : 2019/6/20 下午2:46 import numpy as np path = '/mnt/share/users/zzc/kitti_second/training/velodyne/000000.bin' points = np.fromfile(path, dtype=np.float32, count=-1).reshape([-1, 4]) # path:待打开的文件对象, dtype: 返回的数据类型, count: int,要读取的项目数. # reshape([a, b]),原来a*b个一维数组,每b个为一行,a=-1可表示任意长度为b倍数的数组,重组为b列 np.savetxt('/home/zzc/second.pytorch/test/000000_origin.txt', points)
import urllib.request import csv # Function to retrieve data from Open Data Portal of the City of Rome # url: the location of the dataset (in CSV format) in the Open Data Portal # localfile: the filename that will be used to store the file on the local disk # header: the initial rows that do not include any data and should be excluded # footer: the trailing rows that do not include any data and should be excluded def loadDataRemote(url, localfile, header, footer): # connect and retrieve dataset u = urllib.request.urlopen(url) rawdata = u.read() # store on local filesystem f = open(localfile, "wb") f.write(rawdata) f.close() # load and prepare data structure return loadDataLocal(localfile, header, footer) # Function to retrieve data from Open Data Portal of the City of Rome # localfile: the filename of the dataset in CSV format # header: the initial rows that do not include any data and should be excluded # footer: the trailing rows that do not include any data and should be excluded def loadDataLocal(localfile, header, footer): # load CSV data f = open(localfile) rawdata = [] for row in csv.reader(f, delimiter=';'): rawdata.append(row) # exclude header / footer dataset = rawdata[header: -footer] # convert text into number for row in dataset: for value in range(2, len(row)): row[value] = int(row[value].replace('.','')) # dataset properly loaded return dataset dataset2014 = loadDataRemote('http://dati.comune.roma.it/cms/do/jacms/Content/incrementDownload.action?contentId=DTS542&filename=popolazione_straniera_iscritta_in_anagrafe_per_municipio_e_sesso_e_cittadinanza_al_31_dicembre_20145ee4.csv',\ 'rome-2014.csv', 5, 5) dataset2013 = loadDataRemote('http://dati.comune.roma.it/cms/do/jacms/Content/incrementDownload.action?contentId=DTS725&filename=18-pop_stra_mun_cittad_1310ef.csv',\ 'rome-2013.csv', 7, 5) dataset2012 = loadDataRemote('http://dati.comune.roma.it/cms/do/jacms/Content/incrementDownload.action?contentId=DTS728&filename=18-pop_stra_mun_cittad_1292e6.csv',\ 'rome-2012.csv', 7, 5) dataset2014 = loadDataLocal('rome-2014.csv', 5, 5) dataset2013 = loadDataLocal('rome-2013.csv', 7, 5) dataset2012 = loadDataLocal('rome-2012.csv', 7, 5) dataset2014.sort(key=lambda x: x[len(x)-1], reverse=True) dataset2013.sort(key=lambda x: x[len(x)-1], reverse=True) dataset2012.sort(key=lambda x: x[len(x)-1], reverse=True) #Reference link for data visualization #https://github.com/ichatz/adm/blob/master/lab-visualization/ADM%20Lab%20-%20Visualization.ipynb #using MatPlot lib values = [] for x in range(0, 15): values.append(dataset2014[0][4+x*3]) import matplotlib.pyplot as plt plt.plot(values) plt.show() #For verifying the current working directory import os print(os.getcwd()) #For creating mongo db documents from data from a json file
from _typeshed import Incomplete def from_sparse6_bytes(string): ... def to_sparse6_bytes(G, nodes: Incomplete | None = None, header: bool = True): ... def read_sparse6(path): ... def write_sparse6( G, path, nodes: Incomplete | None = None, header: bool = True ) -> None: ...
from sys import argv from os.path import exists script, from_file, to_file = argv print "copying from %s to %s" % (from_file, to_file) in_file = open(from_file) indata = in_file.read() print " Does the input file %r exit? " % to_file raw_input() out_file = open(to_file, 'w') out_file.write(indata) print "Alright!" out_file.close() in_file.close() print "outfile :" read = open(to_file) print read.read()
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:hua with open("TEST2.txt","r",encoding="utf-8") as f: s11 = f.read() # s1=s.replace('医疗健康人工智能应用落地优秀案例投票医疗健康人工智能应用落地优秀案例投票秒题请至少选择一个案例进行投票谢谢多选题','') s2 =s11.split("查看详情") name = 0 for s in s2: s1 = s.replace('案例名称', '案例名称:') s2 = s1.replace('仿宋申报单位仿宋', ' 申报单位:') s3 = s2.replace('仿宋实施厂商仿宋', ' 实施厂商:') s4 = s3.replace('仿宋一申报类型一华文仿宋', ' 一·申报类型:') s5 = s4.replace('华文仿宋二案例基本情况华文仿宋', ' 二·案例基本情况:') s6 = s5.replace('华文仿宋三使用效果华文仿宋', ' 三·使用效果:') s7 = s6.replace('华文', '') s8 = s7.replace('仿宋', '') s9 = s8.split(' ') # name = s9[1].replace('申报单位:', '') name =name+1 for a in s9: file = open('{}.txt'.format(name), 'a', encoding="utf-8") # file.write(str(a).encode("utf-8")) # file.write('\\n') file.writelines(a + "\n") file.close()
from v2.client import Personnage class Salvateur(Personnage): def __init__(self, pseudo, Emeteur): Personnage.__init__(self, pseudo, Emeteur, Jeu) self.accesChat = 1 self.sauvePrecedent = "" self.role = 'salvateur' def protege(self, perso): if self.sauvePrecedent != perso and perso in self.Jeu.Village.keys(): self.Emeteur.envoi(('protege %s' % perso).encode('Utf-8')) return True else: return False
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import logging from dataclasses import dataclass from typing import Iterable from pants.backend.cc.lint.clangformat.subsystem import ClangFormat from pants.backend.cc.target_types import CCSourceField from pants.backend.python.util_rules.pex import Pex, PexProcess, PexRequest from pants.core.goals.fmt import FmtResult, FmtTargetsRequest from pants.core.util_rules.config_files import ConfigFiles, ConfigFilesRequest from pants.core.util_rules.partitions import PartitionerType from pants.engine.fs import Digest, MergeDigests from pants.engine.process import ProcessResult from pants.engine.rules import Get, MultiGet, Rule, collect_rules, rule from pants.engine.target import FieldSet from pants.engine.unions import UnionRule from pants.util.logging import LogLevel from pants.util.strutil import pluralize logger = logging.getLogger(__name__) @dataclass(frozen=True) class ClangFormatFmtFieldSet(FieldSet): required_fields = (CCSourceField,) sources: CCSourceField class ClangFormatRequest(FmtTargetsRequest): field_set_type = ClangFormatFmtFieldSet tool_subsystem = ClangFormat partitioner_type = PartitionerType.DEFAULT_SINGLE_PARTITION @rule(level=LogLevel.DEBUG) async def clangformat_fmt(request: ClangFormatRequest.Batch, clangformat: ClangFormat) -> FmtResult: # Look for any/all of the clang-format configuration files (recurse sub-dirs) config_files_get = Get( ConfigFiles, ConfigFilesRequest, clangformat.config_request(request.snapshot.dirs), ) clangformat_pex, config_files = await MultiGet( Get(Pex, PexRequest, clangformat.to_pex_request()), config_files_get ) # Merge source files, config files, and clang-format pex process input_digest = await Get( Digest, MergeDigests( [ request.snapshot.digest, config_files.snapshot.digest, clangformat_pex.digest, ] ), ) result = await Get( ProcessResult, PexProcess( clangformat_pex, argv=( "--style=file", # Look for .clang-format files "--fallback-style=webkit", # Use WebKit if there is no config file "-i", # In-place edits "--Werror", # Formatting warnings as errors *clangformat.args, # User-added arguments *request.files, ), input_digest=input_digest, output_files=request.files, description=f"Run clang-format on {pluralize(len(request.files), 'file')}.", level=LogLevel.DEBUG, ), ) return await FmtResult.create(request, result, strip_chroot_path=True) def rules() -> Iterable[Rule | UnionRule]: return ( *collect_rules(), *ClangFormatRequest.rules(), )
import numpy as np # Construct the matrix input = np.matrix([[2, 1, 0, 1], [1, 0, 0, 0], [1, 0, 0, 0]]) # Calculate DFT output = np.fft.fft2(input) print output
from bs4 import BeautifulSoup import random import requests from fake_useragent import UserAgent import datetime import traceback from scraper.functionScraper import * from scraper.classListingObject import * from scraper.classHelpClasses import * # ####### SECOND PART SCRAPER ###### def scraper2(): uncheckedUrls = True # INITIALISE DATABASE CONNECTION urlsToScrape = UrlList(DBOperations("kezenihi_srmidb3")) while uncheckedUrls is True: try: # SET RANDOM PROXY AND FAKE USER AGENT proxies = get_proxies() # GET FAKE USERAGENT VIA FAKE_USERAGENT PACKAGE ua = UserAgent() headers = ua.random # TEST PROXY url = 'https://httpbin.org/ip' proxyWorks = False print("GET PROXY") while proxyWorks is False: global proxy print("Request") proxy = random.choice(proxies) try: print("TRY") response = requests.get(url, proxies={"http": proxy, "https": proxy}, timeout=10) proxyWorks = True print(response.json()) except: # Most free proxies will often get connection errors. You will have retry the entire request using another proxy to work. # We will just skip retries as its beyond the scope of this tutorial and we are only downloading a single url print("Skipping. Connnection error") proxies = { "http": proxy, "https": proxy, } # GET UNCHECKED URLS urlsList = urlsToScrape.getUrlsID() urlsList = random.sample(urlsList, 10) # STORE URLS IN PROGRESS, SO THEY CAN BE UNCHECKED AT THE END urlsIDs = [item[0] for item in urlsList] # CHECK IF THERE ARE UNSCRAPED URLS AVAILABLE if (len(urlsList) == 0): uncheckedUrls = False else: urlsToScrape.markInProgress(1, urlsIDs) try: # SCRAPE url = urlsList[0] for url in urlsList: checkedURL = False print("--> Check URL: "+url[1]) # CREATE LISTING OBJECT listing = listingObject(DBOperations("kezenihi_srmidb3")) listing.listingID = url[0] listing.address = url[2] listing.postalCode = url[3] # c = requests.get(url[1], proxies=proxies, headers={'user-agent': headers}).content c = None try: c = requests.get(url[1], proxies=proxies, headers={'user-agent': headers}, timeout=10).content except Exception as e: print("An error occured") print(e) if (c is not None): print("Url checked successfully") checkedURL = True soup = BeautifulSoup(c, 'html.parser') descrCheck = False try: listing.description = soup.select('#div_Description')[0].text.strip().replace("\n", "") descrCheck = True except: print("No description available") # CONVERT ADDRESS VIA GOOGLE GEOLOCATION API print("RUN GEOLOCATION API") api_key = "AIzaSyDLpLwScHEHrVpIQOVjSj0RaCOwrkuViNI" query = (listing.address+", "+str(listing.postalCode)+", Switzerland").replace(" ","+") try: googleurl = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + query + '&lang=de&key=' + api_key result = requests.get(googleurl) data = result.json() location = data['results'][0] listing.latitude = location['geometry']['location']['lat'] listing.longitude = location['geometry']['location']['lng'] except: print("Google API was not successful") # GET ATTRIBUTES GRID INFOS listingAvailable = False try: infos = get_list_content_pairs(soup) listingAvailable = True except: print("Listing is not available anymore.") if (listingAvailable is True): for info in infos: type = info.find('dt').string.strip() if (type == "Property type"): listing.category = info.find('dd').string.strip() if (type == "Rent per month"): result = info.find('dd').string.strip() if(result != "On request"): substitutions = {"CHF ": "", ",": ""} listing.price = replaceMultiple(result, substitutions) if (type == "Rent per day"): result = info.find('dd').string.strip() if(result != "On request"): substitutions = {"CHF ": "", ",": ""} listing.pricePerDay = replaceMultiple(result, substitutions) if (type == "Rent per week"): result = info.find('dd').string.strip() if(result != "On request"): substitutions = {"CHF ": "", ",": ""} listing.pricePerWeek = replaceMultiple(result, substitutions) if (type == "Annual rent per m²"): result = info.find('dd').string.strip() if(result != "On request"): substitutions = {"CHF ": "", ",": ""} listing.pricePerYear = replaceMultiple(result, substitutions) if (type == "Rent per month (without charges)"): result = info.find('dd').string.strip() if(result != "On request"): substitutions = {"CHF ": "", ",": ""} listing.primaryCosts = replaceMultiple(result, substitutions) if (type == "Supplementary charges"): result = info.find('dd').string.strip() if(result != "On request"): substitutions = {"CHF ": "", ",": ""} listing.additionalCosts = replaceMultiple(result, substitutions) if (type == "Living space"): result = info.find('dd').string.strip().replace(" m²", "") if(result != "On request"): listing.size = result if (type == "Floor space"): result = info.find('dd').string.strip().replace(" m²", "") if(result != "On request"): listing.floorSpace = result if (type == "Property area"): result = info.find('dd').string.strip().replace(" m²", "") if(result != "On request"): listing.propertyArea = result if (type == "Rooms"): listing.rooms = info.find('dd').string.strip().replace("½", ".5") if (type == "Floor"): result = info.find('dd').string.strip().replace(". floor", "") if (result == "Ground floor"): listing.floor = 0 elif (result == "Basement"): listing.floor = -1 else: listing.floor = result if (type == "Available"): listing.available = info.find('dd').string.strip() if (type == "Year of construction"): listing.construction = info.find('dd').string.strip() if (type == "Lift"): listing.elevator = 1 if (type == "Balcony/ies"): listing.balconies = 1 if (type == "Motorway"): listing.motorway = info.find('dd').string.strip().replace(" m", "") if (type == "Shops"): listing.shops = info.find('dd').string.strip().replace(" m", "") if (type == "Public transport stop"): listing.publicTransport = info.find('dd').string.strip().replace(" m", "") if (type == "Kindergarten"): listing.kindergarten = info.find('dd').string.strip().replace(" m", "") if (type == "Primary school"): listing.primarySchool = info.find('dd').string.strip().replace(" m", "") if (type == "Secondary school"): listing.secondarySchool = info.find('dd').string.strip().replace(" m", "") if (type == "Minergie certified"): listing.minergie = 1 if (type == "Pets allowed"): listing.pets = 1 if (type == "Child-friendly"): listing.childFriendly = 1 if (type == "Cable TV"): listing.cableTV = 1 if (type == "New building"): listing.newBuilding = 1 if (type == "Wheelchair accessible"): listing.wheelchair = 1 if (type == "Outdoor parking"): listing.parkingOutdoor = 1 if (type == "Indoor parking"): listing.parkingIndoor = 1 if (type == "Veranda"): listing.veranda = 1 if (type == "Swimming pool"): listing.pool = 1 # CREATE LIST WITH ONLY FILLED OUT VALUES, MAKES IT EASIER TO SEND PER SQL insertDetails = [] insertDetailsKeys = [] for k, v in vars(listing).items(): if (k in ["listingID", "category", "postalCode", "address", "latitude", "longitude", "price", "pricePerDay", "pricePerWeek", "pricePerYear", "primaryCosts", "additionalCosts", "size", "floorSpace", "propertyArea", "rooms", "floor", "available", "construction"]): if (v is not None): insertDetailsKeys.append(k) insertDetails.append(v) insertDetailsKeys = str(tuple(insertDetailsKeys)).replace("'", "") insertDistances = [] insertDistancesKeys = [] for k, v in vars(listing).items(): if (k in ["listingID", "motorway", "shops", "publicTransport", "kindergarten", "primarySchool", "secondarySchool"]): if (v is not None): insertDistancesKeys.append(k) insertDistances.append(v) len(insertDistancesKeys) if (len(insertDistancesKeys) > 1): insertDistancesKeys = str(tuple(insertDistancesKeys)).replace("'", "") # INSERT listingDetails listing.insertInfos(table="listingDetails", columns=str(insertDetailsKeys), listings=[tuple(insertDetails)]) # INSERT listingDistances if (len(insertDistancesKeys) > 1): listing.insertInfos(table="listingDistances", columns=str(insertDistancesKeys), listings=[tuple(insertDistances)]) # CHECK IF ATTRIBUTES ARE AVAILABLE attributesAvailable = sum([listing.elevator, listing.balconies, listing.minergie, listing.pets, listing.childFriendly, listing.cableTV, listing.newBuilding, listing.wheelchair, listing.parkingOutdoor, listing.parkingIndoor, listing.veranda, listing.pool]) if (attributesAvailable > 0): # INSERT listingAttributes listing.insertInfos(table="listingAttributes", columns="(listingID, elevator, balconies, minergie, pets, childFriendly, cableTV, newBuilding, wheelchair, parkingIndoor, parkingOutdoor, veranda, pool)", listings=[(listing.listingID, listing.elevator, listing.balconies, listing.minergie, listing.pets, listing.childFriendly, listing.cableTV, listing.newBuilding, listing.wheelchair, listing.parkingOutdoor, listing.parkingIndoor, listing.veranda, listing.pool)]) # INSERT listingDescription if(descrCheck is True): listing.insertInfos(table="listingDescription", columns="(listingID, description)", listings=[(listing.listingID, listing.description)]) # UPDATE LISTING URL if (checkedURL is True): d = datetime.datetime.today() urlsToScrape.updateUrl(date=d.strftime('%Y-%m-%d'), id=listing.listingID) except Exception as e: print("THIS URL HAD AN ERROR") print(traceback.format_exc()) print(e) urlsToScrape.markInProgress(0, urlsIDs) print("\n\n") except Exception as e: print("SCRAPING ERROR \n\n") print(traceback.format_exc()) print(e)
from datetime import datetime, timedelta from typing import Any, Dict, Optional from fastapi import Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer from jose import JWTError, jwt from passlib.context import CryptContext from sqlalchemy.ext.asyncio import AsyncSession from app.config import HASHING_ALGORITHM, settings from app.database.crud import get_user_by_username from app.database.models import User from app.database.sqlite import db from app.schema import TokenData pwd_context = CryptContext(schemes=['bcrypt'], deprecated='auto') oauth2_scheme = OAuth2PasswordBearer(tokenUrl='token') def verify_password(plain_password: str, hashed_password: str) -> bool: return pwd_context.verify(plain_password, hashed_password) def get_password_hash(password: str) -> str: return pwd_context.hash(password) async def authenticate_user( session: AsyncSession, username: str, password: str ) -> Optional[User]: user = await get_user_by_username(session, username) if not user: return None if not verify_password(password, user.hashed_password): return None return user def create_access_token( data: Dict[str, Any], expires_delta: Optional[timedelta] = None ) -> str: # pragma: no cover to_encode = data.copy() if expires_delta: expire = datetime.utcnow() + expires_delta else: expire = datetime.utcnow() + timedelta(minutes=15) to_encode.update({'exp': expire}) encoded_jwt = jwt.encode( to_encode, settings.secret_key, algorithm=HASHING_ALGORITHM ) return encoded_jwt async def get_current_active_user( session: AsyncSession = Depends(db.get_session), token: str = Depends(oauth2_scheme) ) -> User: credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail='Could not validate credentials', headers={'WWW-Authenticate': 'Bearer'}, ) try: payload = jwt.decode(token, settings.secret_key, algorithms=[HASHING_ALGORITHM]) username: str = payload.get('sub') if not username: raise credentials_exception token_data = TokenData(username=username) except JWTError as e: raise credentials_exception from e user = await get_user_by_username(session, token_data.username) if user is None: raise credentials_exception return user
#!/usr/bin/env /proj/sot/ska/bin/python ######################################################################################################### # # # extract_data_redo.py: extract data from archive # # modify lines around 124 - 133 to an appropriate period # # # # author: t. isobe (tisobe@cfa.harvard.edu) # # # # last update: Nov 20, 2014 # # # ######################################################################################################### import os import sys import re import string import random import operator import math import numpy from astropy.io import fits # #--- from ska # from Ska.Shell import getenv, bash ascdsenv = getenv('source /home/ascds/.ascrc -r release; source /home/mta/bin/reset_param', shell='tcsh') # #--- reading directory list # path = '/data/mta/Script/Trending/Recovery/dir_list_py' f= open(path, 'r') data = [line.strip() for line in f.readlines()] f.close() for ent in data: atemp = re.split(':', ent) var = atemp[1].strip() line = atemp[0].strip() exec "%s = %s" %(var, line) # #--- append pathes to private folders to a python directory # sys.path.append(bin_dir) sys.path.append(mta_dir) # #--- import several functions # import convertTimeFormat as tcnv #---- contains MTA time conversion routines import mta_common_functions as mcf #---- contains other functions commonly used in MTA scripts # #--- temp writing file name # rtail = int(10000 * random.random()) #---- put a romdom # tail so that it won't mix up with other scripts space zspace = '/tmp/zspace' + str(rtail) # #--- the name of data set that we want to extract # #name_list = ['compaciscent', 'compacispwr', 'compephinkeyrates', 'compgradkodak', 'compsimoffset'] #---- comp*fits are not avaialble name_list = ['gradablk', 'gradahet', 'gradaincyl', 'gradcap', 'gradfap', 'gradfblk', 'gradhcone',\ 'gradhhflex', 'gradhpflex', 'gradhstrut', 'gradocyl', 'gradpcolb', 'gradperi', \ 'gradsstrut', 'gradtfte'] # #--- a couple of things needed # dare = mcf.get_val('.dare', dir = bindata_dir, lst=1) hakama = mcf.get_val('.hakama', dir = bindata_dir, lst=1) #-------------------------------------------------------------------------------------------------------- #-------------------------------------------------------------------------------------------------------- #-------------------------------------------------------------------------------------------------------- def run_script(name_list): """ extract the new data and update the data sets. Input: name_list --- a list of the name of dataset that we want to extract/update Output: updated fits file (e.g. avg_compaciscent.fits) """ for dir in name_list: nfile = house_keeping + dir f = open(nfile, 'r') data = [line.strip() for line in f.readlines()] f.close() col_list = [] for ent in data: atemp = re.split('\s+', ent) col_list.append(atemp[0]) # #--- prepare the input for the case there is no data or bad data # dlen = len(col_list) dlen2 = 2 * dlen eline = '-999' for i in range(1, dlen2): eline = eline + '\t-999' outfile = './Results/' + dir # #--- collect data # try: collect_data(dir, col_list, outfile, eline) except: pass # #---- now creating fits file # convert_to_fits(dir, col_list) #-------------------------------------------------------------------------------------------------------- #-- CHANGE THE YEAR AND MONTH BELOW TO RECOVER THE DATA !!! --------------------------------------- #-------------------------------------------------------------------------------------------------------- def collect_data(dir, col_list, outfile, eline): # #--- now loop through year and ydate # for year in range(2015, 2017): for month in range(1, 13): if year == 2014 and month < 12: continue chk = tcnv.isLeapYear(year) if(year == 2016) and (month > 6): break print "Date year: " + str(year) + ' month: ' + str(month) + ' : ' + str(dir) try: line = extract_new_data(dir, col_list, year, month) except: line = 'na' cmd = 'rm ./mta*fits* ./Working_dir/mta*fits*' os.system(cmd) fo = open(outfile, 'a') if line != 'na': fo.write(line) else: dom = int(tcnv.YdateToDOM(year, yday)) line = str(dom) + '\t' + eline + '\n' fo.write(line) fo.close() #-------------------------------------------------------------------------------------------------------- #-------------------------------------------------------------------------------------------------------- #-------------------------------------------------------------------------------------------------------- def convert_to_fits(dir, col_list): file = './Results/' + dir f = open(file, 'r') data = [line.strip() for line in f.readlines()] f.close() # #--- define column names # col_names =[] for ent in col_list: aname = ent + '_AVG' col_names.append(aname) ename = ent + '_DEV' col_names.append(ename) dlen = len(col_list) dlen2 = 2 * dlen time = [] data_set = [[] for x in range(0, dlen2)] for ent in data: atemp = re.split('\t', ent) time.append(atemp[0]) for j in range(1, len(atemp)): data_set[j-1].append(atemp[j]) time = numpy.array(time) col = fits.Column(name='Time', format='D', array=time) col_list = [col] for j in range(0, dlen2): data_set[j] = numpy.array(data_set[j]) col = fits.Column(name=col_names[j], format='D', array=data_set[j]) col_list.append(col) cols = fits.ColDefs(col_list) tbhdu = fits.BinTableHDU.from_columns(cols) # --- version 0.42 # tbhdu = fits.new_table(cols) # --- versuib 0.30 # #---- create a bare minimum header # prihdr = fits.Header() prihdu = fits.PrimaryHDU(header=prihdr) out_name = './Results/avg_' + dir + '.fits' # #--- create the fits file # cmd = 'rm ' + out_name os.system(cmd) thdulist = fits.HDUList([prihdu, tbhdu]) thdulist.writeto(out_name) #-------------------------------------------------------------------------------------------------------- #-- extract_new_data: read out currently available data from mp report directory -- #-------------------------------------------------------------------------------------------------------- def extract_new_data(dir, col_list, year, month): syear = str(year) smon = str(month) if month < 10: smon = '0' + smon lyear = year lmonth = month +1 if lmonth > 12: lmonth = 1 lyear += 1 slyear = str(lyear) slmon = str(lmonth) if lmonth < 10: slmon = '0' + slmon #start = smon + '/01/' + syear[2] + syear[3] + ',00:00:00' #stop = slmon + '/01/' + slyear[2] + slyear[3] + ',00:00:00' start = syear + '-' + smon + '-01T00:00:00' stop = slyear + '-' + slmon + '-01T00:00:00' print "\tPeriod: " + start + '<--->' + stop out = extract_new_data_sub(dir, col_list, start, stop, year, month) if out != 'na': line = out else: line = '' return line #-------------------------------------------------------------------------------------------------------- #-------------------------------------------------------------------------------------------------------- #-------------------------------------------------------------------------------------------------------- def extract_new_data_sub(dir, col_list, start, stop, year, month): # #--- extract data # line = 'operation=retrieve\n' line = line + 'dataset = mta\n' line = line + 'detector = grad\n' line = line + 'level = 0.5\n' line = line + 'filetype =' + dir + '\n' line = line + 'tstart=' + start + '\n' line = line + 'tstop=' + stop + '\n' line = line + 'go\n' fo = open(zspace, 'w') fo.write(line) fo.close() cmd1 = "/usr/bin/env PERL5LIB=" #cmd2 = ' echo ' + hakama + ' |arc4gl -U' + dare + ' -Sarcocc -i' + zspace cmd2 = ' /proj/axaf/simul/bin/arc5gl -user isobe -script ' + zspace cmd = cmd1 + cmd2 bash(cmd, env=ascdsenv) mcf.rm_file(zspace) cmd = 'mv *gz ./Working_dir/.' os.system(cmd) cmd = 'gzip -d ./Working_dir/*.gz' os.system(cmd) cmd = 'ls ./Working_dir/*.fits > ' + zspace os.system(cmd) f = open(zspace, 'r') data = [line.strip() for line in f.readlines()] f.close() mcf.rm_file(zspace) if len(data) == 0: return 'na' # #--- extract each column data and stored in arrays # elen = len(col_list) dat_save = [[] for x in range(0, elen)] time_dat = [] for file in data: dout = fits.getdata(file, 1) time = dout.field('time') for ent in time: time_dat.append(ent) for k in range(0, elen): col = col_list[k] sta = 'ST_' + col val = dout.field(col) chk = dout.field(sta) for j in range(0, len(chk)): if chk[j] >= 0: dat_save[k].append(val[j]) # #--- set the beginning of the and the end of the first day of the data # ydate = tcnv.findYearDate(year, month, 1) tent = str(year) + ':' + str(ydate) + ':00:00:00' begin = tcnv.axTimeMTA(tent) smonth = month + 1 syear = year if smonth > 12: smonth = 1 syear += 1 ydate = tcnv.findYearDate(syear, smonth, 1) tent = str(syear) + ':' + str(ydate) + ':00:00:00' stop = tcnv.axTimeMTA(tent) end = begin + 86400 if end > stop: end = stop dom = int(tcnv.stimeToDom(begin)) sline = str(dom) dsumming= [[] for x in range(0, elen)] # #--- find mean and std of each columns # for k in range(0, len(time_dat)): if time_dat[k] >= begin and time_dat[k] < end: for i in range(0, elen): dsumming[i].append(dat_save[i][k]) elif time_dat[k] < begin: continue elif time_dat[k] >= end: for i in range(0, elen): narray = numpy.array(dsumming[i]) avg = numpy.mean(narray) avg = '%.4f' % round(avg, 4) err = numpy.std(narray) err = '%.4f' % round(err, 4) sline = sline + '\t' + str(avg) + '\t' + str(err) sline = sline + '\n' # #--- reintialize for the next day # begin += 86400 if begin >= stop: break end = begin + 86400 if end > stop: end = stop dom = int(tcnv.stimeToDom(begin)) sline = sline + str(dom) dsumming= [[] for x in range(0, elen)] cmd = 'rm ./Working_dir/*.fits*' os.system(cmd) return sline #----------------------------------------------------------------------- if __name__ == "__main__": run_script(name_list)
""" Create a set of turtles and set them on a starting line. Turtles are created with a function. User sets number of turtles to be created. Each turtle is a different random color. Turtles race to finish line. """ import turtle import random num_t = int(input("Please input the number of turtles desired: ")) t_screen = turtle.Screen() color_lst = ["red","blue","yellow","green","black","violet","gold", "orange", "magenta"] t=[] def fn_start_finish_line(): # Set width of track for number of turtles racing width = (num_t * 50) + 50 # Create turtle that will draw start/finish lines my_line = turtle.Turtle() my_line.speed(1000) my_line.hideturtle() # Draw start line my_line.penup() my_line.goto(-300,-200) my_line.pendown() my_line.forward(width) # Draw finish line my_line.penup() my_line.goto(-300,200) my_line.pendown() my_line.forward(width) def fn_create_turtles(num_t): for i in range(1,(num_t+1)): name = 't{}'.format(i) name = turtle.Turtle() t.append(name) name.color(random.choice(color_lst)) def fn_startline(): for my_turtle in t: my_turtle.penup() my_turtle.speed(1000) x_pos = -300 + (50 * (t.index(my_turtle)+1)) my_turtle.goto(x_pos,-200) my_turtle.pendown() my_turtle.left(90) def fn_move_forward(): while (True): for item in t: dist = random.randint(0,10) item.speed(random.randint(0,1000)) item.forward(dist) if (item.ycor() >= 200): # Check if winner winner_name = "{}".format(t.index(item)+1) print("We have a winner: Turtle 't{}'!!".format(winner_name)) return None fn_create_turtles(num_t) fn_start_finish_line() fn_startline() fn_move_forward() #turtle.mainloop() t_screen.exitonclick()
import paho.mqtt.subscribe as subscribe class Communication(object): def __init__(self): super(Communication, self).__init__() subscribe.callback(lambda client, userdata, message: self.onMessageReceive(message.payload), "/dtc", hostname="localhost") def onMessageReceive(self, dtc_msg): print(dtc_msg) c = Communication()
#!/usr/bin/python """ Using the tau amino acid sequence from 5o3l, this script threads a sliding frame of 6 tau residues into the substrate of Htra1 protease 3nzi then runs a FastRelax. The aim is to determine the most favorable docking points along the tau chain based only on sequence. """ from os import makedirs from os.path import basename, isdir, isfile, join from pyrosetta import * from pyrosetta.rosetta.core.id import AtomID from pyrosetta.rosetta.core.kinematics import FoldTree from pyrosetta.rosetta.core.pack.task.operation import \ ExtraRotamers, IncludeCurrent, RestrictToRepacking from pyrosetta.rosetta.protocols.enzdes import ADD_NEW, AddOrRemoveMatchCsts from pyrosetta.rosetta.protocols.relax import FastRelax from pyrosetta.teaching import SimpleThreadingMover from pyrosetta.toolbox import mutate_residue from sys import exit tau_seq = 'AKSRLQTAPVPMPDLKNVKSKIGSTENLKHQPGGGK\ VQIVYKPVDLSKVTSKCGSLGNIHHKPGGGQVEVKSEKLDFKDRVQSKIGSLDNITHVPGGGNKKIETHKLTF\ RENAKAKTDHGAEIVYKSPVV' def apply_constraints(pose): """ Applies enzdes constraints form the input CST file to a pose """ cstm = AddOrRemoveMatchCsts() cstm.set_cst_action(ADD_NEW) cstm.apply(pose) return pose def make_fold_tree(): """ Make a fold tree that connects the res 385 to the substrate terminal residue. More efficient sampling. Presently hard-coded for Htra1 PDZ I385 is residue 10. Last residue of PDZ chain A is 105 Terminal residue of substrate chain B is 112 Substrate chain B is 7 residues """ ft = FoldTree() ft.add_edge(10, 1, -1) ft.add_edge(10, 105, -1) ft.add_edge(10, 112, 1) ft.add_edge(112 ,106, -1) assert ft.check_fold_tree() return ft def setup_fastrelax(sf): """ Creates FastRelax mover with appropriate score function, movemap, and packer rules. List of neighbor residues was generated using a 8A PyMOL selection expansion around the peptide chain. """ relax = FastRelax() relax.set_scorefxn(sf) # MoveMap mm = MoveMap() mm.set_bb_true_range(106, 112) neighbors = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 22, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 53, 59, 62, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 83, 85, 98, 100, 101, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112] # Did 8A selection separately for n in neighbors: mm.set_chi(n, True) relax.set_movemap(mm) # Packer tasks tf = standard_task_factory() tf.push_back(RestrictToRepacking()) tf.push_back(IncludeCurrent()) tf.push_back(ExtraRotamers(0, 1, 1)) tf.push_back(ExtraRotamers(0, 2, 1)) relax.set_task_factory(tf) return relax def thread_to_htra1(sequence, pose): """ Uses SimpleThreadingMover to swap out the native substrate and put in a new test sequence docked with Htra1 protease. The substrate peptide begins at residue 212 of the pose, based on 3nzi. """ assert len(sequence) == 7 # Constructing and applying mover tm = SimpleThreadingMover(sequence, 106) threaded_pose = Pose() threaded_pose.assign(pose) tm.apply(threaded_pose) return threaded_pose def main(): # Destination folder for PDB files out_dir = 'pdz_tau_slide' if not isdir(out_dir): makedirs(out_dir) # Initialize Rosetta opts = '-enzdes::cstfile htra1_pdz.cst \ -cst_fa_weight 1.0 -run:preserve_header' init(opts) # Score function sf = create_score_function('ref2015_cst') # Starting poses poses = [] pdbs = ['pdz_relaxed_1.pdb', 'pdz_relaxed_2.pdb', 'pdz_relaxed_3.pdb', 'pdz_relaxed_4.pdb'] for pdb in pdbs: p = pose_from_pdb(pdb) # Applying fold tree and constraints to the pose p.fold_tree(make_fold_tree()) p = apply_constraints(p) poses.append(p) # Making FastRelax mover fr = setup_fastrelax(sf) # Going through all 7-residue frames in tau for frame in range(len(tau_seq))[:-6]: # Making name from position within tau sequence and the frame sequence position_name = '{:03d}'.format(frame + 276) # First res is V270 # P276 is the first frame's C-terminal residue seq = tau_seq[frame:frame + 7] set_name = '_'.join([position_name, seq]) print(set_name) for n, pose in enumerate(poses): # Creating relaxed decoys r_name = 'relaxed_pdz_' + str(n) + '_tau_' + set_name jd = PyJobDistributor(join(out_dir, r_name), 50, sf) while not jd.job_complete: # Make threaded, relaxed models threaded_pose = thread_to_htra1(seq, pose) fr.apply(threaded_pose) jd.output_decoy(threaded_pose) if __name__ == '__main__': main()
''' Created on 30. mar. 2017 @author: tsy ''' class specialRules(object): ''' classdocs ''' def __init__(self, attacker,defender): ''' Constructor ''' self.attacker=None self.defender=None
#!/usr/bin/env python3 # Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. import os import sys def main(args): for file in os.listdir(args[0]): if file.endswith('.cpp') or file.endswith('.h'): print(file) if __name__ == '__main__': main(sys.argv[1:])
from flask_restful import Resource, reqparse, fields, marshal from models import User, db from common.crypto import encode, decode import jwt import os import uuid user_fields = { 'id': fields.String, 'username': fields.String } class Register(Resource): def __init__(self): self.post_parser = reqparse.RequestParser() self.post_parser.add_argument( 'username', dest='username', required=True, help='Required field username', ) self.post_parser.add_argument( 'password', dest='password', required=True, help='Required field password' ) def post(self): args = self.post_parser.parse_args() if User.query.filter_by(username=args['username']).count(): return {'message': 'user already exist'}, 400 user = User(id=uuid.uuid4().hex, username=args['username'], password=encode(args['password'])) # need to prevent commit user with a '-' in his username db.session.add(user) db.session.commit() return marshal(user, user_fields) class Login(Resource): def __init__(self): self.post_parser = reqparse.RequestParser() self.post_parser.add_argument( 'username', dest='username', required=True, help='Required field username', ) self.post_parser.add_argument( 'password', dest='password', required=True, help='Required field password' ) def post(self): args = self.post_parser.parse_args() user = User.query.filter_by(username=args['username']).first() if user is None: return {'message': 'wrong username / password combinaison'}, 400 if decode(user.password) != args['password']: return {'message': 'wrong username / password combinaison'}, 400 encoded = jwt.encode({'id': user.id}, os.environ['JWT_SECRET'], algorithm='HS256') return {'token': encoded.decode('utf-8')}
import micro_nw as nw import numpy as np from sklearn.linear_model import Lasso, LassoCV import pandas as pd import sys from scipy import stats folde = sys.argv[1] fo1 = open(folde+'/disease_list','w') fo1.write(sys.argv[2]) dis =[] dis.append(sys.argv[2]) if len(sys.argv)>3: dis.append(sys.argv[3]) fo1.write('\t'+sys.argv[3]) if len(sys.argv)>4: dis.append(sys.argv[4]) fo1.write('\t'+sys.argv[4]) fo1.close() alp = 0.0001 reps = 1000 D = pd.read_csv(folde+'/healthy.csv').as_matrix().astype('float64') max_degree ,components, degrees, GG = nw.max_deg_stat(D,alp,reps) for d in dis: D= pd.read_csv(folde+'/'+d).as_matrix().astype('float64') md ,c, d, g = nw.max_deg_stat(D,alp,reps) max_degree = np.concatenate((max_degree,md),axis=0) components = np.concatenate((components,c),axis=0) degrees = np.concatenate((degrees,d),axis=0) GG=GG+g np.savetxt(folde+'/degrees.csv',degrees,delimiter=',') R,P = nw.rank_corr(degrees) np.savetxt(folde+'/degree_r.csv',R,delimiter=',') np.savetxt(folde+'/degree_p.csv',P,delimiter=',') S=nw.graph_similarity(GG) np.savetxt(folde+'/graph_similar.csv',S,delimiter=',')
from .catalog_ref import CatalogRef from .exchange_ref import ExchangeRef
# Copyright 2017 The Forseti Security Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Provides the data access object (DAO) for buckets.""" from MySQLdb import DataError from MySQLdb import IntegrityError from MySQLdb import InternalError from MySQLdb import NotSupportedError from MySQLdb import OperationalError from MySQLdb import ProgrammingError from google.cloud.security.common.data_access import errors from google.cloud.security.common.data_access import project_dao from google.cloud.security.common.data_access.sql_queries import select_data # pylint: disable=line-too-long from google.cloud.security.common.gcp_type import bucket_access_controls as bkt_acls # pylint: enable=line-too-long from google.cloud.security.common.util import log_util LOGGER = log_util.get_logger(__name__) class BucketDao(project_dao.ProjectDao): """Data access object (DAO) for Organizations.""" RESOURCE_RAW_BUCKETS = 'raw_buckets' def get_buckets_by_project_number(self, resource_name, timestamp, project_number): """Select the buckets for project from a buckets snapshot table. Args: resource_name (str): String of the resource name. timestamp (str): String of timestamp, formatted as YYYYMMDDTHHMMSSZ. project_number (int): Project number Returns: list: List of project buckets. Raises: MySQLError: An error with MySQL has occurred. """ buckets_sql = select_data.BUCKETS_BY_PROJECT_ID.format(timestamp) rows = self.execute_sql_with_fetch( resource_name, buckets_sql, (project_number,)) return [row['bucket_name'] for row in rows] def get_buckets_acls(self, resource_name, timestamp): """Select the bucket acls from a bucket acls snapshot table. Args: resource_name (str): String of the resource name. timestamp (str): String of timestamp, formatted as YYYYMMDDTHHMMSSZ. Returns: list: List of bucket acls. Raises: MySQLError: An error with MySQL has occurred. """ bucket_acls = {} cnt = 0 try: bucket_acls_sql = select_data.BUCKET_ACLS.format(timestamp) rows = self.execute_sql_with_fetch(resource_name, bucket_acls_sql, None) for row in rows: bucket_acl = bkt_acls.\ BucketAccessControls(bucket=row['bucket'], entity=row['entity'], email=row['email'], domain=row['domain'], role=row['role'], project_number=row['project_number']) bucket_acls[cnt] = bucket_acl cnt += 1 except (DataError, IntegrityError, InternalError, NotSupportedError, OperationalError, ProgrammingError) as e: LOGGER.error(errors.MySQLError(resource_name, e)) return bucket_acls def get_raw_buckets(self, timestamp): """Select the bucket and its raw json. Args: timestamp (str): The snapshot timestamp, formatted as YYYYMMDDTHHMMSSZ. Returns: list: List of dict mapping buckets to their raw json. """ buckets_sql = select_data.RAW_BUCKETS.format(timestamp) rows = self.execute_sql_with_fetch( self.RESOURCE_RAW_BUCKETS, buckets_sql, None) return rows
from django.conf.urls import url from message.views import HistoriqueView urlpatterns = [ url('', HistoriqueView.as_view(), name='historique'), ]
import numpy as np import cv2 def show_img(img): cv2.imshow("canvas",img) cv2.waitKey(0) return canvas = np.zeros((300,300,3), dtype= 'uint8') green = (0,255,0) cv2.line(canvas, (0,0), (300,300), green) # (0,0) starting coordinate and # (300,300) ending coordinate show_img(canvas) red = (0,0,255) cv2.line(canvas, (0,300), (300,0), red, thickness=5) show_img(canvas) cv2.rectangle(canvas, (10,10), (60,60), green) show_img(canvas) cv2.rectangle(canvas, (50,200), (200,225), green, thickness=3) show_img(canvas) cv2.rectangle(canvas, (200,200), (250,225), red, thickness=-1) show_img(canvas) #-1 to fill the rectanagle ### Draw circle ''' To draw circle on image, we first find the center (x,y) coordinate of image''' canvas = np.zeros((300,300,3), dtype='uint8') centerx, centery = (canvas.shape[1]//2, canvas.shape[0]//2) white = (255,255,255) for r in range(0,175,25): cv2.circle(canvas, (centerx, centery), r, white) show_img(canvas) # we loop over a number of radius and increament by 25 # the dot in the very center is drawn by radius of zero
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import threading class WorkerThread(threading.Thread): def __init__(self, method, params): threading.Thread.__init__(self) self.method = method self.params = params self.completed = False self.results = None def run(self): self.results = self.method(*self.params) self.completed = True def __areAllComplete(threads): for thread in threads: if not thread.completed: return False return True def wait(threads, startFirst=False, poll=0.5): if startFirst: for thread in threads: thread.start() while not __areAllComplete(threads): threading._sleep(poll) def foo(param1, param2): print(param1, param2) return "c" if __name__ == "__main__": thread = WorkerThread(foo, params=("a", "b")) thread.start() while not thread.completed: threading._sleep(0.5) print(thread.results)
import down_util import pandas as pd import os from glob import glob from os import path # os.environ['http_proxy']='127.0.0.1:1080' # os.environ['https_proxy']='127.0.0.1:1080' if __name__=='__main__': df, _ = down_util.split_collection(r"Z:\yinry\Landsat.Data\GOOGLE\landsat_index.csv.gz") # pr_list_file = r"Z:\yinry\global_mosaic\2018.need.1.pidlist.txt" # condi_df = down_util.condi_thumbnail_by_pr(df, pr_list_file, '2017-10-01', '2018-12-31', 20, mode='PID') # condi_df.to_csv(r'Z:\yinry\global_mosaic\2018.thumb.need.1\condi_df.csv') # condi_df = pd.read_csv(r'Z:\yinry\global_mosaic\2018.thumb.need.1\condi_df.csv') # down_util.download_c1df_thumbnail(condi_df, # r'D:\PROJECT\A_Project\global_download\2000\cloud2000.thumbnail') pr_lists = [r"Z:\yinry\0.DEFINITION\wrs2landwithmonth.csv"] # pr_lists = [r"Z:\yinry\china.mosaic\china.pr.txt"] # down_root = r'Z:\yinry\china.mosaic\1990\thumbnail' ref_root = r'Z:\yinry\global_mosaic\global_thumbnail_ref\global_thumbnail_0203' # condi_df_list = [] # # for i, one_pr_list in enumerate(pr_lists): # # condi_df_list.append([]) startdate = '2003-01-01' enddate = '2007-12-31' yearroot = r'Z:\yinry\global_mosaic\2005' # thumb_root = r'Z:\yinry\global_mosaic\2005\0.thumbnail' thumb_root = path.join(yearroot, '0.thumbnail') # this_condi = down_util.condi_thumbnail_by_pr(df, one_pr_list, startdate, enddate, 20, mode='PR') # # this_down_root = path.join(down_root, str(year)) # down_util.download_c1df_thumbnail(this_condi, down_root) good = down_util.BestsceneWoker(ref_root, pr_lists[0], startdate, enddate, thumb_root, copydir=path.join(yearroot, '1.good'), df=df, nprocess=20) pd.DataFrame(data={'good': good}).to_csv(path.join(thumb_root, 'good.csv'), index=False, header=False) exit(0)
import tensorflow as tf from tensorflow import keras from keras.models import load_model import numpy as np import random import matplotlib.pyplot as plt # Generate the Model using Keras def generate_model(train_data, test_data, train_label, test_label, epochs): # Create the Multilayer Network model = keras.Sequential([ keras.layers.Flatten(input_shape=(28, 28)), keras.layers.Dense(256, activation='relu'), keras.layers.Dense(128, activation='relu'), keras.layers.Dropout(.2), keras.layers.Dense(64, activation='sigmoid'), keras.layers.Dense(32, activation='relu'), keras.layers.Dense(10, activation='softmax') ]) # Compile the model model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # Fit model and get training history data history_model = model.fit(train_data, train_label, epochs=epochs, validation_split=0.2) plot_accuracy(history_model.history, epochs) plot_loss(history_model.history, epochs) # Evaluate model metrics test_loss, test_acc = model.evaluate(test_data, test_label, verbose=2) print(f'Mean Accuracy:{test_acc*100}\nMean Loss:{test_loss*100}\n') return model def plot_accuracy(history, epoch): accuracy = [acc * 100 for acc in history['accuracy']] val_accuracy = [val_acc * 100 for val_acc in history['val_accuracy']] plt.figure() plt.plot(accuracy) plt.plot(val_accuracy) plt.title('Accuracy by Epochs') plt.xlabel('Epochs') plt.xticks(range(epoch)) plt.ylabel('Accuracy(%)') plt.legend(['Train', 'Validation']) plt.show() def plot_loss(history, epoch): loss = [loss * 100 for loss in history['loss']] val_loss = [val_loss * 100 for val_loss in history['val_loss']] plt.figure() plt.plot(loss) plt.plot(val_loss) plt.title('Loss by Epochs') plt.xlabel('Epochs') plt.xticks(range(epoch)) plt.ylabel('Loss (%)') plt.legend(['Train', 'Validation']) plt.show() def plot_image(i, predictions_array, true_label, img): predictions_array, true_label, img = predictions_array[i], true_label[i], img[i] plt.grid(False) plt.xticks([]) plt.yticks([]) plt.imshow(img, cmap=plt.cm.binary) predicted_label = np.argmax(predictions_array) if predicted_label == true_label: color = 'blue' else: color = 'red' plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label], 100 * np.max(predictions_array), class_names[true_label]), color=color) def plot_value_array(i, predictions_array, true_label): predictions_array, true_label = predictions_array[i], true_label[i] plt.grid(False) thisplot = plt.bar(range(10), predictions_array, color="#777777") plt.ylim([0, 1]) predicted_label = np.argmax(predictions_array) thisplot[predicted_label].set_color('red') thisplot[true_label].set_color('blue') plt.xticks(range(10), class_names, rotation=35, fontsize=8) print(f'TensorFlow Version: {tf.__version__}') # Loading the fashion_mnist Dataset fashion_mnist = keras.datasets.fashion_mnist (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data() # Data Info print(40 * "=") print(f'Fashion Mnist Dataset') print(f'Train Image Dimensions:{train_images.shape}') print(f'Test Image Dimensions:{test_images.shape}') print(40 * "=") # Plot Images plt.figure() plt.imshow(train_images[random.randint(0, len(train_images))]) plt.colorbar() plt.grid(False) plt.show() class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] for image in range(0, 10): plt.subplot(2, 5, image + 1) plt.xticks([]) plt.yticks([]) plt.grid(False) plt.imshow(train_images[image], cmap=plt.cm.binary) plt.xlabel(class_names[train_labels[image]]) plt.show() # no_normalize_model = generate_model(train_data=train_images, test_data=test_images, # train_label=train_labels, test_label=test_labels, epochs=5) # predictions = no_normalize_model.predict(test_images) # Normalize Data train_images = train_images / 255.0 test_images = test_images / 255.0 normalize_model = generate_model(train_data=train_images, test_data=test_images, train_label=train_labels, test_label=test_labels, epochs=5) predictions = normalize_model.predict(test_images) num_rows = 5 num_cols = 2 num_images = num_rows * num_cols plt.figure(figsize=(10 * num_cols, 4 * num_rows)) for image_index in range(num_images): plt.subplot(num_rows, 2 * num_cols, 2 * image_index + 1) plot_image(image_index, predictions, test_labels, test_images) plt.subplot(num_rows, 2 * num_cols, 2 * image_index + 2) plot_value_array(image_index, predictions, test_labels) plt.show() # Saving a model normalize_model.save('mnist_model.h5') save_model = load_model('mnist_model.h5') tests = save_model.predict(test_images) print(tests)
import numpy as np class SLHMM: h_cnt = None sym_cnt = None p1 = None p21 = None p31 = None b1 = None binf = None bx = None U = None V = None Sig = None def initMatrices(self): self.p1 = np.zeros(self.sym_cnt) self.p21 = np.zeros((self.sym_cnt, self.sym_cnt)) self.p31 = np.zeros((self.sym_cnt, self.sym_cnt, self.sym_cnt)) def __init__(self, h_cnt, sym_cnt): self.h_cnt = h_cnt self.sym_cnt = sym_cnt self.initMatrices() def normalizePs(self): self.p1 = self.p1 / np.sum(self.p1) self.p21 = self.p21 / np.sum(self.p21) self.p31 = self.p31 / np.sum(self.p31) def computePs(self, triples): for s in triples: self.p1[s[0]] = self.p1[s[0]] + 1 self.p21[s[1], s[0]] =self.p21[s[1], s[0]] + 1 self.p31[s[1], s[2], s[0]] = self.p31[s[1], s[2], s[0]] + 1 def computeBx(self, t): self.bx = np.zeros((self.sym_cnt, self.h_cnt, self.h_cnt)) for i in range(0,self.sym_cnt): tmp = np.dot(self.U.T, self.p31[i]) self.bx[i] = np.dot(tmp, t.T) def learn(self, sequences): triples = np.array([sequence[idx: idx+3] for sequence in sequences for idx in xrange(len(sequence)-2)]) self.computePs(triples) self.normalizePs() self.U, self.Sig, self.V = np.linalg.svd(self.p21) self.U = self.U[:, 0:self.h_cnt] self.V = self.V[0:self.h_cnt, :] temp = np.linalg.pinv(np.dot(self.p21.T, self.U)) self.b1 = np.dot(self.U.T, self.p1) self.binf = np.dot(temp, self.p1) self.computeBx(temp) # Overwrite the prediction algorithm using DP provided in base class def predict(self, sequence): prob = self.b1 for ob in sequence: prob = np.dot(self.bx[ob], prob) prob = np.dot(self.binf.T, prob) return prob def get_rankings(self,seq): probs = [] seq.append(0) for i in range(0,self.sym_cnt): seq[len(seq) - 1] = i probs.append(self.predict(seq)) r = np.argsort(probs)[::-1] r[r == self.sym_cnt - 1] = -1 return r
import sqlite3 def loadTables(regionFile, salesFile): regions = open(regionFile, "r") sales = open(salesFile, "r") conn = sqlite3.connect('Avocado.db') c = conn.cursor() # drop tables c.execute('DROP TABLE IF EXISTS region') c.execute('DROP TABLE IF EXISTS sales') # create new tables c.execute('''CREATE TABLE Region (pmkRegionID int NOT NULL, fldRegionName varchar(64), fldAvgPriceCon smallmoney, fldAvgPriceOrg smallmoney, pfkBestMonConID int, pfkBestMonOrgID int, PRIMARY KEY (pmkRegionID), FOREIGN KEY (pfkBestMonConID) REFERENCES Sales(pmkSalesID), FOREIGN KEY (pfkBestMonOrgID) REFERENCES Sales(pmkSalesID))''') c.execute('''CREATE TABLE Sales (pmkSalesID int NOT NULL, pfkRegionID int NOT NULL, fldAvgPrice smallmoney, fldTotalVolume int, fldMonth tinyint, fldType varchar(64), PRIMARY KEY (pmkSalesID), FOREIGN KEY (pfkRegionID) REFERENCES Region(pmkRegionID))''') # fill region table for line in regions: regionData = line.strip("\n") regionData = regionData.strip() regionData = regionData.split(",") #print(regionData) c.execute('INSERT INTO Region VALUES (?, ?, ?, ?, ?, ?)', regionData) # fill sales table for line in sales: saleData = line.strip("\n") saleData = saleData.split(",") c.execute('INSERT INTO Sales VALUES (?, ?, ?, ?, ?, ?)', saleData) # save changes conn.commit() # close connection and files conn.close() regions.close() sales.close() def regionToID(arg): switch = { "albany": 1, "atlanta": 2, "baltimore washington": 3, "boise": 4, "boston": 5, "buffalo rochester": 6, "california": 7, "charlotte": 8, "chicago": 9, "cincinnati dayton": 10, "columbus": 11, "dallas ft worth": 12, "denver": 13, "detroit": 14, "grand rapids": 15, "great lakes": 16, "harrisburg scranton": 17, "hartford springfield": 18, "houston": 19, "indianapolis": 20, "jacksonville": 21, "las vegas": 22, "los angeles": 23, "louisville": 24, "miami ft lauderdale": 25, "nashville": 26, "new orleans mobile": 27, "new york": 28, "northeast": 29, "northern new england": 30 } return switch.get(arg, "null") def getSalesData(queryList): conn = sqlite3.connect('Avocado.db') c = conn.cursor() if queryList[0] == "TotalVolume": c.execute( '''SELECT fldTotalVolume FROM Sales WHERE fldMonth == (?) AND fldType == (?) AND pfkRegionID == (?) ''', (queryList[2], queryList[3], regionToID(queryList[1]))) result = c.fetchall() print(result) elif queryList[0] == "AveragePrice": c.execute( '''SELECT fldAvgPrice FROM Sales WHERE fldMonth == (?) AND fldType == (?) AND pfkRegionID == (?) ''', (queryList[2], queryList[3], regionToID(queryList[1]))) result = c.fetchall() print(result) conn.close() def main(): loadTables("avocado-region-data.csv", "avocado-sales-data.csv") getSalesData(['TotalVolume', 'great lakes', 12, 'conventional']) getSalesData(['AveragePrice', 'cincinnati dayton', 1, 'organic']) getSalesData(['AveragePrice', 'albany', 1, 'organic']) getSalesData(['TotalVolume', 'miami ft lauderdale', 4, 'conventional']) main()
# Exercício 6.12 - Livro numeros = [2, 6, 8, 4, 1, 20, -26] menor = numeros[0] for num in numeros: if num < menor: menor = num print('=-=' * 10) print(f'Menor → {menor}')
# -*- coding: utf-8 -*- """ ytelapi This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). """ import jsonpickle import dateutil.parser from .controller_test_base import ControllerTestBase from ..test_helper import TestHelper from ytelapi.api_helper import APIHelper class EmailControllerTests(ControllerTestBase): @classmethod def setUpClass(cls): super(EmailControllerTests, cls).setUpClass() cls.controller = cls.api_client.email # Retrieve a list of emails that have been blocked. def test_test_blocked_emails(self): # Parameters for the API call offset = None limit = None # Perform the API call through the SDK function result = self.controller.create_blocked_emails(offset, limit) # Test response code self.assertEquals(self.response_catcher.response.status_code, 200) # Test headers expected_headers = {} expected_headers['content-type'] = 'application/json' self.assertTrue(TestHelper.match_headers(expected_headers, self.response_catcher.response.headers)) # Retrieve a list of invalid email addresses. def test_test_invalid_emails(self): # Parameters for the API call offset = None limit = None # Perform the API call through the SDK function result = self.controller.create_invalid_emails(offset, limit) # Test response code self.assertEquals(self.response_catcher.response.status_code, 200) # Test headers expected_headers = {} expected_headers['content-type'] = 'application/json' self.assertTrue(TestHelper.match_headers(expected_headers, self.response_catcher.response.headers)) # Retrieve a list of emails that have bounced. def test_test_bounced_emails(self): # Parameters for the API call offset = None limit = None # Perform the API call through the SDK function result = self.controller.create_bounced_emails(offset, limit) # Test response code self.assertEquals(self.response_catcher.response.status_code, 200) # Test headers expected_headers = {} expected_headers['content-type'] = 'application/json' self.assertTrue(TestHelper.match_headers(expected_headers, self.response_catcher.response.headers)) # Retrieve a list of emails that are on the spam list. def test_test_spam_emails(self): # Parameters for the API call offset = None limit = None # Perform the API call through the SDK function result = self.controller.create_spam_emails(offset, limit) # Test response code self.assertEquals(self.response_catcher.response.status_code, 200) # Test headers expected_headers = {} expected_headers['content-type'] = 'application/json' self.assertTrue(TestHelper.match_headers(expected_headers, self.response_catcher.response.headers)) # Retrieve a list of email addresses from the unsubscribe list. def test_test_list_unsubscribed_emails(self): # Parameters for the API call offset = None limit = None # Perform the API call through the SDK function result = self.controller.create_list_unsubscribed_emails(offset, limit) # Test response code self.assertEquals(self.response_catcher.response.status_code, 200) # Test headers expected_headers = {} expected_headers['content-type'] = 'application/json' self.assertTrue(TestHelper.match_headers(expected_headers, self.response_catcher.response.headers))
import time from _base.base_actions import BaseActions from _base.base_elements import BaseElements from _test_suites._variables.variables import Variables class BasePopup(BaseActions): def _set_popup(self, name): locator = "//span[text()='" + str(name) + "']" \ "[@dir='LTR'][contains(@style,'White')]/ancestor::div[contains(@id,'WRP')][last()]" # locator = "//span[text()='" + str(name) + "'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" return str(locator) def _set_popup_header(self, set_popup_method): locator = str(set_popup_method) + "/div[@class='Panel-Control']" cond = self._wait_for_element_present(locator) return str(locator) if cond else None def _set_popup_table_header(self, set_screen_method): #INPUT SCREEN METHOD FOR CURRENT SCREEN locator = str(set_screen_method) + BaseElements.TABLE_HEADER cond = self._wait_for_element_present(locator) return str(locator) if cond else None def _set_popup_table_body(self, set_screen_method): locator = str(set_screen_method) + BaseElements.TABLE_BODY cond = self._wait_for_element_present(locator) return str(locator) if cond else None class AdminAccountsPopup(BaseActions): BODY = "//span[text()='Admin Accounts'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" BUTTON_ADD_MEMBERS = BODY + "/*//span[text()='Add Members']/ancestor::div[contains(@class,'Button')]" LEFT_MENU = BODY + "/*//div[@class='TreeView-Control']" TAB = BODY + "/*//div[@class='TabControl-Control']" FIELD_GROUP_NAME = BODY + "/*//input[contains(@class,'TextBox-Input')][@type='text']" def check_popup_is_presented(self): cond = self._wait_for_element_present(AdminAccountsPopup.BODY) return True if cond else False def click_icon_help(self): self._click_icon_help(AdminAccountsPopup.BODY) def click_button_ok(self): self._click_button_ok(AdminAccountsPopup.BODY) self._wait_for_element_not_present(AdminAccountsPopup.BODY) def click_button_cancel(self): self._click_button_cancel(AdminAccountsPopup.BODY) self._wait_for_element_not_present(AdminAccountsPopup.BODY) def click_system_button_close(self): self._click_system_button_close(AdminAccountsPopup.BODY) def click_button_add_members(self): self._click_element(AdminAccountsPopup.BUTTON_ADD_MEMBERS) self._wait_for_element_present(SelectTargetsPopup.BODY) def enter_text_into_group_name_text_field(self, text = None): self._find_element(AdminAccountsPopup.FIELD_GROUP_NAME).send_keys(text) def click_button_add(self): self._click_button_add(AdminAccountsPopup.BODY) self._wait_for_element_present(UserConfigurationPopup.BODY) class AreYouSurePopup(BaseActions): # PAGE_BODY = "//span[text()='Are you sure?'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" ARE_YOU_SURE = "Are you sure?" def _set_popup(self, locator): body = "//span[text()='" + locator + "'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" return body def _get_popup(self): body = self._set_popup(self.ARE_YOU_SURE) # print "PopupBase: ", body return body def click_button_ok(self): self._click_button_ok(self._get_popup()) # self._click_button_ok(self.PAGE_BODY) def click_system_button_close(self): self._click_system_button_close(self._get_popup()) # self._click_system_button_close(self.PAGE_BODY) def click_button_cancel(self): self._click_button_cancel(self._get_popup()) # self._click_button_cancel(self.PAGE_BODY) def click_button_no(self): self._click_button_no(self._get_popup()) # self._click_button_no(self.PAGE_BODY) def click_button_yes(self): self._click_button_yes(self._get_popup()) # self._click_button_yes(self.PAGE_BODY) def check_popup_is_presented(self): cond = self._wait_for_element_present(self._get_popup()) # cond = self._wait_for_element_present(self.PAGE_BODY) return True if cond else False class ColumnSetDesignerPopup(BaseActions): #CONSTANTS BODY = "//span[text()='Column Set Designer'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" TABLE_HEADER = BODY + "/*//div[contains(@id,'HEADER')]" TABLE_BODY = BODY + "/*//div[contains(@id,'VWGLVBODY')]" BUTTON_ADD = BODY + "/*//span[text()='Add >>']/ancestor::div[contains(@class,'Button')]" BUTTON_REMOVE = BODY + "/*//span[text()='<< Remove']/ancestor::div[contains(@class,'Button')]" BUTTON_ARROW_UP = BODY + BaseElements.BUTTON_ARROW_UP BUTTON_ARROW_DOWN = BODY + BaseElements.BUTTON_ARROW_DOWN TEXT_FIELD_NAME = BODY + "/*//div[2]/input" TEXT_FIELD_DESCRIPTION = BODY + "/*//div[1]/input" LEFT_SIDE_TREE = BODY + "/*//div[contains(@class,'PaddingContainer')]" LEFT_SIDE_SUBNODE = LEFT_SIDE_TREE + "/*//div[contains(@class,'SubNodesContainer')]" LEFT_SIDE_NODE = LEFT_SIDE_TREE + "/*//div[contains(@class,'RowContainer')]" TABLE_HEADER_COLUMNS = TABLE_HEADER + "/*//span[contains(text(),'Columns')]" TABLE_HEADER_DEFAULT_WIDTH = TABLE_HEADER + "/*//span[contains(text(),'Default Width')]" TABLE_HEADER_AGGREGATE = TABLE_HEADER + "/*//span[contains(text(),'Aggregate')]" TABLE_ROW = "/ancestor::tr[contains(@class,'ListView-DataFullRow')]" ELEMENT_LABEL = "/ancestor::div[contains(@class,'RowContainer')]" def check_popup_is_presented(self): cond = self._wait_for_element_present(ColumnSetDesignerPopup.BODY) return True if cond else False def click_button_ok(self): self._click_button_ok(ColumnSetDesignerPopup.BODY) def click_button_cancel(self): self._click_button_cancel(ColumnSetDesignerPopup.BODY) def click_button_add(self, columnname): self._click_element(ColumnSetDesignerPopup.BUTTON_ADD) self._wait_for_element_present(ColumnSetDesignerPopup.TABLE_BODY + "/*//span[contains(text(),'" + columnname + "')]") def click_icon_help(self): self._click_icon_help(ColumnSetDesignerPopup.BODY) def click_system_button_close(self): self._click_system_button_close(ColumnSetDesignerPopup.BODY) def click_system_button_maximize(self): self._click_system_button_maximize(ColumnSetDesignerPopup.BODY) def enter_text_into_text_field_name(self, columnsetname): self._find_element(ColumnSetDesignerPopup.TEXT_FIELD_NAME).send_keys(columnsetname) def enter_text_into_text_field_description(self, text): self._find_element(ColumnSetDesignerPopup.TEXT_FIELD_DESCRIPTION).send_keys(text) def click_column_in_left_side_list(self, columnname): elem = ColumnSetDesignerPopup.LEFT_SIDE_SUBNODE + "/*//span[text()='" + columnname + "']" self._click_element(elem) self._wait_for_element_selected(elem + ColumnSetDesignerPopup.ELEMENT_LABEL) def expand_all_left_side_lists(self): self._expand_all_lists(ColumnSetDesignerPopup.LEFT_SIDE_NODE) # self._wait_for_element_present(ColumnSetDesignerPopup.PAGE_BODY) # elements = self._find_elements(ColumnSetDesignerPopup.LEFT_SIDE_TREE + "/div/div/div[contains(@id,'VWGJOINT')]") # elements = self._find_elements(ColumnSetDesignerPopup.LEFT_SIDE_TREE + BaseElements.ARROW_EXPAND) # for element in elements: # self.driver.execute_script("arguments[0].click();", element) def collaps_all_left_side_lists(self): self._collaps_all_lists(ColumnSetDesignerPopup.LEFT_SIDE_NODE) def add_columns_to_list_view(self, columns_list): for columnname in list(columns_list): self.scroll_to_element(ColumnSetDesignerPopup.BODY + "/*//span[contains(text(),'" + columnname + "')]") self.click_column_in_left_side_list(columnname) self.click_button_add(columnname) def check_is_columnname_in_list_view(self, columnname): cond = self._wait_for_element_present(ColumnSetDesignerPopup.TABLE_BODY + "/*//span[contains(text(),'" + columnname + "')]") return True if cond else False def create_columnset(self, columnsetname=None, columns_list=None): self.click_system_button_maximize() self.enter_text_into_text_field_name(columnsetname) self.expand_all_left_side_lists() self.add_columns_to_list_view(columns_list) self.click_button_ok() class ColumnSetsPopup(BaseActions): BODY = "//span[contains(text(),'Column Sets')][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" BUTTON_NEW = BODY + "/*//img[@alt='New']/ancestor::div[contains(@class,'RibbonBarButton')]" BUTTON_EDIT = BODY + "/*//img[@alt='Edit']/ancestor::div[contains(@class,'RibbonBarButton')]" BUTTON_COPY = BODY + "/*//img[@alt='Copy']/ancestor::div[contains(@class,'RibbonBarButton')]" BUTTON_DELETE = BODY + "/*//img[@alt='Delete']/ancestor::div[contains(@class,'RibbonBarButton')]" BUTTON_SET_AS_DEFAULT = BODY + "/*//img[@alt='Set As Default']/ancestor::div[contains(@class,'RibbonBarButton')]" TABLE_HEADER_IS_DEFAULT = BODY + "/*//div[contains(@id,'HEADER')]/*//span[contains(text(),'Is Default')]" TABLE_HEADER_NAME = BODY + "/*//div[contains(@id,'HEADER')]/*//span[contains(text(),'Name')]" TABLE_HEADER_DESCRIPTION = BODY + "/*//div[contains(@id,'HEADER')]/*//span[contains(text(),'Description:')]" TABLE_HEADER_COLUMNS = BODY + "/*//div[contains(@id,'HEADER')]/*//span[contains(text(),'Columns')]" TABLE_BODY = BODY + "/*//div[contains(@id,'VWGLVBODY')]" TABLE_ROW = "/ancestor::tr[contains(@class,'ListView-DataFullRow')]" def click_button_ok(self): self._click_button_ok(ColumnSetsPopup.BODY) # self._click_element(self.PAGE_BODY + "/*" + Locators.BUTTON_OK) # self._wait_for_element_not_present(self.PAGE_BODY) def click_icon_help(self): self._click_icon_help(ColumnSetsPopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Column Sets") return True if cond else False def click_button_cancel(self): self._click_button_cancel(ColumnSetsPopup.BODY) def click_button_new(self): self._click_element(ColumnSetsPopup.BUTTON_NEW) self._wait_for_element_present(ColumnSetDesignerPopup.BODY) def click_popup_button_edit(self): self._click_element(ColumnSetsPopup.BUTTON_EDIT) self._wait_for_element_present(ColumnSetDesignerPopup.BODY) def click_popup_button_copy(self): self._click_element(ColumnSetsPopup.BUTTON_COPY) # self._wait_for_element_present(ColumnSetsPopup.TABLE_BODY + "/*//span[text()='Copy of " + columnsetname + "']") def click_button_delete(self): self._click_element(ColumnSetsPopup.BUTTON_DELETE) # self._wait_for_element_present(AreYouSurePopup.PAGE_BODY) def click_popup_button_set_as_default(self): self._click_element(ColumnSetsPopup.BUTTON_SET_AS_DEFAULT) def click_system_button_close(self): self._click_system_button_close(ColumnSetsPopup.BODY) def click_popup_help_icon(self): self._click_icon_help(ColumnSetsPopup.BODY) def click_popup_table_header_is_default(self): self._click_element(ColumnSetsPopup.TABLE_HEADER_IS_DEFAULT) def click_popup_table_header_name(self): self._click_element(ColumnSetsPopup.TABLE_HEADER_NAME) def click_popup_table_header_description(self): self._click_element(ColumnSetsPopup.TABLE_HEADER_DESCRIPTION) def click_popup_table_header_columns(self): self._click_element(ColumnSetsPopup.TABLE_HEADER_COLUMNS) def click_columnset_in_table_list(self, columnsetname): element = ColumnSetsPopup.TABLE_BODY + "/*//span[text()='" + columnsetname + "']" + ColumnSetsPopup.TABLE_ROW self._click_element(element) self._wait_for_element_selected(element) def check_is_columnset_present(self, columsetname): cond = self._wait_for_element_present(ColumnSetsPopup.TABLE_BODY + "/*//span[text()='" + columsetname + "']") return True if cond else False def check_popup_is_presented(self): cond = self._wait_for_element_present(ColumnSetsPopup.BODY) return True if cond else False def delete_columnset_if_exists(self, columnsetname): elem = ColumnSetsPopup.TABLE_BODY + "/*//span[text()='" + columnsetname + "']" cond = self._is_element_present(elem) if cond: ColumnSetsPopup.click_columnset_in_table_list(self, columnsetname) ColumnSetsPopup.click_button_delete(self) are_you_sure_popup = AreYouSurePopup(self.driver) are_you_sure_popup.click_button_yes() self._wait_for_element_not_present(elem) else: pass class ConditionEditorPopup(BaseActions): BODY = "//span[text()='Condition Editor'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" LEFT_MENU = BODY + "/*//div[@class='TreeView-Control']" TAB = BODY + "/*//div[@class='TabControl-Control']" def check_popup_is_presented(self): cond = self._wait_for_element_present(ConditionEditorPopup.BODY) return True if cond else False def click_icon_help(self): self._click_icon_help(ConditionEditorPopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Create a Query") return True if cond else False def click_button_ok(self): self._click_button_ok(ConditionEditorPopup.BODY) self._wait_for_element_not_present(ConditionEditorPopup.BODY) def click_button_cancel(self): self._click_button_cancel(ConditionEditorPopup.BODY) self._wait_for_element_not_present(ConditionEditorPopup.BODY) def click_system_button_close(self): self._click_system_button_close(ConditionEditorPopup.BODY) class ConnectingPopup(BaseActions): CONNECTING = "//span[text()='Connecting....'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" PING = "//span[text()='Ping....'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" def _check_popup_is_presented(self, name): global BODY NAME = "//span[text()='" + str(name) + "'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" PARTIAL_NAME = "//span[contains(text(),'" + name + "')][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" full_name = self._is_element_present(NAME) partial_name = self._is_element_present(PARTIAL_NAME) if full_name: BODY = NAME elif partial_name: BODY = PARTIAL_NAME cond = self._wait_for_element_present(BODY) return str(BODY) if cond else None def check_popup_is_presented(self): cond = self._check_popup_is_presented("Connecting") return True if cond is not None else False def _get_popup(self): name = self._check_popup_is_presented("Connecting") return str(name) if name is not None else None def click_button_close(self): self._click_button_close(self._get_popup()) self._wait_for_element_not_present(self._get_popup()) class CurrencyPopup(BaseActions): BODY = "//span[text()='Currency'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" LEFT_MENU = BODY + "/*//div[@class='TreeView-Control']" TAB = BODY + "/*//div[@class='TabControl-Control']" def check_popup_is_presented(self): cond = self._wait_for_element_present(CurrencyPopup.BODY) return True if cond else False def click_icon_help(self): self._click_icon_help(CurrencyPopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Currency") return True if cond else False def click_button_ok(self): self._click_button_ok(CurrencyPopup.BODY) self._wait_for_element_not_present(CurrencyPopup.BODY) def click_button_cancel(self): self._click_button_cancel(CurrencyPopup.BODY) self._wait_for_element_not_present(CurrencyPopup.BODY) def click_system_button_close(self): self._click_system_button_close(CurrencyPopup.BODY) class DiscoverDevicesPopup(BasePopup): DISCOVER_DEVICES = "Discover Devices" def popup_body(self): locator = self._set_popup(self.DISCOVER_DEVICES) return str(locator) def check_popup_is_presented(self): cond = self._wait_for_element_present(self.popup_body()) msg_true = "Popup '" + self.DISCOVER_DEVICES + "' is presented" msg_false = "Popup '" + self.DISCOVER_DEVICES + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) def enter_text_into_task_name_field(self, text): self._find_element(self.popup_body() + BaseElements.FIELD).send_keys(text) def clear_text_name_text_field(self): self._find_element(self.popup_body() + BaseElements.FIELD).clear() def select_site_in_list(self, name=Variables.help_test): element = self.popup_body() + "/*//span[text()='" + name + "']/ancestor::tr/*//img[contains(@src,'CheckBox')]" cond = self._is_element_present(element + "[contains(@src,'CheckBox1')]") if cond is not True: self._click_element(element) def click_button_select_none(self): self._click_button_select_none(self.popup_body()) def click_button_next(self): self._click_button_next(self.popup_body()) def click_button_finish(self): self._click_button_finish(self.popup_body()) def check_none_patches_selected(self): element = self.popup_body() + "/*//span[text()='None']/ancestor::tr/td[contains(@style,'Radio1')]" cond = self._wait_for_element_present(element) return True if cond else False def check_start_now_selected(self): element = self.popup_body() + "/*//span[text()='Start Now']/ancestor::tr/td[contains(@style,'Radio1')]" cond = self._wait_for_element_present(element) return True if cond else False class SoftwareDeploymentPopup(BasePopup): SOFTWARE_DEPLOYMENT = "Software Deployment" def popup_body(self): locator = self._set_popup(self.SOFTWARE_DEPLOYMENT) return str(locator) def check_popup_is_presented(self): cond = self._wait_for_element_present(self.popup_body()) msg_true = "Popup '" + self.SOFTWARE_DEPLOYMENT + "' is presented" msg_false = "Popup '" + self.SOFTWARE_DEPLOYMENT + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) class PatchManagerScanningPopup(BasePopup): PATCH_MANAGER_SCANNING = "Patch Manager Scanning" def popup_body(self): locator = self._set_popup(self.PATCH_MANAGER_SCANNING) return str(locator) def check_popup_is_presented(self): cond = self._wait_for_element_present(self.popup_body()) msg_true = "Popup '" + self.PATCH_MANAGER_SCANNING + "' is presented" msg_false = "Popup '" + self.PATCH_MANAGER_SCANNING + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) def click_radio_button_specific_devices(self): self._click_element(self.popup_body() + "/*//span[contains(text(),'Specific devices')]/ancestor::tr/td[1]") def click_radio_button_all_devices(self): self._click_element(self.popup_body() + "/*//span[contains(text(),'All')]/ancestor::tr/td[1]") def click_radio_button_all(self): self._click_element(self.popup_body() + "/*//span[text()='All']/ancestor::tr/td[1]") def click_radio_button_start_now(self): self._click_element(self.popup_body() + "/*//span[text()='Start Now']/ancestor::tr/td[1]") def open_select_targets_popup(self): element = self.popup_body() + "/*//span[contains(text(),'Specific devices')]/ancestor::tr/td[1]" cond = self._is_element_present(element + self.RB_CHECKED) if cond: self.click_button_add() else: self.click_radio_button_specific_devices() def click_button_add(self): self._click_button_add(self.popup_body()) def select_radio_button_all(self): element = self.popup_body() + "/*//span[text()='All']/ancestor::tr/td[1]" cond = self._is_element_present(element + self.RB_CHECKED) if cond is not True: self.click_radio_button_all() def check_radio_button_all_is_selected(self): element = self.popup_body() + "/*//span[text()='All']/ancestor::tr/td[1]" cond = self._wait_for_element_present(element + self.RB_CHECKED) return True if cond else False def click_button_next(self): self._click_button_next(self.popup_body()) def select_radio_button_start_now(self): element = self.popup_body() + "/*//span[text()='Start Now']/ancestor::tr/td[1]" cond = self._is_element_present(element + self.RB_CHECKED) if cond is not True: self.click_radio_button_start_now() def check_radio_button_start_now_is_selected(self): element = self.popup_body() + "/*//span[text()='Start Now']/ancestor::tr/td[1]" cond = self._wait_for_element_present(element + self.RB_CHECKED) return True if cond else False def clear_text_name_text_field(self): self._find_element(self.popup_body() + BaseElements.FIELD).clear() def enter_text_into_task_name_field(self, text): self._find_element(self.popup_body() + BaseElements.FIELD).send_keys(text) def click_button_finish(self): self._click_button_finish(self.popup_body()) class DeploySoftwareUpdatesPopup(BasePopup): DEPLOY_SOFTWARE_UPDATES = "Deploy Software Updates" def popup_body(self): locator = self._set_popup(self.DEPLOY_SOFTWARE_UPDATES) return str(locator) def check_popup_is_presented(self): cond = self._wait_for_element_present(self.popup_body()) msg_true = "Popup '" + self.DEPLOY_SOFTWARE_UPDATES + "' is presented" msg_false = "Popup '" + self.DEPLOY_SOFTWARE_UPDATES + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) class ScannedAddressesPopup(BasePopup): SCANNED_ADDRESSES = "Scanned Addresses" def popup_body(self): locator = self._set_popup(self.SCANNED_ADDRESSES) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self.popup_body() msg_true = "Popup '" + self.SCANNED_ADDRESSES + "' is presented" msg_false = "Popup '" + self.SCANNED_ADDRESSES + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_close(self): self._click_button_close(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) class DiscoverdDevicesPopup(BasePopup): DISCOVERED_DEVICES = "Discovered Devices" def popup_body(self): locator = self._set_popup(self.DISCOVERED_DEVICES) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self.popup_body() msg_true = "Popup '" + self.DISCOVERED_DEVICES + "' is presented" msg_false = "Popup '" + self.DISCOVERED_DEVICES + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_close(self): self._click_button_close(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) class UnknownDevicesPopup(BasePopup): UNKNOWN_DEVICES = "Unknown Devices" def popup_body(self): locator = self._set_popup(self.UNKNOWN_DEVICES) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self.popup_body() msg_true = "Popup '" + self.UNKNOWN_DEVICES + "' is presented" msg_false = "Popup '" + self.UNKNOWN_DEVICES + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_close(self): self._click_button_close(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) class SuccessfulDevicesPopup(BasePopup): SUCCESSFUL_DEVICES = "Successful Devices" def popup_body(self): locator = self._set_popup(self.SUCCESSFUL_DEVICES) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self.popup_body() msg_true = "Popup '" + self.SUCCESSFUL_DEVICES + "' is presented" msg_false = "Popup '" + self.SUCCESSFUL_DEVICES + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_close(self): self._click_button_close(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) class DevicesInProgressPopup(BasePopup): DEVICES_IN_PROGRESS = "Devices In Progress" def popup_body(self): locator = self._set_popup(self.DEVICES_IN_PROGRESS) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self.popup_body() msg_true = "Popup '" + self.DEVICES_IN_PROGRESS + "' is presented" msg_false = "Popup '" + self.DEVICES_IN_PROGRESS + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_close(self): self._click_button_close(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) class FailedDevicesPopup(BasePopup): FAILED_DEVICES = "Failed Devices" def popup_body(self): locator = self._set_popup(self.FAILED_DEVICES) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self.popup_body() msg_true = "Popup '" + self.FAILED_DEVICES + "' is presented" msg_false = "Popup '" + self.FAILED_DEVICES + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_close(self): self._click_button_close(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) class DevicesWithPartialSuccessPopup(BasePopup): DEVICES_WITH_PARTIAL_SUCCESS = "Devices with Partial Success" def popup_body(self): locator = self._set_popup(self.DEVICES_WITH_PARTIAL_SUCCESS) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self.popup_body() msg_true = "Popup '" + self.DEVICES_WITH_PARTIAL_SUCCESS + "' is presented" msg_false = "Popup '" + self.DEVICES_WITH_PARTIAL_SUCCESS + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_close(self): self._click_button_close(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) class EditFolderPopup(BaseActions): BODY = "//span[text()='Edit Folder'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" FIELD_EDIT_FOLDER = BODY + "/*//input" def check_popup_is_presented(self): cond = self._wait_for_element_present(EditFolderPopup.BODY) return True if cond else False def click_icon_help(self): self._click_icon_help(EditFolderPopup.BODY) def click_button_ok(self): self._click_button_ok(EditFolderPopup.BODY) self._wait_for_element_not_present(EditFolderPopup.BODY) def click_button_cancel(self): self._click_button_cancel(EditFolderPopup.BODY) self._wait_for_element_not_present(EditFolderPopup.BODY) def click_system_button_close(self): self._click_system_button_close(EditFolderPopup.BODY) def enter_text_into_edit_folder_text_field(self, name): self._find_element(EditFolderPopup.FIELD_EDIT_FOLDER).send_keys(name) class EndUserAccessPopup(BasePopup): END_USER_ACCESS = "End User Access" def popup_body(self): locator = self._set_popup(self.END_USER_ACCESS) return str(locator) def check_popup_is_presented(self): cond = self._wait_for_element_present(self.popup_body()) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_close(self): self._click_button_close(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) def get_end_user_access_link(self): link = self._get_text(self.popup_body() + "/*//input[@readonly]") print link return str(link) class ErrorPopup(BaseActions): ERROR = "Error" BODY = "//span[text()='Error']/ancestor::div[contains(@id,'WRP')]" def check_popup_is_presented(self): cond = self._wait_for_element_present(ErrorPopup.BODY) msg_true = "Popup '" + self.ERROR + "' is presented" msg_false = "Popup '" + self.ERROR + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def check_popup_is_not_presented(self): cond = self._is_element_present(ErrorPopup.BODY) msg_false = "Popup '" + self.ERROR + "' is presented" msg_true = "Popup '" + self.ERROR + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond is not True else False def click_system_button_close(self): self._click_system_button_close(ErrorPopup.BODY) def click_button_ok(self): self._click_button_ok(ErrorPopup.BODY) class EventViewerPopup(BaseActions): BODY = "//span[text()='Event Viewer'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" TABLE_HEADER = BODY + "/*//div[contains(@id,'HEADER')]" TABLE_BODY = BODY + "/*//div[contains(@id,'VWGLVBODY')]" LEFT_SIDE_TREE = BODY + "/*//div[contains(@class,'PaddingContainer')]" LEFT_SIDE_SUBNODE = LEFT_SIDE_TREE + "/*//div[contains(@class,'SubNodesContainer')]" LEFT_SIDE_NODE = LEFT_SIDE_TREE + "/*//div[contains(@class,'RowContainer')]" TABLE_HEADER_NAME = TABLE_HEADER + "/*//span[contains(text(),'Name')]" TABLE_HEADER_TYPE = TABLE_HEADER + "/*//span[contains(text(),'Type')]" TABLE_HEADER_SIZE = TABLE_HEADER + "/*//span[contains(text(),'Size')]" TABLE_ROW = TABLE_BODY + "/*//tr" ELEMENT_LABEL = "/ancestor::div[contains(@class,'RowContainer')]" def check_popup_is_presented(self): cond = self._wait_for_element_present(EventViewerPopup.BODY) return True if cond else False def click_icon_help(self): self._click_icon_help(EventViewerPopup.BODY) def click_button_ok(self): self._click_button_ok(EventViewerPopup.BODY) self._wait_for_element_not_present(EventViewerPopup.BODY) def click_button_cancel(self): self._click_button_cancel(EventViewerPopup.BODY) self._wait_for_element_not_present(EventViewerPopup.BODY) def click_system_button_close(self): self._click_system_button_close(EventViewerPopup.BODY) def click_label_in_left_side_list(self, label): elem = EventViewerPopup.LEFT_SIDE_SUBNODE + \ "/*//span[text()='" + label + "']/ancestor::div[contains(@class,'RowContainer')]" self._click_label(elem) def expand_all_left_side_lists(self): self._expand_all_lists(EventViewerPopup.LEFT_SIDE_TREE) def check_text_is_in_list_view(self, text): cond = self._wait_for_element_present(EventViewerPopup.TABLE_BODY + "/*//span[contains(text(),'" + text + "')]") return True if cond else False def select_device_in_table(self, name): self._wait_for_element_present(EventViewerPopup.TABLE_ROW) row = EventViewerPopup.TABLE_ROW + "/*//span[text()='" + name + "']/ancestor::tr" self._click_element(row) self._wait_for_element_selected(row) class ExcludeDevicePopup(BaseActions): EXCLUDE_DEVICE = "Exclude Device" BODY = "//span[text()='Exclude Device'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" FIELD_NAME = BODY + "/*//input" def check_popup_is_presented(self): cond = self._wait_for_element_present(ExcludeDevicePopup.BODY) msg_true = "Popup '" + self.EXCLUDE_DEVICE + "' is presented" msg_false = "Popup '" + self.EXCLUDE_DEVICE + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def enter_text_into_name_text_field(self, sitename): self._find_element(ExcludeDevicePopup.FIELD_NAME).send_keys(sitename) def click_button_ok(self): self._click_button_ok(ExcludeDevicePopup.BODY) def click_button_cancel(self): self._click_button_cancel(ExcludeDevicePopup.BODY) def click_system_button_close(self): self._click_system_button_close(ExcludeDevicePopup.BODY) def click_icon_help(self): self._click_icon_help(ExcludeDevicePopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Exclude Device") return True if cond else False class ExcludeIPAddressPopup(BaseActions): BODY = "//span[text()='Exclude IP Address'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" FIELD_NAME = BODY + "/*//input" def check_popup_is_presented(self): cond = self._wait_for_element_present(ExcludeIPAddressPopup.BODY) return True if cond else False def enter_text_into_name_text_field(self, sitename): self._find_element(ExcludeIPAddressPopup.FIELD_NAME).send_keys(sitename) def click_button_ok(self): self._click_button_ok(ExcludeIPAddressPopup.BODY) def click_button_cancel(self): self._click_button_cancel(ExcludeIPAddressPopup.BODY) def click_system_button_close(self): self._click_system_button_close(ExcludeIPAddressPopup.BODY) def click_icon_help(self): self._click_icon_help(ExcludeIPAddressPopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Exclude IP Address") return True if cond else False class ExcludeSitePopup(BaseActions): BODY = "//span[text()='Exclude Site'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" FIELD_NAME = BODY + "/*//input" def check_popup_is_presented(self): cond = self._wait_for_element_present(ExcludeSitePopup.BODY) return True if cond else False def enter_text_into_name_text_field(self, sitename): self._find_element(ExcludeSitePopup.FIELD_NAME).send_keys(sitename) def click_button_ok(self): self._click_button_ok(ExcludeSitePopup.BODY) def click_button_cancel(self): self._click_button_cancel(ExcludeSitePopup.BODY) def click_system_button_close(self): self._click_system_button_close(ExcludeSitePopup.BODY) def click_icon_help(self): self._click_icon_help(ExcludeSitePopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Exclude Site") return True if cond else False class FileExplorerPopup(BaseActions): BODY = "//span[text()='File Explorer'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" LEFT_MENU = BODY + "/*//div[@class='TreeView-Control']" TAB = BODY + "/*//div[@class='TabControl-Control']" def check_popup_is_presented(self): cond = self._wait_for_element_present(FileExplorerPopup.BODY) return True if cond else False def click_icon_help(self): self._click_icon_help(FileExplorerPopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("File Explorer") return True if cond else False def click_system_button_close(self): self._click_system_button_close(FileExplorerPopup.BODY) class InitialSetupPopup(BaseActions): BODY = "//span[text()='Welcome To Cloud Management Suite'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" LEFT_MENU = BODY + "/*//div[@class='TreeView-Control']" TAB = BODY + "/*//div[@class='TabControl-Control']" def check_popup_is_presented(self): cond = self._wait_for_element_present(InitialSetupPopup.BODY) return True if cond else False def click_icon_help(self): self._click_icon_help(InitialSetupPopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Initial Setup") return True if cond else False def click_system_button_close(self): self._click_system_button_close(InitialSetupPopup.BODY) class InventoryViewPopup(BaseActions): #CONSTANTS BODY = "//div[contains(@id,'WRP')][last()]" TABLE_HEADER = BODY + "/*//div[contains(@id,'HEADER')]" TABLE_BODY = BODY + "/*//div[contains(@id,'VWGLVBODY')]" LEFT_SIDE_TREE = BODY + "/*//div[contains(@class,'PaddingContainer')]" LEFT_SIDE_SUBNODE = LEFT_SIDE_TREE + "/*//div[contains(@class,'SubNodesContainer')]" LEFT_SIDE_NODE = LEFT_SIDE_TREE + "/*//div[contains(@class,'RowContainer')]" TABLE_HEADER_COLUMNS = TABLE_HEADER + "/*//span[contains(text(),'Columns')]" TABLE_HEADER_DEFAULT_WIDTH = TABLE_HEADER + "/*//span[contains(text(),'Default Width')]" TABLE_HEADER_AGGREGATE = TABLE_HEADER + "/*//span[contains(text(),'Aggregate')]" TABLE_ROW = "/ancestor::tr[contains(@class,'ListView-DataFullRow')]" ELEMENT_LABEL = "/ancestor::div[contains(@class,'RowContainer')]" def check_popup_is_presented(self, name): element = "//span[text()='" + name + "'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" cond = self._wait_for_element_present(element) # cond = self._wait_for_element_present(InventoryViewPopup.PAGE_BODY) return True if cond else False def click_button_ok(self): self._click_button_ok(InventoryViewPopup.BODY) def click_button_close(self): self._click_button_close(InventoryViewPopup.BODY) def click_system_button_close(self): self._click_system_button_close(InventoryViewPopup.BODY) def click_icon_help(self): self._click_icon_help(InventoryViewPopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Inventory") return True if cond else False def click_label_in_left_side_list(self, label): elem = InventoryViewPopup.LEFT_SIDE_SUBNODE + "/*//span[text()='" + label + "']/ancestor::div[contains(@class,'RowContainer')]" self._click_label(elem) def expand_all_left_side_lists(self): self._expand_all_lists(InventoryViewPopup.LEFT_SIDE_TREE) def check_text_is_in_list_view(self, text): cond = self._wait_for_element_present(InventoryViewPopup.TABLE_BODY + "/*//span[contains(text(),'" + text + "')]") return True if cond else False class IPAddressPopup(BaseActions): BODY = "//span[text()='IP Address'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" FIELD_START = BODY + "/*//div[4]/input" FIELD_END = BODY + "/*//div[1]/input" def check_popup_is_presented(self): cond = self._wait_for_element_present(IPAddressPopup.BODY) return True if cond else False def click_icon_help(self): self._click_icon_help(IPAddressPopup.BODY) def click_button_ok(self): self._click_button_ok(IPAddressPopup.BODY) self._wait_for_element_not_present(IPAddressPopup.BODY) def click_button_cancel(self): self._click_button_cancel(IPAddressPopup.BODY) self._wait_for_element_not_present(IPAddressPopup.BODY) def click_system_button_close(self): self._click_system_button_close(IPAddressPopup.BODY) def enter_start_ip_address(self, ipaddress = "0.0.0.0"): self._find_element(IPAddressPopup.FIELD_START).send_keys(ipaddress) def enter_end_ip_address(self, ipaddress = "1.1.1.1"): self._find_element(IPAddressPopup.FIELD_END).send_keys(ipaddress) class MaintenanceWindowPopup(BaseActions): BODY = "//span[text()='Maintenance Window'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" TABLE_HEADER = BODY + "/*//div[contains(@id,'HEADER')]" TABLE_BODY = BODY + "/*//div[contains(@id,'VWGLVBODY')]" LEFT_SIDE_TREE = BODY + "/*//div[contains(@class,'PaddingContainer')]" LEFT_SIDE_SUBNODE = LEFT_SIDE_TREE + "/*//div[contains(@class,'SubNodesContainer')]" LEFT_SIDE_NODE = LEFT_SIDE_TREE + "/*//div[contains(@class,'RowContainer')]" TABLE_HEADER_COLUMNS = TABLE_HEADER + "/*//span[contains(text(),'Columns')]" TABLE_HEADER_DEFAULT_WIDTH = TABLE_HEADER + "/*//span[contains(text(),'Default Width')]" TABLE_HEADER_AGGREGATE = TABLE_HEADER + "/*//span[contains(text(),'Aggregate')]" TABLE_ROW = TABLE_BODY + "/*//tr" ELEMENT_LABEL = "/ancestor::div[contains(@class,'RowContainer')]" def popup_body(self): pass def check_popup_is_presented(self): cond = self._wait_for_element_present(MaintenanceWindowPopup.BODY) return True if cond else False def click_icon_help(self): self._click_icon_help(MaintenanceWindowPopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Move a site or device") return True if cond else False def click_button_ok(self): self._click_button_ok(MaintenanceWindowPopup.BODY) self._wait_for_element_not_present(MaintenanceWindowPopup.BODY) def click_button_cancel(self): self._click_button_cancel(MaintenanceWindowPopup.BODY) self._wait_for_element_not_present(MaintenanceWindowPopup.BODY) def click_system_button_close(self): self._click_system_button_close(MaintenanceWindowPopup.BODY) class ManufacturerAliasPopup(BaseActions): BODY = "//span[text()='Manufacturer Alias'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" LEFT_MENU = BODY + "/*//div[@class='TreeView-Control']" TAB = BODY + "/*//div[@class='TabControl-Control']" def check_popup_is_presented(self): cond = self._wait_for_element_present(ManufacturerAliasPopup.BODY) return True if cond else False def click_icon_help(self): self._click_icon_help(ManufacturerAliasPopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Manufacturers") return True if cond else False def click_button_close(self): self._click_button_close(ManufacturerAliasPopup.BODY) self._wait_for_element_not_present(ManufacturerAliasPopup.BODY) def click_system_button_close(self): self._click_system_button_close(ManufacturerAliasPopup.BODY) class ModelAliasPopup(BaseActions): BODY = "//span[text()='Model Alias'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" LEFT_MENU = BODY + "/*//div[@class='TreeView-Control']" TAB = BODY + "/*//div[@class='TabControl-Control']" def check_popup_is_presented(self): cond = self._wait_for_element_present(ModelAliasPopup.BODY) return True if cond else False def click_icon_help(self): self._click_icon_help(ModelAliasPopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Models") return True if cond else False def click_button_close(self): self._click_button_close(ModelAliasPopup.BODY) self._wait_for_element_not_present(ModelAliasPopup.BODY) def click_system_button_close(self): self._click_system_button_close(ModelAliasPopup.BODY) class MoveDevicePopup(BaseActions): BODY = "//span[text()='Move Device'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" TABLE_HEADER = BODY + "/*//div[contains(@id,'HEADER')]" TABLE_BODY = BODY + "/*//div[contains(@id,'VWGLVBODY')]" LEFT_SIDE_TREE = BODY + "/*//div[contains(@class,'PaddingContainer')]" LEFT_SIDE_SUBNODE = LEFT_SIDE_TREE + "/*//div[contains(@class,'SubNodesContainer')]" LEFT_SIDE_NODE = LEFT_SIDE_TREE + "/*//div[contains(@class,'RowContainer')]" TABLE_HEADER_COLUMNS = TABLE_HEADER + "/*//span[contains(text(),'Columns')]" TABLE_HEADER_DEFAULT_WIDTH = TABLE_HEADER + "/*//span[contains(text(),'Default Width')]" TABLE_HEADER_AGGREGATE = TABLE_HEADER + "/*//span[contains(text(),'Aggregate')]" TABLE_ROW = TABLE_BODY + "/*//tr" ELEMENT_LABEL = "/ancestor::div[contains(@class,'RowContainer')]" def check_popup_is_presented(self): cond = self._wait_for_element_present(MoveDevicePopup.BODY) return True if cond else False def click_icon_help(self): self._click_icon_help(MoveDevicePopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Move a site or device") return True if cond else False def click_button_ok(self): self._click_button_ok(MoveDevicePopup.BODY) self._wait_for_element_not_present(MoveDevicePopup.BODY) def click_button_cancel(self): self._click_button_cancel(MoveDevicePopup.BODY) self._wait_for_element_not_present(MoveDevicePopup.BODY) def click_system_button_close(self): self._click_system_button_close(MoveDevicePopup.BODY) def click_label_in_left_side_list(self, label): elem = MoveDevicePopup.LEFT_SIDE_SUBNODE + "/*//span[text()='" + label + "']/ancestor::div[contains(@class,'RowContainer')]" self._click_label(elem) def expand_all_left_side_lists(self): self._expand_all_lists(MoveDevicePopup.LEFT_SIDE_TREE) # self._wait_for_element_present(MoveDevicePopup.PAGE_BODY) # elements = self._find_elements(MoveDevicePopup.LEFT_SIDE_TREE + "/div/div/div[contains(@id,'VWGJOINT')]") # for element in elements: # self.driver.execute_script("arguments[0].click();", element) def check_text_is_in_list_view(self, text): cond = self._wait_for_element_present(MoveDevicePopup.TABLE_BODY + "/*//span[contains(text(),'" + text + "')]") return True if cond else False def select_device_in_table(self, name): self._wait_for_element_present(MoveDevicePopup.TABLE_ROW) row = MoveDevicePopup.TABLE_ROW + "/*//span[text()='" + name + "']/ancestor::tr" self._click_element(row) self._wait_for_element_selected(row) class MoveSitePopup(BaseActions): BODY = "//span[text()='Move Site'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" LEFT_MENU = BODY + "/*//div[@class='TreeView-Control']" def check_popup_is_presented(self): cond = self._wait_for_element_present(MoveSitePopup.BODY) return True if cond else False def click_icon_help(self): self._click_icon_help(MoveSitePopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Move a site or device") return True if cond else False def click_button_ok(self): self._click_button_ok(MoveSitePopup.BODY) self._wait_for_element_not_present(MoveSitePopup.BODY) def click_button_cancel(self): self._click_button_cancel(MoveSitePopup.BODY) self._wait_for_element_not_present(MoveSitePopup.BODY) def click_system_button_close(self): self._click_system_button_close(MoveSitePopup.BODY) class NewFolderPopup(BaseActions): NEW_FOLDER = "New Folder" BODY = "//span[text()='New Folder'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" LEFT_MENU = BODY + "/*//div[@class='TreeView-Control']" TAB = BODY + "/*//div[@class='TabControl-Control']" FIELD_NEW_FOLDER = BODY + "/*//input" def check_popup_is_presented(self): cond = self._wait_for_element_present(NewFolderPopup.BODY) return True if cond else False def click_icon_help(self): self._click_icon_help(NewFolderPopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("New Folder") return True if cond else False def click_button_ok(self): self._click_button_ok(NewFolderPopup.BODY) self._wait_for_element_not_present(NewFolderPopup.BODY) def click_button_cancel(self): self._click_button_cancel(NewFolderPopup.BODY) self._wait_for_element_not_present(NewFolderPopup.BODY) def click_system_button_close(self): self._click_system_button_close(NewFolderPopup.BODY) def click_button_add_members(self): self._click_button_cancel(NewFolderPopup.BODY) self._wait_for_element_not_present(NewFolderPopup.BODY) def enter_text_into_new_folder_text_field(self, name): self._find_element(NewFolderPopup.FIELD_NEW_FOLDER).send_keys(name) class NewGroupPopup(BaseActions): BODY = "//span[text()='New Group'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" BUTTON_ADD_MEMBERS = BODY + "/*//span[text()='Add Members']/ancestor::div[contains(@class,'Button')]" LEFT_MENU = BODY + "/*//div[@class='TreeView-Control']" TAB = BODY + "/*//div[@class='TabControl-Control']" FIELD_GROUP_NAME = BODY + "/*//input[contains(@class,'TextBox-Input')][@type='text']" def check_popup_is_presented(self): cond = self._wait_for_element_present(NewGroupPopup.BODY) return True if cond else False def click_icon_help(self): self._click_icon_help(NewGroupPopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Create a new Group") return True if cond else False def click_button_ok(self): self._click_button_ok(NewGroupPopup.BODY) def click_button_cancel(self): self._click_button_cancel(NewGroupPopup.BODY) def click_system_button_close(self): self._click_system_button_close(NewGroupPopup.BODY) def click_button_add_members(self): self._click_element(NewGroupPopup.BUTTON_ADD_MEMBERS) def enter_text_into_group_name_text_field(self, text = None): self._find_element(NewGroupPopup.FIELD_GROUP_NAME).send_keys(text) class OnDemandInventoryScanPopup(BaseActions): BODY = "//span[text()='On demand inventory scan'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" BUTTON_START_NOW = BODY + "/*//span[text()='Start Now']/ancestor::div[contains(@class,'RibbonBarButton')]" LEFT_MENU = BODY + "/*//div[@class='TreeView-Control']" TAB = BODY + "/*//div[@class='TabControl-Control']" def check_popup_is_presented(self): cond = self._wait_for_element_present(OnDemandInventoryScanPopup.BODY) return True if cond else False def click_icon_help(self): self._click_icon_help(OnDemandInventoryScanPopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("On Demand Inventory Scan") return True if cond else False def click_button_close(self): self._click_button_close(OnDemandInventoryScanPopup.BODY) self._wait_for_element_not_present(OnDemandInventoryScanPopup.BODY) def click_button_start_now(self): self._click_element(OnDemandInventoryScanPopup.BUTTON_START_NOW) def click_system_button_close(self): self._click_system_button_close(OnDemandInventoryScanPopup.BODY) class PatchManagerPopup(BaseActions): #CONSTANTS BODY = "//span[text()='Patch Manager'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" TABLE_HEADER = BODY + "/*//div[contains(@id,'HEADER')]" TABLE_BODY = BODY + "/*//div[contains(@id,'VWGLVBODY')]" SEARCH_FIELD = BODY + "/*//input" LEFT_SIDE_TREE = BODY + "/*//div[contains(@class,'PaddingContainer')]" LEFT_SIDE_SUBNODE = LEFT_SIDE_TREE + "/*//div[contains(@class,'SubNodesContainer')]" LEFT_SIDE_NODE = LEFT_SIDE_TREE + "/*//div[contains(@class,'RowContainer')]" TABLE_HEADER_NAME = TABLE_HEADER + "/*//span[contains(text(),'Name')]" TABLE_ROW = "/ancestor::tr[contains(@class,'ListView-DataFullRow')]" ELEMENT_LABEL = "/ancestor::div[contains(@class,'RowContainer')]" LABEL_HISTORY = LEFT_SIDE_TREE + "/*//span[text()='History']" def check_popup_is_presented(self): cond = self._wait_for_element_present(PatchManagerPopup.BODY) return True if cond else False def check_device_name_is_presented(self, device_name): cond = self._wait_for_element_present(PatchManagerPopup.BODY + "/*//span[text()='" + device_name + "']") return True if cond else False def click_button_ok(self): self._click_button_ok(PatchManagerPopup.BODY) def click_button_cancel(self): self._click_button_cancel(PatchManagerPopup.BODY) def click_icon_help(self): self._click_icon_help(PatchManagerPopup.BODY) def click_system_button_close(self): self._click_system_button_close(PatchManagerPopup.BODY) def click_patch_in_table(self, name): element = self.TABLE_BODY + "/*//span[text()='" + name + "']" self._click_element(element) def check_patch_is_presented(self, name): element = self.TABLE_BODY + "/*//span[text()='" + name + "']" cond = self._wait_for_element_present(element) return True if cond else False def enter_text_into_search_text_field_and_click_enter(self, text): self._send_keys_and_enter(PatchManagerPopup.SEARCH_FIELD, text) # self._find_element(PatchManagerPopup.SEARCH_FIELD).send_keys(text) def click_label_in_left_side_list(self, label): elem = PatchManagerPopup.BODY + "/*//span[text()='" + label + "']/ancestor::div[contains(@class,'RowContainer')]" self._click_label(elem) def click_label_history(self): self.click_label_in_left_side_list("History") def expand_all_left_side_lists(self): self._expand_all_lists(PatchManagerPopup.LEFT_SIDE_TREE) def click_first_component_in_table(self): self._click_element( self.BODY + "/*//span[text()='Patch Components']/following::div[contains(@id,'BODY')]/*//tr[1]") def check_button_component_details_is_presented(self): cond = self._wait_for_element_present(self.BODY + BaseElements.BUTTON_COMPONENT_DETAILS) return True if cond else False def click_button_component_details(self): self._click_button_component_details(self.BODY) def check_patch_components_table_is_presented(self): element = self.BODY + "/*//span[text()='Patch Components']" cond = self._wait_for_element_present(element) return True if cond else False class PatchComponentDetailsPopup(BasePopup): PATCH_COMPONENT_DETAILS = "Patch Component Details" def popup_body(self): locator = self._set_popup(self.PATCH_COMPONENT_DETAILS) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self._wait_for_element_present(self.popup_body()) msg_true = "Popup '" + self.PATCH_COMPONENT_DETAILS + "' is presented" msg_false = "Popup '" + self.PATCH_COMPONENT_DETAILS + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_close(self): self._click_button_close(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) class PingResultPopup(BaseActions): PING_RESULT = "Ping Result" BODY = "//span[text()='Ping Result'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" LEFT_MENU = BODY + "/*//div[@class='TreeView-Control']" TAB = BODY + "/*//div[@class='TabControl-Control']" def check_popup_is_presented(self): cond = self._wait_for_element_present(PingResultPopup.BODY) msg_true = "Popup '" + self.PING_RESULT + "' is opened" msg_false = "Popup '" + self.PING_RESULT+ "' is NOT opened" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(PingResultPopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Ping Result") return True if cond else False def click_system_button_close(self): self._click_system_button_close(PingResultPopup.BODY) class ProcessExplorerPopup(BaseActions): BODY = "//span[text()='Process Explorer'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" TABS_PANEL = BODY + "/*//div[contains(@id,'VWGScrollable')]/div" TAB_PROCESSES = BODY + "/*//span[text()='Processes'][contains(@class,'Tab')]/ancestor::div[contains(@id,'TAB')]" TAB_SERVICES = BODY + "/*//span[text()='Services'][contains(@class,'Tab')]/ancestor::div[contains(@id,'TAB')]" BUTTON_OPEN = BODY + "/*//span[text()='...']/ancestor::div[contains(@class,'Button')]" def check_popup_is_presented(self): cond = self._wait_for_element_present(ProcessExplorerPopup.BODY) return True if cond else False def check_tabs_panel_is_presented(self): cond = self._wait_for_element_present(ProcessExplorerPopup.TABS_PANEL) return True if cond else False def click_button_ok(self): self._click_button_ok(ProcessExplorerPopup.BODY) def click_button_cancel(self): self._click_button_cancel(ProcessExplorerPopup.BODY) def click_button_open(self): self._click_element(ProcessExplorerPopup.BUTTON_OPEN) def click_system_button_close(self): self._click_system_button_close(ProcessExplorerPopup.BODY) def click_icon_help(self): self._click_icon_help(ProcessExplorerPopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Process Explorer") return True if cond else False def click_services_tab(self): self._click_element(ProcessExplorerPopup.TAB_SERVICES) self._wait_for_element_selected(ProcessExplorerPopup.TAB_SERVICES) def click_processes_tab(self): self._click_element(ProcessExplorerPopup.TAB_PROCESSES) self._wait_for_element_selected(ProcessExplorerPopup.TAB_PROCESSES) class QueryDesignerPopup(BaseActions): BODY = "//span[text()='Query Designer'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" LEFT_MENU = BODY + "/*//div[@class='TreeView-Control']" TAB = BODY + "/*//div[@class='TabControl-Control']" def check_popup_is_presented(self): cond = self._wait_for_element_present(QueryDesignerPopup.BODY) return True if cond else False def click_icon_help(self): self._click_icon_help(QueryDesignerPopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Queries") return True if cond else False def click_button_ok(self): self._click_button_ok(QueryDesignerPopup.BODY) self._wait_for_element_not_present(QueryDesignerPopup.BODY) def click_system_button_close(self): self._click_system_button_close(QueryDesignerPopup.BODY) def click_button_add(self): self._click_button_add(QueryDesignerPopup.BODY) self._wait_for_element_present(ConditionEditorPopup.BODY) class RemoveDevicesPopup(BaseActions): BODY = "//span[text()='Remove Devices'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" CHECKBOX_KEEP_HIST_INFORM = BODY + "//span[contains(text(),'Keep')][@class='CheckBox-Label']/" \ "ancestor::tr/td[contains(@id,'TRG')]" def check_popup_is_presented(self): cond = self._wait_for_element_present(RemoveDevicesPopup.BODY) return True if cond else False def click_button_ok(self): self._click_button_ok(RemoveDevicesPopup.BODY) def click_system_button_close(self): self._click_system_button_close(RemoveDevicesPopup.BODY) def click_button_cancel(self): self._click_button_cancel(RemoveDevicesPopup.BODY) def click_icon_help(self): self._click_icon_help(RemoveDevicesPopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Delete/Archive") return True if cond else False def check_keep_historical_information_check_box(self): self._wait_for_element_checked(RemoveDevicesPopup.BODY) self._click_element(RemoveDevicesPopup.CHECKBOX_KEEP_HIST_INFORM) self._wait_for_element_checked(RemoveDevicesPopup.CHECKBOX_KEEP_HIST_INFORM) def uncheck_keep_historical_information_check_box(self): self._wait_for_element_present(RemoveDevicesPopup.BODY) self._click_element(RemoveDevicesPopup.CHECKBOX_KEEP_HIST_INFORM) self._wait_for_element_unchecked(RemoveDevicesPopup.CHECKBOX_KEEP_HIST_INFORM) class ReportsPopup(BaseActions): BODY = "//span[text()='Reports'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" def check_popup_is_presented(self): cond = self._wait_for_element_present(ReportsPopup.BODY) return True if cond else False def click_icon_help(self): self._click_icon_help(ReportsPopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Reports") return True if cond else False def click_system_button_close(self): self._click_system_button_close(ReportsPopup.BODY) class ResetPasswordPopup(BaseActions): BODY = "//span[text()='Reset Password'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" def check_popup_is_presented(self): cond = self._wait_for_element_present(ResetPasswordPopup.BODY) return True if cond else False def click_icon_help(self): self._click_icon_help(ResetPasswordPopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Reset Password") return True if cond else False class SelectDashboardPopup(BaseActions): BODY = "//span[text()='Select Dashboard'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" LEFT_MENU = BODY + "/*//div[@class='TreeView-Control']" TAB = BODY + "/*//div[@class='TabControl-Control']" def check_popup_is_presented(self): cond = self._wait_for_element_present(SelectDashboardPopup.BODY) return True if cond else False def click_icon_help(self): self._click_icon_help(SelectDashboardPopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Select Dashboard") return True if cond else False def click_button_ok(self): self._click_button_ok(SelectDashboardPopup.BODY) self._wait_for_element_not_present(SelectDashboardPopup.BODY) def click_button_cancel(self): self._click_button_cancel(SelectDashboardPopup.BODY) self._wait_for_element_not_present(SelectDashboardPopup.BODY) def click_system_button_close(self): self._click_system_button_close(SelectDashboardPopup.BODY) class SelectTargetsPopup(BasePopup): SELECT_TARGETS = "Select Targets" def popup_body(self): locator = self._set_popup(self.SELECT_TARGETS) return str(locator) def check_popup_is_presented(self): cond = self._wait_for_element_present(self.popup_body()) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_ok(self): self._click_button_ok(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) def select_site_in_list(self, site_name): element = self.popup_body() + "/*//div[@class ='Common-Unselectable TreeView-Container']" \ "/*//span[text()='" + site_name + "']/ancestor::div[contains(@class,'RowContainer')]" self._expand_all_lists(self.popup_body() + "/*//div[contains(@id,'NODE')]") cond = self._is_element_present(element) if cond: self._click_label(element) else: self.logger.info("Site " + site_name + " is NOT found in the list") def select_device_in_list(self, device_name): element = self.popup_body() + "/*//div[@data-vwgdocking='T']/*//span[text()='" + device_name + "']" cond = self._is_element_present(element) if cond: self._click_element(element + "/ancestor::tr/td[1]") else: self.logger.info("Device " + device_name + " is NOT found in the list") class SiteConfigPopup(BaseActions): BODY = "//span[text()='Site Config'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" LEFT_TREE_VIEW = BODY + "/*//div[@class='TreeView-PaddingContainer']/div" LIST_GLOBAL_SITE_VIEW = LEFT_TREE_VIEW + "/div[contains(@class,'SubNodesContainer')]" LABEL_GLOBAL_SITE_VIEW = LEFT_TREE_VIEW + "/div[contains(@class,'RowContainer')]" LABEL_DEFAULT_SITE = LIST_GLOBAL_SITE_VIEW \ + "/div/div/*//span[text()='Default Site']/ancestor::div[contains(@class,'RowContainer')]" BUTTON_ADD_IP_RANGE = BODY + "/*//img[@alt='Add IP Range']/ancestor::div[contains(@class,'Button')]" BUTTON_ADD_SITE = BODY + "/*//img[@alt='Add Site']/ancestor::div[contains(@class,'Button')]" BUTTON_EDIT = BODY + "/*//img[@alt='Edit']/ancestor::div[contains(@class,'Button')]" BUTTON_DELETE = BODY + "/*//img[@alt='Delete']/ancestor::div[contains(@class,'Button')]" BUTTON_MOVE_SITE = BODY + "/*//img[@alt='Move Site']/ancestor::div[contains(@class,'Button')]" def check_popup_is_presented(self): cond = self._wait_for_element_present(SiteConfigPopup.BODY) return True if cond else False def click_icon_help(self): self._click_icon_help(SiteConfigPopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Create") return True if cond else False def click_button_close(self): self._click_button_close(SiteConfigPopup.BODY) self._wait_for_element_not_present(SiteConfigPopup.BODY) def click_system_button_close(self): self._click_system_button_close(SiteConfigPopup.BODY) def click_button_add_ip_range(self): self._click_element(SiteConfigPopup.BUTTON_ADD_IP_RANGE) self._wait_for_element_present(IPAddressPopup.BODY) def click_button_add_site(self): self._click_element(SiteConfigPopup.BUTTON_ADD_SITE) self._wait_for_element_present(SiteNamePopup.BODY) def click_button_move_site(self): self._click_element(SiteConfigPopup.BUTTON_MOVE_SITE) self._wait_for_element_present(MoveSitePopup.BODY) def create_site_if_not_exists(self, sitename): self.scroll_to_element(SiteConfigPopup.LIST_GLOBAL_SITE_VIEW) self.click_global_site_view_label() self.expand_global_site_view_list() cond = self.check_site_is_in_global_site_view_list(sitename) if cond is not True: site_name_popup = SiteNamePopup(self.driver) self.click_global_site_view_label() self.click_button_add_site() site_name_popup.enter_text_into_name_text_field(sitename) site_name_popup.click_button_ok() self.scroll_to_element(SiteConfigPopup.LIST_GLOBAL_SITE_VIEW \ + "/*//span[text()='" + sitename + "']/ancestor::div[contains(@class,'RowContainer')]") self.click_site_in_global_site_view_list(sitename) def click_global_site_view_label(self): self.scroll_to_element(SiteConfigPopup.LIST_GLOBAL_SITE_VIEW) self._click_label(SiteConfigPopup.LABEL_GLOBAL_SITE_VIEW) # def click_subsite_in_site_list(self, sitename, subsitename): # site_name = SiteConfigPopup.BODY \ # + "/*//span[text()='" + sitename + "']/ancestor::div[contains(@class,'RowContainer')]" # subsite_name = SiteConfigPopup.BODY + \ # "/*//span[text()='" + subsitename + "']/ancestor::div[contains(@class,'RowContainer')]" # element = SiteConfigPopup.LIST_GLOBAL_SITE_VIEW + site_name + "/parent::div/div[2]/*" + subsite_name # self._click_element(element) # self._wait_for_element_selected(element) def expand_global_site_view_list(self): arrow = self._is_element_present(SiteConfigPopup.LABEL_GLOBAL_SITE_VIEW + BaseElements.ARROW_EXPAND) if arrow: self._expand_list(SiteConfigPopup.LABEL_GLOBAL_SITE_VIEW) def click_site_in_global_site_view_list(self, sitename): element = SiteConfigPopup.LIST_GLOBAL_SITE_VIEW \ + "/*//span[text()='" + sitename + "']/ancestor::div[contains(@class,'RowContainer')]" self._click_element(element) self._wait_for_element_enabled(SiteConfigPopup.BUTTON_ADD_IP_RANGE) self._wait_for_element_enabled(SiteConfigPopup.BUTTON_EDIT) self._wait_for_element_enabled(SiteConfigPopup.BUTTON_DELETE) self._wait_for_element_enabled(SiteConfigPopup.BUTTON_MOVE_SITE) def check_site_is_in_global_site_view_list(self, sitename): cond = self._wait_for_element_present(SiteConfigPopup.LIST_GLOBAL_SITE_VIEW + "/*//span[text()='" + sitename + "']") return True if cond else False class SiteNamePopup(BaseActions): SITE_NAME = "Site Name" BODY = "//span[text()='Site Name'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" FIELD_NAME = BODY + "/*//input" def check_popup_is_presented(self): cond = self._wait_for_element_present(SiteNamePopup.BODY) msg_true = "Popup '" + self.SITE_NAME + "' is presented" msg_false = "Popup '" + self.SITE_NAME + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def check_popup_is_not_presented(self): cond = self._is_element_not_present(SiteNamePopup.BODY) msg_false = "Popup '" + self.SITE_NAME + "' is presented" msg_true = "Popup '" + self.SITE_NAME + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def enter_text_into_name_text_field(self, sitename): self._find_element(SiteNamePopup.FIELD_NAME).send_keys(sitename) def click_button_ok(self): self._click_button_ok(SiteNamePopup.BODY) def click_system_button_close(self): self._click_system_button_close(SiteNamePopup.BODY) def click_button_cancel(self): self._click_button_cancel(SiteNamePopup.BODY) def click_icon_help(self): self._click_icon_help(SiteNamePopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Create a site") return True if cond else False class SubscriptionHasExpiredPopup(BaseActions): BODY = "//span[text()='Manage Subscriptions'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" def click_system_button_close(self): self._click_system_button_close(SubscriptionHasExpiredPopup.BODY) # def close_popup(self): # cond = self._is_element_present(SubscriptionHasExpitredPopup.PAGE_BODY) # if cond: # self._click_system_button_close() # else: # pass class SubscriptionsPopup(BaseActions): BODY = "//span[text()='Subscriptions'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" def check_popup_is_presented(self): cond = self._wait_for_element_present(SubscriptionsPopup.BODY) return self._find_element(SubscriptionsPopup.BODY) if cond else None def click_icon_help(self): self._click_icon_help(SubscriptionsPopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Subscriptions") return True if cond else False class LicencesPopup(BasePopup): LICENSES = "Licenses" def popup_body(self): locator = self._set_popup(self.LICENSES) return str(locator) def check_popup_is_presented(self): cond = self._wait_for_element_present(self.popup_body()) msg_true = "Popup '" + self.LICENSES + "' is presented" msg_false = "Popup '" + self.LICENSES + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) def click_button_close(self): self._click_button_close(self.popup_body()) class TermsAndConditionsPopup(BaseActions): BODY = "//span[text()='Terms and Conditions'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" BUTTON_I_AGREE = "//span[text()='I Agree']" BUTTON_I_DO_NOT_AGREE = "//span[text()='I Do Not Agree']" def click_button_i_agree(self): self._click_element(TermsAndConditionsPopup.BUTTON_I_AGREE) self._wait_for_element_not_present(TermsAndConditionsPopup.BODY) def click_button_i_do_not_agree(self): self._click_element(TermsAndConditionsPopup.BUTTON_I_DO_NOT_AGREE) def click_system_button_close(self): self._click_system_button_close(TermsAndConditionsPopup.BODY) def close_popup_if_exists(self): cond = self._is_element_present(TermsAndConditionsPopup.BODY) if cond: self.click_button_i_agree() class UnableToRemovePopup(BaseActions): BODY = "//span[text()='Unable to remove']/ancestor::div[contains(@id,'WRP')]" def check_popup_is_presented(self): cond = self._wait_for_element_present(UnableToRemovePopup.BODY) return True if cond else False def click_button_ok(self): self._click_button_ok(UnableToRemovePopup.BODY) def click_system_button_close(self): self._click_system_button_close(UnableToRemovePopup.BODY) class UserConfigurationPopup(BaseActions): BODY = "//span[text()='User Configuration'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" FIELD_NAME = BODY + "/*//input" def check_popup_is_presented(self): cond = self._wait_for_element_present(UserConfigurationPopup.BODY) return True if cond else False def enter_text_into_name_text_field(self, sitename): self._find_element(UserConfigurationPopup.FIELD_NAME).send_keys(sitename) def click_button_ok(self): self._click_button_ok(UserConfigurationPopup.BODY) def click_system_button_close(self): self._click_system_button_close(UserConfigurationPopup.BODY) def click_button_cancel(self): self._click_button_cancel(UserConfigurationPopup.BODY) def click_icon_help(self): self._click_icon_help(UserConfigurationPopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Create") return True if cond else False class UserSettingsPopup(BaseActions): BODY = "//span[text()='User Settings'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" LEFT_MENU = BODY + "/*//div[@class='TreeView-Control']" TAB = BODY + "/*//div[@class='TabControl-Control']" def check_popup_is_presented(self): cond = self._wait_for_element_present(UserSettingsPopup.BODY) return True if cond else False def click_icon_help(self): self._click_icon_help(UserSettingsPopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("User Settings") return True if cond else False def click_button_ok(self): self._click_button_ok(UserSettingsPopup.BODY) self._wait_for_element_not_present(UserSettingsPopup.BODY) def click_button_cancel(self): self._click_button_cancel(UserSettingsPopup.BODY) self._wait_for_element_not_present(UserSettingsPopup.BODY) def click_system_button_close(self): self._click_system_button_close(UserSettingsPopup.BODY) class ViewLogsPopup(BaseActions): BODY = "//span[contians(text(),'View Logs')][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" def check_popup_is_presented(self): cond = self._wait_for_element_present(ViewLogsPopup.BODY) return True if cond else False def click_system_button_close(self): self._click_system_button_close(ViewLogsPopup.BODY) class WakeOnLANPopup(BaseActions): BODY = "//span[text()='Wake on LAN'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" def check_popup_is_presented(self): cond = self._wait_for_element_present(WakeOnLANPopup.BODY) return True if cond else False def click_icon_help(self): self._click_icon_help(WakeOnLANPopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Wake Up") return True if cond else False def click_button_close(self): self._click_button_close(WakeOnLANPopup.BODY) self._wait_for_element_not_present(WakeOnLANPopup.BODY) def click_system_button_close(self): self._click_system_button_close(WakeOnLANPopup.BODY) class WeightDisplayPopup(BaseActions): BODY = "//span[text()='Weight Display'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" LEFT_MENU = BODY + "/*//div[@class='TreeView-Control']" TAB = BODY + "/*//div[@class='TabControl-Control']" def check_popup_is_presented(self): cond = self._wait_for_element_present(WeightDisplayPopup.BODY) return True if cond else False def click_icon_help(self): self._click_icon_help(WeightDisplayPopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Imperial Metric") return True if cond else False def click_button_ok(self): self._click_button_ok(WeightDisplayPopup.BODY) def click_button_cancel(self): self._click_button_cancel(WeightDisplayPopup.BODY) def click_system_button_close(self): self._click_system_button_close(WeightDisplayPopup.BODY) class WMIExplorerPopup(BaseActions): BODY = "//span[text()='WMI Explorer'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" def check_popup_is_presented(self): cond = self._wait_for_element_present(WMIExplorerPopup.BODY) return True if cond else False def click_button_ok(self): self._click_button_ok(WMIExplorerPopup.BODY) def click_button_cancel(self): self._click_button_cancel(WMIExplorerPopup.BODY) def click_system_button_close(self): self._click_system_button_close(WMIExplorerPopup.BODY) def click_icon_help(self): self._click_icon_help(WMIExplorerPopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Process Explorer") return True if cond else False class SettingsPopup(BaseActions): BODY = "//span[text()='Settings'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" TREE_VIEW = BODY + "/*//div[@class='TreeView-Control']" TAB = BODY + "/*//div[@class='TabControl-Control']" LABEL_CONTENT_SERVICES = TREE_VIEW + "/*//span[text()='Content Services']/ancestor::div[contains(@id,'VWGNODE')]" LABEL_EMAIL_SETTINGS = TREE_VIEW + "/*//span[text()='Email Settings']/ancestor::div[contains(@id,'VWGNODE')]" LABEL_INITIAL_SETUP = TREE_VIEW + "/*//span[text()='Initial Setup']/ancestor::div[contains(@id,'VWGNODE')]" LABEL_INVENTORY = TREE_VIEW + "/*//span[text()='Inventory']/ancestor::div[contains(@id,'VWGNODE')]" LABEL_LOCALE_OPTIONS = TREE_VIEW + "/*//span[text()='Locale Options']/ancestor::div[contains(@id,'VWGNODE')]" LABEL_USER_OPTIONS = TREE_VIEW + "/*//span[text()='User Options']/ancestor::div[contains(@id,'VWGNODE')]" LABEL_AUDIT_LOG_SETTINGS = TREE_VIEW + "/*//span[text()='Audit Log Settings']/ancestor::div[contains(@id,'VWGNODE')]" TAB_LABEL_AUDIT_LOG_SETTINGS = TAB + "/*//span[text()='Audit Log Settings']" LABEL_AUDIT_EMAIL_SETTINGS = TAB + "/*//span[text()='Audit Email Settings']" BUTTON_PURGE_ENTRIES = TAB + "/*//span[text()='Purge older entries now']/ancestor::div[contains(@class,'Button')]" BUTTON_DELETE_LOGS = TAB + "/*//span[text()='Delete all audit logs']/ancestor::div[contains(@class,'Button')]" TAB_OPTIONS = TAB + "/*//span[text()='Options']/ancestor::div[contains(@id,'TAB')]" TAB_LOG = TAB + "/*//span[text()='Log']/ancestor::div[contains(@id,'TAB')]" TAB_SMTP = TAB + "/*//span[text()='SMTP']/ancestor::div[contains(@id,'TAB')]" TAB_IMAP = TAB + "/*//span[text()='IMAP']/ancestor::div[contains(@id,'TAB')]" LABEL_DATE_AND_TIME_SETTINGS = TAB + "/*//span[text()='Date And Time Settings']" LABEL_DATE_FORMAT = TAB + "/*//span[text()='Date Format']" LABEL_TIME_ZONE = TAB + "/*//span[text()='Time Zone']" LABEL_USER_AUTHENTICATION = TAB + "/*//span[text()='User Authentication']" CHECKBOX_CHECK_NEW_DATA = TAB + \ "/*//span[contains(text(),'check for new data')]/ancestor::div[contains(@class,'CheckBox')]" BUTTON_RUN_INITIAL_SETUP = TAB + \ "/*//span[text()='Run Initial Setup']/ancestor::div[contains(@class,'Button')]" CHECKBOX_TERMS_AND_CONDITIONS = TAB + \ "/*//span[contains(text(),'Show Terms')]/ancestor::div[contains(@class,'CheckBox')]" LABEL_INVENTORY_ARCHIVE_SETTINGS = TAB + "/*//span[text()='Inventory Archive Settings']" BUTTON_PURGE_RECORDS = TAB + "/*//span[text()='Purge Older Records']/ancestor::div[contains(@class,'Button')]" BUTTON_DELETE_DATA = TAB + "/*//span[text()='Delete ALL Archive Data']/ancestor::div[contains(@class,'Button')]" def check_popup_is_presented(self): cond = self._wait_for_element_present(SettingsPopup.BODY) return True if cond else False def click_icon_help(self): self._click_icon_help(SettingsPopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Settings") return True if cond else False def click_content_services_label(self): self._click_label(SettingsPopup.LABEL_CONTENT_SERVICES) def click_email_settings_label(self): self._click_label(SettingsPopup.LABEL_EMAIL_SETTINGS) def click_initial_setup_label(self): self._click_label(SettingsPopup.LABEL_INITIAL_SETUP) def click_locale_options_label(self): self._click_label(SettingsPopup.LABEL_LOCALE_OPTIONS) def click_inventory_label(self): self._click_label(SettingsPopup.LABEL_INVENTORY) def click_user_options_label(self): self._click_label(SettingsPopup.LABEL_USER_OPTIONS) def click_audit_log_settings_label(self): self._click_label(SettingsPopup.LABEL_AUDIT_LOG_SETTINGS) def click_button_run_initial_setup(self): self._click_element(SettingsPopup.BUTTON_RUN_INITIAL_SETUP) self._wait_for_element_present(InitialSetupPopup.BODY) def check_content_services_tab_is_presented(self): cond = self._wait_for_element_present(SettingsPopup.TAB_OPTIONS) msg_true = "Tab 'Content Services' is opened" msg_false = "Tab 'Content Services' is NOT opened" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def check_email_settings_tab_is_presented(self): cond = self._wait_for_element_present(SettingsPopup.TAB_SMTP) msg_true = "Tab 'Email Settings' is opened" msg_false = "Tab 'Email Settings' is NOT opened" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def check_initial_setup_tab_is_presented(self): cond = self._wait_for_element_present(SettingsPopup.BUTTON_RUN_INITIAL_SETUP) msg_true = "Tab 'Initial Setup' is opened" msg_false = "Tab 'Initial Setup' is NOT opened" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def check_locale_options_tab_is_presented(self): cond = self._wait_for_element_present(SettingsPopup.LABEL_DATE_AND_TIME_SETTINGS) msg_true = "Tab 'Locale Options' is opened" msg_false = "Tab 'Locale Options' is NOT opened" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def check_inventory_tab_is_presented(self): self.wait_for_screen_is_unlocked() # WebDriverWait(SettingsPopup.driver, 600). \ # until(EC.presence_of_element_located((By.XPATH, self.LABEL_INVENTORY_ARCHIVE_SETTINGS))) cond = self._wait_for_element_present(SettingsPopup.LABEL_INVENTORY_ARCHIVE_SETTINGS) msg_true = "Tab 'Inventory' is opened" msg_false = "Tab 'Inventory' is NOT opened" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def check_user_options_tab_is_presented(self): cond = self._wait_for_element_present(SettingsPopup.LABEL_USER_AUTHENTICATION) return True if cond else False def check_audit_log_settings_tab_is_presented(self): cond= self._is_element_present(SettingsPopup.TAB_LABEL_AUDIT_LOG_SETTINGS) msg_true = "Tab 'Audit Log Settings' is opened" msg_false = "Tab 'Audit Log Settings' is NOT opened" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False class ConfigurationPopup(BaseActions): IP_ADDRESS_RANGES = "IP Address Ranges" BODY = "//span[text()='Configuration'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" SUCCESS_POPUP = "//span[text()='Success'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" TAB = BODY + "/*//div[1][@class='TabPage-Control_bj']" BUTTONS_PANEL = TAB + "/*//div[contains(@class,'FlatToolBar')]" TABLE_HEADER = TAB + "/*//div[contains(@id,'HEADER')]" TABLE_BODY = TAB + "/*//div[contains(@id,'VWGLVBODY')]" BUTTON_APPLY_CHANGES = TAB + "/*//span[text()='Apply Changes']" TABS_PANEL = BODY + "/*//div[contains(@id,'VWGScrollable')]/div" TAB_IP_ADDRESS_RANGES = BODY + "/*//span[text()='IP Address Ranges']" \ "[contains(@class,'Tab')]/ancestor::div[contains(@id,'TAB')]" TAB_SITE = BODY + "/*//span[text()='Site'][contains(@class,'Tab')]/ancestor::div[contains(@id,'TAB')]" TAB_VREPS = BODY + "/*//span[text()='vReps'][contains(@class,'Tab')]/ancestor::div[contains(@id,'TAB')]" TAB_CONFIGURATION = BODY + "/*//div[1][@class='TabPage-Control_bj']" COLUMN_SET_DROP_DOWN_LIST = TAB + "/following::div[@class='ComboBox-PopupWindow']" DROP_DOWN_APPLIED_VALUE = TAB + "/*//div[contains(@class,'ComboBox-Container')]/*//span[@data-vwg_appliedvalue]" FIELD_NAME = TAB + "/*//input" def check_popup_is_presented(self): cond = self._wait_for_element_present(self.BODY) return True if cond else False def check_tabs_panel_is_presented(self): cond = self._wait_for_element_present(self.TABS_PANEL) return True if cond else False def click_button_close(self): self._click_button_close(self.BODY) def click_button_add(self): self._click_button_add(self.BODY) # self._wait_for_element_present(IPAddressPopup.BODY) def click_button_delete(self): self._click_button_delete(self.BODY) # self._wait_for_element_present(IPAddressPopup.BODY) def click_button_apply_changes(self): self._click_element(self.BUTTON_APPLY_CHANGES) def click_button_ok_on_success_popup(self): self._click_button_ok(self.SUCCESS_POPUP) def click_system_button_close(self): self._click_system_button_close(self.BODY) def click_icon_help(self): self._click_icon_help(self.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Configure a site") return True if cond else False def click_site_tab(self): self._click_element(self.TAB_SITE) # self._wait_for_element_selected(ConfigurationPopup.TAB_SITE) def click_ip_address_ranges_tab(self): self._click_element(self.TAB_IP_ADDRESS_RANGES) # self._wait_for_element_selected(ConfigurationPopup.TAB_IP_ADDRESS) def click_vreps_tab(self): self._click_element(self.TAB_VREPS) # self._wait_for_element_selected(ConfigurationPopup.TAB_VREPS) def click_button_new(self): self._click_button_new(self.TAB) # self._wait_for_element_present(ColumnSetDesignerPopup.BODY) def click_column_set_dropdown_button(self): self._click_system_button_drop_down(self.BODY) # self._wait_for_element_present(ConfigurationPopup.COLUMN_SET_DROP_DOWN_LIST) def click_icon_restore(self): self._click_icon_restore(ConfigurationPopup.TAB) # self._wait_for_element_not_present(ConfigurationPopup.DROP_DOWN_APPLIED_VALUE) def enter_text_into_name_text_field(self, sitename): self._click_element(ConfigurationPopup.FIELD_NAME) self._find_element(ConfigurationPopup.FIELD_NAME).send_keys(sitename) def get_name_text_field_value(self): actual_attribute_value = self._get_attribute_value(ConfigurationPopup.FIELD_NAME, "value") print ("The actual value in the Name textfield is: " + actual_attribute_value) return actual_attribute_value def select_columnset_in_drop_down_list(self, columnsetname): self.click_column_set_dropdown_button() self.scroll_list_to_top() row = "//table[contains(@id,'VWGVL_')]/*//tr" scroll = "//div[contains(@id,'VWGVLSC_')]/div" scroll_height = self._find_element(scroll).size['height'] row_height = self._find_element(row).size['height'] rows_number = scroll_height / row_height # print "DROP-DOWN: list_height, one row height, number of rows are: ", scroll_height, row_height, rows_number element = ConfigurationPopup.COLUMN_SET_DROP_DOWN_LIST + "/*//span[text()='" + columnsetname + "']" i = 0 visible_rows = 8 one_scroll = row_height * visible_rows step = one_scroll while i <= rows_number: cond = self._is_element_not_present(element) if cond: self.scroll_list_down(step) step += one_scroll i += visible_rows else: break # self._click_element(BaseElements._DROP_DOWN_LIST + "/*//span[text()='" + columnsetname + "']") self._click_element(element) self._wait_for_element_not_present(ConfigurationPopup.COLUMN_SET_DROP_DOWN_LIST) def check_columnset_is_selected_from_drop_down_list(self, columnsetname): cond = self._wait_for_element_present( ConfigurationPopup.DROP_DOWN_APPLIED_VALUE + "[text()='" + columnsetname + "']") return True if cond else False def check_name_text_field_disabled(self): cond = self._is_element_disabled(ConfigurationPopup.FIELD_NAME) return True if cond else False def check_tab_is_presented(self): cond = self._wait_for_element_present(self.TAB) msg_true = "Tab 'IP Address Ranges' is opened" msg_false = "Tab 'IP Address Ranges' is NOT opened" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def apply_vrep_to_the_site(self, name=Variables.vrep): element = self.BODY + "/*//div[contains(@id,'VWGLVBODY')]" \ "/*//span[text()='" + name + "']/ancestor::tr/*//img[contains(@src,'CheckBox')]" cond = self._is_element_present(element + "[contains(@src,'CheckBox1')]" ) if cond is not True: self._click_element(element) print "Check the vRep" else: print "Vrep is already checked" # self._wait_for_element_checked(element) # error_popup = self._is_element_present() def delete_all_ip_address_ranges(self): table_row = self.BODY + "/*//div[contains(@id,'VWGLVBODY')]" \ "/*//table[contains(@style,'CheckBox')]/ancestor::tr[last()]/td[1]" cond = self._is_element_present(table_row) if cond: # cond = self._is_element_present(table_row) # ranges = {} # if cond: # elements = self._find_elements(table_row) # x = 1 # print len(elements) # for element in elements: # start_ip = element.text # # ranges.get('Start IP', str(start_ip)) # # # ranges.append(start_ip) # print ranges while True: cond = self._is_element_present(table_row) if cond: self._click_element(table_row) self._wait_for_element_enabled(self.BODY + BaseElements.BUTTON_DELETE) self.click_button_delete() # while True: # cond = self._is_element_present(table_row) # if cond: # self._click_element(table_row) # self.click_button_delete() # else: # print "All ip ranges are deleted from the table" # break print "Delete a row" else: print "All ip ranges are deleted from the table" break else: print "There is no ip ranges in the table" def add_single_ip_address_range(self, name=Variables.ip_address): ip_address_popup = IPAddressPopup(self.driver) self.click_button_add() ip_address_popup.enter_start_ip_address(name) ip_address_popup.enter_end_ip_address(name) ip_address_popup.click_button_ok() cond1 = self.check_start_ip_is_presented(name) cond2 = self.check_end_ip_is_presented(name) if cond1 and cond2: print "Single ip address range " + name + " is created" cond3 = self.check_ip_range_is_not_excluded(name) if cond3: print "ip address range " + name + " is not excluded" return True else: print "ip address range " + name + " is excluded" return False else: print "IP address range " + name + " is NOT created" def check_start_ip_is_presented(self, start_ip=Variables.ip_address): element = self.BODY + "/*//div[contains(@id,'VWGLVBODY')]/*//td[1]/*//span[text()='" + start_ip + "']" cond = self._wait_for_element_present(element) return True if cond else False def check_end_ip_is_presented(self, end_ip=Variables.help_test): element = self.BODY + "/*//div[contains(@id,'VWGLVBODY')]/*//td[3]/*//span[text()='" + end_ip + "']" cond = self._wait_for_element_present(element) return True if cond else False def check_ip_range_is_not_excluded(self, start_ip=Variables.help_test): element = self.BODY + "/*//div[contains(@id,'VWGLVBODY')]/*//td[1]" \ "/*//span[text()='" + start_ip + "']/ancestor::tr/*//table[contains(@style,'CheckBox')]" cond = self._wait_for_element_unchecked(element) return True if cond else False class ConfigureExclusionsPopup(BaseActions): BODY = "//span[text()='Configure Exclusions'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" TAB = BODY + "/*//div[@class='TabControl-Control']" TABLE_HEADER = BODY + "/*//div[contains(@id,'HEADER')]" TABLE_BODY = BODY + "/*//div[contains(@id,'VWGLVBODY')]" LEFT_MENU = BODY + "/*//div[@class='Common-Unselectable TreeView-Container']" # LEFT_SIDE_TREE = BODY + "/*//div[contains(@class,'PaddingContainer')]" # LEFT_SIDE_SUBNODE = LEFT_SIDE_TREE + "/*//div[contains(@class,'SubNodesContainer')]" # LEFT_SIDE_NODE = LEFT_SIDE_TREE + "/*//div[contains(@class,'RowContainer')]" TABLE_ROW = TABLE_BODY + "/*//tr" ELEMENT_LABEL = "/ancestor::div[contains(@class,'RowContainer')]" def check_popup_is_presented(self): cond = self._wait_for_element_present(ConfigureExclusionsPopup.BODY) return True if cond else False def click_icon_help(self): self._click_icon_help(ConfigureExclusionsPopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Exclusions") return True if cond else False def click_button_close(self): self._click_button_close(ConfigureExclusionsPopup.BODY) self._wait_for_element_not_present(ConfigureExclusionsPopup.BODY) def click_system_button_close(self): self._click_system_button_close(ConfigureExclusionsPopup.BODY) def click_label_in_left_side_list(self, label): elem = ConfigureExclusionsPopup.LEFT_MENU + \ "/*//span[text()='" + str(label) + "']/ancestor::div[contains(@class,'RowContainer')]" self._click_label(elem) def check_text_is_in_list_view(self, text): cond = self._wait_for_element_present(ConfigureExclusionsPopup.TABLE_BODY + "/*//span[contains(text(),'" + text + "')]") return True if cond else False def select_item_in_table(self, item): self._wait_for_element_present(ConfigureExclusionsPopup.TABLE_ROW) row = ConfigureExclusionsPopup.TABLE_ROW + "/*//span[text()='" + item + "']/ancestor::tr" self._click_element(row) self._wait_for_element_selected(row) def click_list_label_sites(self): self.click_label_in_left_side_list("Sites") def click_list_label_ip_address(self): self.click_label_in_left_side_list("IP Address") def click_list_label_device_name(self): self.click_label_in_left_side_list("Device Name") def click_sites_tab_button_add(self): self._click_button_add(ConfigureExclusionsPopup.TAB) # self._wait_for_element_present(ExcludeSitePopup.BODY) def click_ip_address_tab_button_add(self): self._click_button_add(ConfigureExclusionsPopup.TAB) # self._wait_for_element_present(ExcludeIPAddressPopup.BODY) def click_device_name_tab_button_add(self): self._click_button_add(ConfigureExclusionsPopup.TAB) # self._wait_for_element_present(ExcludeDevicePopup.BODY) def check_sites_tab_is_opened(self): pass class ClientSettingsPopup(BaseActions): TIMERS = "Timers" FEATURES = "Features" CLIENT_URLS = "Client URLs" REBOOT_UI_CONFIG = "Reboot UI Config" CLIENT_PROXY_SETTINGS = "Client Proxy Settings" BODY = "//span[text()='Client Settings'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" LEFT_MENU = BODY + "/*//div[@class='TreeView-Control']" TAB = BODY + "/*//div[@class='TabControl-Control']" LABEL_TIMERS = LEFT_MENU + "/*//span[text()='Timers']/ancestor::div[contains(@id,'VWGNODE')]" LABEL_FEATURES = LEFT_MENU + "/*//span[text()='Features']/ancestor::div[contains(@id,'VWGNODE')]" LABEL_REBOOT_UI_CONFIG = LEFT_MENU + "/*//span[text()='Reboot UI Config']/ancestor::div[contains(@id,'VWGNODE')]" LABEL_CLIENT_URLS = LEFT_MENU + "/*//span[text()='Client URLs']/ancestor::div[contains(@id,'VWGNODE')]" LABEL_CLIENT_PROXY_SETTINGS = LEFT_MENU + \ "/*//span[text()='Client Proxy Settings']/ancestor::div[contains(@id,'VWGNODE')]" LABEL_PROXY_SERVER_URL = TAB + "/*//span[text()='Proxy Server URL:']" LABEL_PORT_NUMBER = TAB + "/*//span[text()='Port Number:']" LABEL_LOGIN_CREDENTIALS = TAB + "/*//span[text()='Login Credentials']" LABEL_PASSWORD = TAB + "/*//span[text()='Password']" LABEL_VREP_INSTALLER = TAB + "/*//span[text()='vRep Installer']" LABEL_MICRO_RESPONDER_INSTALLER = TAB + "/*//span[text()='Micro Responder Installer']" LABEL_REBOOT_MASSAGE = TAB + "/*//span[text()='Custom Reboot Message']" LABEL_REBOOT_TIMERS = TAB + "/*//span[text()='Reboot Timers']" LABEL_SNOOZE = TAB + "/*//span[text()='Snooze']" CHECKBOX_ARCHIVE = TAB + "/*//span[text()='Auto Archive:']/ancestor::div[contains(@class,'CheckBox')]" CHECKBOX_DISSOLVE = TAB + "/*//span[contains(text(),'Dissolve')]/ancestor::div[contains(@class,'CheckBox')]" def check_popup_is_presented(self): cond = self._wait_for_element_present(ClientSettingsPopup.BODY) return True if cond else False def click_icon_help(self): self._click_icon_help(ClientSettingsPopup.BODY) def check_help_link_is_correct(self): cond = self._check_help_frame_header("Client") return True if cond else False def click_timers_tab(self): self._click_element(self.LABEL_TIMERS) self._wait_for_element_selected(self.LABEL_TIMERS) def click_features_label(self): self._click_label(self.LABEL_FEATURES) def click_client_urls_label(self): self._click_label(self.LABEL_CLIENT_URLS) def click_reboot_ui_config_tab(self): self._click_label(self.LABEL_REBOOT_UI_CONFIG) def click_client_proxy_settings_tab(self): self._click_label(self.LABEL_CLIENT_PROXY_SETTINGS) def check_timers_tab_is_presented(self): cond = self._wait_for_element_present(self.CHECKBOX_DISSOLVE) msg_true = "Tab " + self.TIMERS + "' is presented" msg_false = "Tab" + self.TIMERS + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def check_features_tab_is_presented(self): cond = self._wait_for_element_present(self.CHECKBOX_ARCHIVE) msg_true = "Tab " + self.FEATURES + "' is presented" msg_false = "Tab" + self.FEATURES + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def check_client_urls_tab_is_presented(self): cond = self._wait_for_element_present(self.LABEL_VREP_INSTALLER) msg_true = "Tab " + self.CLIENT_URLS + "' is presented" msg_false = "Tab" + self.CLIENT_URLS + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def check_reboot_ui_config_tab_is_presented(self): cond = self._wait_for_element_present(self.LABEL_REBOOT_MASSAGE) msg_true = "Tab " + self.REBOOT_UI_CONFIG + "' is presented" msg_false = "Tab" + self.REBOOT_UI_CONFIG + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def check_client_proxy_settings_tab_is_presented(self): cond = self._wait_for_element_present(self.LABEL_PROXY_SERVER_URL) msg_true = "Tab " + self.CLIENT_PROXY_SETTINGS + "' is presented" msg_false = "Tab" + self.LABEL_CLIENT_PROXY_SETTINGS + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False class EditUserPopup(BaseActions): EDIT_USER = "Edit User" BODY = "//span[text()='Edit User'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" def check_popup_is_presented(self): cond = self._wait_for_element_present(EditUserPopup.BODY) msg_true = "Popup '" + self.EDIT_USER + "' is presented" msg_false = "Popup '" + self.EDIT_USER + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(EditUserPopup.BODY) class InventoryConfigurationPopup(BaseActions): INVENTORY_CONFIGURATION = "Inventory Configuration" BODY = "//span[text()='Inventory Configuration'][@dir='LTR']/ancestor::div[contains(@id,'WRP')]" TABLE_HEADER = BODY + "/*//div[contains(@id,'HEADER')]" TABLE_BODY = BODY + "/*//div[contains(@id,'VWGLVBODY')]" LEFT_SIDE_TREE = BODY + "/*//div[contains(@class,'PaddingContainer')]" LEFT_SIDE_SUBNODE = LEFT_SIDE_TREE + "/*//div[contains(@class,'SubNodesContainer')]" LEFT_SIDE_NODE = LEFT_SIDE_TREE + "/*//div[contains(@class,'RowContainer')]" TABLE_HEADER_COLUMNS = TABLE_HEADER + "/*//span[contains(text(),'Columns')]" TABLE_HEADER_DEFAULT_WIDTH = TABLE_HEADER + "/*//span[contains(text(),'Default Width')]" TABLE_HEADER_AGGREGATE = TABLE_HEADER + "/*//span[contains(text(),'Aggregate')]" TABLE_ROW = TABLE_BODY + "/*//tr" ELEMENT_LABEL = "/ancestor::div[contains(@class,'RowContainer')]" def check_popup_is_presented(self): cond = self._wait_for_element_present(InventoryConfigurationPopup.BODY) msg_true = "Popup '" + self.INVENTORY_CONFIGURATION + "' is presented" msg_false = "Popup '" + self.INVENTORY_CONFIGURATION + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(InventoryConfigurationPopup.BODY) def click_button_ok(self): self._click_button_ok(InventoryConfigurationPopup.BODY) self._wait_for_element_not_present(InventoryConfigurationPopup.BODY) def click_button_cancel(self): self._click_button_cancel(InventoryConfigurationPopup.BODY) self._wait_for_element_not_present(InventoryConfigurationPopup.BODY) def click_system_button_close(self): self._click_system_button_close(InventoryConfigurationPopup.BODY) def click_label_in_left_side_list(self, label): elem = InventoryConfigurationPopup.LEFT_SIDE_SUBNODE + "/*//span[text()='" + label + "']/ancestor::div[contains(@class,'RowContainer')]" self._click_label(elem) def expand_all_left_side_lists(self): self._expand_all_lists(InventoryConfigurationPopup.LEFT_SIDE_TREE) # self._wait_for_element_present(MoveDevicePopup.PAGE_BODY) # elements = self._find_elements(MoveDevicePopup.LEFT_SIDE_TREE + "/div/div/div[contains(@id,'VWGJOINT')]") # for element in elements: # self.driver.execute_script("arguments[0].click();", element) def check_text_is_in_list_view(self, text): cond = self._wait_for_element_present(InventoryConfigurationPopup.TABLE_BODY + "/*//span[contains(text(),'" + text + "')]") return True if cond else False def select_item_in_table(self, name): self._wait_for_element_present(InventoryConfigurationPopup.TABLE_ROW) row = InventoryConfigurationPopup.TABLE_ROW + "/*//span[text()='" + name + "']/ancestor::tr" self._click_element(row) self._wait_for_element_selected(row) class InventoryForceUpdatePopup(BasePopup): INVENTORY_FORCE_UPDATE = "Inventory Force Update" def popup_body(self): locator = self._set_popup(self.INVENTORY_FORCE_UPDATE) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self.popup_body() msg_true = "Popup '" + self.INVENTORY_FORCE_UPDATE + "' is presented" msg_false = "Popup '" + self.INVENTORY_FORCE_UPDATE + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond is not None else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_ok(self): self._click_button_ok(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) class CreatePatchGroupPopup(BasePopup): CREATE_PATCH_GROUP = "Create Patch Group" BUTTON_EDIT_MEMBERS = "/*//span[text()='Edit Members']/ancestor::div[contains(@class,'Button')]" def popup_body(self): locator = self._set_popup(self.CREATE_PATCH_GROUP) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self.popup_body() msg_true = "Popup '" + self.CREATE_PATCH_GROUP + "' is presented" msg_false = "Popup '" + self.CREATE_PATCH_GROUP + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond is not None else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_ok(self): self._click_button_ok(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) def click_button_edit_members(self): self._click_element(self.popup_body() + self.BUTTON_EDIT_MEMBERS) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) def enter_text_into_group_name_text_field(self, name): self._find_element(self.popup_body() + "/*//input").send_keys(name) class EditPatchGroupPopup(BasePopup): EDIT_PATCH_GROUP = "Edit Patch Group" BUTTON_EDIT_MEMBERS = "/*//span[text()='Edit Members']/ancestor::div[contains(@class,'Button')]" def popup_body(self): locator = self._set_popup(self.EDIT_PATCH_GROUP) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self.popup_body() msg_true = "Popup '" + self.EDIT_PATCH_GROUP + "' is presented" msg_false = "Popup '" + self.EDIT_PATCH_GROUP + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond is not None else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_ok(self): self._click_button_ok(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) def click_button_edit_members(self): self._click_element(self.popup_body() + self.BUTTON_EDIT_MEMBERS) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) class SelectPatchesPopup(BasePopup): SELECT_PATCHES = "Select Patches" def popup_body(self): locator = self._set_popup(self.SELECT_PATCHES) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self.popup_body() msg_true = "Popup '" + self.SELECT_PATCHES + "' is presented" msg_false = "Popup '" + self.SELECT_PATCHES + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond is not None else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_ok(self): self._click_button_ok(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) class CreateApplicationWizardPopup(BasePopup): CREATE_APPLICATION_WIZARD = "Create Application Wizard" SELECT_FILE = "SELECT FILE" IMPORT_INFORMATION = "IMPORT INFORMATION" ADVANCED = "ADVANCED" BUTTON_CHOOSE_FROM_SERVER = "/*//span[contains(text(),'Verismic server')]/ancestor::div[contains(@class,'Button')]" BUTTON_CHOOSE_FROM_DEVICE = "/*//span[contains(text(),'your device')]/ancestor::div[contains(@class,'Button')]" BUTTON_CONFIGURE_ADVANCED_OPTIONS = "/*//span[contains(text(),'Options')]/ancestor::div[contains(@class,'Button')]" LABEL_SELECT_FILE = "/*//span[text()='SELECT FILE']" LABEL_IMPORT_INFORMATION = "/*//span[text()='IMPORT INFORMATION']" LABEL_ADVANCED = "/*//span[text()='ADVANCED']" def popup_body(self): locator = BaseElements.POPUP cond = self._wait_for_element_present(locator) return str(locator) if cond else None def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) def click_button_next(self): self._click_button_next(self.popup_body()) def click_button_previous(self): self._click_button_previous(self.popup_body()) def click_button_finish(self): self._click_button_finish(self.popup_body()) def click_button_choose_installer_on_sever(self): self._click_element(self.BUTTON_CHOOSE_FROM_SERVER) def click_button_configure_advanced_options(self): self._click_element(self.BUTTON_CONFIGURE_ADVANCED_OPTIONS) def check_popup_is_presented(self): cond = self._wait_for_element_present(self.popup_body()) # self.logger.critical( # "Popup HAS NO title name. Add title '" + self.CREATE_APPLICATION_WIZARD + "'!!!") msg_true = "Popup '" + self.CREATE_APPLICATION_WIZARD + "' is presented" msg_false = "Popup '" + self.CREATE_APPLICATION_WIZARD + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def check_select_file_tab_is_presented(self): cond = self._wait_for_element_present(self.popup_body() + self.LABEL_SELECT_FILE + BaseElements.BLACK_COLOR) msg_true = "Tab '" + self.SELECT_FILE + "' is presented" msg_false = "Tab '" + self.SELECT_FILE + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def check_import_information_tab_is_presented(self): cond = self._wait_for_element_present(self.popup_body() + self.LABEL_IMPORT_INFORMATION + BaseElements.BLACK_COLOR) msg_true = "Tab '" + self.IMPORT_INFORMATION + "' is presented" msg_false = "Tab '" + self.IMPORT_INFORMATION + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def check_advanced_tab_is_presented(self): cond = self._wait_for_element_present(self.popup_body() + self.LABEL_ADVANCED + BaseElements.BLACK_COLOR) msg_true = "Tab '" + self.ADVANCED + "' is presented" msg_false = "Tab '" + self.ADVANCED + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False class CreateUpdateWizardPopup(BasePopup): CREATE_UPDATE_WIZARD = "Create Update Wizard" SELECT_FILE = "SELECT FILE" IMPORT_INFORMATION = "IMPORT INFORMATION" ADVANCED = "ADVANCED" BUTTON_CHOOSE_FROM_SERVER = "/*//span[contains(text(),'Verismic server')]/ancestor::div[contains(@class,'Button')]" BUTTON_CHOOSE_FROM_DEVICE = "/*//span[contains(text(),'your device')]/ancestor::div[contains(@class,'Button')]" BUTTON_CONFIGURE_ADVANCED_OPTIONS = "/*//span[contains(text(),'Options')]/ancestor::div[contains(@class,'Button')]" LABEL_SELECT_FILE = "/*//span[text()='SELECT FILE']" LABEL_IMPORT_INFORMATION = "/*//span[text()='IMPORT INFORMATION']" LABEL_ADVANCED = "/*//span[text()='ADVANCED']" def popup_body(self): locator = self._set_popup(self.CREATE_UPDATE_WIZARD) cond = self._wait_for_element_present(locator) return str(locator) if cond else None def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) def click_button_next(self): self._click_button_next(self.popup_body()) def click_button_previous(self): self._click_button_previous(self.popup_body()) def click_button_finish(self): self._click_button_finish(self.popup_body()) def click_button_choose_installer_on_sever(self): self._click_element(self.BUTTON_CHOOSE_FROM_SERVER) def click_button_configure_advanced_options(self): self._click_element(self.BUTTON_CONFIGURE_ADVANCED_OPTIONS) def check_popup_is_presented(self): cond = self._wait_for_element_present(self.popup_body()) self.logger.critical( "Popup HAS NO title name. Add titile '" + self.CREATE_UPDATE_WIZARD + "'!!!") msg_true = "Popup '" + self.CREATE_UPDATE_WIZARD + "' is presented" msg_false = "Popup '" + self.CREATE_UPDATE_WIZARD + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def check_select_file_tab_is_presented(self): cond = self._wait_for_element_present(self.popup_body() + self.LABEL_SELECT_FILE + BaseElements.BLACK_COLOR) msg_true = "Tab '" + self.SELECT_FILE + "' is presented" msg_false = "Tab '" + self.SELECT_FILE + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def check_import_information_tab_is_presented(self): cond = self._wait_for_element_present(self.popup_body() + self.LABEL_IMPORT_INFORMATION + BaseElements.BLACK_COLOR) msg_true = "Tab '" + self.IMPORT_INFORMATION + "' is presented" msg_false = "Tab '" + self.IMPORT_INFORMATION + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def check_advanced_tab_is_presented(self): cond = self._wait_for_element_present(self.popup_body() + self.LABEL_ADVANCED + BaseElements.BLACK_COLOR) msg_true = "Tab '" + self.ADVANCED + "' is presented" msg_false = "Tab '" + self.ADVANCED + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False class InstallersPopup(BasePopup): INSTALLERS = "Installers" def popup_body(self): locator = self._set_popup(self.INSTALLERS) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self.popup_body() msg_true = "Popup '" + self.INSTALLERS + "' is presented" msg_false = "Popup '" + self.INSTALLERS + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_ok(self): self._click_button_ok(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) class AdvancedEditorPopup(BasePopup): ADVANCED_EDITOR = "Advanced Editor" PRE_REQUISITES = "Pre-Requisites" LABEL_PRE_REQUISITES = "/*//span[contains(text(),'Pre-Requisites')][contains(@class,'ListItemLabel')]" + BaseElements.LABEL LABEL_INFORMATION = "/*//span[contains(text(),'Information')][contains(@class,'ListItemLabel')]" + BaseElements.LABEL LABEL_COMPONENTS = "/*//span[contains(text(),'Components')][contains(@class,'ListItemLabel')]" + BaseElements.LABEL TAB_PRE_REQUISITES = "/*//span[contains(text(),'Pre-Requisites')][@dir='LTR']" + BaseElements.TAB TAB_INFORMATION = "/*//span[contains(text(),'Information')][@dir='LTR']" + BaseElements.TAB TAB_COMPONENTS = "/*//span[contains(text(),'Components')][@dir='LTR']" + BaseElements.TAB def popup_body(self): locator = self._set_popup(self.ADVANCED_EDITOR) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_ok(self): self._click_button_ok(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) def click_button_add(self): self._click_button_add(self.popup_body()) def click_button_edit(self): self._click_button_edit(self.popup_body()) def click_button_delete(self): self._click_button_delete(self.popup_body()) def click_infromation_label(self): self._click_element(self.LABEL_INFORMATION) def click_pre_requisites_label(self): self._click_element(self.LABEL_PRE_REQUISITES) def click_components_label(self): self._click_element(self.LABEL_COMPONENTS) def click_first_row_in_table(self): table_row = self._set_popup_table_body(self.popup_body()) + "/*//tr[1]" self._click_element(table_row) def select_first_row_in_table(self): table_row = self._set_popup_table_body(self.popup_body()) + "/*//tr[1]" cond = self._wait_for_element_present(table_row) if cond: self.click_first_row_in_table() return True else: self.logger.info("NO rows in the tab table") return False def select_patch_in_table(self, name): table_row = self._set_popup_table_body(self.popup_body()) + "/*//tr/*//span[text()='" + name + "']/ancestor::tr" self._click_element(table_row) self._wait_for_element_selected(table_row) def check_popup_is_presented(self): cond = self.popup_body() msg_true = "Popup '" + self.ADVANCED_EDITOR + "' is presented" msg_false = "Popup '" + self.ADVANCED_EDITOR + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def check_tab_pre_requisites_is_presented(self): cond = self._wait_for_element_selected(self.LABEL_PRE_REQUISITES) msg_true = "Tab '" + self.PRE_REQUISITES + "' is presented" msg_false = "Tab '" + self.PRE_REQUISITES + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def check_tab_information_is_presented(self): cond = self._wait_for_element_selected(self.LABEL_INFORMATION) msg_true = "Tab '" + self.PRE_REQUISITES + "' is presented" msg_false = "Tab '" + self.PRE_REQUISITES + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def check_tab_components_is_presented(self): cond = self._wait_for_element_selected(self.LABEL_COMPONENTS) msg_true = "Tab '" + self.PRE_REQUISITES + "' is presented" msg_false = "Tab '" + self.PRE_REQUISITES + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def check_first_row_is_selected(self): table_row = self._set_popup_table_body(self.popup_body()) + "/*//tr[1]" cond = self._wait_for_element_selected(table_row) return True if cond else False def check_patch_is_presented(self, name): table_row = self._set_popup_table_body(self.popup_body()) + "/*//tr/*//span[text()='" + name + "']/ancestor::tr" cond = self._wait_for_element_present(table_row) return True if cond else False def check_patch_is_selected(self, name): table_row = self._set_popup_table_body(self.popup_body()) + "/*//tr/*//span[text()='" + name + "']/ancestor::tr" cond = self._wait_for_element_selected(table_row) return True if cond else False class SelectInstallMediaPopup(BasePopup): SELECT_INSTALL_MEDIA = "Select Install Media" def popup_body(self): locator = self._set_popup(self.SELECT_INSTALL_MEDIA) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self.popup_body() msg_true = "Popup '" + self.SELECT_INSTALL_MEDIA + "' is presented" msg_false = "Popup '" + self.SELECT_INSTALL_MEDIA + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_ok(self): self._click_button_ok(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) class SelectPreRequisitesPopup(BasePopup): SELECT_PRE_REQUISITES = "Select Pre-Requisites" def popup_body(self): locator = self._set_popup(self.SELECT_PRE_REQUISITES) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self.popup_body() msg_true = "Popup '" + self.SELECT_PRE_REQUISITES + "' is presented" msg_false = "Popup '" + self.SELECT_PRE_REQUISITES+ "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_ok(self): self._click_button_ok(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) class ComponentPopup(BasePopup): COMPONENT = "Component" BUTTON_EDIT_FILTERS = "/*//span[text()='Edit Filters']/ancestor::div[contains(@class,'Button')]" BUTTON_EDIT_DETECTORS = "/*//span[text()='Edit Detectors']/ancestor::div[contains(@class,'Button')]" BUTTON_EDIT_DEPLOYMENTS = "/*//span[text()='Edit Deployments']/ancestor::div[contains(@class,'Button')]" BUTTON_VIEW_DETAILS = "/*//span[text()='View Details']/ancestor::div[contains(@class,'Button')]" def popup_body(self): locator = self._set_popup(self.COMPONENT) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self.popup_body() msg_true = "Popup '" + self.COMPONENT + "' is presented" msg_false = "Popup '" + self.COMPONENT + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_ok(self): self._click_button_ok(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) def click_button_edit_filters(self): self._click_element(self.popup_body() + self.BUTTON_EDIT_FILTERS) def click_button_edit_detectors(self): self._click_element(self.popup_body() + self.BUTTON_EDIT_DETECTORS) def click_button_edit_deployments(self): self._click_element(self.popup_body() + self.BUTTON_EDIT_DEPLOYMENTS) def click_button_view_details(self): self._click_element(self.popup_body() + self.BUTTON_VIEW_DETAILS) class FiltersPopup(BasePopup): FILTERS = "Filters" def popup_body(self): locator = self._set_popup(self.FILTERS) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self.popup_body() msg_true = "Popup '" + self.FILTERS + "' is presented" msg_false = "Popup '" + self.FILTERS + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_ok(self): self._click_button_ok(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) class ExistingSoftwareUpdateDetectionPopup(BasePopup): EXISTING_SOFTWARE_UPDATE_DETECTION = "Existing Software Update Detection" def popup_body(self): locator = self._set_popup(self.EXISTING_SOFTWARE_UPDATE_DETECTION) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self.popup_body() msg_true = "Popup '" + self.EXISTING_SOFTWARE_UPDATE_DETECTION + "' is presented" msg_false = "Popup '" + self.EXISTING_SOFTWARE_UPDATE_DETECTION + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_ok(self): self._click_button_ok(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) class DeploymentsPopup(BasePopup): DEPLOYMENTS = "Deployments" INSTALLER_FILES = "Installer Files" INSTALL_COMMANDS = "Install Commands" UNINSTALL_COMMANDS = "Uninstall Commands" BUTTON_EDIT_COMMANDS = "/*//span[text()='Edit Commands']/ancestor::div[contains(@class,'Button')]" LABEL_INSTALLER_FILES = "/*//span[contains(text(),'Installer Files')][contains(@class,'ListItemLabel')]" \ + BaseElements.LABEL LABEL_INSTALL_COMMANDS = "/*//span[contains(text(),'Install Commands')][contains(@class,'ListItemLabel')]" \ + BaseElements.LABEL LABEL_UNINSTALL_COMMANDS = "/*//span[contains(text(),'Uninstall Commands')][contains(@class,'ListItemLabel')]" \ + BaseElements.LABEL TAB_INSTALLER_FILES = "/*//span[contains(text(),'Installer Files')][@dir='LTR']" + BaseElements.TAB TAB_INSTALL_COMMANDS = "/*//span[contains(text(),'Install Commands')][@dir='LTR']" + BaseElements.TAB TAB_UNINSTALL_COMMANDS = "/*//span[contains(text(),'Uninstall Commands')][@dir='LTR']" + BaseElements.TAB def popup_body(self): locator = self._set_popup(self.DEPLOYMENTS) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self.popup_body() msg_true = "Popup '" + self.DEPLOYMENTS + "' is presented" msg_false = "Popup '" + self.DEPLOYMENTS + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_ok(self): self._click_button_ok(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) def click_button_edit_commands(self): self._click_element(self.popup_body() + self.BUTTON_EDIT_COMMANDS) def click_installer_files_label(self): self._click_element(self.LABEL_INSTALLER_FILES) def click_install_commands_label(self): self._click_element(self.LABEL_INSTALL_COMMANDS) def click_uninstall_commands_label(self): self._click_element(self.LABEL_UNINSTALL_COMMANDS) def check_tab_installer_files_is_presented(self): cond = self._wait_for_element_selected(self.LABEL_INSTALLER_FILES) msg_true = "Tab '" + self.INSTALLER_FILES + "' is presented" msg_false = "Tab '" + self.INSTALLER_FILES + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def check_tab_install_commands_is_presented(self): cond = self._wait_for_element_selected(self.LABEL_INSTALL_COMMANDS) msg_true = "Tab '" + self.INSTALL_COMMANDS + "' is presented" msg_false = "Tab '" + self.INSTALL_COMMANDS + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def check_tab_uninstall_commands_is_presented(self): cond = self._wait_for_element_selected(self.LABEL_UNINSTALL_COMMANDS) msg_true = "Tab '" + self.UNINSTALL_COMMANDS + "' is presented" msg_false = "Tab '" + self.UNINSTALL_COMMANDS + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False class InstallCommandsPopup(BasePopup): INSTALL_COMMANDS = "Install Commands" def popup_body(self): locator = self._set_popup(self.INSTALL_COMMANDS) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self.popup_body() msg_true = "Popup '" + self.INSTALL_COMMANDS + "' is presented" msg_false = "Popup '" + self.INSTALL_COMMANDS + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_ok(self): self._click_button_ok(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) class UninstallCommandsPopup(BasePopup): UNINSTALL_COMMANDS = "Uninstall Commands" def popup_body(self): locator = self._set_popup(self.UNINSTALL_COMMANDS) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self.popup_body() msg_true = "Popup '" + self.UNINSTALL_COMMANDS + "' is presented" msg_false = "Popup '" + self.UNINSTALL_COMMANDS + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_ok(self): self._click_button_ok(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) class SupersedingPatchesPopup(BasePopup): SUPERSEDING_PATCHES = "Superseding Patches" def popup_body(self): locator = self._set_popup(self.SUPERSEDING_PATCHES) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self.popup_body() msg_true = "Popup '" + self.SUPERSEDING_PATCHES + "' is presented" msg_false = "Popup '" + self.SUPERSEDING_PATCHES + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_ok(self): self._click_button_ok(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) def click_button_edit(self): self._click_button_edit(self.popup_body()) class SelectSupersedingPatchesPopup(BasePopup): SELECT_SUPERSEDING_PATCHES = "Select Superseding Patches" def popup_body(self): locator = self._set_popup(self.SELECT_SUPERSEDING_PATCHES) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self.popup_body() msg_true = "Popup '" + self.SELECT_SUPERSEDING_PATCHES + "' is presented" msg_false = "Popup '" + self.SELECT_SUPERSEDING_PATCHES + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_ok(self): self._click_button_ok(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) class PatchManagerSettingsPopup(BasePopup): PATCH_MANAGER_SETTINGS = "Patch Manager Settings" def popup_body(self): locator = self._set_popup(self.PATCH_MANAGER_SETTINGS) return str(locator) def check_popup_is_presented(self): cond = self._wait_for_element_present(self.popup_body()) msg_true = "Popup '" + self.PATCH_MANAGER_SETTINGS + "' is presented" msg_false = "Popup '" + self.PATCH_MANAGER_SETTINGS + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) class ManagementTreePopup(BasePopup): MANAGEMENT_TREE = "Management Tree" def popup_body(self): locator = self._set_popup(self.MANAGEMENT_TREE) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self._wait_for_element_present(self.popup_body()) msg_true = "Popup '" + self.MANAGEMENT_TREE + "' is presented" msg_false = "Popup '" + self.MANAGEMENT_TREE + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) def expand_all_lists(self): self._expand_all_lists(self.popup_body() + "/*//div") class ScanSchedulePopup(BasePopup): SCAN_SCHEDULE = "Scan Schedule" BUTTON_SCAN_NOW = "/*//span[text()='Scan Now']/ancestor::div[contains(@class,'Button')]" def popup_body(self): locator = self._set_popup(self.SCAN_SCHEDULE) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self._wait_for_element_present(self.popup_body()) msg_true = "Popup '" + self.SCAN_SCHEDULE + "' is presented" msg_false = "Popup '" + self.SCAN_SCHEDULE + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) def click_button_scan_now(self): self._click_element(self.popup_body() + self.BUTTON_SCAN_NOW) class ImportSoftwareUpdateDefinitionsPopup(BasePopup): IMPORT_SOFTWARE_UPDATE_DEFINITION = "Import Software Update Definitions" BUTTON_UPLOAD = "/*//span[text()='Upload']/ancestor::div[contains(@class,'Button')]" def popup_body(self): locator = self._set_popup(self.IMPORT_SOFTWARE_UPDATE_DEFINITION) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self._wait_for_element_present(self.popup_body()) msg_true = "Popup '" + self.IMPORT_SOFTWARE_UPDATE_DEFINITION + "' is presented" msg_false = "Popup '" + self.IMPORT_SOFTWARE_UPDATE_DEFINITION + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) def click_button_upload(self): self._click_element(self.popup_body() + self.BUTTON_UPLOAD) class GadgetsDirectoryPopup(BasePopup): GADGETS_DIRECTORY = "Gadgets Directory" BUTTON_ADD_IT_NOW = "/*//span[text()='Add it now']/ancestor::div[contains(@class,'Button')]" LABEL_ALL = "/*//div[@class='FlowLayoutPanel-ControlContainer']" \ "/*//span[contains(text(),'All')]/ancestor::div[contains(@class,'Button')]" GADGET_BODY = "/*//div[@class='FlowLayoutPanel-ControlContainer']" GADGET_TITLE = "/*//span[contains(@style,'#0000C0')]" def popup_body(self): locator = self._set_popup(self.GADGETS_DIRECTORY) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def gadget_body(self): locator = self.popup_body() + self.GADGET_BODY return str(locator) def gadget_title(self): locator = self.gadget_body() + self.GADGET_TITLE return str(locator) def check_popup_is_presented(self): cond = self._wait_for_element_present(self.popup_body()) msg_true = "Popup '" + self.GADGETS_DIRECTORY + "' is presented" msg_false = "Popup '" + self.GADGETS_DIRECTORY + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) def click_button_close(self): self._click_button_close(self.popup_body()) def click_button_add_it_now(self): self._click_element(self.gadget_body() + self.BUTTON_ADD_IT_NOW) def click_label_all(self): self._click_element(self.popup_body() + self.LABEL_ALL) def select_all_gadgets(self): self.click_label_all() gadgets_list = [] # self._wait_for_all_elements_present(self.popup_body() + self.BUTTON_ADD_IT_NOW) elements = self._find_elements(self.gadget_body() + self.BUTTON_ADD_IT_NOW) for element in elements: gadget_title = self._get_text(self.popup_body() + self.GADGET_TITLE) gadgets_list.append(gadget_title) element.click() print gadgets_list print len(gadgets_list) class CreateNewDashboardPopup(BasePopup): CREATE_NEW_DASHBOARD = "Create New Dashboard" BUTTON_ADD_GADGETS = "/*//span[text()='Add gadgets']/ancestor::div[contains(@class,'Button')]" FIELD_NAME = "/*//input" FIELD_DESCRIPTION = "/*//textarea" def popup_body(self): locator = self._set_popup(self.CREATE_NEW_DASHBOARD) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self.popup_body() msg_true = "Popup '" + self.CREATE_NEW_DASHBOARD + "' is presented" msg_false = "Popup '" + self.CREATE_NEW_DASHBOARD + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond is not None else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_previous(self): self._click_button_previous(self.popup_body()) def click_button_next(self): self._click_button_next(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) def click_button_finish(self): self._click_button_finish(self.popup_body()) def click_button_add_gadgets(self): self._click_element(self.popup_body() + self.BUTTON_ADD_GADGETS) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) def enter_text_into_name_text_field(self, name): self._find_element(self.popup_body() + self.FIELD_NAME).send_keys(name) def clear_text_name_text_field(self): self._find_element(self.popup_body() + self.FIELD_NAME).clear() class DashboardConfigPopup(BasePopup): DASHBOARD_CONFIG = "Dashboard Config" BUTTON_OPEN = "/*//span[text()='Open']/ancestor::div[contains(@class,'Button')]" FIELD_NAME = "/*//input" FIELD_DESCRIPTION = "/*//textarea" def popup_body(self): locator = self._set_popup(self.DASHBOARD_CONFIG) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self.popup_body() msg_true = "Popup '" + self.DASHBOARD_CONFIG + "' is presented" msg_false = "Popup '" + self.DASHBOARD_CONFIG + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond is not None else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_previous(self): self._click_button_next(self.popup_body()) def click_button_next(self): self._click_button_previous(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) def click_button_finish(self): self._click_button_finish(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) def enter_text_into_name_text_field(self, name): self._find_element(self.popup_body() + self.FIELD_NAME).send_keys(name) class ReportSchedlulerPopup(BasePopup): REPORT_SCHEDULER = "Report Scheduler" FIELD_NAME = "/*//input" def popup_body(self): locator = self._set_popup(self.REPORT_SCHEDULER) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self.popup_body() msg_true = "Popup '" + self.REPORT_SCHEDULER + "' is presented" msg_false = "Popup '" + self.REPORT_SCHEDULER + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond is not None else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_previous(self): self._click_button_next(self.popup_body()) def click_button_next(self): self._click_button_previous(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) def click_button_finish(self): self._click_button_finish(self.popup_body()) def click_button_open_data_range(self): self._click_button_open(self.popup_body() + "/*//div[@class='FlowLayoutPanel-Control']") def click_button_open_management_tree(self): self._click_button_open(self.popup_body() + "/*//div[@class='Label-Control']") def click_system_button_close(self): self._click_system_button_close(self.popup_body()) def enter_text_into_name_text_field(self, name): self._find_element(self.popup_body() + self.FIELD_NAME).send_keys(name) class SavedDateRangesPopup(BasePopup): SAVED_DATE_RANGES = "Saved date ranges" def popup_body(self): locator = self._set_popup(self.SAVED_DATE_RANGES) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self.popup_body() msg_true = "Popup '" + self.SAVED_DATE_RANGES + "' is presented" msg_false = "Popup '" + self.SAVED_DATE_RANGES + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_ok(self): self._click_button_ok(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) def click_button_add(self): self._click_button_add(self.popup_body()) class BaselinePopup(BasePopup): BASELINE = "Baseline" def popup_body(self): locator = self._set_popup(self.BASELINE) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self.popup_body() msg_true = "Popup '" + self.BASELINE + "' is presented" msg_false = "Popup '" + self.BASELINE + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_ok(self): self._click_button_ok(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) def click_button_add(self): self._click_button_add(self.popup_body()) class QueriesPopup(BasePopup): QUERIES = "Queries" def popup_body(self): locator = self._set_popup(self.QUERIES) cond = self._wait_for_element_present(locator) return str(locator) if cond else False def check_popup_is_presented(self): cond = self._wait_for_element_present(self.popup_body()) msg_true = "Popup '" + self.QUERIES + "' is presented" msg_false = "Popup '" + self.QUERIES + "' is NOT present" self._set_log_for_true_or_false(cond, msg_true, msg_false) return True if cond else False def click_icon_help(self): self._click_icon_help(self.popup_body()) def click_button_ok(self): self._click_button_ok(self.popup_body()) def click_button_cancel(self): self._click_button_cancel(self.popup_body()) def click_system_button_close(self): self._click_system_button_close(self.popup_body()) def click_button_new(self): self._click_button_new(self.popup_body())
# -*- coding: utf-8 -*- """ Created on Thu Mar 3 18:42:45 2016 Cache class to store a specified number of data elements in memory to reduce loading time from DB @author: alex """ import time import copy """ Basic Cache FIFO - Max Length Cache """ class BasicCache(object): """ Initialization Function :max_leng: The maximum length of the cache """ def __init__(self, max_leng, logging): self.max_length = max_leng self.data = {} self.log = logging """ Add An Object & Key to the cache :key: The Key :obj: The Data Object """ def add(self, key, obj): self.data[key] = obj # if len(self.data) > self.max_length: # key_list = list(self.data) # del self.data[key_list[self.max_length]] """ Get an object from the cache :key: The key for the object """ def get(self, key): resp = None try: resp = self.data[key] except Exception as e: self.log.debug(e) return resp """ Clear the Cache """ def clear(self): self.data.clear() """ The number of elements in the Cache """ def size(self): return len(self.data) """ Advanced Cache FIFO - Max Length & Max Duration Cache """ class AdvancedCache(object): """ Initialization Function :max_leng: The maximum length of the cache :dur: The maximum duration of an object in the cache """ def __init__(self, max_leng, dur, logging): self.max_length = max_leng self.duration = dur self.data = {} self.log = logging """ Add An Object & Key to the cache :key: The Key :obj: The Data Object """ def add(self, key, obj): self.data[key] = [obj, time.time()] # if len(self.data) > self.max_length: # key_list = list(self.data) # del self.data[key_list[self.max_length]] """ Get an object from the cache :key: The key for the object """ def get(self, key): return self.data[key][0] self.data[key][1] = time.time() """ Clear the Cache """ def clear(self): self.data.clear() def has_key(self, in_key): if in_key in self.data: return True return False """ The number of elements in the Cache """ def size(self): return len(self.data) def find_oldest_value(self): self.log.debug('Find Oldest Value Initialized') count=0 oldest_key = None for key, value in self.data.iteritems(): count+=1 if count == 0: oldest_key = key self.log.debug('First element used with key %s and time %s' % (key, self.data[oldest_key][1])) else: tm = time.time() - value[1] self.log.debug('element comparison started with tm = %s' % (tm)) old_tm = time.time() - self.data[oldest_key][1] if old_tm > tm: self.log.debug('New oldest element added with key = %s' % (key)) oldest_key = key return oldest_key """ Cull the Cache Clean out objects that have been in the cache past the max duration Add the values being culled to the removed list for writing to the DB """ def cull_cache(self, removed_list): self.log.debug('Cull Cache Initialized') new_cache = None #Test for max length if len(self.data) > self.max_length: new_cache = {} self.log.debug('Max length checks initialized, building new_cache from None') oldest_key = None count=0 #Compare each value in the cache with the oldest object in the #new cache. If it's newer, add it to the new cache. If we #are at the limit, then remove the oldest key and find the #next oldest key for key, value in self.data.iteritems(): count+=1 if count == 0: new_cache[key] = value oldest_key = key else: old_time = self.data[oldest_key][1] new_time = value[1] if abs(new_time) < abs(old_time): new_cache[key] = value if len(new_cache) > self.max_length: removed_list.append(new_cache[oldest_key]) del new_cache[oldest_key] oldest_key = self.find_oldest_value() else: self.log.debug('Pull up a deep copy of the cache dictionary') new_cache = copy.deepcopy(self.data) #Test for max duration self.log.debug('Tests for max duration') for key, value in self.data.iteritems(): self.log.debug('') sec = value[1] if key in new_cache: self.log.debug('Key %s found in new cache' % (key)) #Test the current time - the recorded time against the duration self.log.debug('Starting compare with current time %s, data input time %s, and duration %s' % (time.time(), sec, self.duration)) if abs(time.time() - sec) > self.duration: removed_list.append(new_cache[key]) del new_cache[key] self.log.debug('Re-assign the cache dictionary') self.data = new_cache
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @author = 'wyx' @time = 16/5/25 14:07 @annotation = '' """ debug = True encoding = 'utf8' # MySQL配置 db_config = { "db_reader": {"host": "192.168.1.20", "port": 13306, "db": "statics", "user": "bulu", "passwd": "123456", "charset": encoding}, "db_writer": {"host": "192.168.1.20", "port": 13306, "db": "statics", "user": "bulu", "passwd": "123456", "charset": encoding}, } # lostash配置output connection_string = "jdbc:mysql://192.168.1.20:13306/statics?user=bulu&password=123456&useSSL=false" pool_coroutine_mode = True pool_log = "pool-log" db_conn_pool_size = (3, 10) db_connection_idle = 60 db_pool_clean_interval = 1000 db_query_log = "query-log" log_config = [ ["pool-log", "pool.log", "debug"], ["query-log", "query.log", "debug"], ]
from setuptools import setup import sys APP = ['gierzwaluw/gui.py'] DATA_FILES = [('static', ['static/swallow.png', 'static/index.html'])] MAC_OPTIONS = { 'argv_emulation': True, 'iconfile':'static/swallow.icns', 'plist': { "LSUIElement": True, }, } WIN_OPTIONS = {} options = {} if sys.platform == 'darwin': import py2app options.update({ 'options': {'py2app': MAC_OPTIONS}, 'app': APP, }) if sys.platform == 'win32': import py2exe options.update({ 'options': {'py2exe': WIN_OPTIONS}, 'windows': [{ "script": 'gierzwaluw/gui.py', "icon_resources": [(0, "static/swallow.ico")], "dest_base" : "Gierzwaluw" }], }) setup( name="Gierzwaluw", packages=['gierzwaluw'], scripts=['gierzwaluw/gui.py', 'gierzwaluw/cli.py'], data_files=DATA_FILES, **options )
import urllib import urllib2 import re import os from BeautifulSoup import BeautifulSoup base_url = 'http://comment.rsablogs.org.uk/videos/page/' def open_page(url): ''' Returns the contents of a page as a string ''' # Fool the page into thinking it's a request from Firefox on Windows user_agent='Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3' # Open a request URL object (which is what we'll use to get the page) req = urllib2.Request(url) # Tell the object to use the user agent req.add_header('User_Agent', user_agent) # Open the URL with the urlopen method response = urllib2.urlopen(req) # Read the response output = response.read() response.close() return output.decode('ascii', 'ignore') def scrape_site(contents): ''' Scrapes the RSA Animate Video site Returns an array of dictionaries ''' output = [] # Using BeautifulSoup to parse the HTML soup = BeautifulSoup(str(contents)) # All the H3s on the page appear to be video titles, let get the title string from each one posts = soup.findAll('div', 'post') for post in posts: # Clean titles title = post.h3.a.string # Remove Unicode characters title = re.sub('&#8211; ', '', title) # Remove the unneccessary prefix title = re.sub('RSA Animate', '', title) # Remove white space title = title.lstrip(' ') # Get the dates date = post.find('p', 'postmetadata').find('span', 'alignleft') # Get the Youtube URLs ifram = (post.findAll('p')[1]).find('iframe') if ifram is not None: url = ifram["src"] if url.startswith("//www.youtube.com/"): url = "http:" + url else: obj = post.findAll('p')[1].find('object') for param in obj.findAll("param"): if param["name"] in ["movie", "src"]: url = param["value"] if url is not None and url.startswith("http://www.youtube.com/"): final_title = title + ' (' + date.string + ')' output.append({'title':final_title, 'url':url}) return output if __name__ == '__main__': contents = open_page(base_url + '1') print scrape_site(contents)
import numpy as np import datetime from scipy.special import gamma # References: # [1] S. Sra, D. Karp, The multivariate Watson distribution: # Maximum-likelihood estimation and other aspects, # Journal of Multivariate Analysis 114 (2013) 256-269 def pdf(X, mu, kappa): """Evaluates the pdf defined from a Watson distribution Parameters ---------- X: Points to evaluate the pdf in with shape (N, p), where N is number of points and p is dimensionality mu: Mean kappa: Concentration """ (N, p) = X.shape cp = gamma(p/2) / (2*np.pi**(p/2) * (kummer(1/2, p/2, kappa))) return cp * np.exp(kappa * np.einsum('i,ji->j', mu, X)**2) def wmm_pdf(X, Mu, Kappa, Pi): """Evaluates the pdf defined from a mixture of Watson distributions Parameters ---------- X: Points to evaluate the pdf in with shape (N, p), where N is number of points and p is dimensionality Mu: List of means Kappa: List of concentration Pi: List of priors """ return np.sum([pi * pdf(X, mu, kappa) for mu, kappa, pi in zip(Mu, Kappa, Pi)], axis=0) def wmm_fit(X, k, maxiter=200, tol=1e-4, verbose=False, seed=None, init=None, return_steps=False, gamma=0): """Fits a mixture of Watsons Parameters ---------- X: Data to base the model on with shape (N, p), where N is number of points and p is dimensionality k: Number of kernels init: How to initialize the model. "random" for random initialization "spiral" for initialization based on golden spiral method (only works for 3d) a dict with keys 'mu', 'kappa', 'pi' for another predetermined initialization """ np.random.seed(seed) # Get dimensions (N, p) = X.shape # Initialization if isinstance(init, dict): mu = init['mu'].copy() kappa = init['kappa'].copy() pi = init['pi'].copy() elif isinstance(init, str) and init.lower() == 'spiral': assert p == 3 mu, kappa, pi = golden_spiral_init(k) elif isinstance(init, str) and init.lower() == 'random': mu, kappa, pi = random_init(k, p) else: if p == 3: mu, kappa, pi = golden_spiral_init(k) else: mu, kappa, pi = random_init(k, p) # Allocation llh = np.zeros((maxiter)) Mu = np.zeros((maxiter, ) + mu.shape) Kappa = np.zeros((maxiter, ) + kappa.shape) Bounds = np.zeros((maxiter, ) + kappa.shape + (3, )) Pi = np.zeros((maxiter, ) + pi.shape) iter = 0 converged = -1 # EM loop while converged < 0: beta, llh[iter] = e_step(X, mu, kappa, pi, k, p) mu, kappa, pi, bounds = m_step(X, mu, beta, k, N, p, gamma) converged = convergence(llh, iter, maxiter, tol, verbose) Mu[iter] = mu Kappa[iter] = kappa Bounds[iter] = bounds Pi[iter] = pi iter += 1 llh = llh[:converged+1] if return_steps: Mu = Mu[:converged+1] Kappa = Kappa[:converged+1] Bounds = Bounds[:converged+1] Pi = Pi[:converged+1] return Mu, Kappa, Pi, llh, Bounds return Mu[converged], Kappa[converged], Pi[converged], llh, Bounds[converged] def random_init(k, p): # Randomly initialize mu mu = np.random.normal(size=(k, p)) mu = mu/np.linalg.norm(mu, axis=1)[:, np.newaxis] # Initalize kappa and pi kappa = np.ones(k) pi = np.ones(k)/k return mu, kappa, pi def golden_spiral_init(k): # Initialise mu based on "The golden spiral method" https://stackoverflow.com/a/44164075/6843855 indices = np.arange(0, k, dtype=float) + 0.5 phi = np.arccos(1 - 2*indices/(2*k)) theta = np.pi * (1 + 5**0.5) * indices mu = np.stack((np.cos(theta) * np.sin(phi), np.sin(theta) * np.sin(phi), np.cos(phi)), axis=1) # Initalize kappa and pi kappa = np.ones(k) pi = np.ones(k)/k return mu, kappa, pi def e_step(X, mu, kappa, pi, k, p): # Expectation num = np.zeros((X.shape[0], k)) for j in range(k): # For each component cp = gamma(p/2) / (2*np.pi**(p/2) * (kummer(1/2, p/2, kappa[j]))) # Uses Watson distribution (2.1) [1], compute using 4.3 [1] num[:, j] = pi[j] * cp * np.exp(kappa[j] * np.einsum('i,ji->j', mu[j, :], X)**2) beta = num/np.sum(num, axis=1)[:, np.newaxis] llh = np.sum(np.log(np.sum(num, axis=1))) return beta, llh def m_step(X, mu, beta, k, N, p, gamma): bounds = np.zeros((k, 3)) # Maximization kappa = np.zeros(k) pi = np.sum(beta, axis=0)/N for j in range(k): # For each component # Compute Sj (4.5) Sj = np.einsum('i,ij,ik->jk', beta[:, j], X, X, optimize='greedy') / np.sum(beta[:, j]) # Compute mu using (4.4) [1], ignoring negative kappa case [w, v] = np.linalg.eig(Sj) idx = np.argmax(w) mu[j, :] = np.real(v[:, idx]) # Compute Kappa using (4.5) [1] r = np.real(w[idx]) r = 0.99 if r > 0.999 else r bounds[j, :] = [lower_bound(1/2, p/2, r), bound(1/2, p/2, r), upper_bound(1/2, p/2, r)] # Reguralize bounds = bounds + gamma*(bounds.mean(axis=0) - bounds) kappa = bounds[:, 1] return mu, kappa, pi, bounds def convergence(llh, iter, maxiter, tol, verbose): # Convergece if iter > 0: print_t('Iteration: {:d}, llh: {:.2g}, relative llh change: {:.2g}'.format(iter+1, llh[iter], (llh[iter] - llh[iter-1])/abs(llh[iter-1])), verbose) else: print_t('Iteration: {:d}, llh: {:.2g}'.format(iter+1, llh[iter]), verbose) if iter > 0 and (llh[iter] - llh[iter-1])/abs(llh[iter-1]) < tol: if llh[iter] - llh[iter-1] > 0: print_t('Conveged in {} iterations'.format(iter+1), verbose) return iter else: print_t('Conveged in {} iterations (Igoring iteration after maximum was reached)'.format(iter+1), verbose) return iter-1 elif iter >= maxiter-1: print_t('Did not converge in maximum iterations') return iter return -1 # Definition of bounds solutions for Kappa (3.7)(3.8)(3.9) [1] def lower_bound(a, c, r): return (r*c-a)/(r*(1-r))*(1+(1-r)/(c-a)) def bound(a, c, r): return (r*c-a)/(2*r*(1-r))*(1+np.sqrt(1+(4*(c+1)*r*(1-r)) / (a*(c-a)))) def upper_bound(a, c, r): return (r*c-a)/(r*(1-r))*(1+r/a) def kummer(a, b, kappa, tol=1e-10, return_iter=False): term = a*kappa/b f = 1+term j = 1 while abs(term) > tol: j += 1 a += 1 b += 1 term *= a*kappa/b/j f += term if return_iter: return f, j return f def print_t(s, verbose=True): if verbose: print('{:%H:%M:%S}: {}'.format(datetime.datetime.now(), s))
import matplotlib.pyplot as plt import numpy as np import sys import os from io import StringIO from io import BytesIO import mnist_cnn from PIL import Image from recog.image3 import ImageParser dir = '/home/mhkim/data/images' if os.path.exists(dir) == False : os.mkdir('/home/mhkim/data/images') param = b'testing' 'fewfe' #im = Image.new("RGB", (512,512), "white") img1 = Image.open(os.path.join(dir, 'number_font.png')) # pix = img1.load() img1Width = img1.size[0] - 40 img1Height = img1.size[1] - 20 #len(pix) rate = 28 / img1Height resizeWidth = int(img1Width * rate) resizeHeight = 28 img2 = img1.crop((20, 10 , img1Width, img1Height)) img3 = img2.resize((int(resizeWidth), resizeHeight)) #plt.imshow(img3) #plt.show() position = 1 size = 28 begin = (position - 1) * size test_data = img3.crop(((position - 1) * size, 0, begin + size, 28)) #plt.imshow(test_data) #plt.show() pix = test_data.load() array = [ round(0.2126 * pix[i, j][0] + 0.7152 * pix[i, j][1] + 0.0722 * pix[i, j][2]) for j in range(28) for i in range(28) ] _arr1 = [] _arr2 = [] index = 0 for i in range(len(array)) : num = array[i] if num > 0 : _arr2.append([0]) else : _arr2.append([1]) if (i+1) % 28 == 0: #print ( _arr2) _arr1.append(_arr2) _arr2 = [] #plt.imshow(_arr1) #plt.show() #print ( array ) imageDir = '/home/mhkim/data/images' parser = ImageParser(os.path.join(imageDir, 'number_font.png'), channel=1 , resize=28) images = parser.getImageArray() mnistCnn = mnist_cnn.MnistCnn() for i in range(len(images)): resultValue = mnistCnn.execute([images[i]]) print ( resultValue) #
""" Not yet implemented. added FMC v6.5.0 Appears to only be valid for Firepower 1010 devices. """
# -*- coding: utf-8 -*- import logging import sys from yyfeed.fetcher import * logger = logging.getLogger(__name__) def test_fetcher(fetcher): count = 0 for i, item in enumerate(fetcher.fetch()): logger.info(' -------- [%d] ------[[', i) logger.info(item) logger.info(']]------ [%d] --------', i) count += 1 logger.info('-------- total[%d] --------', count) def main(): test_fetcher(IYingDiFetcher()) # test_fetcher(JandanFetcher(browser='baiduspider')) # test_fetcher(IAppsFetcher()) # test_fetcher(SmzdmFetcher()) # test_fetcher(TtrssFetcher()) # test_fetcher(PoemFetcher()) pass if __name__ == '__main__': logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) logging.getLogger('PIL.Image').setLevel(logging.WARNING) main()
from .funcs import MathFunctions # noqa: F401 from .groups import MultiplicativeGroup # noqa: F401
#TOIMII def isInTriangle(x,y,x1,y1,x2,y2,x3,y3): det = (y2-y3)*(x1-x3)+(x3-x2)*(y1-y3) detPositive = det > 0 l1nodet = (y2-y3)*(x-x3)+(x3-x2)*(y-y3) l2nodet = (y3-y1)*(x-x3)+(x1-x3)*(y-y3) l3nodet = det - l1nodet - l2nodet l1Pos = l1nodet >= 0 l2Pos = l2nodet >= 0 l3Pos = l3nodet >= 0 return (l1Pos == l2Pos == l3Pos == detPositive) #TOIMII def d3determinant(a,b,c,d,e,f,g,h,i): """ [[a,b,c] [d,e,f] [g,h,i]] """ return a*d2determinant(e,f,h,i) - b*d2determinant(d,f,g,i) + c*d2determinant(d,e,g,h) #TOIMII def d2determinant(a,b,c,d): """ [[a,b] [c,d]] """ return (a*d)-(b*c) #TOIMII def solve2x2(x0,y0,x1,y1,x2,y2): """ [[x1,x2] [a, [x0, [y1,y2]] * b] = y0] """ det = d2determinant(x1,x2,y1,y2) a = d2determinant(x0,x2,y0,y2)/det b = d2determinant(x1,x0,y1,y0)/det return (a,b) #TOIMII def solve3x3(x0,y0,z0,x1,y1,z1,x2,y2,z2,x3,y3,z3): """ [[x1,x2,x3] [a, [x0 [y1,y2,y3] * b, = y0 [z1,z2,z3]] c] z0] Solve by Cramer's rule. """ det = d3determinant(x1,x2,x3,y1,y2,y3,z1,z2,z3) a = d3determinant(x0,x2,x3,y0,y2,y3,z0,z2,z3)/det b = d3determinant(x1,x0,x3,y1,y0,y3,z1,z0,z3)/det c = d3determinant(x1,x2,x0,y1,y2,y0,z1,z2,z0)/det return (a,b,c) #TESTAA def ray_hits_triangle(screenpoint,triangle): """ screenpoint = (x,y,z) triangle = ((x,y,z),(x,y,z),(x,y,z)) """ #vector defining line: t = screenpoint #vectors defining plane: u = (triangle[1][0]-triangle[0][0],triangle[1][1]-triangle[0][1],triangle[1][2]-triangle[0][2]) v = (triangle[2][0]-triangle[0][0],triangle[2][1]-triangle[0][1],triangle[2][2]-triangle[0][2]) #plane's origo: o = (triangle[0][0],triangle[0][1],triangle[0][2]) """ input(-o,au,bv,-ct) solve plane = line ct = o + au + bv <=> au + bv + -ct = -o [[-xu,xv,xt] [a, [-xo, <=> [-yu,yv,yt] * b, = -yo, [-zu,zv,zt]] c] -zo,] return (a,b,c) """ #intersection point vector p = solve3x3(-o[0],-o[1],-o[2],u[0],u[1],u[2],v[0],v[1],v[2],-t[0],-t[1],-t[2]) """ solve intersection point vector = nu + mv <=> p = nu + mv <=> [[ux,vx], * [n, = [px, [uy,vy]] m] py] """ planecoords = solve2x2(p[0],p[1],u[0],u[1],v[0],v[1]) return isInTriangle(planecoords[0],planecoords[1],0,0,1,0,0,1)
from artiq.experiment import * import socket import time class TCPIP_LaserFrequency(EnvExperiment): """TCPIP_LaserFrequency""" def build(self): pass def prepare(self): pass def run(self): sk = socket.socket() # 绑定一个ip和端口 # Bind an IP sk.bind(("192.168.0.76",8888)) # 服务器端一直监听是否有客户端进行连接 # listening for the Client sk.listen(5) conn,addr = sk.accept() # 设置光速 # Define the speed of the light C_Chamber=299792.458 # 设置397与866的失谐量标定值 Standard_397=755.222800 Standard_866=346.000280 while 1: #从客户端接收数据 # Recieve the data from the Client rev_data = conn.recv(1024).decode('GB2312') #数据类型为:X Y, X 为激光的参数, Y 为激光的波长 #The data should be like: X Y,X is the number of the laser,Y is nanometer. rev_array = rev_data.split() # 根据收集到的信息来对特定的激光频率赋值 # brodcast the frequency of lasers according to the number of the laser # NA if rev_array[0]=="1": data_nm = float(rev_array[1]) data_frequency = C_Chamber/data_nm self.set_dataset("Laser1", float(format(data_frequency, '.6f')), broadcast=True) # 866 elif rev_array[0]=="2": data_nm = float(rev_array[1]) data_frequency = C_Chamber/data_nm data_deturning = (data_frequency-Standard_866)*10**6 self.set_dataset("Laser2", float(format(data_frequency, '.6f')), broadcast=True) self.set_dataset("Deturning866", float(format(data_deturning, '.0f')), broadcast=True) # 729 elif rev_array[0]=="3": data_nm = float(rev_array[1]) data_frequency = C_Chamber/data_nm self.set_dataset("Laser3", float(format(data_frequency, '.6f')), broadcast=True) # 423 elif rev_array[0]=="4": data_nm = float(rev_array[1]) data_frequency = C_Chamber/data_nm self.set_dataset("Laser4", float(format(data_frequency, '.6f')), broadcast=True) # 397 elif rev_array[0]=="5": data_nm = float(rev_array[1]) data_frequency = C_Chamber/data_nm data_deturning = (data_frequency-Standard_397)*10**6 self.set_dataset("Laser5", float(format(data_frequency, '.6f')), broadcast=True) self.set_dataset("Deturning397", float(format(data_deturning, '.0f')), broadcast=True) # 854 elif rev_array[0]=="6": data_nm = float(rev_array[1]) data_frequency = C_Chamber/data_nm self.set_dataset("Laser6", float(format(data_frequency, '.6f')), broadcast=True) # NA elif rev_array[0]=="7": data_nm = float(rev_array[1]) data_frequency = C_Chamber/data_nm self.set_dataset("Laser7", float(format(data_frequency, '.6f')), broadcast=True) # NA elif rev_array[0]=="8": data_nm = float(rev_array[1]) data_frequency = C_Chamber/data_nm self.set_dataset("Laser8", float(format(data_frequency, '.6f')), broadcast=True) # 设置每个数据的刷新时间 # Set the period for updating time.sleep(0.1) # 服务端给客户端回消息 # Send the message back to the Client to_be_sent_data="1" conn.send(to_be_sent_data.encode('GB2312')) # 关闭socket对象 # Close the socket conn.close()
import unittest from katas.beta.lowest_product_of_4_consecutive_nums import lowest_product class LowestProductTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(lowest_product('123456789'), 24) def test_equals_2(self): self.assertEqual(lowest_product('2345611117899'), 1) def test_equals_3(self): self.assertEqual(lowest_product('2305611117899'), 0) def test_equals_4(self): self.assertEqual(lowest_product('333'), 'Number is too small') def test_equals_5(self): self.assertEqual(lowest_product('1234111'), 4)
import gensim from gensim import corpora from pprint import pprint import pandas as pd import numpy as np import gensim.downloader as api import matplotlib.pyplot as plt # Стандартное импортирование plotly import plotly.plotly as py import plotly.graph_objs as go from plotly.offline import iplot from gensim.utils import simple_preprocess from smart_open import smart_open import os from gensim.models.word2vec import Word2Vec from multiprocessing import cpu_count # Использование cufflinks в офлайн-режиме import cufflinks cufflinks.go_offline() with open("reviews.txt", "r", encoding='utf-8') as file: my_docs = file.readlines() # Tokenize the docs tokenized_list = [simple_preprocess(doc) for doc in my_docs] print(tokenized_list) # Create the Corpus """ # Create gensim dictionary form a single tet file dictionary = corpora.Dictionary(simple_preprocess(line, deacc=True) for line in open('reviews.txt', encoding='utf-8')) #print(dictionary.token2id) mycorpus = [dictionary.doc2bow(doc, allow_update=True) for doc in tokenized_list] #print(mycorpus) #print(mycorpus) word_counts = [[(dictionary[id], count) for id, count in line] for line in mycorpus] #print(word_counts) #for items,value in word_counts[0]: # print(items,value) # Настройка глобальной темы cufflinks cufflinks.set_config_file(world_readable=True, theme='pearl', offline=True) word_counts[0].value.iplot( x = word_counts[0].value # Specify the category ) # Download the models model = Word2Vec.load('model/model.w2v') #sim_words = model.wv.most_similar('intelligence') vocabulary = model.wv.vocab print(vocabulary) #sim_words = model.wv.most_similar('экран') #print(sim_words) """
#!/usr/bin/python # #import inspect_shell # from logging import getLogger, setLoggerClass, FileHandler, Formatter, StreamHandler, INFO from random import seed from sys import argv from time import time from traceback import format_exc from PyQt4 import uic from PyQt4.QtCore import Qt, QTimer from PyQt4.QtGui import QApplication, QCursor, QIntValidator from PyQt4.QtGui import QPushButton, QDesktopWidget, QLabel, QLineEdit, QMainWindow, QSlider from MeshDevice import COLUMNS_DATA, START_TIME from MeshDevice import TICKS_IN_SLOT, TICKS_IN_CYCLE, CYCLES_IN_SUPERCYCLE, CYCLES_IN_MINUTE, MINUTES_IN_HOUR, HOURS_IN_DAY from MeshDevice import CheckerLogger, timeFormat from MeshTestDevice import TestDevice from MeshView import DevicesModel, Column, ColumnAction, FONT_METRICS_CORRECTION MAX_INT = 2 ** 31 - 1 SEED = 0 WINDOW_SIZE = 2.0 / 3 WINDOW_POSITION = (1 - WINDOW_SIZE) / 2 DeviceClass = TestDevice class SeedValidator(QIntValidator): def __init__(self, parent): QIntValidator.__init__(self, -MAX_INT - 1, MAX_INT, parent) def validate(self, inp, pos): return QIntValidator.validate(self, inp, pos) if str(inp).strip() else (self.Acceptable, pos) class SeedLineEdit(QLineEdit): def configure(self): self.setText(str(SEED)) self.setFixedWidth(self.fontMetrics().boundingRect(self.placeholderText()).width() * FONT_METRICS_CORRECTION) self.setValidator(SeedValidator(self)) class ResetButton(QPushButton): def configure(self): self.setFixedWidth(self.fontMetrics().boundingRect(self.text()).width() * (FONT_METRICS_CORRECTION + 0.3)) # Yes, it's a hack on a hack class SpeedSlider(QSlider): minValue = None maxValue = None defaultValue = None speeds = None def configure(self, label, callback = None): self.label = label fontMetrics = self.label.fontMetrics() self.label.setMinimumWidth(max(fontMetrics.boundingRect(text).width() + 2 for (speed, text) in self.speeds)) # Yes, +2 is a hack self.callback = callback self.setMinimum(self.minValue) self.setMaximum(self.maxValue) self.setValue(self.defaultValue) self.valueChanged.connect(self.setValue) def setValue(self, value): QSlider.setValue(self, value) (self.speed, self.text) = self.speeds[value - self.minValue] self.label.setText(self.text) if self.callback: self.callback() def getSpeed(self): return self.speed class TimeSpeedSlider(SpeedSlider): minValue = -13 maxValue = 1 defaultValue = 1 # ToDo 0 speeds = tuple((1000 * 2 ** i / TICKS_IN_CYCLE, '1/%d' % 2 ** i) for i in xrange(-minValue, 0, -1)) + ((1, '1'),) + \ tuple((1000.0 / 2 ** i / TICKS_IN_CYCLE, str(2 ** i)) for i in xrange(1, maxValue)) + ((0, 'max'),) class MoveSpeedSlider(SpeedSlider): minValue = -7 maxValue = 7 defaultValue = 0 speeds = ((0, 'stop'),) + \ tuple((1.0 / 2 ** i, '1/%d' % 2 ** i) for i in xrange(-minValue - 1, 0, -1)) + \ tuple((2 ** i, str(2 ** i)) for i in xrange(0, maxValue + 1)) class TimeLabel(QLabel): def configure(self): self.pittanceStyle = self.styleSheet() def setValue(self, value, pittance = False): self.setText(timeFormat(value)) self.setStyleSheet(self.pittanceStyle if pittance else '') class Mesh(QMainWindow): def __init__(self, *args, **kwargs): QMainWindow.__init__(self, *args, **kwargs) uic.loadUi('Mesh.ui', self) def configure(self): # Setting window size resolution = QDesktopWidget().screenGeometry() width = resolution.width() height = resolution.height() self.setGeometry(width * WINDOW_POSITION, height * WINDOW_POSITION, width * WINDOW_SIZE, height * WINDOW_SIZE) # Configuring widgets self.seedEdit.configure() self.seedEdit.returnPressed.connect(self.reset) self.resetButton.configure() self.resetButton.clicked.connect(self.reset) self.playButton.clicked.connect(self.play) self.playButton.setFocus() self.pauseButton.clicked.connect(self.pause) self.skipTickButton.clicked.connect(lambda: self.skip(1)) self.skipSlotButton.clicked.connect(lambda: self.skip(TICKS_IN_SLOT)) self.skipCycleButton.clicked.connect(lambda: self.skip(TICKS_IN_CYCLE)) self.skipSuperCycleButton.clicked.connect(lambda: self.skip(TICKS_IN_CYCLE * CYCLES_IN_SUPERCYCLE)) self.skipMinuteButton.clicked.connect(lambda: self.skip(TICKS_IN_CYCLE * CYCLES_IN_MINUTE)) self.skipHourButton.clicked.connect(lambda: self.skip(TICKS_IN_CYCLE * CYCLES_IN_MINUTE * MINUTES_IN_HOUR)) self.skipDayButton.clicked.connect(lambda: self.skip(TICKS_IN_CYCLE * CYCLES_IN_MINUTE * MINUTES_IN_HOUR * HOURS_IN_DAY)) self.setRwS(self.rwsCheckBox.checkState()) self.rwsCheckBox.stateChanged.connect(self.setRwS) self.playing = self.skippingTo = None # for TimeSpeedSlider callback self.timeSpeedSlider.configure(self.timeSpeedValueLabel, self.wait) self.moveSpeedSlider.configure(self.moveSpeedValueLabel) self.globalTimeValueLabel.configure() self.statusBar.hide() self.timer = QTimer(self) # Setup logging formatter = Formatter('%(asctime)s %(levelname)s\t%(message)s', '%Y-%m-%d %H:%M:%S') handler = StreamHandler() handler.setFormatter(formatter) rootLogger = getLogger('') rootLogger.addHandler(handler) fileHandler = FileHandler('mesh.log') fileHandler.setFormatter(formatter) rootLogger.addHandler(fileHandler) rootLogger.setLevel(INFO) self.logger = getLogger('Mesh') self.logger.info("Start") # Configure devices setLoggerClass(CheckerLogger) DeviceClass.configure(self.moveSpeedSlider.getSpeed, self) columns = tuple(Column(nColumn, *args) for (nColumn, args) in enumerate(COLUMNS_DATA)) self.devicesModel = DevicesModel(DeviceClass.devices, columns, self) self.devicesTableView.configure(self.devicesModel, self.devicesMapFrame, self.deviceTableViewChangedSample) for column in columns: ColumnAction(column, self.devicesTableView.setColumnHidden, self.columnsMenu) self.devicesMapFrame.configure(DeviceClass.devices, lambda a, b: DeviceClass.relation(a, b).distance, self.devicesModel.getDeviceSelection, self.devicesTableView.selectDevice, self.activeDeviceVisualSample, self.inactiveDeviceVisualSample) for sample in (self.activeDeviceVisualSample, self.inactiveDeviceVisualSample, self.deviceTableViewChangedSample): sample.hide() # Starting up! self.playing = True # will be toggled immediately by pause() self.pause() self.reset() self.show() self.devicesMapFrame.afterShow() # must be performed after show() self.resize(self.width() + self.leftLayout.geometry().height() - self.devicesMapFrame.width(), self.height()) def closeEvent(self, _event): self.logger.info("Close") def getTime(self): return self.time def reset(self): text = str(self.seedEdit.text()).strip() s = int(text) if text else None seed(s) self.logger.info("Reset %s" % s) self.time = START_TIME - 1 # will be +1 at the first tick for device in DeviceClass.devices: device.reset() self.tick(firstTick = True) def play(self): assert not self.playing self.playing = True self.skippingTo = None self.playButton.setEnabled(False) self.pauseButton.setEnabled(True) self.pauseButton.setFocus() self.wait(True, True) def _pause(self): self.timer.stop() self.playing = False self.pauseButton.setEnabled(False) self.playButton.setEnabled(True) def pause(self): assert self.playing self._pause() self.skippingTo = None self.playButton.setFocus() def skip(self, ticksToSkip): def addAndCut(what, by): return (what + by) // by * by self._pause() self.skippingTo = addAndCut(self.time, ticksToSkip) if self.redrawWhileSkipping: self.timer.singleShot(0, self.tick) else: # not redrawing if ticksToSkip > 1: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) while self.time < self.skippingTo: self.tick() self.skippingTo = None self.devicesModel.refresh() self.devicesMapFrame.refresh() if ticksToSkip > 1: QApplication.restoreOverrideCursor() def setRwS(self, state): self.redrawWhileSkipping = bool(state) def wait(self, firstWait = False, start = False): if not self.playing: return now = time() * 1000 if start: self.previousTickTime = now dt = self.timeSpeedSlider.speed else: dt = self.previousTickTime + self.timeSpeedSlider.speed - now if dt > 1: self.timer.singleShot(dt, self.wait) else: self.previousTickTime = now self.tick(firstWait) def tick(self, pittance = False, firstTick = False): self.time += 1 self.globalTimeValueLabel.setValue(self.time, pittance) DeviceClass.fullTick() if self.playing or self.redrawWhileSkipping or firstTick: self.devicesModel.refresh(firstTick) self.devicesMapFrame.refresh() if self.playing: self.timer.singleShot(0, lambda: self.wait(True)) elif self.redrawWhileSkipping: if self.time < self.skippingTo: # redrawWhileSkipping self.timer.singleShot(0, self.tick) else: # done skipping self.skippingTo = None def main(): try: application = QApplication(argv) Mesh().configure() return application.exec_() except KeyboardInterrupt: pass except BaseException: print format_exc() if __name__ == '__main__': main()
# -*- coding: utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def __eq__(self, other): return ( other is not None and self.val == other.val and self.left == other.left and self.right == other.right ) class Solution: def removeLeafNodes(self, root: TreeNode, target: int) -> TreeNode: if root is None: return None return self._removeLeafNodes(root, target) def _removeLeafNodes(self, root: TreeNode, target: int) -> TreeNode: if root.left is not None: root.left = self._removeLeafNodes(root.left, target) if root.right is not None: root.right = self._removeLeafNodes(root.right, target) if root.left is None and root.val == target and root.right is None: return None return root if __name__ == "__main__": solution = Solution() t0_0 = TreeNode(1) t0_1 = TreeNode(2) t0_2 = TreeNode(3) t0_3 = TreeNode(2) t0_4 = TreeNode(2) t0_5 = TreeNode(4) t0_2.right = t0_5 t0_2.left = t0_4 t0_1.left = t0_3 t0_0.right = t0_2 t0_0.left = t0_1 t1_0 = TreeNode(1) t1_1 = TreeNode(3) t1_2 = TreeNode(4) t1_1.right = t1_2 t1_0.right = t1_1 assert t1_0 == solution.removeLeafNodes(t0_0, 2) t2_0 = TreeNode(1) t2_1 = TreeNode(3) t2_2 = TreeNode(3) t2_3 = TreeNode(3) t2_4 = TreeNode(2) t2_1.right = t2_4 t2_1.left = t2_3 t2_0.right = t2_2 t2_0.left = t2_1 t3_0 = TreeNode(1) t3_1 = TreeNode(3) t3_2 = TreeNode(2) t3_1.right = t3_2 t3_0.left = t3_1 assert t3_0 == solution.removeLeafNodes(t2_0, 3) t4_0 = TreeNode(1) t4_1 = TreeNode(2) t4_2 = TreeNode(2) t4_3 = TreeNode(2) t4_2.left = t4_3 t4_1.left = t4_2 t4_0.left = t4_1 t5_0 = TreeNode(1) assert t5_0 == solution.removeLeafNodes(t4_0, 2) t6_0 = TreeNode(1) t6_1 = TreeNode(1) t6_2 = TreeNode(1) t6_0.right = t6_2 t6_0.left = t6_1 t7_0 = None assert t7_0 == solution.removeLeafNodes(t6_0, 1) t8_0 = TreeNode(1) t8_1 = TreeNode(2) t8_2 = TreeNode(3) t8_0.right = t8_2 t8_0.left = t8_1 t9_0 = TreeNode(1) t9_1 = TreeNode(2) t9_2 = TreeNode(3) t9_0.right = t9_2 t9_0.left = t9_1 assert t9_0 == solution.removeLeafNodes(t8_0, 1)
import sqlite3 def loadTables(regionFile, salesFile): regions = open(regionFile, "r") sales = open(salesFile, "r") #create or connect to database conn = sqlite3.connect('Avocado.db') c = conn.cursor() #drop tables c.execute('DROP TABLE IF EXISTS region') c.execute('DROP TABLE IF EXISTS sales') #create new tables c.execute('''CREATE TABLE Region (pmkRegionID int NOT NULL, fldRegionName varchar(64), fldAvgPriceCon smallmoney, fldAvgPriceOrg smallmoney, pfkBestMonConID int, pfkBestMonOrgID int, PRIMARY KEY (pmkRegionID), FOREIGN KEY (pfkBestMonConID) REFERENCES Sales(pmkSalesID), FOREIGN KEY (pfkBestMonOrgID) REFERENCES Sales(pmkSalesID))''') c.execute('''CREATE TABLE Sales (pmkSalesID int NOT NULL, pfkRegionID int NOT NULL, fldAvgPrice smallmoney, fldTotalVolume int, fldMonth tinyint, fldType varchar(64), PRIMARY KEY (pmkSalesID), FOREIGN KEY (pfkRegionID) REFERENCES Region(pmkRegionID))''') #fill region table for line in regions: regionData = line.strip("\n") regionData = regionData.strip() regionData = regionData.split(",") c.execute('INSERT INTO Region VALUES (?, ?, ?, ?, ?, ?)', regionData) #fill sales table for line in sales: saleData = line.strip("\n") saleData = saleData.split(",") c.execute('INSERT INTO Sales VALUES (?, ?, ?, ?, ?, ?)', saleData) #save changes conn.commit() #close connection and files conn.close() regions.close() sales.close()
a, b, c = sorted(map(int, input().split())) print(max(0, c - a - b + 1))
## Logicly group a data and function for reuse ## attributes and methods assosiated with calss # this is a class class Employee: ## this is a constrctore or init method def __init__(self,first,last,pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@company.com' def fullname(self): return '{} {}'.format(self.first,self.last) # this is class instance emp_1 = Employee('Alon','Strikovksy',5000) emp_2 = Employee('Chen','Elakbez',10000) # print (emp_1.email) # print (emp_2.email) #action - call a method print(emp_1.fullname()) print(emp_2.fullname()) # This is the same a above print(Employee.fullname(emp_1)) print(Employee.fullname(emp_2))
#I pledge my honor that I have abided by the Stevens Honor System def month_review(month): if month > 0 and month <= 12: return True else: return False def day_review(month, day): month_list_31days = [1, 3, 5, 7, 8, 10, 12] month_list_30days = [4, 6, 9, 11] month_list_28days = 2 for data in month_list_31days: if month == data: if day >= 1 and day <= 31: return True else: return False for data in month_list_30days: if month == data: if day >= 1 and day <= 30: return True else: return False for data in month_list_28days: if month == data: if day >= 1 and day <= 28: return True else: return False def year_review(year): if len(year) >= 1 and len(year) <= 4: return True else: return False def main(): date = str(input("Enter the date in mm/dd/yyyy format:")) month,day,year = date.split("/") month_valid = month_review(int(month)) day_valid = day_review(int(month),int(day)) year_valid = year_review(year) if month_valid == True and day_valid == True and year_valid == True: print("The date",date,"is valid.") else: print("The date",date,"is not valid.") main()
import numpy as np import matplotlib.pyplot as plt from sympy import * from sympy.parsing.sympy_parser import parse_expr s="-y+sin(x)" z=Symbol("x") w=Symbol("y") F=parse_expr(s) # variables to be read S-> striing of equation # x0,y0 initial condition # xf -> x to stop at it , n-> number of interval slices # output is the graph drawn of the equation x0 = 0 y0 = 1 xf = 10 n = 101 delta=(xf-x0)/(n-1) x = np.linspace ( x0 , xf , n ) y = np.zeros ( [ n ] ) y [ 0 ] = y0 for i in range ( 1 , n ) : y [i]= delta * F.evalf(subs={z:x[i-1], w:y[i-1]})+y[i-1] for i in range ( n ) : print ( x [ i ] , y [ i ] ) plt.plot(x,y,'o') plt.xlabel (" Value of x " ) plt.ylabel (" Value of y " ) plt.title ("Approximate S ol u ti o n with Forward Euler ’ s Method " ) plt.show ( ) #---------------------------------------------------------------------- # # heun.py # # calculate the curve which is the solution to an ordinary differential # equation with an initial value using Heun's method # import math import numpy as np import matplotlib.pyplot as plt from sympy import * from sympy.parsing.sympy_parser import parse_expr s="y" z=Symbol("x") w=Symbol("y") F=parse_expr(s) # variables to be read S-> striing of equation # x0,y0 initial condition # h->stepsize # we will use the differential equation y'(t) = y(t). The analytic solution is y = e^t. def y1(x,y): return F.evalf(subs={z:x, w:y }) def asol(x): return math.exp(x) yasol = np.vectorize(asol) h = 0.5 x0 = 0.0 y0 = 1.0 x = np.arange(0.0, 5.0, h) y = np.zeros(x.size) y[0] = y0 for i in range(1, x.size): y_intermediate = y[i-1] + h*y1(x[i-1],y[i-1]) y[i] = y[i-1] + (h/2.0)*(y1(x[i-1],y[i-1]) + y1(x[i],y_intermediate)) plt.plot(x,y,'r-')
import csv , sys import utils import random def reproducefile(filename): trainpath = 'data/twitter.txt' train_object = open(trainpath, 'w') text2id = {} with open(filename) as f: for line in f: text = line.split('\t') # print(text[0]) assert '.' in text[0] or text[0].strip()=='NaN' assert len(text)==3 # s = text[1] # s1=text[2] s = utils.clarify(text[1]).lower() s1 = utils.clarify(text[2]).lower() slen = len(s.split()) s1len = len(s1.split()) if not text2id.has_key(s) and slen<15 and slen>1: text2id[s] = 1 if not text2id.has_key(s1) and s1len<15 and s1len>1: text2id[s1] = 1 for x in text2id.keys(): train_object.write(x) train_object.close( ) def reproducetest(filename): trainpath = 'data/twitterdata/twitter-test.txt' trainrefer = 'data/twitterdata/twitter-refer.txt' train_object = open(trainpath, 'w') train_object_refer = open(trainrefer, 'w') text2id = {} tests = [] refers = [] with open(filename) as f: for line in f: text = line.split('\t') if len(text)==4: pass else: continue tup = text[2] if int(tup[1])<= int(tup[3])/2: continue s = utils.clarify(text[0]).lower().strip().strip('.') s1 = utils.clarify(text[1]).lower().strip().strip('.') if len(s.split())>15: temp = s s=s1 s1=temp if len(s.split())>15: continue tests.append(s) refers.append(s1) for x,y in zip(tests, refers): train_object.write(x) train_object.write('\n') train_object_refer.write(y) train_object_refer.write('\n') train_object.close() train_object_refer.close() def generate_twitter_test(filename): trainpath = 'data/twitterdata/twitter-test.txt' trainrefer = 'data/twitterdata/twitter-refer.txt' train_object = open(trainpath, 'w') train_object_refer = open(trainrefer, 'w') text2id = {} tests = [] refers = [] test2refer = {} with open(filename) as f: for line in f: text = line.split('\t') if len(text)==4: pass else: continue tup = text[2] if int(tup[1])<= int(tup[3])/2: continue s = utils.clarify(text[0]).lower().strip().strip('.') s1 = utils.clarify(text[1]).lower().strip().strip('.') s1 = s1.replace('#',' ') s = ' '.join(s.split()[:15]) if test2refer.has_key(s): test2refer[s].append(s1) else: test2refer[s] = s1 for x,y in test2refer.items(): train_object.write(x) train_object.write('\n') train_object_refer.write(' # '.join(y)) train_object_refer.write('\n') train_object.close() train_object_refer.close() def transfer2utf(filename): path = 'temp.txt' train_object = open(path, 'w') with open(filename) as f: for line in f: textsss = ''.join([x for x in line if (ord(x)<128 and ord(x)>-1)]) textsss = textsss.decode('utf-8').encode('gb2312') train_object.write(textsss) # train_object.write('\n') train_object.close() if __name__ == "__main__": filename = sys.argv[1] print(filename) transfer2utf(filename) # reproducefile(filename)
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). """This is an empty Pants plugin for the help info extracter test."""
__copyright__ = ''' Copyright (c) 2016 Qualcomm Technologies, Inc. All Rights Reserved. Confidential and Proprietary - Qualcomm Technologies, Inc. ''' import xml.etree.ElementTree import sys import time from optparse import OptionParser class ProcessScopePacketTypeFile: def __init__(self): use = 'usage: %prog [options] arg1 arg2' desc = ("arg1: input xml file " "arg2: output directory for header file" ) parser = OptionParser(usage=use, description=desc) (options, args) = parser.parse_args() if len(args) != 2: parser.error("incorrect number of arguments, need 2 arguments") self.inputXMLFilePath = str(args[0]) self.outputHeaderFilePath = str(args[1]) self.inputXML = 0 self.outputHeaderFile = 0 def openFiles(self): self.inputXML = ( xml.etree.ElementTree.parse(self.inputXMLFilePath).getroot()) self.outputHeaderFile = open(str(self.outputHeaderFilePath) + '/camscope_packet_type.h', 'w') def closeFiles(self): self.outputHeaderFile.close() def run(self): self.openFiles() current_year = time.strftime('%Y') year_str = "" if current_year != '2016': year_str = "-" + current_year copyrightString = ( "//****************************************************************\n" "// Copyright (c) 2016" + year_str + " Qualcomm Technologies, Inc.\n" "// All Rights Reserved.\n" "// Confidential and Proprietary - Qualcomm Technologies, Inc.\n" "//\n" "//****************************************************************\n" "\n" "/*\n" " *****************************************************************\n" " * @file camscope_packet_type.h\n" " * @brief CameraScope Packet Types\n" " * <<DO NOT EDIT: Created at build time>>\n" " * See camscope_packet_type.xml for changes\n" " *****************************************************************\n" " */\n") self.outputHeaderFile.write(copyrightString) self.outputHeaderFile.write('#ifndef __CAMSCOPE_PACKET_TYPE_H__\n' '#define __CAMSCOPE_PACKET_TYPE_H__\n') self.outputHeaderFile.write('#include <stdint.h>\n'); self.outputHeaderFile.write('#include <time.h>\n'); #Write camscope_packet_type enum for enumType in self.inputXML.findall('enum'): self.outputHeaderFile.write('typedef enum {\n') for type in enumType.findall('enumVal'): self.outputHeaderFile.write(' ' + type.get('Value') + ' = ' + type.get('Number') + ',\n') self.outputHeaderFile.write('} ' + enumType.get('Name') + ';\n\n') #Write camscope structs for struct in self.inputXML.findall('struct'): self.outputHeaderFile.write('typedef struct {\n') for variable in struct.findall('var'): self.outputHeaderFile.write(' ' + variable.get('Type') + ' ' + variable.get('Name') + ';\n') self.outputHeaderFile.write('} ' + struct.get('Name') + ';\n\n') self.outputHeaderFile.write('#endif') self.closeFiles() if __name__ == "__main__": scope = ProcessScopePacketTypeFile() scope.run()
from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String from app import db from flask import Blueprint snippet = Blueprint('snippet', __name__) engine = create_engine('sqlite:///database.db', echo=True) db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base = declarative_base() Base.query = db_session.query_property() class Snippet(Base): __tablename__ = 'Snippets' id = db.Column(db.Integer, primary_key=True) content = db.Column(db.String, unique=True) def __init__(self, content=None): self.content = content # Create tables. Base.metadata.create_all(bind=engine)
#!/usr/bin/python # -*- coding: cp936 -*- import os import sqlite3 import re import pandas as pd def importHisClientLoginEventToSQLite(): with sqlite3.connect('C:\sqlite\db\hxdata.db') as db: # ExcelDocument('..\input\营销人员和营业部列表.xlsx') as src: insert_template1 = "INSERT INTO hisclientloginevent " \ "(clientid, logindate, logintime, eventtype, eventmsg) " \ "VALUES (?, ?, ?, ?, ?);" insert_template2 = "INSERT INTO hisclientloginevent " \ "(clientid, logindate, eventmsg) " \ "VALUES (?, ?, ?);" # 清空的数据库遗留的数据(选择) db.execute('DELETE FROM hisclientloginevent;') totalNumberOfRecords = 0 totalNumberOfFiles = 0 inputFolder = '..\hisInput\\tradelogin\\' for root, dirs, files in os.walk(inputFolder): for file_ in files: workbookName = os.path.splitext(file_)[0] sheetName = str(os.path.splitext(file_)[0]) if re.match(r'2019.', file_) is not None: print(file_) df = pd.read_excel(root + file_, sheet_name=sheetName) #print("df Column headings:") #print(df.columns) no = df.iloc[:, 0].size print(no) # 行数 3 totalNumberOfRecords = totalNumberOfRecords + no # for sheet in src: # if sheet.name == 'SQL Results': df1 = None if df.shape[1] == 7: df1 = df[['OperatorID', 'OperateDate', 'OperateTime', 'EventType', 'EventMsg']] # 选取你需要的列数 # 转变operatetime列的类型 df1['OperateDate'] = df1['OperateDate'].astype('str') df1['OperateTime'] = df1['OperateTime'].astype('str') df1['EventType'] = df1['EventType'].astype('str') df1['EventMsg'] = df1['EventMsg'].astype('str') else: if df.shape[1] == 5: df1 = df[['OperatorID', 'OperateDate', 'EventMsg']] # 选取你需要的列数 try: #print('3') if df.shape[1] == 7: print('7') db.executemany(insert_template1, df1.values) # iter_rows() 自动跳过了抬头首行 else: if df.shape[1] == 5: print('5') db.executemany(insert_template2, df1.values) # iter_rows() 自动跳过了抬头首行 totalNumberOfFiles = totalNumberOfFiles + 1 except sqlite3.Error as e: print('2') print(e) db.rollback() else: db.commit() print('total records', totalNumberOfRecords) print('total files', totalNumberOfFiles) # 检查是不是所有的数据都被加载了 #select_stmt = 'SELECT DISTINCT eventno FROM clientloginevent;' #for row in db.execute(select_stmt).fetchall(): #print("importing...", file_) #print("event number:", row) #importHisClientLoginEventToSQLite()
import numpy as np import pandas as pd #read main and meta data appl = pd.read_csv('application_train.csv') bur = pd.read_csv('bureau.csv') ccb = pd.read_csv('credit_card_balance.csv') pos = pd.read_csv('pos_cash_balance.csv') pre = pd.read_csv('previous_application.csv') #create new columns in main data appl ['debt_to_income_ratio'] = appl['AMT_ANNUITY']/appl['AMT_INCOME_TOTAL'] appl ['dur_payments_years'] = appl['AMT_CREDIT']/appl['AMT_ANNUITY'] appl.loc[appl['DAYS_EMPLOYED'] == 365243,'DAYS_EMPLOYED'] = np.nan print(appl) #preprocess and select meta bureau bur = bur[['SK_ID_CURR','CREDIT_DAY_OVERDUE','DAYS_ENDDATE_FACT','AMT_CREDIT_SUM_DEBT','AMT_CREDIT_SUM_OVERDUE','AMT_ANNUITY']] bur['active'] = np.where(bur['DAYS_ENDDATE_FACT']> 0, 1,0) bur = bur.groupby('SK_ID_CURR').mean() bur['active_outer'] = bur['active'].apply(lambda x: 1 if x >0 else 0) bur = bur.drop(['active','DAYS_ENDDATE_FACT'],axis=1) print(bur) #preprocess and selcect meta data credit card balance ccb = ccb[['SK_ID_CURR','SK_DPD_DEF']] ccb = ccb.rename({'SK_DPD_DEF': 'DPD_AVR_REV'}, axis=1) ccb = ccb.groupby('SK_ID_CURR').mean() print(ccb) #preprocess and select meta data POS_cash pos = pos[['SK_ID_CURR','SK_DPD_DEF']] pos = pos.rename({'SK_DPD_DEF': 'DPD_AVR_CASH'}, axis=1) pos = pos.groupby('SK_ID_CURR').mean() print(pos) # preprocess nad select meta data previous_credits pre = pre[['SK_ID_CURR','DAYS_TERMINATION','NAME_CONTRACT_STATUS']] pre = pre.drop(pre[pre.NAME_CONTRACT_STATUS == 'Refused'].index) pre['active'] = np.where(pre['DAYS_TERMINATION'] > 0, 1,0) pre = pre.drop(['DAYS_TERMINATION','NAME_CONTRACT_STATUS'],axis=1) pre = pre.groupby('SK_ID_CURR').mean() pre['active_inner'] = pre['active'].apply(lambda x: 1 if x >0 else 0) del pre['active'] print(pre) #merg to final data result = appl.merge(bur,on='SK_ID_CURR',how='left').merge(ccb ,on='SK_ID_CURR',how='left').merge(pos ,on='SK_ID_CURR',how='left').merge(pre ,on='SK_ID_CURR',how='left') print(result) #save to csv result.to_csv('merged_final.csv',index=False) appl.to_csv('appl.csv', index=False) bur.to_csv('bur.csv') ccb.to_csv('ccb.csv') pos.to_csv('pos.csv') pre.to_csv('pre.csv')
import random import math import game_framework from BehaviorTree import BehaviorTree, SelectorNode, SequenceNode, LeafNode from pico2d import * import world_build_state # zombie Run Speed PIXEL_PER_METER = (10.0 / 0.3) # 10 pixel 30 cm RUN_SPEED_KMPH = 10.0 # Km / Hour RUN_SPEED_MPM = (RUN_SPEED_KMPH * 1000.0 / 60.0) RUN_SPEED_MPS = (RUN_SPEED_MPM / 60.0) RUN_SPEED_PPS = (RUN_SPEED_MPS * PIXEL_PER_METER) # zombie Action Speed TIME_PER_ACTION = 0.5 ACTION_PER_TIME = 1.0 / TIME_PER_ACTION FRAMES_PER_ACTION = 10 animation_names = ['Attack', 'Dead', 'Idle', 'Walk'] class Zombie: images = None font = None def load_images(self): if Zombie.images == None: Zombie.images = {} for name in animation_names: Zombie.images[name] = [load_image("./zombiefiles/female/"+ name + " (%d)" % i + ".png") for i in range(1, 11)] def __init__(self, name='NONAME', x=0, y=0, size=1): self.name = name self.x, self.y = x * PIXEL_PER_METER, y * PIXEL_PER_METER self.size = size if Zombie.font is None: Zombie.font = load_font('ENCR10B.TTF', 16) self.load_images() self.dir = random.random()*2*math.pi # random moving direction self.speed = 0 self.timer = 1.0 # change direction every 1 sec when wandering self.frame = 0 self.build_behavior_tree() def __getstate__(self): state = {'x': self.x, 'y': self.y, 'dir': self.dir, 'name': self.name, 'size': self.size} return state def __setstate__(self, state): self.__init__() self.__dict__.update(state) def wander(self): self.speed = RUN_SPEED_PPS self.timer -= game_framework.frame_time if self.timer < 0: self.timer += 1.0 self.dir = random.random()*2*math.pi return BehaviorTree.SUCCESS def find_player(self): boy = world_build_state.get_boy() distance = (boy.x - self.x)**2 + (boy.y - self.y)**2 if distance < (PIXEL_PER_METER * 10)**2: self.dir = math.atan2(boy.y - self.y, boy.x - self.x) return BehaviorTree.SUCCESS else: self.speed = 0 return BehaviorTree.FAIL def move_to_player(self): self.speed = RUN_SPEED_PPS return BehaviorTree.SUCCESS def build_behavior_tree(self): wander_node = LeafNode("Wander", self.wander) find_player_node = LeafNode("Find Player", self.find_player) move_to_player_node = LeafNode("Move to Player", self.move_to_player) chase_node = SequenceNode("Chase") chase_node.add_children(find_player_node, move_to_player_node) wander_chase_node = SelectorNode("WanderChase") wander_chase_node.add_children(chase_node, wander_node) self.bt = BehaviorTree(wander_chase_node) def get_bb(self): return self.x - 50, self.y - 50, self.x + 50, self.y + 50 def update(self): self.bt.run() self.frame = (self.frame + FRAMES_PER_ACTION * ACTION_PER_TIME * game_framework.frame_time) % FRAMES_PER_ACTION self.x += self.speed * math.cos(self.dir)* game_framework.frame_time self.y += self.speed * math.sin(self.dir)* game_framework.frame_time self.x = clamp(50, self.x, get_canvas_width() - 50) self.y = clamp(50, self.y, get_canvas_height() - 50) def draw(self): tw, th = int(100*self.size), int(100*self.size) if math.cos(self.dir) < 0: if self.speed == 0: Zombie.images['Idle'][int(self.frame)].composite_draw(0, 'h', self.x, self.y, tw, th) else: Zombie.images['Walk'][int(self.frame)].composite_draw(0, 'h', self.x, self.y, tw, th) else: if self.speed == 0: Zombie.images['Idle'][int(self.frame)].draw(self.x, self.y, tw, th) else: Zombie.images['Walk'][int(self.frame)].draw(self.x, self.y, tw, th) Zombie.font.draw(self.x - 30, self.y + 50, self.name, (255, 255, 0)) def handle_event(self, event): pass