def testDependMatrix(): global sequenceCombinationDependMatrix for j in range(Main.countComp): sequenceCombinationDependMatrix[j] = 1 while (getNextVarietyOfDependecyMatrix()): depMatr = [] tmpMatr = [] for k in range(len(sequenceCombinationDependMatrix)): tmpMatr.append(generalD[k][sequenceCombinationDependMatrix[k]-1]) for k in range(len(tmpMatr)): tmparr = [] for k1 in range(len(tmpMatr)): tmparr.append(-1) depMatr.append(tmparr) for k in range(len(tmpMatr)): for k1 in range(len(tmpMatr)): depMatr[k1][k] = tmpMatr[k][k1] #Now we have depend matrix and we should test is it works isCorrect = 1 for i in range (1,len(resultMatrix)): testState = [] Main.modelingNextState(resultMatrix[i],testState,depMatr,Main.countComp,Main.KState) val = i + 1 if val == len(resultMatrix): val = 0 if testState != resultMatrix[val]: isCorrect = 0 break if isCorrect == 1: print "Yes" print depMatr
def main(): for filename in os.listdir(os.getcwd() + '/Output'): if(filename[-4:] == '.mp3'): os.remove('Output/' + filename) localAudioFiles = [] for filename in os.listdir(os.getcwd() + '/Input'): print filename if(filename != '.DS_Store' and filename != 'Thumb.db'): localAudioFiles.append(audio.LocalAudioFile('Input/' + filename)) keys = [localAudioFiles[0].analysis.key['value'], localAudioFiles[1]. analysis.key['value'], 0,0,0] for i,laf in enumerate(localAudioFiles[0:2]): if(laf.analysis.mode['value'] == 0): keys[i] = keys[i]+3 if(keys[i] > 11): keys[i] = keys[i] - 12 tempos = [localAudioFiles[0].analysis.tempo['value'], localAudioFiles[1]. analysis.tempo['value'], 0,0,0] localAudioFiles = matchTempoAndKey(localAudioFiles, tempos, keys) for i in range(3): localAudioFiles[i+2].encode(str(i)+'.mp3') print "tempos after match should equal midTempo: ", [laf.analysis.tempo['value'] for laf in localAudioFiles] equalize_tracks([localAudioFiles[0],localAudioFiles[1],localAudioFiles[2]]) equalize_tracks([localAudioFiles[3],localAudioFiles[4]]) print "len(localAudioFiles)/5 after match: ", len(localAudioFiles)/5 loudnessMarkers = Main.findLoudestRegion([localAudioFiles[0].analysis.segments, localAudioFiles[1].analysis.segments], [localAudioFiles[0].analysis.tempo['value'], localAudioFiles[1].analysis.tempo['value']]) beatMarkers = Main.getBeatMarkers(loudnessMarkers, [localAudioFiles[0].analysis.segments, localAudioFiles[1].analysis.segments],[localAudioFiles[0].analysis.beats, localAudioFiles[1].analysis.beats]) mashComponents(localAudioFiles, beatMarkers)
def plot_data(flood_lst, ahbp_lst, sba_lst, ax): """ Plot results of each algorithm Dictionaries contain connectivity as key and mean value and standart deviation as values Plot, with errorbars, all in the same axes-object. Arguments: flood_lst -- list with the values for flooding ahbp_lst -- list with the values for the ahbp sba_lst -- list with the values for the sba ax -- axes object into which the data will be plotted mode -- integer for choosing the y-axis label Return-type: None """ conn_flood, y_flood, flood_err = mn.sort_dict(flood_lst) conn_ahbp, y_ahbp, ahbp_err = mn.sort_dict(ahbp_lst) conn_sba, y_sba, sba_err = mn.sort_dict(sba_lst) ax.errorbar(conn_flood, y_flood, yerr=None, marker='o', markersize=6) ax.errorbar(conn_ahbp, y_ahbp, yerr=None, color='red', marker='s', markersize=9) ax.errorbar(conn_sba, y_sba, yerr=None, color='orange', marker='D', markersize=7) plt.setp(ax.get_xticklabels(), fontsize=21, fontstyle='oblique') plt.setp(ax.get_yticklabels(), fontsize=21, fontstyle='oblique')
def handler(self, request, threads): # Record the start timestamp start_time = datetime.datetime.strftime(datetime.datetime.now(), "%Y%m%d-%H:%M:%S") # Call Main to execute the kernel function # TODO: set configargs, json configargs = request Main.handler(configloader=ITRIConfigLoader.SQL2K5TConfig, configargs=configargs, db_handler=ITRIOutput.db_handler)
def get_result(self): Main.main(self.text) # заменить на target.txt for item in open("target.txt"): self.sys_txt.insert(END, item) if self.sys_txt.get("1.0", END + "-1c"): self.buffer_btn["state"] = NORMAL
def test_worker_get(self): if Main.server_state == 1: self.assertEqual(Main.worker_get(), {'state': 'PAUSE', 'task': [], 'main_dot': Main.main_dot, 'worker_number': -1}) elif Main.server_state == 0: self.assertEqual(Main.worker_get(), {'state': 'STOP', 'task': [], 'main_dot': [], 'worker_number': -1}) elif Main.server_state == 2: self.assertNotEqual(Main.worker_get(), {})
def createTestDataSet(fileName, numExpr): global matrixA,pirsonMatrix,fileNameResult,fileNameDepend pirsonMatrix = [] matrixA = [] fileRes = fileNameResult + str(numExpr)+".txt" Main.read(fileRes, matrixA) global size size = len(matrixA) CalculatePirsonCorelation(size) Main.write("DataMatrixExpr"+ str(numExpr)+".txt",pirsonMatrix)
def get_image(self): """ Prompts the Ximea camera to capture a photo after the next GPI spike. """ try: self.camera.get_image(self.image) return self.image.get_image_data_numpy() except xiapi.Xi_error: Interface.choose_print(self.gui, 'camera', 'Xi_error: ERROR 10: Timeout') Main.abort_session() return None
def general(): for message in file_read: if message.startswith("#"): pass else: try: Main.check_Message_Contents(message) time.sleep(1) Main.Word_based_string(message) time.sleep(1) Main.Unusual_charecter_codes(message) time.sleep(1) except Exception as e: print(e) input(" ")
def __init__(self, unknown=None): self.variables = [] self.authors = [] self.author_names = [] self.essay_names = [] i=-1 # Checks if supplied data is a dict if isinstance(unknown, dict): self.essay_vectors = unknown else: self.essay_vectors = Main.get_essay_vectors(unknown) for author, data in self.essay_vectors.iteritems(): i += 1 self.author_names.append(author) for essay, data in data.iteritems(): self.authors.append(i) self.variables.append(data) self.essay_names.append(essay) # Add padding zeros to make vectors uniform length max_length = max(map(len, self.variables)) for i in range(len(self.variables)): self.variables[i].extend([0] * (max_length - len(self.variables[i]))) X = np.array(self.variables) #@UndefinedVariable self.y = np.array(self.authors) #@UndefinedVariable self.target_names = np.array(self.author_names) #@UndefinedVariable self.pca = PCA(n_components=2) self.X_r = self.pca.fit(X).transform(X)
def OnInit(self): self.main = Main.create(None) self.main.Show() self.SetTopWindow(self.main) # self.main.SetTransparent(200) return True
def show(self, color, options): # scan for options that can override the ctor options self.__wantspec = options.get('wantspec', self.__wantspec) dbfile = options.get('databasefile', self.__databasefile) # load the database file colordb = None if dbfile <> self.__databasefile: colordb = ColorDB.get_colordb(dbfile) if not self.__master: from Tkinter import Tk self.__master = Tk() if not self.__pw: self.__pw, self.__sb = \ Main.build(master = self.__master, initfile = self.__initfile, ignore = self.__ignore) else: self.__pw.deiconify() # convert color if colordb: self.__sb.set_colordb(colordb) else: colordb = self.__sb.colordb() if color: r, g, b = Main.initial_color(color, colordb) self.__sb.update_views(r, g, b) # reset the canceled flag and run it self.__sb.canceled(0) Main.run(self.__pw, self.__sb) rgbtuple = self.__sb.current_rgb() self.__pw.withdraw() # check to see if the cancel button was pushed if self.__sb.canceled_p(): return None, None # Try to return the color name from the database if there is an exact # match, otherwise use the "#rrggbb" spec. BAW: Forget about color # aliases for now, maybe later we should return these too. name = None if not self.__wantspec: try: name = colordb.find_byrgb(rgbtuple)[0] except ColorDB.BadColor: pass if name is None: name = ColorDB.triplet_to_rrggbb(rgbtuple) return rgbtuple, name
def start(self): configs = {} configs['n'] = int(self.leSelectionSize.text()) configs['dimX1'] = int(self.leSizeX1.text()) configs['dimX2'] = int(self.leSizeX2.text()) configs['dimX3'] = int(self.leSizeX3.text()) configs['dimY'] = int(self.leSizeY.text()) configs['polynomType'] = self.cbPolynomType.currentIndex() configs['startdegX1'] = 0 configs['startdegX2'] = 0 configs['startdegX3'] = 0 configs['enddegX1'] = int(self.lePowerX1.text()) configs['enddegX2'] = int(self.lePowerX2.text()) configs['enddegX3'] = int(self.lePowerX3.text()) configs['weight'] = self.cbWeight.currentIndex() configs['lambda'] = self.cbThreeLambda.isChecked() configs['findBest'] = False configs['inputFile'] = self.leInputFile.text() solve.compute(configs) graphs = { 'Y' : 'y_all', 'X1' : 'x1_all', 'X2' : 'x2_all', 'X3' : 'x3_all', 'Error1' : 'err_1', 'Error1Norm' : 'err_1norm', 'Error2' : 'err_2', 'Error2Norm' : 'err_2norm', 'Y1' : 'y_1', 'Y1Norm' : 'y_1norm', 'Y2' : 'y_2', 'Y2Norm' : 'y_2norm', } for (k,v) in graphs.items(): graph = QPixmap('img_' + v + '.png') self.__getattribute__('lGraph' + k) self.__getattribute__('lGraph' + k).setPixmap(graph); self.__getattribute__('lGraph' + k).setMask(graph.mask()); results = open('results.txt').read() self.tOutput.setPlainText(results)
def main(args): """Then entry point to this program. Arguments: args -- a list of specifications to how the program should be run. The format should be: - output_file -- The file to write the result to - markov_order -- The number of words each generated word uses (must be integer greater than 0) - training_file -- This is a varargs argument. Each training_file will be used for data to generate words. """ if len(args) < 2: sys.stderr.write("Usage: <markov_order> <training_file> ...") return try: chunk_size = int(args[0]) # the size of each the word chunks that will make up the output except ValueError: sys.stderr.write("Numerical arguments must be non-negative integers") return files = args[1:] # the training files # Error Handling if chunk_size < 1: sys.stderr.write("Markov order must exceed 0") return """maps tuples of words maps of the words that are preceded by the tuples in the training docs. Each map matches the following-word with the number of times it occurs as a following word""" bigram_counts = {} try: for file_name in files: # for each file passed in, store data from that file in global maps process_file(file_name, chunk_size, bigram_counts) except IOError: print "Invalid file path" return print "Training data recorded" probabilities = {} Main.calculate_probabilities( bigram_counts, probabilities ) # determine probabilities of generating a word given a previous word print "Markov probabilities calculated" result = produce_text(probabilities, chunk_size) print "RESULT: " + result
def write_value(self,value): """ Write a value to the Arduino over Serial. :argument value: Value to be written to Arduino :type value: string, int, float :argument pause: Amount of time spent paused in seconds :type pause: int, float """ Interface.choose_print(self.gui, 'arduino', 'Writing "{}"...'.format(value)) try: self.serial.write('{}'.format(value)) self.serial.readline() Interface.choose_print(self.gui, 'arduino', 'Wrote: {}'.format(value)) except serial.SerialException: Interface.choose_print(self.gui, 'arduino', 'SerialException: WriteFile failed') Main.abort_session()
def index(): form = BookForm(csrf_enabled=False) if form.validate_on_submit(): # Check the password and log the user in # [...] artist=Main.main(form.book.data) return redirect(url_for('index')) return redirect(url_for('qwerty')) return render_template('index.html', form=form)
def find_product_trends(database,product_codes): print("Getting Product Trends...") Main.fill_values(database) for hs,product in product_codes.items(): # Find all the Long, Medium, and Short term Trends in products # print (one_year_val) five_year_val = Main.getProduct(product, last_year-5) first_year_val= Main.getProduct(product, first_year) last_year_val = Main.getProduct(product, last_year) one_year_val = Main.getProduct(product, last_year-1) three_year_val= Main.getProduct(product, last_year-3) # Attempts to lower the calculation requirements by not calculating for products # that have no values in the data set given total = first_year_val + last_year_val + one_year_val + five_year_val + three_year_val if (total == 0): continue if (one_year_val != 0): one_year_trend = (last_year_val - one_year_val )/ one_year_val one_year_label = "%s-%s" % (product,"one_year_trend") SQL_Handler.insert("product_trends",one_year_label,one_year_trend,Main.database) if (three_year_val != 0): three_year_trend = (last_year_val - three_year_val )/ three_year_val three_year_trend_label = "%s-%s" % (product,"three_year_trend") SQL_Handler.insert("product_trends",three_year_trend_label,three_year_trend,Main.database) if (five_year_val != 0): five_year_trend = (last_year_val - five_year_val )/ five_year_val five_year_trend_label = "%s-%s" % (product,"five_year_trend") SQL_Handler.insert("product_trends",five_year_trend_label,five_year_trend,Main.database) if (first_year_val != 0): long_trend = (last_year_val - first_year_val )/ first_year_val long_trend_label = "%s-%s" % (product,"long_trend") SQL_Handler.insert("product_trends",long_trend_label,long_trend,Main.database)
def prepareRegister(self, threadName, proxy, changeImg, myLock, conditions): print(threadName + "-" + proxy) cj = cookielib.MozillaCookieJar() cj.load("cookie.txt") #opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)); opener = urllib2.build_opener(urllib2.ProxyHandler({"http" : proxy}), urllib2.HTTPCookieProcessor(cj)) #urllib2.install_opener(opener); self.initPage(threadName, opener) self.inputValues(opener) for index, cookie in enumerate(cj): print '[',index, ']',cookie; myLock.acquire() print("---Get Lock---") changeImg(threadName) Util.curName = threadName conditions[threadName].acquire() conditions[threadName].wait() conditions[threadName].release() ret = self.register(Util.code, opener) Main.writeToFile(ret + '\n')
def mainFunc (): realDependecyMatrix = [] Main.read("ResultMatrix6.txt", resultMatrix) Main.read("DependMatrix6.txt",realDependecyMatrix) listPermutation = [k for k in range(len(resultMatrix))] allPermutations = list(itertools.permutations(listPermutation)) for i in range(len (allPermutations)): ReNullGlovalVariables() global resultMatrix resultMatrix = [] for k in range(len(listPermutation[i])): resultMatrix.append(listPermutation[i][k]) print resultMatrix findDependMatrix(resultMatrix[0],resultMatrix[1]) setFisrtAndLastElementSequens() if [] in generalD: continue testDependMatrix()
def __init__(self,com_number,gui=None): """ Initializes an instance of ArduinoController. :argument com_number: Port number of the Arduino. :type com_number: int :keyword gui: Optional interface used to print(default None). :type gui: Interface.ScarberryGui """ self.gui = gui try: self.serial = serial.Serial('COM{}'.format(com_number),115200) Interface.choose_print(gui, 'arduino', 'Waiting for COM{}...'.format(com_number)) print('Waiting for COM{}...'.format(com_number)) time.sleep(ArduinoController.INITIAL_SLEEP); Interface.choose_print(gui, 'arduino', 'Connected to COM{}.'.format(com_number)) print('Connected to COM{}.'.format(com_number)) except serial.SerialException: Interface.choose_print(self.gui, 'arduino', 'SerialException: could not open COM{}'.format(com_number)) Main.abort_session()
def update(self): # pos = pygame.mouse.get_pos() self.lock.acquire() # self.setXY(pos[0], pos[1]) self.setXY(self.pos_toset[0], self.pos_toset[1]) self.lock.release() if self.toshoot and self.shoot_released: self.shoot_lock.acquire() self.toshoot = False self.shoot_lock.release() self.shoot_released_lock.acquire() self.shoot_released = False self.shoot_released_lock.release() # self.shoot_obj.shootMain() import Main Main.shoot() if self.shot and self.recoil >= 6: self.recoil -= 6 else: self.recoil = 0 self.shot = False
def excludeFilesTest(): manga = mangas['liar_game'] parametros = ParamDescarga(None, None) lstExclusions = Main.exclusionFiles(manga) log.info(" exclusions.txt == %s" % lstExclusions) MangaGet.lstCapitulos(manga, parametros) listCapitulos = [] #TODO: Debo seguir trabajando en el tema de las exclusiones que no esta bien for capitulo in manga.capitulos: if not (capitulo.code in lstExclusions): print capitulo.code listCapitulos.append(capitulo)
def test_find_Overmarket(self): Main.multi_thread(Main.getFiles,first_year,last_year,arg=file_name,wait=5) Main.multi_thread(Main.populate_values,first_year,last_year,num=1,wait=5) Main.multi_thread(Main.single_country_over_values,first_year,last_year,wait=5)
def createDataSet( indexI, indexJ,numExpr): for i in range (1,countStates): global matrixA,pirsonMatrix,fileNameResult,fileNameDepend pirsonMatrix = [] matrixA = [] fileRes = fileNameResult + str(i)+".txt" Main.read(fileRes, matrixA) tmpDepMatrix = [] fileDep = fileNameDepend + str(i)+".txt" Main.read(fileDep,tmpDepMatrix) global size size = len(matrixA) CalculatePirsonCorelation(size) if i != numExpr : Main.write("Answer" + str(i)+".txt",[[tmpDepMatrix[indexI][indexJ]]]) Main.write("DataMatrix"+ str(i)+".txt",pirsonMatrix)
def main(): flushDirectory() filenames = getAudioFiles() for j in range(len(filenames)/5): localAudioFiles = [audio.LocalAudioFile(filenames[5*j], verbose=False), audio.LocalAudioFile(filenames[5*j+1], verbose=False)] localAudioFiles.append(audio.AudioData(filenames[5*j+2], sampleRate=44100, numChannels=2, verbose=False)) localAudioFiles.append(audio.AudioData(filenames[5*j+3], sampleRate=44100, numChannels=2, verbose=False)) localAudioFiles.append(audio.AudioData(filenames[5*j+4], sampleRate=44100, numChannels=2, verbose=False)) keys = [localAudioFiles[0].analysis.key['value'], localAudioFiles[1]. analysis.key['value'], 0,0,0] for i,laf in enumerate(localAudioFiles[0:2]): if(laf.analysis.mode['value'] == 0): keys[i] = keys[i]+3 if(keys[i] > 11): keys[i] = keys[i] - 12 print "keys: ", keys tempos = [localAudioFiles[0].analysis.tempo['value'], localAudioFiles[1]. analysis.tempo['value'], 0,0,0] deleteOldSongs([os.path.basename(laf.filename) for laf in localAudioFiles]) localAudioFiles = matchTempoAndKey(localAudioFiles, tempos, keys) for i in range(3): localAudioFiles[i+2].encode(str(i)+'.mp3') print "tempos after match should equal midTempo: ", [laf.analysis.tempo['value'] for laf in localAudioFiles] equalize_tracks([localAudioFiles[0],localAudioFiles[1],localAudioFiles[2]]) equalize_tracks([localAudioFiles[3],localAudioFiles[4]]) print "len(localAudioFiles)/5 after match: ", len(localAudioFiles)/5 loudnessMarkers = Main.findLoudestRegion([localAudioFiles[0].analysis.segments, localAudioFiles[1].analysis.segments], [localAudioFiles[0].analysis.tempo['value'], localAudioFiles[1].analysis.tempo['value']]) beatMarkers = Main.getBeatMarkers(loudnessMarkers, [localAudioFiles[0].analysis.segments, localAudioFiles[1].analysis.segments],[localAudioFiles[0].analysis.beats, localAudioFiles[1].analysis.beats]) mashComponents(localAudioFiles, beatMarkers)
def __init__(self,framerate,gain=0,gui=None): """ Initializes an instance of XimeaCamera. :argument framerate: Number of pictures taken a second. :type framerate: int :keyword gain: Brightness modifier of pictures taken. type gain: int, float [0 to 6](default 0) :keyword gui: Optional interface used to print(default None). :type gui: Interface.ScarberryGui """ self.gui = gui self.image = xiapi.Image() self.camera = xiapi.Camera() Interface.choose_print(gui, 'camera', 'Opening camera...') try: self.camera.open_device() exposure = (1000000 / (int(framerate))) exposure -= math.pow(10, math.floor(math.log(exposure, 10)) - 1) self.camera.set_exposure(int(exposure)) if gain < 0: gain = 0 if gain > 6: gain = 6 self.camera.set_gain(float(gain)) self.camera.set_trigger_source('XI_TRG_EDGE_RISING') self.camera.set_gpi_mode('XI_GPI_TRIGGER') self.camera.set_gpo_selector('XI_GPO_PORT1') self.camera.set_gpo_mode('XI_GPO_FRAME_TRIGGER_WAIT') self.camera.set_imgdataformat('XI_MONO8') except xiapi.Xi_error: Interface.choose_print(gui, 'camera', 'Xi_error: ERROR 56: No Devices Found') Main.abort_session()
def produce_text(probabilities, markov_order): """Create a random sequence of words from probabilities calculated from the training data. Arguments: probabilities -- markov_order -- """ selected_key = tuple(["@@pad@@" for _ in range(markov_order)]) generated_word = to_print = "" while generated_word != "@@pad@@": to_print += generated_word + " " generated_word = Main.choose_next_word(selected_key, probabilities) temp = list(selected_key)[1:] temp.append(generated_word) selected_key = tuple(temp) return to_print[1 : len(to_print) - 1]
def help_button(self): path = QtWidgets.QFileDialog.getOpenFileName() print(path) if len(path[0]) <= 0: self.console.append("未选择任何文件.") self.isReadHelp = False return -1 if path[0][-4:] != ".csv": self.console.append(str(path[0]) + " 不是CSV文件") self.isReadHelp = False return -2 # ---------- 辅助信息 清洗与检验 fileHelpName = path[0] gloV.LNG_MIN = gloV.CN_LNG_MIN gloV.LNG_MAX = gloV.CN_LNG_MAX gloV.LAT_MIN = gloV.CN_LAT_MIN gloV.LAT_MAX = gloV.CN_LAT_MAX gloV.incomeList = {} gloV.incomeListKeys = [] returnHelp = Main.readHelpCSV(fileHelpName) if returnHelp < 0: self.console.append(str(path[0]) + " 文件读取错误, 代码:" + str(returnHelp)) self.console.append("-1表示文件不存在, -2表示文件编码不明, -3表示人均可支配收入不是数字") self.console.append(" ") self.isReadHelp = False return returnHelp self.isReadHelp = True self.console.append("Help.csv文件 <" + str(path[0]) + "> 打开成功!\n") self.console.append("经度范围: %f - %f" % (gloV.LNG_MIN, gloV.LNG_MAX)) self.console.append("纬度范围: %f - %f" % (gloV.LAT_MIN, gloV.LAT_MAX)) self.console.append("") self.console.append("人均可支配收入列表:") for i in gloV.incomeListKeys: tmpOut = ("%s : \t%f" % (i, gloV.incomeList[i])) self.console.append(tmpOut) self.console.append(" \n") return 0
def test_importing(self): problemFile = "Puzzles/Testing/test1.txt" g = Main.Grid() g.setGrid(GameReader.getGridFromFile(problemFile)) self.assertEqual(7, g.getCell((0, 0)).getValue())
def test_gridSetup(self): g = Main.Grid() self.assertEqual(0, g.getCell((0, 0)).getValue())
def getApp(appName_): _main = Main.Main() _app = _main.createAppByName(appName_) _app.start() return _app
def tearDown(self): Main.terminate() self.browser.quit()
ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="path to input image") ap.add_argument("-y", "--yolo", default='yolo-coco', help="base path to YOLO directory") ap.add_argument("-c", "--confidence", type=float, default=0.5, help="minimum probability to filter weak detections") ap.add_argument("-t", "--threshold", type=float, default=0.3, help="threshold when applying non-maxima suppression") args = vars(ap.parse_args()) car_make_model_classifier_yolo3.classify(args["image"]) makeAndModel = car_make_model_classifier_yolo3.getMakeAndModel() plate = Main.getLicensePlate() print("Result: \nMake: " + makeAndModel[0] + ", Model: " + makeAndModel[1] + ", plate: " + plate) makeFlag = False modelFlag = False plateFlag = False with open("CarList.csv", 'r') as file: reader = csv.reader(file) for row in reader: if makeAndModel[0] == row[0]: makeFlag = True if makeAndModel[1] == row[1]: modelFlag = True if plate == row[2]:
poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False) # MQ准备数据 case_name = "39" log("前提条件:多楼层地图功能打开,主机有一张地图已经保存") # 确保主机在充电座 try: Charge.check_lighting_icon(expectation='存在') logger.debug("主机在充电座") except: logger.debug("主机当前不在充电座,使其回充") Charge.anyhow_go_charge() Main.click_any_popMsg_on_main() log("导入地图-只有地图1") cp_cmd = 'cp -r ' + MAP1_PATH + DESTINATION_MAP_PATH cmd = [cp_cmd, REBOOT_CMD] app.telnet_to_deboot(cmd) # 刷新地图-通过进出主界面 Main.click_any_popMsg_on_main() Main.main_to_deviceslist() Main.deviceslist_to_main_using_first_device() Main.click_any_popMsg_on_main() sleep(10) # 打开多层地图 mapmgr.click_main_to_mapmgr() # 如果主机有新环境整图,首次打开多层地图,会弹出地图保存的引导框 mapmgr.click_autosave_map_popmsg() # 如果已经开启了多层地图,app重新安装后首次打开错层地图,会弹出“多层地图建图注意事项”
def client(window=None): global state #create window window = pygame.display.set_mode((window_width, window_height)) net = Network() #filled positions positions = {} #do need create new shape new_shape = False #connect to server , receive shape and next shape data = net.connect() #current player shape player_shape = data[0] #next shape next_shape = data[1] #friend shape friend_shape = None #friend filled positions friend_positions = {} #friend next shape friend_next_shape = None #score score = 0 #friend score friend_score = 0 #how often we descend our shape fall_speed = 0.5 ''' when this variable will reach time as fall speed we will descend our shape at one position ''' fall_time = 0 #create clock we need it to count elapsed time clock = pygame.time.Clock() while True: if state == 'waiting': #handling events for event in pygame.event.get(): #quit game if event.type == pygame.QUIT: pygame.display.quit() quit() draw_waiting(window) state = net.send_object("") if state == 'play': ''' send shape to server and receive friend shape from server ''' friend_shape = net.send_object(player_shape) ''' send positions to server and receive friend positions from server ''' net.client.send(pickle.dumps(positions)) data = pickle.loads(net.client.recv(8192)) positions = data[0] grid = data[1] state = data[2] ''' send score to server and receive friend score from server ''' total_score = net.send_object(score) ''' send next shape to server and receive friend next shape from server ''' friend_next_shape = net.send_object(next_shape) ''' update_time - elapsed time since last update clock.tick - determinate fps ''' update_time = clock.tick(60) #update fall time fall_time += update_time #move shape down if fall_time / 1000 > fall_speed: player_shape.y += 1 fall_time = 0 ''' if shape collide border or another shape return shape to previus previous and create new shape ''' if not check_free_space(player_shape, grid): player_shape.y -= 1 new_shape = True #get pressed keys keys = pygame.key.get_pressed() #handling events for event in pygame.event.get(): #quit game if event.type == pygame.QUIT: pygame.display.quit() quit() #handling down keys if event.type == pygame.KEYDOWN: #move left if event.key == pygame.K_LEFT: player_shape.x -= 1 '''if shape collide border or another shape return shape to previus previous and create new shape ''' if not check_free_space(player_shape, grid): player_shape.x += 1 #move right if event.key == pygame.K_RIGHT: player_shape.x += 1 '''if shape collide border or another shape return shape to previus previous and create new shape ''' if not check_free_space(player_shape, grid): player_shape.x -= 1 #rotate if event.key == pygame.K_UP: player_shape.rotation += 1 '''if shape collide border or another shape return shape to previus previous and create new shape ''' if not check_free_space(player_shape, grid): player_shape.rotation -= 1 #fall shape if event.key == pygame.K_SPACE: player_shape.y = fall(player_shape, grid) pass #descend player shape if keys[pygame.K_DOWN]: player_shape.y += 1 if not check_free_space(player_shape, grid): player_shape.y -= 1 player_convert_positions = convert_shape_to_position(player_shape) friend_convert_positions = convert_shape_to_position(friend_shape) #add player shape to grid for i in range(len(player_convert_positions)): x, y = player_convert_positions[i] if y >= 0: grid[y][x] = player_shape.color #add friend shape to grid for i in range(len(friend_convert_positions)): x, y = friend_convert_positions[i] if y >= 0: grid[y][x + 10] = friend_shape.color #create new shape if new_shape: #add current player shape to grid for pos in player_convert_positions: p = (pos[0], pos[1]) positions[p] = player_shape.color new_shape = False player_shape = next_shape next_shape = create_new_shape() score += 10 #draw all components draw_window(window, grid, next_shape, friend_next_shape, total_score) if state == 'game_over': #handling events for event in pygame.event.get(): #quit game if event.type == pygame.QUIT: pygame.display.quit() quit() #handling down keys if event.type == pygame.KEYDOWN: Main.menu(window)
import Main import sys CHAR_ASPECT_RATIO_INTERVAL = [float(x)/float(10) for x in range(11)] PLATE_ASPECT_RATIO_INTERVAL = [float(x)/float(10) for x in range(20, 101, 5)] start = int(sys.argv[1]) combs = [] # Plate Aspect Ratio for min_plate_aspect_ratio in PLATE_ASPECT_RATIO_INTERVAL: for max_plate_aspect_ratio in PLATE_ASPECT_RATIO_INTERVAL: if min_plate_aspect_ratio>=max_plate_aspect_ratio: continue if min_plate_aspect_ratio<=4: continue combs.append([min_plate_aspect_ratio, max_plate_aspect_ratio]) for combination in combs[start::6]: if combination is []: continue Main.run([0.1, 1.0], combination)
def test_workbookShouldNotBeNone(self): expect = None actual = Main.get_workbook() self.assertNotEqual(actual, expect)
def test_labelShouldGetText(self): expect = 'Amount' actual = Main.get_label('all') self.assertEqual(actual, expect)
for c in population: c.fitness = fitnessess[x].fitness x += 1 for c in population: if int(c.fitness) is 1: return c newpop = [] for i in range(0, numofChildren): num = random.randint(0, population[0].id.__len__()) children = geneticOperators.crossover(population[0], population[1], num) child1 = Chromosome() child2 = Chromosome() child1.id = geneticOperators.mutate(children[0]) child2.id = geneticOperators.mutate(children[1]) newpop.append(child1) newpop.append(child2) i += 1 if (i >= 1000): print("No Solution found :(") break population = newpop if __name__ == '__main__': import Main as Main Main.main()
or classifier == 'LogisticRegression' or classifier == 'Boosting'): print "Classifier name is incorrect" sys.exit() feature = sys.argv[3] if not (feature == 'wackerman' or feature == 'BP' or feature == 'logbp' or feature == 'morlet' or feature == 'AR'): print "feature name is incorrect" sys.exit() number_of_CSPs = int(sys.argv[4]) channels = sys.argv[5] train_or_test = sys.argv[6].rstrip() print dataset_name, classifier, feature, number_of_CSPs ######################################################################MLP############################################# ##### perform grid search to find optimal parameters print sys.argv if train_or_test == 'run': print "run" bcic = Main.Main('BCI_Framework', dataset_name, classifier, feature, channels, number_of_CSPs, myPython_path) bcic.run_learner_gridsearch() # bcic.write_feature_matrices_gridsearch() else: print "eval" bcic = Main.Main('BCI_Framework', dataset_name, classifier, feature) bcic.test_learner()
def run(): """ gloV.shopData gloV.shopGridId gloV.shopValid gloV.shopOutput """ # -------------------- Get shopDataAll and hospitalDataAll -------------------- # gloV.shopVariableNameStr # gloV.shopVariableName # gloV.shopOutput # gloV.shopDataAll # gloV.LNG_MIN gloV.LNG_MAX # gloV.LAT_MIN gloV.LAT_MAX noSave = readDiskData() if noSave == 'NO_SAVE.': return noSave # -------------------- Compute Shop -------------------- gloV.shopData = [] gloV.shopGridId = [] gloV.shopValid = {} for i in gloV.shopVariableName: gloV.shopValid[i] = [] gloV.shopOutput[0].append('Type') gloV.shopOutput[0].append('GridId') gloV.shopOutput[0].append('Score') gloV.shopOutput[0].append('GenerateTime') for i in gloV.shopDataAll: if Main.is_valid(i[0]) and Main.is_valid(i[1]): if gloV.LNG_MIN <= i[0] <= gloV.LNG_MAX and gloV.LAT_MIN <= i[1] <= gloV.LAT_MAX: tmpDataStr = [] # --- gloV.shopValid + gloV.shopData tmpData = [] for j in range(0, len(i)): tmpData.append(i[j]) tmpDataStr.append(str(i[j])) if Main.is_valid(i[j]): gloV.shopValid[gloV.shopVariableName[j]].append(i[j]) gloV.shopData.append(tmpData) # --- gloV.shopGridId lngId = int((i[0] - gloV.LNG_MIN) / gloV.lngLeap) latId = int((i[1] - gloV.LAT_MIN) / gloV.latLeap) gloV.shopGridId.append(gloV.gridId[latId][lngId]) tmpDataStr.append('宠物店') tmpDataStr.append(str(gloV.gridId[latId][lngId])) tmpDataStr.append('1.5') tmpDataStr.append(gloV.generateTime) gloV.shopOutput.append(tmpDataStr) # -------------------- Compute Hospital -------------------- gloV.hospitalData = [] gloV.hospitalGridId = [] gloV.hospitalValid = {} for i in gloV.hospitalVariableName: gloV.hospitalValid[i] = [] gloV.hospitalOutput[0].append('Type') gloV.hospitalOutput[0].append('GridId') gloV.hospitalOutput[0].append('Score') gloV.hospitalOutput[0].append('GenerateTime') for i in gloV.hospitalDataAll: if Main.is_valid(i[0]) and Main.is_valid(i[1]): if gloV.LNG_MIN <= i[0] <= gloV.LNG_MAX and gloV.LAT_MIN <= i[1] <= gloV.LAT_MAX: tmpDataStr = [] # --- gloV.hospitalValid + gloV.hospitalData tmpData = [] for j in range(0, len(i)): tmpData.append(i[j]) tmpDataStr.append(str(i[j])) if Main.is_valid(i[j]): gloV.hospitalValid[gloV.hospitalVariableName[j]].append(i[j]) gloV.hospitalData.append(tmpData) # --- gloV.hospitalGridId lngId = int((i[0] - gloV.LNG_MIN) / gloV.lngLeap) latId = int((i[1] - gloV.LAT_MIN) / gloV.latLeap) gloV.hospitalGridId.append(gloV.gridId[latId][lngId]) tmpDataStr.append('宠物医院') tmpDataStr.append(str(gloV.gridId[latId][lngId])) # --- gloV.hospitalScore if Main.is_valid(i[2]): if i[2] > 10: gloV.hospitalScore.append(2) tmpDataStr.append('2') else: gloV.hospitalScore.append(1) tmpDataStr.append('1') else: gloV.hospitalScore.append(0) tmpDataStr.append('0') tmpDataStr.append(gloV.generateTime) gloV.hospitalOutput.append(tmpDataStr) if len(gloV.shopData) == 0 or len(gloV.hospitalData) == 0: return 'NO_DATA.'
def POST(self): form = web.input(name="Nobody", greet="Hello") greeting = (Main.getTransalation(str(form.greet))) return render.index(greeting=greeting)
import serial import Main conexao = serial.Serial('COM3', 9600) plateImagePath = 'LicPlateImages/br2.png' allowedPlates = ['PLACA011' 'BEE4R22'] plateNumber = Main.main(plateImagePath) # O(pen) / C(lose) print(f'Placa lida: {plateNumber}') if plateNumber in str(allowedPlates): print('Abrindo...') conexao.write(b'O') # Open else: print('Fechando...') conexao.write(b'C') # Close conexao.close()
# cv2.imshow('logo',logo) # cv2.imshow('try',img) # imgT = trial() logo2 = logoDetect(logo, img, imgk) # cv2.namedWindow('plate',cv2.WINDOW_NORMAL) # cv2.resizeWindow('plate',600,400) # cv2.imshow('Logo',logo) # cv2.imshow('plate',img) # cv2.imwrite('./ouputs/Extract.jpg',img) # cv2.imshow('logo',logo) # cv2.waitKey(0) if __name__ == '__main__': # img=cv2.imread('./test/2.jpg') img = Main.readInput() imgk = img plateImg = process(img) cv2.imshow('img', imgk) # cv2.imshow('plateimg',plateImg) # cv2.imshow('img',img) logo = plateDetect(plateImg, img, imgk) cv2.imshow('logo', logo) # cv2.imshow('try',img) # imgT = trial() logo2 = logoDetect(logo, img, imgk) cv2.namedWindow('plate', cv2.WINDOW_NORMAL) cv2.resizeWindow('plate', 600, 400) # cv2.imshow('Logo',logo) # cv2.imshow('plate',img)
for cnt in countours0: area = cv2.contourArea(cnt) #print(area) #print(cnt) if area > areaTH + 10000: ####Tracking###### m = cv2.moments(cnt) cx = int(m['m10'] / m['m00']) cy = int(m['m01'] / m['m00']) x, y, w, h = cv2.boundingRect(cnt) crop_vehicle = frame[y:y + h, x:x + w] cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) result, plateCoordinates = Main.main(crop_vehicle) if result != "": print("License Plate: " + str(result) + "\n") color = color_recognition_api.color_recognition( frame[int(plateCoordinates[2][1] - 150):int(plateCoordinates[0][1] - 100), int(plateCoordinates[1][0] ):int(plateCoordinates[3][0])]) print("Color: " + str(color) + "\n") print( "-----------------------------------------------------------------\n" ) if previous != result:
def test_raise(self): app = Main.run([]) config_dialog = ConfigurationDialog.ConfigurationDialog( app.editor, app.localisation)
def event(self, event): if event.type == PG.KEYDOWN: G.Globals.STATE = Main.Game(1)
def startbutton(): print('Mode is given to Main program', ModeNo) Main.start(ModeNo.get())
tuple2 += (IRange * S * i, ) return tuple2 tuple1 = Send(SigRange, IRange) tuple2 = Recieve(SigRange, IRange) comm.Scatterv([checker, tuple1, tuple2, MPI.BOOL], checkerpiece) if rank != 0: sig = rank for s in xrange(S): for i in xrange(Istart, IUB): try: mn.Multi_Country(Sinputs[s], i, sig) checkerpiece = np.reshape(checkerpiece, (IRange, S)) checkerpiece[i - Istart, s] = True checkerpiece = np.reshape(checkerpiece, (IRange) * (S)) print "Success at:", Sinputs[ s], "cohorts,", i, "countries", sig, "slope" except: checkerpiece = np.reshape(checkerpiece[:, np.newaxis], (IRange, S)) checkerpiece[i - Istart, s] = False checkerpiece = np.reshape(checkerpiece, (IRange) * (S)) print "Failure at:", Sinputs[ s], "cohorts,", i, "countries", sig, "slope" comm.Gatherv(checkerpiece, [checker, tuple1, tuple2, MPI.BOOL])
import Main if __name__ == "__main__": _main = Main.Main() # # 框架的测试,以及引用类的测试 # _testApp = _main.createAppByName("Test") # _testApp.testStart() # _sparkApp = _main.createAppByName("Spark") # _sparkApp.testStart() # _lohoApp = _main.createAppByName("Loho") # _lohoApp.testStart() # _sparkApp = _main.createAppByName("SparkTest") # _sparkApp.testStart() # _testApp = _main.createAppByName("ExcelWork") # _testApp.testStart() # _testApp = _main.createAppByName("Math") # _testApp.testStart() _execlWorkFlowApp = _main.createAppByName("ExcelWorkFlow") _execlWorkFlowApp.testStart() # _cocosCreatorApp = _main.createAppByName("CocosCreator") # _cocosCreatorApp.testStart() # _unityApp = _main.createAppByName("Unity") # _unityApp.testStart()
def main(self): self.main = Main.main()
def test_barWidthShouldGetSize(self): expect = 0.15 actual = Main.get_barWidth('all') self.assertEqual(actual, expect)
if __name__ == "__main__": from utils import pyServiceUtils _appName, _svrName, _subSvrName = pyServiceUtils.getProgramInfo(__file__) _functionName = "Build" _parameterDict = { # 所需参数 "cocosCreatorAppPath": "/Applications/CocosCreator/Creator/2.3.3/CocosCreator.app/Contents/MacOS/CocosCreator", "projectFolderPath": "/Volumes/18604037792/develop/ShunYuan/wxGame/", } Main.excelProcessStepTest( _svrName, _subSvrName, _functionName, _parameterDict, { # 命令行参数 "executeType": "单体测试" } ) Main.execExcelCommand( _svrName, _subSvrName, _functionName, { # 命令行参数 "executeType": "单体测试", "projectFolderPath": "/Volumes/18604037792/develop/ShunYuan/wxGame/", "publicType": "test", "version": "1146", }
def test_worksheetShouldGetData(self): expect = 'Sheet' actual = Main.get_worksheet(Main.get_workbook()) self.assertEqual(type(actual).__name__, expect)
def setUp(self): Main.run() self.browser = webdriver.Firefox() self.browser.implicitly_wait(3)
def test_dataSetShouldBeList(self): expect = 0 actual = Main.get_dataset(Main.get_worksheet(Main.get_workbook())) self.assertGreater(len(actual), expect)
def test_demo_function_int(self): test_value1 = 10 test_value2 = 10 result = Main.demo_function(test_value1, test_value2) self.assertEqual(result, 20)
def test_meansmenShouldHaveData(self): expect = (88.3, 55.6, 24.7, 29.0, 22.9, 20.8, 13.5, 10.5, 11.1, 7.2) actual = Main.get_means_men( Main.get_dataset(Main.get_worksheet(Main.get_workbook())), 2009) self.assertEqual(actual, expect)
def readShopAll(fileShopName): """ 使用到的变量: gloV.communityVariableName gloV.communityVariableNamePosition gloV.communityDataType 存储的变量 gloV.communityVariableNameStr gloV.communityDataAll """ # ---得到编码 fileShopEncoding = Main.try_encoding(fileShopName) if fileShopEncoding == "NO_FILE.": print('<%s> 文件无法打开. 程序退出*********' % fileShopName) return -1 if fileShopEncoding == "FAILED.": print("<%s> 文件编码不明. 程序退出*********" % fileShopName) return -2 fileShop = open(fileShopName, encoding=fileShopEncoding) # ---读取列标题 gloV.shopVariableNameStr = fileShop.readline().strip() gloV.shopVariableName = gloV.shopVariableNameStr.split(',') if not (gloV.shopVariableName[0] == '经度' and gloV.shopVariableName[1] == '纬度'): print('<全国宠物店.csv> 文件前两列不是规定的 [经度, 纬度] 顺序, 程序退出******') return -3 # ---读取全国数据 readFailed = False shopRead = [] tmpReadLine = 'Begin' tmpReadCount = 1 while tmpReadLine: try: tmpReadLine = fileShop.readline() except Exception: tmpReadCount += 1 print('文件第 %d 行包含未知汉字, 读取失败, 已跳过.' % tmpReadCount) readFailed = True continue tmpReadCount += 1 i = tmpReadLine # 检测 i 中是否有<引号">,如果有则必须成对出现,而且中间部分必须不以<逗号,>切分 tmpRead = i.strip() tmpCountDouHao = tmpRead.count(',') tmpCountYinHao = tmpRead.count('"') if tmpCountDouHao == (len(gloV.shopVariableName) - 1): tmpReadResult = tmpRead.split(",") shopRead.append(tmpReadResult) elif tmpCountYinHao == 2: # 当恰有一对引号出现, 而且没有引号出现在结尾or开头处时, 这段程序可以解析 tmpReadList = tmpRead.split('"') tmpReadHead = tmpReadList[0][:-1].split(",") tmpReadTail = tmpReadList[2][1:].split(',') tmpReadHead.append("NULL") tmpReadHead.extend(tmpReadTail) tmpReadResult = tmpReadHead tmpCountDouHaoAgain = 0 for k in tmpReadResult: tmpCountDouHaoAgain += k.count(',') if tmpCountDouHaoAgain == 0: shopRead.append(tmpReadResult) else: readFailed = True print('文件第 %d 行出错: %s' % (tmpReadCount, tmpRead)) else: readFailed = True print('文件第 %d 行出错: %s' % (tmpReadCount, tmpRead)) fileShop.close() if readFailed: print("****** 以上内容无法解析, 列出的数据跳过 ******\n") # ---数据清洗 for i in shopRead: tmpData = [] for j in range(0, len(i)): tmpData0 = i[j] if gloV.shopVariableName[j] in gloV.shopDataType: tmpData1 = Main.clean_data(tmpData0, gloV.shopDataType[gloV.shopVariableName[j]]) else: tmpData1 = Main.clean_data(tmpData0, 6) tmpData.append(tmpData1) gloV.shopDataAll.append(tmpData) # ---gloV.SAVE[0] 保存变量名称的字符串 gloV.SAVE = [""] # [0] gloV.SAVE[0] += "shopVariableNameStr," gloV.SAVE.append(gloV.shopVariableNameStr) # [1] gloV.SAVE[0] += "shopDataAll," gloV.SAVE.append(gloV.shopDataAll) # [2] return 0
def test_barShouldGetColor(self): expect = '#3300FF' actual = Main.get_color(2009) self.assertEqual(actual, expect)