def OUTPUT_CALCULATE(): global output if method == 'sigmoid': for i in range(10): output[i] = round(Method.sigmoid(layer[i]), precision) elif method == 'softmax': output = Method.softmax(layer)
def add_call(self, calling_method_node, called_method_node): calling_method = Method.Method(calling_method_node.spelling, calling_method_node.type.spelling, calling_method_node.access_specifier) called_method = Method.Method(called_method_node.spelling, called_method_node.type.spelling, called_method_node.access_specifier) self.__callgraph.call_node(calling_method, called_method)
def main(name): with open(name, "r") as f: parser = XMLParser() for line in f: parser.feed(line) xml = XMLTree(parser.close(), False) M.run(xml.get("files"), xml.get("structure"), xml.get("pages"))
def fromUML(self,json): for uml_attribut in json["attributs"]: if len(uml_attribut)>0: attribut = Attribut() attribut.fromUML(uml_attribut) self.attributs.append(attribut) for uml_method in json["methods"]: method = Method() method.fromUML(uml_method) self.methods.append(method)
def extractFileData(self, path): curClass = Class.Class() for line in fileinput.input([path]): if line.startswith('.class '): if self.pkgpath not in line: continue curClass.setPackage(self.extractPackage(line)) curClass.setName(self.extractClassName(line)) elif line.startswith('.super '): if (self.pkgpath in line): curClass.setParent(self.extractClassName(line)) matches = re.findall("Landroid/app/(.*?)Activity", line) curClass.isController = (len(matches) > 0) elif (line.startswith('.field')): fieldName = line[line.rfind(" ") + 1:line.rfind(":")] curClass.addField(fieldName) if (' public ' in line or ' protected ' in line): curClass.addPublicField(fieldName) elif (line.startswith('.method ')): if ('<init>' in line): curMethod = Method.Method('constructor') else: match = re.findall(".method (.*?)\(", line)[0].split(" ") l = len(re.findall(".method (.*?)\(", line)[0].split(" ")) if l == 3: curMethod = Method.Method(str(match[2])) elif l == 2: curMethod = Method.Method(str(match[1])) elif l == 1: curMethod = Method.Method(str(match[0])) curMethod = Method.Method("Generic") curClass.addMethod(curMethod) elif (";->" in line): if (self.usesField(curClass, line)): #for LCOM fieldName = line[line.rfind(";->") + 3:line.rfind(":")] curMethod.addFieldUsed(fieldName) if fieldName in curClass.getPublicFields(): self.apd = self.apd + 1 else: #for CBO if not curClass.isController and self.refsNonJavaClass( line): objName = line[line.index("L"):line.index(";->")] if not objName == curClass.getName( ) and not self.inSameTree(curClass, objName): curClass.addCoupledObject(objName) self.classes.append(curClass)
def __init__(self): self.sqlite_conn = db.connect("resource/ast.db", check_same_thread=False) self.cursor = self.sqlite_conn.cursor() self.initialDatabase() sql = "select name, className, content from methodinfo " self.methods = [] self.methodNames = [] for methodinfo in self.executequery(sql): self.methods.append(Method(methodinfo)) self.methodNames.append(methodinfo[0]) sql = 'select callMethodName, calledMethodName from methodInvocationinfo' self.invocations = [] for invocation in self.executequery(sql): self.invocations.append(MethodInovation(invocation)) sql = 'select ID,origiMethods, methods from goldSets ' self.goldSet = [] for item in self.executequery(sql): self.goldSet.append(GoldSet(item)) #用于计算距离 self.dic_distance = {} sql = 'select callmethodname, calledmethodname, length from simdistance' for distance in self.executequery(sql): if ((distance[0], distance[1]) in self.dic_distance.keys() == False): self.dic_distance[distance[0], distance[1]] = np.power(0.7, distance[2])
def parse_method(diagram, method, order_num, colorstring, master_component): print("parse method: " + method.attrib["label"]) if "order_number" in method.attrib: current_method_order_num = int(method.attrib["order_number"]) else: current_method_order_num = order_num if "id" in method.attrib: current_method_id = method.attrib["id"] else: current_method_id = "noid" new_method = me.Method(label=method.attrib["label"], order_number=current_method_order_num, method_id=current_method_id) master_component.add_method(new_method) diagram.add_method(new_method)
def add_method(self, method_node, is_pure_virtual, is_static): method = Method.Method(method_node.spelling, method_node.type.spelling, method_node.access_specifier) self.__callgraph.add_node(method, is_pure_virtual) if is_static: self.__static_methods += 1 if method_node.access_specifier == AccessSpecifier.PUBLIC: self.__inc_public_methods__() else: self.__inc_nonpublic_methods__() if method.get_purpose == Method.GETTER: self.__f3_getters += 1 elif method.get_purpose == Method.SETTER: self.__f3_setters += 1
def ReverseDoc(html, location): """ Creates the class or interface file for the given class :param html: html of class file :param location: URL of top level documentation. Used so fields can look for constants :return: Written class object that can be printed to a file """ my_class = WrittenClass() soup = BeautifulSoup(html) my_class.package = find_package(soup) my_class.head_text = ClassName.find_class_name(soup) my_class.fields = Fields.find_fields(soup, location) my_class.methods = Method.find_methods(soup) my_class.constructor = Constructor.find_constructor(soup, my_class.fields) return my_class
def ReverseDoc(html, location): """ method ReverseDoc takes a pages html and prints out the class that's described on the page Arguments: html - the pages html """ my_class = WrittenClass() soup = BeautifulSoup(html) my_class.package = find_package(soup) my_class.head_text = ClassName.find_class_name(soup) my_class.fields = Fields.find_fields(soup, location) my_class.methods = Method.find_methods(soup) my_class.constructor = Constructor.find_constructor(soup) return my_class
def split_method(self, text: str) -> Method: m = Method() m.text = text m.mType = text.split('(')[0].strip(' ') rough_tokens = re.split(r"\(|\)", text) for i, token in enumerate(rough_tokens): if (i-4) % 3 == 0: token = token.lstrip().rstrip() m.tokens.extend(token.split(' ')) else: m.tokens.append(token) for i, token in enumerate(m.tokens): if i == 0: m.mType = token.strip() elif i == 1: m.returnType = token elif (i-2) % 3 == 0: m.paramHeaders.append(token.strip()) elif (i-2) % 3 == 1: m.paramTypes.append(token) elif (i-2) % 3 == 2: m.params.append(token.strip()) m.paramsCount = len(m.params) m.hookMethod += m.mType + ' ' m.hookMethod += '({})'.format(m.returnType) m.hookMethod += 'hook_' for i in range(m.paramsCount): m.hookMethod += m.paramHeaders[i] m.hookMethod += '({})'.format(m.paramTypes[i]) m.hookMethod += m.params[i] m.oriCall += m.paramHeaders[i] m.oriCall += m.params[i] if i == m.paramsCount-1: m.oriCall += '];' m.hookMethod += ' {' else: m.oriCall += ' ' m.hookMethod += ' ' m.body += m.hookMethod + '\n ' if m.returnType != 'void': m.body += 'return ' m.body += m.oriCall + '\n}' return m
def zclass_candidate_view_actions(self): r = {} zclass = self._zclass_ # Step one, look at all of the methods. # We can cheat (hee hee) and and look in the _zclass_ # dict for wrapped objects. for id in Method.findMethodIds(zclass): r[id] = 1 # OK, now lets check out the inherited views: findActions(zclass, r) # OK, now add our property sheets. for id in self.propertysheets.common.objectIds(): r['propertysheets/%s/manage' % id] = 1 r = r.keys() r.sort() return r
def zclass_candidate_view_actions(self): r = {} zclass = self._zclass_ # Step one, look at all of the methods. # We can cheat (hee hee) and and look in the _zclass_ # dict for wrapped objects. for id in Method.findMethodIds(zclass): r[id] = 1 # OK, now lets check out the inherited views: findActions(zclass, r) # OK, now add our property sheets. for id in self.propertysheets.common.objectIds(): r["propertysheets/%s/manage" % id] = 1 r = r.keys() r.sort() return r
def test_search_in_python_org(self): # 登录 driver = self.drviet driver.save_screenshot('xuyun.png') driver.get('http://10.0.0.9/login') time.sleep(1) driver.find_element_by_xpath('//*[@id="username"]').send_keys('Xadmin') driver.find_element_by_xpath('//*[@id="username"]').send_keys(Keys.TAB) time.sleep(1) driver.find_element_by_xpath('//*[@id="password"]').send_keys('123456') driver.find_element_by_xpath('//*[@id="password"]').send_keys(Keys.TAB) time.sleep(1) driver.find_element_by_xpath('//*[@id="loginBtn"]').click() time.sleep(1) driver.find_element_by_xpath( '//*[@id="content"]/div/div[2]/div[1]/div[1]/a').click() # 添加设备 time.sleep(1) driver.find_element_by_xpath( '//*[@id="addDevice"]/div[1]/div').click() # 点击设备类型选框 time.sleep(1) # 百度了半个小时发现要把display=none设置为display=block设置为可见 js = 'document.querySelectorAll("select")[0].style.display="block";' driver.execute_script(js) sel = driver.find_element_by_tag_name('select') # 选择value = 1也就是ap选项 Select(sel).select_by_value('1') time.sleep(1) # 选择设备型号 driver.find_element_by_xpath( '//*[@id="model_auto_chosen"]/a/span').click() time.sleep(1) # 导入js方法把display设置为可见 js = 'document.querySelectorAll("select")[0].style.display="block";' driver.execute_script(js) model_xpath = '//*[@id="model_auto_chosen"]/div/ul/li[' + str( random.randint(1, 9)) + ']' time.sleep(2) # 点击选择设备型号 driver.find_element_by_xpath(model_xpath).click() time.sleep(2) # 点击设备mac填写选项 driver.find_element_by_xpath('//*[@id="mac"]').click() # 定义一个随机生成mac函数 def randomMAC(): mac = [ 0x52, 0x54, 0x00, random.randint(0x00, 0x7f), random.randint(0x00, 0xff), random.randint(0x00, 0xff) ] return ':'.join(map(lambda x: "%02x" % x, mac)) print(randomMAC()) # 填写设备mac driver.find_element_by_xpath('//*[@id="mac"]').send_keys(randomMAC()) time.sleep(1) # 点击序列号填写框 driver.find_element_by_xpath('//*[@id="serialNum"]').click() time.sleep(1) # 生成20长度的数字+字母组合随机字符串 def generate_random_str(randomlength=20): string.digits = '0123456789' string.ascii_letters = 'DFGC' str_list = [ random.choice(string.digits + string.ascii_letters) for i in range(randomlength) ] random_str = ''.join(str_list) return random_str # 输入随机字符串 driver.find_element_by_xpath('//*[@id="serialNum"]').send_keys( generate_random_str()) time.sleep(2) # 点击位置信息输入框 driver.find_element_by_xpath('//*[@id="positionDescription"]').click() def generate_random_str(randomlength=20): string.digits = '窗前明月光,疑是地上霜。举头望明月,低头思故乡' string.ascii_letters = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM!@#$%^&*()_+?><.//*\|' str_list = [ random.choice(string.digits + string.ascii_letters) for i in range(randomlength) ] random_str = ''.join(str_list) return random_str driver.find_element_by_xpath( '//*[@id="positionDescription"]').send_keys(generate_random_str()) time.sleep(2) # 点击提交添加设备信息 driver.find_element_by_xpath( '//*[@id="addDevice"]/div[7]/div/input').send_keys(Keys.ENTER) time.sleep(2) # 查询并勾选全部设备 driver.find_element_by_xpath( '//*[@id="content"]/div/div[2]/form/div[16]/button[3]').click() time.sleep(1) # 点击修改位置 driver.find_element_by_xpath( '//*[@id="content"]/div/div[2]/div[1]/div[1]/button[3]').click() time.sleep(1) # 生成随机字符串 def generate_random_str(randomlength=20): string.digits = '西风烈,长空雁叫霜晨月,霜晨月,马蹄声碎,喇叭声咽。雄关漫道真如铁,而今迈步从头越,从头越,苍山如海,残阳如血' string.ascii_letters = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM!@#$%^&*()_+?><.//*\|' str_list = [ random.choice(string.digits + string.ascii_letters) for i in range(randomlength) ] random_str = ''.join(str_list) return random_str # 输入随机位置信息字符串 driver.find_element_by_xpath('//*[@id="position"]').send_keys( generate_random_str()) time.sleep(2) # 点击提交 driver.find_element_by_xpath( '//*[@id="updatePosition"]/div/div/div[3]/input').click() time.sleep(2) # 接受函数方法(确定) driver.switch_to.alert.accept() time.sleep(2) # 查询并勾选全部设备 driver.find_element_by_xpath( '//*[@id="content"]/div/div[2]/form/div[16]/button[3]').click() time.sleep(1) # 点击修改描述 driver.find_element_by_xpath( '//*[@id="content"]/div/div[2]/div[1]/div[1]/button[4]').click() time.sleep(1) # 生成随机字符串 def generate_random_str(randomlength=20): string.digits = '北国风光,千里冰封,万里雪飘,望长城内外,惟馀莽莽;大河上下,顿失滔滔。山舞银蛇,原驰蜡象,欲与天公试比高。须晴日,看红妆素裹,分外妖娆' string.ascii_letters = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM!@#$%^&*()_+?><.//*\|' str_list = [ random.choice(string.digits + string.ascii_letters) for i in range(randomlength) ] random_str = ''.join(str_list) return random_str # 输入描述信息随机字符串 driver.find_element_by_xpath('//*[@id="description"]').send_keys( generate_random_str()) time.sleep(2) driver.find_element_by_xpath( '//*[@id="updateDescription"]/div/div/div[3]/input').click() # 接受函数方法(确定) alert = driver.switch_to_alert() alert.accept() time.sleep(2) # 打开终端管理 driver.find_element_by_xpath( '//*[@id="treeMenu"]/li[2]/a/span').click() time.sleep(2) # 点击项目开局 driver.find_element_by_xpath( '//*[@id="treeMenu"]/li[3]/a/span').click() time.sleep(2) # 刷新当前页面 driver.refresh() # 点击项目名称 driver.find_element_by_xpath( '//*[@id="addUpdateProject"]/div[1]/div[1]/div/input').click() time.sleep(2) # 生成随机字符串 def generate_random_str(randomlength=20): string.digits = '独立寒秋,湘江北去,橘子洲头。看万山红遍,层林尽染;漫江碧透,百舸争流。鹰击长空,鱼翔浅底,万类霜天' string.ascii_letters = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM!@#$%^&*()_+?><.//*\|' str_list = [ random.choice(string.digits + string.ascii_letters) for i in range(randomlength) ] random_str = ''.join(str_list) return random_str time.sleep(2) # 输入随机字符串 driver.find_element_by_xpath( '//*[@id="addUpdateProject"]/div[1]/div[1]/div/input').send_keys( generate_random_str()) time.sleep(2) #点击项目地址下拉框 driver.find_element_by_id('province').click() # pro = Select(driver.find_element_by_id('province')) # pro.select_by_value('北京市') # pro = driver.find_element_by_tag_name('select') # ret = Select(pro).options # time.sleep(2) # ret = Select(pro).options # srant = random.Random().choice(ret[0:]) # Select(pro).deselect_by_value(srant) model_xpath = '//*[@id="province"]/option[8]' # 点击选择设备型号 driver.find_element_by_xpath(model_xpath).click() time.sleep(2) # 点击详细地址输入框 driver.find_element_by_xpath('//*[@id="street"]').click() def generate_random_str(randomlength=20): string.digits = '风雨送春归,飞雪迎春到。已是悬崖百丈冰,犹有花枝俏。俏也不争春,只把春来报。待到山花烂漫时,她在丛中' string.ascii_letters = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM!@#$%^&*()_+?><.//*\|' str_list = [ random.choice(string.digits + string.ascii_letters) for i in range(randomlength) ] random_str = ''.join(str_list) return random_str # 输入详细地址随机字符串 driver.find_element_by_xpath('//*[@id="street"]').send_keys( generate_random_str()) time.sleep(2) # 点击行业选框 driver.find_element_by_xpath('//*[@id="trade_chosen"]/a/span').click() js = 'document.querySelectorAll("select")[0].style.display="block";' driver.execute_script(js) driver.find_element_by_xpath( '//*[@id="trade_chosen"]/div/ul/li[3]').click() time.sleep(2) # 点击输入项目标识 driver.find_element_by_xpath( '//*[@id="addUpdateProject"]/div[1]/div[6]/div/input').click() driver.find_element_by_xpath( '//*[@id="addUpdateProject"]/div[1]/div[6]/div/input').send_keys( generate_random_str()) time.sleep(2) # 点击输入项目描述 driver.find_element_by_xpath( '//*[@id="addUpdateProject"]/div[1]/div[7]/div/textarea').click() driver.find_element_by_xpath( '//*[@id="addUpdateProject"]/div[1]/div[7]/div/textarea' ).send_keys(generate_random_str()) time.sleep(2) # 点击输入客户密码 driver.find_element_by_xpath( '//*[@id="addUpdateProject"]/div[1]/div[9]/div/input').click() driver.find_element_by_xpath( '//*[@id="addUpdateProject"]/div[1]/div[9]/div/input').send_keys( Method.generate_random_int()) time.sleep(2) # 点击输入客户名称 driver.find_element_by_xpath( '//*[@id="addUpdateProject"]/div[1]/div[10]/div/input').click() driver.find_element_by_xpath( '//*[@id="addUpdateProject"]/div[1]/div[10]/div/input').send_keys( Method.generate_random_numbers()) time.sleep(2) # 点击输入联系人 driver.find_element_by_xpath( '//*[@id="addUpdateProject"]/div[1]/div[11]/div/input').click() driver.find_element_by_xpath( '//*[@id="addUpdateProject"]/div[1]/div[11]/div/input').send_keys( generate_random_str()) time.sleep(2) # 点击输入客户电话 driver.find_element_by_xpath( '//*[@id="addUpdateProject"]/div[1]/div[12]/div/input').click() driver.find_element_by_xpath( '//*[@id="addUpdateProject"]/div[1]/div[12]/div/input').send_keys( generate_random_str()) time.sleep(2) # 点击输入客户邮箱 driver.find_element_by_xpath( '//*[@id="addUpdateProject"]/div[1]/div[13]/div/input').click() driver.find_element_by_xpath( '//*[@id="addUpdateProject"]/div[1]/div[13]/div/input').send_keys( '*****@*****.**') # 选择客户地址 # pro = Select(driver.find_element_by_id('province')) # pro.select_by_value('北京市') # pro = driver.find_element_by_tag_name('select') # ret = Select(pro).options # time.sleep(2) # ret = Select(pro).options # srant = random.Random().choice(ret[0:]) # Select(pro).deselect_by_value(srant) # 选择客户地址 time.sleep(2) pro = Select(driver.find_element_by_class_name('form-control')) ret = Select(pro).options srant = random.Random().choice(ret[0:]) Select(pro).deselect_by_value(srant) driver.find_element_by_xpath( '//*[@id="addUpdateProject"]/div[1]/div[15]/div/input').click() driver.switch_to_alert() time.sleep(2) driver.find_element_by_xpath('//*[@id="treeMenu"]/li[4]/a').click() time.sleep(3) driver.find_element_by_xpath( '//*[@id="treeMenu"]/li[5]/a/span').click() time.sleep(3) driver.find_element_by_xpath( '//*[@id="treeMenu"]/li[6]/a/span').click() time.sleep(3) driver.find_element_by_xpath( '//*[@id="treeMenu"]/li[7]/a/span').click() time.sleep(3) driver.find_element_by_xpath( '//*[@id="treeMenu"]/li[8]/a/span').click() time.sleep(3) driver.find_element_by_xpath( '//*[@id="treeMenu"]/li[9]/a/span').click() time.sleep(3)
from Method import * from Write import * import os # inputs can be .pkl file (pyton chach file) or .csv ( if .csv .pkl file will be created) os.chdir("e:\projects\standfire\data") a = Method(x=40,y=40,file_name='PLOT1.csv',TreePlaceMethod='sr') write('green',a,'PLOT1')
def define_method(self, method_node): method = Method.Method(method_node.spelling, method_node.type.spelling, method_node.access_specifier) self.__callgraph.define(method)
def fromUML(self, json): for uml_method in json["methods"]: method = Method() method.fromUML(uml_method) self.methods.append(method)
def nextWindow(self): self.window = QMainWindow() self.ui = Method() self.ui.method() self.close()
methodFlow = "prflow" paramTag = "param" paramType = "prtype" paramName = "prname" tree = ET.ElementTree(file='protocol.xml') root = tree.getroot() # 读取所有类 cVector = [] for elem in root: if elem.tag == classTag: tClass = N.ClassNode(elem.attrib[className]) for methods in elem: if methods.tag == methodTag: tMethods = M.Method(methods.attrib[methodName], methods.attrib[methodFlow]) for params in methods: if params.tag == paramTag: tParam = Parameter.Parameter(params.attrib[paramName], params.attrib[paramType]) tMethods.appendPara(tParam) tClass.addMethod(tMethods) cVector.append(tClass) print(cVector) for t in cVector: t.display() for t in cVector: dec = decode.Decode(t) dec.decode()
y = 80 tree_function = ['green'] #['green','red','mpb_truth'] humidity = .43 # humidity of the air (mass H20/volume air+H20) wind = 2 #[2,3,4] # wind speed from the "x" wall (m/s) init_temp = 25 #[20,30] # initial temp of the simulation, this will be the air temp as well as initial veg temp (degrees C) sf_moisture = 0.1 # surface fuel moisture (weight H20/weight dry) sf_ht = .5 # [.5,.6] # surface fuel (m) sf_load = [.7] # surface fuel (kg/m^2) mesh = 1 # number of meshes in simulation (see note 2 in Write.py) (int) sim_time = 50 # time of simulation (s) dt_part = .1 # dump simulation data every dt_part seconds (used in "&DUMP DT_PART" line)(s) dt_slice = .5 # dump slice every dt_slice seconds (used in "&DUMP DT_SLCF" line) (s) resolution = 0.5 # cell size (m) weather = [humidity, wind, init_temp] surface_fuels = [sf_moisture, sf_ht, sf_load] simulation = [mesh, resolution, sim_time, dt_part, dt_slice] tslice = [('y', 't', 10), ('y', 't', 20), ('x', 't', 20)] #file_name2 = [[x,y],'E:\Projects\STANDFIRE\Data\PLOT1.csv'] print "Calling Method" a = Method(x=x, y=y, file_name='E:\Projects\STANDFIRE\Data\PLOT300105950421_M2.csv', TreePlaceMethod='sr') print "Calling Writer" write('E:\Projects\STANDFIRE\Data\Sims', a, tree_function, weather, surface_fuels, simulation, tslice)
def OUTPUT2_CALCULATE( ): global output2 output2 = Method.softmax( layer2 )
def OUTPUT1_CALCULATE(): global output1 for i in range(800): output1[ i ] = round( Method.sigmoid( layer1[ i ] ), precision )
def __init__(self): self.methods = Method.ZClassMethodsSheet('methods') self.common = Property.ZInstanceSheetsSheet('common')
class Classification(QMainWindow): def __init__(self): super(Classification, self).__init__() self.setGeometry(450, 250, 500, 350) self.setWindowTitle('Classification') self.classification() self.stylesheet = ''' QMainWindow{ background-color: #F8CCD9; } QLabel { font: bold 14px; font-style: arial; } QPushButton { background-color: #EC769A; border-style: outset; border-width: 2px; border-radius: 22px; border-color: black; font: bold 12px; padding: 6px; } QPushButton:hover { background-color: #F199B3; border-style: inset; font: bold 13px; } QPushButton:pressed { background-color: #E75480; border-style: inset; font: bold 12px; } QPushButton:disabled { background-color: #F3AAC0; border-color: grey; border-style: inset; } QLineEdit { background-color: white; border-radius: 10px; border: 2px solid black; color: white; } QProgressBar { border: 2px solid grey; border-radius: 5px; text-align: center; } QProgressBar::chunk { background-color: #FFC0CB; margin: 0.5px; width: 10px; } ''' self.setStyleSheet(self.stylesheet) def classification(self): #LABEL label = QLabel('Project Name:', self) label.move(40, 20) label2 = QLabel('File Path:', self) label2.move(70, 60) label3 = QLabel('CHOOSE CLASSIFICATION', self) label3.resize(200, 25) label3.move(180, 110) #TEXT INPUT BOX text = QLineEdit(self) text.resize(335, 25) text.move(150, 25) text.setDisabled(True) text2 = QLineEdit(self) text2.resize(335, 25) text2.move(150, 65) text2.setDisabled(True) #BUTTON btn1 = QPushButton('CLASSIFICATION 1', self) # btn.clicked.connect(QCoreApplication.instance().quit) btn1.resize(150, 45) btn1.move(90, 150) btn2 = QPushButton('CLASSIFICATION 2', self) # btn.clicked.connect(QCoreApplication.instance().quit) btn2.resize(150, 45) btn2.move(90, 210) btn3 = QPushButton('CLASSIFICATION 3', self) # btn.clicked.connect(QCoreApplication.instance().quit) btn3.resize(150, 45) btn3.move(290, 150) btn4 = QPushButton('CLASSIFICATION 4', self) # btn.clicked.connect(QCoreApplication.instance().quit) btn4.resize(150, 45) btn4.move(290, 210) btn5 = QPushButton('PROCEED', self) btn5.clicked.connect(self.nextWindow) self.centralWidget() btn5.resize(150, 45) btn5.move(190, 280) self.show() def nextWindow(self): self.window = QMainWindow() self.ui = Method() self.ui.method() self.close()
input_dir = input('--input_dir:') output_dir = input('--output_dir:') datas = loaddata.Dataset(input_dir) datas.creat_outdir(output_dir) SIZE = 5 for i in range(datas.getlen()): print(datas.getname(i)) img = datas.getitem(i) r = Detect.search(img) img1 = img.copy() img2 = img.copy() for row in range(5, img.shape[0] - 5): for col in range(5, img.shape[1] - 5): if r[row][col] == 255: img1[row][col] = Method.canny1(img, r, row, col) img1[row][col] = Method.equalize(img, img1[row][col], row, col) else: img1[row][col] = img[row][col] for row in range(5, img.shape[0] - 5): for col in range(5, img.shape[1] - 5): if r[row][col] == 255: #img2[row][col] = Method.canny(img1, r, row, col) img2[row][col] = Method.c_mean(img1, row, col, SIZE) img2[row][col] = Method.equalize(img1, img2[row][col], row, col) else: img2[row][col] = img1[row][col] # for row in range(3,img.shape[0]-3):
def hMethod(self): m = Method(self.start, self.goal) if self.n == 0: return m.BFS() else: return m.aStar(self.n)
def fromUML(self,json): for uml_method in json["methods"]: method = Method() method.fromUML(uml_method) self.methods.append(method)
def WEIGHT1_REVISE( ): global weight1 for i in range(800): for j in range(756): weight1[ j, i ] += round( Input[ j ] * HiddenError[ i ] * Method.sigmoid_reverse( layer1[ i ] ) * 0.00001 * Learning_Rate_1, precision )
import Method, json api = Method.Method() def longpolling(): """ Essa funcionalidade permitirá que você faça checagem de novas ações e colete os dados, caso houver, ela retornará o que encontrar, caso não tenha nada, ela retornará algo pré-definido isso fará com que o loop não seja interrompido. """ temp = 100 while True: data = api.sendTG(method="getUpdates", offset=temp, timeout=int(temp + 1), allowed_updates='message') data = data["response"] if len(data["result"]) == 0: resp = json.dumps( dict(ping='pong') ) #Estou definido algo para retorna, caso não encontre resultados elif ("result" in data): temp = int(data['result'][0]['update_id'] + 1) #Aumentando o tempo resp = data['result'][0] handler(resp) def handler(vetor): """ Essa função receberá eventos, porém só irá fazer o tratamento dos evento que possuam a chave: "message"; no vetor; caso seja encontrado essa chave, responderá com a palavra: PONG
def load_data(url): print(url) power = pd.read_csv(url, encoding='utf8') id = power.id.iloc[0] #以便划分数据 data.time = data.time.str.split(' ').str[0] power.time = power.time.str.split(' ').str[0] power.to_csv(url, encoding='utf8', index=False) time = data.time.drop_duplicates().to_list() #找出天气缺失天 delete = [] for t in power.time: if t not in time: delete.append(t) print(delete) #按一天为索引把数据存储在一个字典里,其中一天包含24小时的数据 weatherList = {} tmpList = [data.iloc[0].values] j = 0 for i in range(1, len(data)): if (i == len(data) - 1): tmpList.append(data.iloc[i].values) weatherList[j] = tmpList tmpList = [] if (data.iloc[i].time != data.iloc[i - 1].time): weatherList[j] = tmpList tmpList = [] j += 1 tmpList.append(data.iloc[i].values) else: tmpList.append(data.iloc[i].values) Temperature = [] humidity = [] weatherCode = [] for key, values in weatherList.items(): tem = [] hum = [] wea = [] for j in values: tem.append(j[2]) hum.append(j[3]) wea.append(j[6]) Temperature.append(tem) humidity.append(hum) weatherCode.append(wea) weatherCode = np.asarray(weatherCode) Temperature = np.asarray(Temperature) humidity = np.asarray(humidity) T_MAX = np.hstack(Temperature).max() T_MIN = np.hstack(Temperature).min() H_MAX = np.hstack(humidity).max() H_MIN = np.hstack(humidity).min() wcount = data['weatherCode'].value_counts().count() method = Method.Method(T_MAX, T_MIN, H_MAX, H_MIN, wcount) #归一化处理 uniformTemperatureList = method.temperatureUniform(Temperature) uniformHumidityList = method.humidityUniform(humidity) uniformWeatherList = method.weatherUniform(weatherCode) uniformTemperatureList.reverse() uniformHumidityList.reverse() uniformWeatherList.reverse() #查看数据的从第48个数据开始时错误的,这里可以随意设置 forecastTemperatureList = uniformTemperatureList[10:] forecastHumidityList = uniformHumidityList[10:] forecastWeatherList = uniformWeatherList[10:] time.reverse() dateListResult = time dateListResult = dateListResult[10:] #相似日填充 for i in range(len(dateListResult)): startDate = datetime.datetime.strptime(time[0], '%Y-%m-%d') endDate = datetime.datetime.strptime(dateListResult[i], '%Y-%m-%d') delta = datetime.timedelta(days=1) j = 0 DistanceList = {} dic = {} while startDate > endDate: if datetime.datetime.strftime(startDate, '%Y-%m-%d') in delete: startDate = startDate - delta continue # print(startDate) weatherDistance = method.getDistance(uniformWeatherList[j], forecastWeatherList[i]) humidityDistance = method.getDistance(uniformHumidityList[j], forecastHumidityList[i]) temperatureDistance = method.getDistance( uniformTemperatureList[j], forecastTemperatureList[i]) Distance = 0.6 * weatherDistance + 0.2 * humidityDistance + 0.2 * temperatureDistance # 对三种因素采取不同的权重 DistanceList[startDate.strftime( '%Y-%m-%d')] = Distance # 把每个相似日计算出的欧氏距离放入字典 startDate = startDate - delta j = j + 1 sortedDistance = sorted(DistanceList.items(), key=operator.itemgetter(1)) #print(dateListResult[i]) ''' print('欧氏距离为:', DistanceList) print('相似日期为:',sortedDistance[0][0],sortedDistance[1][0],sortedDistance[2][0], sortedDistance[3][0],sortedDistance[4][0])#,sortedDistance[5][0], sortedDistance[6][0]) ''' s_p0 = power[power['time'] == sortedDistance[0] [0]]['dayPower'].values[0] s_p1 = power[power['time'] == sortedDistance[1] [0]]['dayPower'].values[0] s_p2 = power[power['time'] == sortedDistance[2] [0]]['dayPower'].values[0] s_p3 = power[power['time'] == sortedDistance[3] [0]]['dayPower'].values[0] s_p4 = power[power['time'] == sortedDistance[4] [0]]['dayPower'].values[0] dic['time'] = dateListResult[i] s_p = power[power['time'] == dateListResult[i]]['dayPower'].values[0] if (s_p == 0 or s_p == -1): if (s_p4 != 0 and s_p4 != -1): s_p = s_p4 if (s_p3 != 0 and s_p3 != -1): s_p = s_p3 if (s_p2 != 0 and s_p2 != -1): s_p = s_p2 if (s_p1 != 0 and s_p1 != -1): s_p = s_p1 if (s_p0 != 0 and s_p0 != -1): s_p = s_p0 index = power[power['time'] == dateListResult[i]]['dayPower'].index[0] power.loc[index, 'dayPower'] = s_p power.to_csv('./data/FillData/fill_station' + str(id) + '.csv', index=False, encoding='utf8')
def initialize_ast(): # define In class: cin = Class("In", None) cin.builtin = True # this is a builtin class cout = Class("Out", None) cout.builtin = True # this, too, is a builtin class scanint = Method('scan_int', cin, 'public', 'static', Type('int')) scanint.update_body( SkipStmt(None)) # No line number information for the empty body cin.add_method(scanint) scanfloat = Method('scan_float', cin, 'public', 'static', Type('float')) scanfloat.update_body( SkipStmt(None)) # No line number information for the empty body cin.add_method(scanfloat) printint = Method('print', cout, 'public', 'static', Type('void')) printint.update_body( SkipStmt(None)) # No line number information for the empty body printint.add_var('i', 'formal', Type('int')) # single integer formal parameter cout.add_method(printint) printfloat = Method('print', cout, 'public', 'static', Type('void')) printfloat.update_body( SkipStmt(None)) # No line number information for the empty body printfloat.add_var('f', 'formal', Type('float')) # single float formal parameter cout.add_method(printfloat) printboolean = Method('print', cout, 'public', 'static', Type('void')) printboolean.update_body( SkipStmt(None)) # No line number information for the empty body printboolean.add_var('b', 'formal', Type('boolean')) # single boolean formal parameter cout.add_method(printboolean) printstring = Method('print', cout, 'public', 'static', Type('void')) printstring.update_body( SkipStmt(None)) # No line number information for the empty body printstring.add_var('b', 'formal', Type('string')) # single string formal parameter cout.add_method(printstring) addtotable(classtable, "In", cin) addtotable(classtable, "Out", cout)
import Method nama=Method.ticket_method("Nama") nama.intro(31) print(" ______________________________________ ") print("| SELAMAT DATANG DI TEKKOM AIRWAYS |") print("|______________________________________|") print("| RUTE | Harga |") print("|1. JAKARTA-PALANGKARAYA | Rp 800.000 |") print("|2. JAKARTA-SURABAYA | Rp 650.000 |") print("|3. JAKARTA-SEMARANG | Rp 550.000 |") print("|______________________________________|") def book(): pax = int(input("Jumlah Penumpang = ")) print ("Masukan nama Penumpang : ") for i in range (int(pax)): i += 1 n = input("Penumpang ke- {} ".format(i)) tot=pax*harga print("Total Harga Rp ",tot) print("__________") email=input("Masukkan Alamat Email Anda: ") print("----------") print("Terima Kasih Telah Memilih Terbang Bersama Kami") print("E-Ticket Anda Akan Dikirimkan Melalui Email ", email) print("<<<Tetap Patuhi Protokol Kesehatan>>>") print("----------") rute= int(input("Masukkan Pilihan Rute : ")) if (rute == 1):