def btn_create_presentation_clicked_cb(self, button): if Excel_report.os.path.exists("\\\\files.nipom.org\\res\Razrab-09\Обмен\АИП\\6707" "-Кузнецк\Тренды\Новокузнецк-2020" + '\\Графики.xlsx'): path_load = "\\\\files.nipom.org\\res\Razrab-09\Обмен\АИП\\6707-Кузнецк\Тренды\Новокузнецк-2020" + '\\Графики.xlsx' workbook = Excel_report.xl.load_workbook(path_load, data_only=True) # открываем базу с отчетами, data_only=True - только данные (без формул) ws = workbook.active # выбираем активный лист или Графики = workbook['Графики.xlsx'] Presentation.make_presentations(ws) entry_info.set_text("Создана презентация \"Промежуточные итоги ОПЭ БКЭУ.pptx\"!") entry_info.modify_fg(Gtk.StateFlags.NORMAL, Gdk.color_parse("green")) else: entry_info.set_text("Сначала сформируйте отчет!") entry_info.modify_fg(Gtk.StateFlags.NORMAL, Gdk.color_parse("red"))
def compareProbabilities(): """ Compares the two implementations to make sure that they give the same states for Grover's algorithm search. """ lazy_max_measures = [] numpy_max_measures = [] # 2-9 qubits measured_bits = 1 for n_qubits in range(2, 8): lazy_max_measures.append([]) grover_circuit = QuantumCircuit('Grover', n_qubits) repetitions = int(np.pi / 4 * np.sqrt(2**n_qubits)) - 1 grover_circuit.addGate('h', [i for i in range(n_qubits)]) grover_circuit.addmeasure() # calculate oracle oracle = Sparse.ColMatrix(2**n_qubits) for i in range(2**n_qubits): if i in [measured_bits]: oracle[i, i] = -1 else: oracle[i, i] = 1 #Add Oracle grover_circuit.addCustom(0, n_qubits - 1, oracle, 'oracle') #Add diffuser Presentation.diffuser(grover_circuit) grover_circuit.addmeasure() # Repeat if necessary for i in range(repetitions): # Add Oracle grover_circuit.addCustom(0, n_qubits - 1, oracle, 'oracle') #Add diffuser Presentation.diffuser(grover_circuit) grover_circuit.addmeasure() #show results final_statevec, measurements = grover_circuit.lazysim() for m in measurements[1]: lazy_max_measures[n_qubits - 2].append(max(m * m.conj())) g = Grover() iter, success, desired_amps = g.run_circuit(n_qubits, 1, 'testing') numpy_max_measures.append(desired_amps) print("Checking if the two implementations produce the same results:") print(f"\nResult 1 :") print(np.array(lazy_max_measures, dtype=object)) print(f"\nResult 2 :") print(np.array(numpy_max_measures, dtype=object))
def SearchByAmount(LstToSearch): fltAmount = float(input("Enter the amount you are seeking: ")) LstResult = [] Successful = False for trans in LstToSearch: if fltAmount == trans[6]: LstResult.append(trans) Successful = True if Successful == True: Presentation.PrintRegister(LstResult) else: print("No transactions match your search") return
def timeBenchmarks(): """ Runs Benchmarks for Grover's algorithm for both the Circuit-Builder implementation and the Pre-defined Circuit implementation. It also plots a graph for comparison. """ max_qbits = 8 # the limit of sparse matrices qbits = np.arange(2, max_qbits + 1, 1) times = np.zeros((3, len(qbits))) for q in qbits: t1 = time.time() Presentation.Grover_Circuit(q, [3], plot_results=False) t2 = time.time() times[0, q - 2] = t2 - t1 t1 = time.time() Presentation.LazyGroverDemo(q, [3], plot_results=False) t2 = time.time() times[1, q - 2] = t2 - t1 t1 = time.time() g = Grover() g.run_circuit(q, 1, 'm') t2 = time.time() times[2, q - 2] = t2 - t1 plt.plot(qbits, times[0], label='Sparse') plt.plot(qbits, times[1], label='Lazy') plt.plot(qbits, times[2], label='Numpy') plt.title( "Runtime of Grover's Algorithm over Number of Qubits in the system") plt.xlabel("Number of Qubits") plt.ylabel("Runtime (s)") plt.yscale("log") plt.legend() plt.show()
def actual_builder(algorithm): """ Function which builds the circuit as prompted by the user. """ if algorithm == 'g': size = int(input("\nPlease enter the size of the desired circuit\n")) state = int(input("\nPlease enter the desired state\n")) if state < 2**size: Presentation.LazyGroverDemo(size, [state]) else: print( "\nSomething went wrong. \nThe desired state might be out of bounds" ) actual_builder('grover') elif algorithm == 'BV': mystery_string = str( input( "\nPlease enter a mystery bitstring (i.e. a bunch of 1s and 0s)" )) Presentation.Ber_Vaz(mystery_string) print("Your mystery string was:", mystery_string) print("Does it match the qubits in the register?")
def onclick_open_presentation(self): fpath = self.file_path.get() try: curr_file = open(fpath, 'r') presentation_file = json.load(curr_file) except (FileNotFoundError, json.JSONDecodeError): messagebox.showerror('File Error', 'Invalid MyClicker Presentation File!') return # Convert integer Question numbers stored as JSON text from text # to integers for use in Presentation presentation_dict_numbers = {} for string_key in presentation_file: presentation_dict_numbers[int( string_key)] = presentation_file[string_key] self.curr_presentation = Presentation.Presentation( presentation_dict_numbers)
def DesignateClearedTxs(TxLst): for trans in TxLst: if trans[7] == False: Presentation.PrintRegister([ trans ]) #must put trans in list for this function to work properly Decision = input( "To mark transaction as cleared, hit 'c'; otherwise hit <enter>; hit 'q' to" "return to main menu: ") if Decision.lower() == "c": trans[7] = True elif Decision.lower() == "q": print("Cleared balance review ended") return else: pass print("Cleared balance review complete")
def SearchByText(LstToSearch): strText = input("Enter the text you are seeking: ") strExact = input("For exact match, type 'e'; otherwise hit any key: ") LstResult = [] Successful = False if strExact.lower() == "e": for trans in LstToSearch: if strText in trans: Successful = True LstResult.append(trans) else: for trans in LstToSearch: if strText.lower() in trans[2].lower() or strText.lower() in trans[3].lower()\ or strText.lower() in trans[4].lower() or strText.lower() in trans[5].lower(): Successful = True LstResult.append(trans) if Successful == True: Presentation.PrintRegister(LstResult) else: print("No transactions match your search.") return
def selectQuery(self, tableName, columnListToDisplay=[], condition={}): if self.isTransaction(): if (tableName == self.tableName): tableData = self.tableDataList[-1].copy() else: raise Exception( "transaction have lock on table " + self.tableName + " Commit or rollback to start new transaction") else: tableData = self.getDataFromTable(tableName) if (len(tableData) == 0): print(tableName + " Table is Empty") return else: if (len(condition) > 0): data = list() for row in tableData: colToCheck = condition["columnName"] operator = condition["operator"] valueToCheck = condition["value"] if (colToCheck in row.keys()): if (operator == "="): if (str(row[colToCheck]) == (valueToCheck)): data.append(row) elif (operator == ">"): if (str(row[colToCheck]) > (valueToCheck)): data.append(row) elif (operator == "<"): if (str(row[colToCheck]) < (valueToCheck)): data.append(row) elif (operator == ">="): if (str(row[colToCheck]) >= (valueToCheck)): data.append(row) elif (operator == "<="): if (str(row[colToCheck]) <= (valueToCheck)): data.append(row) elif (operator == "!="): if (str(row[colToCheck]) != (valueToCheck)): data.append(row) ''' tableHeader = dict() for key in tableData[0].keys(): tableHeader[key] = "" data.insert(0, tableHeader) ''' tableData = data if ("*" not in (columnListToDisplay)): data = list() for row in tableData: selectedCols = dict() for col in columnListToDisplay: selectedCols[col] = row[col] data.append(selectedCols) ''' tableHeader = dict() for key in data[0].keys(): tableHeader[key] = "" data.insert(0, tableHeader) ''' tableData = data # Display to user Presentation.displayJSONListData(tableData)
def ReviseTx(TxLst): IdExists = False DidChangeAmt = False DidChangeClearedStatus = False IdNum = int(input("Enter the unique ID of the transaction: ")) #Find the transaction by its unique ID number for i in range(len(TxLst)): if TxLst[i][0] == IdNum: IdExists = True Location = i print("Transaction to revise: ") #, TxLst[Location]) #Need to create a list within a list for the Presentation.PrintRegister function to work DLst = [TxLst[Location]] #Display the transaction to revise: Presentation.PrintRegister(DLst) break if IdExists == False: print("No such unique ID exists.") return print(""" 1 = Change date 2 = Change type 3 = Change description/payee 4 = Change category 5 = Change memo 6 = change amount 7 = change cleared status """) while True: changeItem = input( "Enter the number of the item to revise. Hit 'q' when finished: ") if changeItem == "1": Date = EnterTxs.CustomDate() TxLst[Location][1] = Date elif changeItem == "2": newType = input("Enter the type: ") TxLst[Location][2] = newType elif changeItem == "3": newDescrip = input("Enter the description: ") TxLst[Location][3] = newDescrip elif changeItem == "4": newCat = input("Enter the category: ") TxLst[Location][4] = newCat elif changeItem == "5": newMemo = input("Enter the memo: ") TxLst[Location][5] = newMemo elif changeItem == "6": newAmt = float(input("Enter the new amount: ")) TxLst[Location][6] = newAmt DidChangeAmt = True elif changeItem == "7": TxLst[Location][7] = not TxLst[Location][7] DidChangeClearedStatus = True elif changeItem.lower() == "q": print("Revisions completed.") if DidChangeAmt == True: EnterTxs.CalculateBalance(TxLst) print("Revised balance = ", TxLst[-1][-1]) if DidChangeClearedStatus == True: return True return False else: print("Invalid entry.")
def mainModule(): ###################################################################################### # System Init ###################################################################################### testing = 'false' print("This is the Main Module") status = 'false' controlFlag = 'true' configID = 1 testID = None random.seed() internalLinks = [] connection = GeneralProcesses.sql() ###################################################################################### # Main program loop ###################################################################################### while (controlFlag == 'true'): while not testID: testID = userInput(connection, configID) cue = websiteAquisition(connection, testID) # get configuraton details for sample size query = "SELECT * FROM samples WHERE configID = " + str(configID) result = connection.getOne(query) websiteSampleSize = int(result[0]) webpageSampleSize = int(result[1]) redherringSize = int(result[2]) # choose the redherrings redHerrings = random.sample(cue, redherringSize) print(redHerrings) for siteNo in cue: internalLinks = [] query = "SELECT URL FROM websiteList WHERE siteNo = '" + str( siteNo) + "'" result = connection.getOne(query) URL = result[0] print("the siteURL is: ", URL) # get a siteID for the new websiteSample siteID = connection.getID('websiteSamples') query = """INSERT INTO websiteSamples (siteID,URL,testID) VALUES (:siteID,:URL,:testID)""" connection.query(query, (str(siteID), URL, str(testID))) while not internalLinks: internalLinks = WebScraper.webScraper(connection, testID, URL, siteID) if not internalLinks: print("no internal Links") # no internal links maybe 404 error or no links either way need a new website # pop siteNo from cue # drop the database entries for this site query = """SELECT pageID FROM webpages WHERE siteID = """ + str( siteID) pageID = connection.getOne(query) query = """DELETE FROM webpages WHERE siteID = """ + str( siteID) connection.getOne(query) if pageID: query = """DELETE FROM display WHERE pgID = """ + str( pageID[0]) connection.getOne(query) query = """DELETE FROM tags WHERE pageID = """ + str( pageID[0]) connection.getOne(query) query = """DELETE FROM content WHERE pageID = """ + str( pageID[0]) connection.getOne(query) query = """SELECT COUNT(*) FROM websiteList""" result = connection.getOne(query) maxSample = int(result[0]) newSiteNo = random.randint(1, maxSample) while newSiteNo in cue: newSiteNo = random.randint(1, maxSample) if siteNo in redHerrings: redHerrings.remove(siteNo) redHerrings.append(newSiteNo) query = "SELECT URL FROM websiteList WHERE siteNo = '" + str( newSiteNo) + "'" result = connection.getOne(query) URL = result[0] # update the website information query = """UPDATE websiteSamples SET URL = '""" + URL + """'""" print("new website is: ", URL) connection.update(query) internalLinks = WebScraper.webScraper( connection, testID, URL, siteID) # set the site type and sample size if siteNo in redHerrings: print("RedHerring") query = """UPDATE websiteSamples SET type = 'redHerring' WHERE siteID = """ + str( siteID) connection.update(query) elif siteNo not in redHerrings: print("sample") query = """UPDATE websiteSamples SET type = 'sample' WHERE siteID = """ + str( siteID) connection.update(query) websiteDataCollection(connection, websiteSampleSize, internalLinks, siteID, testID) Parser.Parser(connection, testID) connection.commit(connection) connection.close(connection) DataManipulation.dataManipulation(testID) Presentation.presentation(testID) controlFlag = 'false'
LstTrans = StoreData.RetrieveTransLst() #Each separate transaction is a list. Balance is the last item in the list. # The last item of the last transaction in LstTrans is the final balance. Balance = LstTrans[-1][-1] print("Welcome to the checking account register\n") print("Ending balance:", Balance) print("Today's balance:", Searches.GetTodaysBalance(LstTrans)) print("Cleared balance:", ClearedBal) print("Last unique ID:", intUniqueId) #Print the last 10 transactions on opening the script: print( "\nLast 10 transactions--------------------------------------------------") LstRecentTrans = LstTrans[-10:] Presentation.PrintRegister(LstRecentTrans) #----------------I/O------------------------------------------------------- while True: print(""" MENU of options: Enter a debit......................w Enter a deposit....................d Print register for a date range....p Print complete register............c Search for text....................s Search for an amount...............a Check off cleared entries..........b Display cleared balance history....h Revise a transaction...............r
""" t1 = time.time() Presentation.Grover_Circuit(5, [3]) t2 = time.time() t3 = time.time() Presentation.LazyGroverDemo(5, [3]) t4 = time.time() print(f'Time taken for sparse implementation: {t2-t1}') print(f'Time taken for lazy implementation: {t4-t3}') """ """ # Measuring the time it takes to apply Grover's Algorithm to circuits of different size. times = [] for i in range(2,9): t1 = time.time() Presentation.Grover_Circuit(i, [3]) t2 = time.time() times.append(t2-t1) plt.scatter([i for i in range(2,9)], times) plt.title("Runtime of Grover's Algorithm Compared to Number of Qubits") plt.xlabel("Number of Qubits") plt.ylabel("Runtime (s)") print(times) """ #print('Bernstein-Vazirani Algorithm Example:') Presentation.Ber_Vaz('1011') #print('QFT example:') #Presentation.qft_example()