def addShow(when, show): airs = show['airs'].split(' ') if when == 0: label = util.formatTime(airs[1], airs[2]) icon = util.getIcon('today') elif when == 1: label = airs[0] + ' ' + util.formatTime(airs[1], airs[2]) icon = util.getIcon('soon') elif when == 2: label = util.formatDate( show['airdate']) + ', ' + airs[0] + ' ' + util.formatTime( airs[1], airs[2]) icon = util.getIcon('later') else: icon = None url = util.getShowURL(show['tvdbid']) listItem = xbmcgui.ListItem( label=label + ': ' + util.formatEpisodeName(show), iconImage=icon #thumbnailImage = util.api.getShowPoster(show['tvdbid']) ) listItem.addContextMenuItems( [('Refresh list', util.getContextCommand('refresh'))], True) xbmcplugin.addDirectoryItem(handle=util.pluginId, url=url, listitem=listItem, isFolder=True)
def addShow(when, show): airs = show['airs'].split(' ') if when == 0: label = util.formatTime(airs[1], airs[2]) icon = util.getIcon('today'); elif when == 1: label = airs[0] + ' ' + util.formatTime(airs[1], airs[2]) icon = util.getIcon('soon'); elif when == 2: label = util.formatDate(show['airdate']) + ', ' + airs[0] + ' ' + util.formatTime(airs[1], airs[2]) icon = util.getIcon('later'); else: icon = None url = util.getShowURL(show['tvdbid']) listItem = xbmcgui.ListItem( label = label + ': ' + util.formatEpisodeName(show), iconImage = icon #thumbnailImage = util.api.getShowPoster(show['tvdbid']) ) listItem.addContextMenuItems([ ('Refresh list', util.getContextCommand('refresh')) ], True) xbmcplugin.addDirectoryItem( handle = util.pluginId, url = url, listitem = listItem, isFolder = True )
def jobProperties(job): clear() copyJobPropertiesOptions = jobPropertiesOptions.copy() index = jobs.index(job) copyJobPropertiesOptions["d"] = {"name": "delete job", "function": deleteJob, "arg": [job]} optionsList = [] optionsList.append({"name": "execution type: %20s" % job.executionType, "function": changeJobInterval, "arg": [job]}) optionsList.append({"name": "execution time: %20s" % util.formatTime(job.executionTime), "function": changeJobExecutionTime, "arg": [job]}) if not job.executionType == "daily": optionsList.append({"name": "execution day : %20s" % job.executionDay, "function": changeJobExecutionDay, "arg": [job]}) # append the options to the menu for (x, option) in enumerate(optionsList, 1): copyJobPropertiesOptions[str(x)] = option print "Properties of \"%s\"" % job.recipeRef makeMenu(copyJobPropertiesOptions)
def UpdateText(self): entry = self.entry if entry.running: timeText = "Currently running... %s" % formatTime(entry.currentSessionTime) else: if entry.totalTime == 0.: timeText ="Never played" else: timeText = formatTime(entry.totalTime) + " played" # not enough space for this! only showed in list/details mode (16x16px) currently #timeText += ", last played: " + formatLastPlayed(entry.lastPlayed) if self.showPlaytime: text = entry.label + "\n" + timeText elif entry.running: text = entry.label + " - Currently running..." else: text = entry.label self.nameLbl.setText(text)
def UpdateText(self): entry = self.entry if entry.running: timeText = "Currently running..." else: if entry.totalTime == 0.: timeText ="Never played" else: timeText = formatTime(entry.totalTime) + " played" timeText += "\nLast played: " + formatLastPlayed(entry.lastPlayed) self.playtimeLabel.setText(timeText)
def Start(): db = Connection(DB) try: daykey = formatTime() core_num = db.query(CORE_DELAY_SQL.format(daykey)) core_rate = db.query(CORE_DELAY_RATE_SQL.format(daykey)) full_num = db.query(FULL_DELAY_SQL.format(daykey)) full_rate = db.query(FULL_DELAY_RATE_SQL.format(daykey)) except Exception, e: print "query error!" raise e
def __html__(self): maxTime = self.v2p.maxTime endTime = maxTime + self.startTime elapsedTime = t.time() - self.startTime timeLeft = endTime - t.time() percentDone = 100.*(maxTime-timeLeft)/maxTime strL = [] strL.append( "started at %s for %s, ending at %s"%( formatTime( self.startTime ), formatDelay( maxTime ), formatTime( endTime ) ) ) if self.finished: strL.append( 'Optimization finished.') strL.append( '%d schedules explored.'%self.v2p.i) else: barStr = """<table width="50%%" height="10" cellspacing="0"><tr><td width="%f%%" bgcolor="green"></td><td bgcolor="#AAAAAA"></td></tr> </table>""" # strL.append("Shaking it really hard baby !!!") strL.append( "%s left (%d%% done and %d schedules explored)"%( formatDelay( timeLeft ), percentDone, self.v2p.i) ) strL.append( barStr%( max(1,percentDone) ) ) # strL.append( "Current speed : %.1f schedule / s "% (self.speed) ) strL.append( 'average speed : %.1f schedule / s'%(float(self.v2p.i) / elapsedTime ) ) strL.append( 'Temperature %.3g (%.3g ... %.3g)'%(self.v2p.T, self.v2p.T0, self.v2p.Tend ) ) return "<br/>\n".join( strL )
def mine(self, fuel, chain): if self.node: #get 3 transactions from the mempool try: block = Block() for i in range(3): zeroTransaction = chain.mempool[-i] if zeroTransaction not in chain.verified: transactionDetails = chain.mempoolData[zeroTransaction] if self.verification(transactionDetails, zeroTransaction): #managing wallet transactionDetails[ 'sender'].wallet -= transactionDetails[ 'amount'] transactionDetails[ 'receiver'].wallet += transactionDetails[ 'amount'] prevBlock = chain.chaindata[chain.prevHash] #removing transaction from mempool chain.mempool.remove(zeroTransaction) chain.verified.append(zeroTransaction) #adding transaction to block block.transactions.append(zeroTransaction) block.transactionsData[ zeroTransaction] = transactionDetails #prepating block block.index = prevBlock['index'] + 1 block.prevHash = chain.prevHash block.timestamp = formatTime(datetime.now()) count = 0 blockHash = block() while count < fuel: block.nonce += 1 blockHash = block() if blockHash.startswith('0' * chain.difficulty): chain.chain.append(blockHash) chain.chaindata[blockHash] = to_dict(block) chain.prevHash = blockHash chain.submit(self, blockHash) break count += 1 #linking the block to the chain except IndexError: print('Not Enough Transactions to mine') else: print('Mine Function is not allowed for Non-Node Clients')
def __html__(self): maxTime = self.v2p.maxTime endTime = maxTime + self.startTime elapsedTime = t.time() - self.startTime timeLeft = endTime - t.time() percentDone = 100. * (maxTime - timeLeft) / maxTime strL = [] strL.append("started at %s for %s, ending at %s" % (formatTime( self.startTime), formatDelay(maxTime), formatTime(endTime))) if self.finished: strL.append('Optimization finished.') strL.append('%d schedules explored.' % self.v2p.i) else: barStr = """<table width="50%%" height="10" cellspacing="0"><tr><td width="%f%%" bgcolor="green"></td><td bgcolor="#AAAAAA"></td></tr> </table>""" # strL.append("Shaking it really hard baby !!!") strL.append("%s left (%d%% done and %d schedules explored)" % (formatDelay(timeLeft), percentDone, self.v2p.i)) strL.append(barStr % (max(1, percentDone))) # strL.append( "Current speed : %.1f schedule / s "% (self.speed) ) strL.append('average speed : %.1f schedule / s' % (float(self.v2p.i) / elapsedTime)) strL.append('Temperature %.3g (%.3g ... %.3g)' % (self.v2p.T, self.v2p.T0, self.v2p.Tend)) return "<br/>\n".join(strL)
def order(request): if (request.method == 'POST'): info = json.loads(request.body.decode('utf-8'), encoding='utf-8') uuid = request.META.get("HTTP_TOKEN", None) try: user = models.customer.objects.get(uuid=uuid) except: return HttpResponse('{"error":"user does not exist"}') # check item amount for i in info['products']: sku = models.SKU.objects.get(SKU_id=i['product_id']) if (sku.amount < i['count']): return HttpResponse( json.dumps( { 'pass': False, 'error': "product amount not enough" }, ensure_ascii=False)) newOrder = models.order() newOrder.create_time = util.formatTime(time.localtime(time.time())) newOrder.status = 2 newOrder.belong = user newOrder.snap_address = user.address newOrder.price = 0 newOrder.save() totprice = 0 for i in info['products']: sku = models.SKU.objects.get(SKU_id=i['product_id']) models.order_item.objects.create(toOrder=newOrder, toSKU=sku, amount=i['count']) sku.amount -= i['count'] sku.save() totprice += sku.price newOrder.price = totprice newOrder.save() return HttpResponse( json.dumps({ 'order_id': str(newOrder.order_id), 'pass': True }, ensure_ascii=False))
def saveJobs(jobs): root = ET.Element("jobs") tree = ET.ElementTree(root) for job in jobs: attributes = {} attributes["type"] = job.executionType attributes["time"] = util.formatTime(job.executionTime) if (not job.executionType == "daily"): attributes["day"] = str(job.executionDay) jobElem = ET.SubElement(root, "job", attributes) recipeRefElem = ET.SubElement(jobElem, "recipeRef") recipeRefElem.text = job.recipeRef tree.write(jobsPath) return
def Fill(self, entries): self.entries = entries self.table.setRowCount(len(entries)) row = 0 for e in entries: self.table.setRowHeight(row, 16) twi = QtGui.QTableWidgetItem() # checkbox in tablewidgetitem twi.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) twi.setCheckState(Qt.Checked if not e.isHidden else Qt.Unchecked) twi.setTextAlignment(Qt.AlignHCenter) twi.setToolTip("Uncheck to hide entry") self.table.setItem(row, 0, twi) self.table.setItem(row, 1, QtGui.QTableWidgetItem(e.label)) self.table.setItem(row, 2, QtGui.QTableWidgetItem(e.entryType)) self.table.setItem(row, 3, QtGui.QTableWidgetItem(formatTime(e.totalTime))) row += 1 # connect only after filling list, otherwise the initialization # would be registered as changes already self.table.itemChanged.connect(self.AppendModification)
def init(self): gen0 = Client() gen1 = Client() genesis_transaction = Transactions(gen0, gen1, 3) genesis_transaction(self) #verify transaction = self.mempool[-1] transactionData = self.mempoolData[transaction] #getting signature and public key fromo data transactionSignature = transactionData['signature'] transactionVerifyKey = transactionData['sender'].publickey if gen0.verification(transactionData, transaction): #managing accounts transactionData['sender'].wallet -= transactionData['amount'] transactionData['receiver'].wallet += transactionData['amount'] #deleting the transaction from mempool self.mempool.remove(transaction) self.verified.append(transaction) genesis = Block() genesis.transactions.append(transaction) genesis.transactionsData[transaction] = transactionData genesis.index = 0 genesis.timestamp = formatTime(datetime.now()) genesis.prevHash = "Genesis" #Mining Block proof = genesis() while not proof.startswith('0' * self.difficulty): genesis.nonce += 1 proof = genesis() self.chain.append(proof) self.chaindata[proof] = to_dict(genesis) self.prevHash = genesis.genHash(genesis.nonce) print('Blockchain is initialised')
def UpdateTime(self): self.runtime += 1. self.timeLabel.setText( "A playing time of <b>%s</b> has been tracked." % formatTime(self.runtime, escapeLt=True))
depth = 'Names;Participations;ExternalIdentifiers;Genres;Performances;' url = settings.apiAddress + 'Tracks/?depth=' + depth + '&id=' + trackID + '&format=json' # Send the GET request resp = util.request(url, applicationID, applicationKey) # Interpret the JSON response data = json.loads(resp.decode('utf8')) # Return the track object return data['ResultSet'][0] # Retrieve track with participations result = beginTrackRetrieve('0703d0ef-73bf-40a3-888e-bae8bc96ca7a', settings.applicationID, settings.applicationKey) # Output the results print('Track Information:') print('Name - ' + result['Name']) print('Artists - ' + result['Artists']) print('Track Number - ' + result['TrackNumber']) print('Disc Number - ' + result['DiscNumber']) print('Duration - ' + util.formatTime(result['TotalSeconds'])) print('Participations:') for participant in result['Participations']: print(participant['Name']) raw_input('Press Enter to continue...')
import lights import users import util while True: os.system('clear') print("------------ Highscore ------------") highscore = users.highscore() for i, user in enumerate(highscore): print('{position}: {nick:10} score: {score}'.format( position=i + 1, nick=user['Nick'], score=util.formatTime(user['totalTime']))) time.sleep(0.1) print("---------- People online ----------") logged_in_users = users.logged_in() for user in logged_in_users: print(user['Nick']) if logged_in_users: lights.on() else: lights.off() time.sleep(3)
def paintEvent(self, event): numEntries = min(self.numEntries, len(self.entries)) # geometry calculations entryHeight = self.zoom * ( self.iconSize + 2*self.margin + 2*self.border) entryWidth = self.zoom * (600+2*self.margin + self.vspace + 2*self.border) fullRect = QtCore.QRect(0, 0, entryWidth+ 2*self.vspace, numEntries * (entryHeight+self.vspace) + self.vspace) innerRect = QtCore.QRect(self.margin + self.border, self.margin + self.border, entryWidth - 2*(self.margin+self.border), entryHeight-2*(self.margin+self.border)) self.setMinimumSize(fullRect.size()) # create painter, fonts, pens and brushes painter = QtGui.QPainter(self) labelFont = QtGui.QFont("Cambria", self.zoom*self.fontSize*self.largeFontFactor) labelFont.setBold(True) timeFont = QtGui.QFont("Calibri", self.zoom*self.fontSize) timeFont.setBold(False) textPen = QtGui.QPen(Qt.white) bgGrad = QtGui.QLinearGradient(QtCore.QPointF(0,0), QtCore.QPointF(0,fullRect.height())) bgGrad.setColorAt(0, QtGui.QColor(63,63,61)) bgGrad.setColorAt(0.15, QtGui.QColor(55,55,55)) bgGrad.setColorAt(1, QtGui.QColor(38,38,39)) backgroundBrush = QtGui.QBrush(bgGrad) defaultPen = QtGui.QPen(QtGui.QColor(124,124,124)) defaultBrush = QtGui.QBrush() painter.setPen(defaultPen) painter.setBrush(defaultBrush) barGrad = QtGui.QLinearGradient(QtCore.QPointF(0,0), QtCore.QPointF(innerRect.width(),0)) barGrad.setColorAt(0, QtGui.QColor(138,138,138)) barGrad.setColorAt(0.5, QtGui.QColor(110,110,110)) barGrad.setColorAt(1, QtGui.QColor(75,75,75)) barPen = QtGui.QPen(Qt.NoPen) barBrush = QtGui.QBrush(barGrad) # draw background painter.save() painter.setBrush(backgroundBrush) painter.setPen(Qt.NoPen) painter.drawRect(fullRect) painter.restore() painter.translate(self.vspace, self.vspace) tmax = max([e.totalTime for e in self.entries]) iEntry = 0 for entry in self.entries: if iEntry >= numEntries: break # begin painting if self.border != 0: painter.save() defaultPen.setWidth(self.border) borderRect = QtCore.QRect(0, 0, entryWidth, entryHeight) painter.drawRect(borderRect) painter.restore() barRect = copy.copy(innerRect) barRect.setLeft(barRect.left()+ self.iconSize + self.vspace) # playtime bar fillPct = entry.totalTime / tmax barRect.setWidth(max(1, fillPct * barRect.width())) painter.save() painter.setPen(barPen) painter.setBrush(barBrush) painter.drawRect(barRect) painter.restore() # icon and title painter.save() painter.setFont(labelFont) painter.drawPixmap(innerRect.topLeft(), entry.icon.pixmap(self.iconSize, self.iconSize)) painter.setPen(textPen) painter.drawText(innerRect.translated(self.iconSize+self.vspace, 0), Qt.AlignVCenter, entry.label) # playtime painter.setFont(timeFont) painter.drawText(innerRect, Qt.AlignRight | Qt.AlignBottom, formatTime(entry.totalTime)+ " played") painter.restore() painter.translate(0, entryHeight + self.vspace) iEntry += 1
# Set the request URL depth = 'Names;Participations;ExternalIdentifiers;Genres;Performances;' url = settings.apiAddress + 'Tracks/?depth=' + depth + '&id=' + trackID + '&format=json' # Send the GET request resp = util.request(url, applicationID, applicationKey) # Interpret the JSON response data = json.loads(resp.decode('utf8')) # Return the track object return data['ResultSet'][0] # Retrieve track with participations result = beginTrackRetrieve('0703d0ef-73bf-40a3-888e-bae8bc96ca7a', settings.applicationID, settings.applicationKey) # Output the results print('Track Information:') print('Name - ' + result['Name']) print('Artists - ' + result['Artists']) print('Track Number - ' + result['TrackNumber']) print('Disc Number - ' + result['DiscNumber']) print('Duration - ' + util.formatTime(result['TotalSeconds'])) print('Participations:'); for participant in result['Participations']: print(participant['Name']); raw_input('Press Enter to continue...')
def paintEvent(self, event): numEntries = min(self.numEntries, len(self.entries)) # geometry calculations entryHeight = self.zoom * (self.iconSize + 2 * self.margin + 2 * self.border) entryWidth = self.zoom * (600 + 2 * self.margin + self.vspace + 2 * self.border) fullRect = QtCore.QRect( 0, 0, entryWidth + 2 * self.vspace, numEntries * (entryHeight + self.vspace) + self.vspace) innerRect = QtCore.QRect(self.margin + self.border, self.margin + self.border, entryWidth - 2 * (self.margin + self.border), entryHeight - 2 * (self.margin + self.border)) self.setMinimumSize(fullRect.size()) # create painter, fonts, pens and brushes painter = QtGui.QPainter(self) labelFont = QtGui.QFont( "Cambria", self.zoom * self.fontSize * self.largeFontFactor) labelFont.setBold(True) timeFont = QtGui.QFont("Calibri", self.zoom * self.fontSize) timeFont.setBold(False) textPen = QtGui.QPen(Qt.white) bgGrad = QtGui.QLinearGradient(QtCore.QPointF(0, 0), QtCore.QPointF(0, fullRect.height())) bgGrad.setColorAt(0, QtGui.QColor(63, 63, 61)) bgGrad.setColorAt(0.15, QtGui.QColor(55, 55, 55)) bgGrad.setColorAt(1, QtGui.QColor(38, 38, 39)) backgroundBrush = QtGui.QBrush(bgGrad) defaultPen = QtGui.QPen(QtGui.QColor(124, 124, 124)) defaultBrush = QtGui.QBrush() painter.setPen(defaultPen) painter.setBrush(defaultBrush) barGrad = QtGui.QLinearGradient(QtCore.QPointF(0, 0), QtCore.QPointF(innerRect.width(), 0)) barGrad.setColorAt(0, QtGui.QColor(138, 138, 138)) barGrad.setColorAt(0.5, QtGui.QColor(110, 110, 110)) barGrad.setColorAt(1, QtGui.QColor(75, 75, 75)) barPen = QtGui.QPen(Qt.NoPen) barBrush = QtGui.QBrush(barGrad) # draw background painter.save() painter.setBrush(backgroundBrush) painter.setPen(Qt.NoPen) painter.drawRect(fullRect) painter.restore() painter.translate(self.vspace, self.vspace) tmax = max([e.totalTime for e in self.entries]) iEntry = 0 for entry in self.entries: if iEntry >= numEntries: break # begin painting if self.border != 0: painter.save() defaultPen.setWidth(self.border) borderRect = QtCore.QRect(0, 0, entryWidth, entryHeight) painter.drawRect(borderRect) painter.restore() barRect = copy.copy(innerRect) barRect.setLeft(barRect.left() + self.iconSize + self.vspace) # playtime bar fillPct = entry.totalTime / tmax barRect.setWidth(max(1, fillPct * barRect.width())) painter.save() painter.setPen(barPen) painter.setBrush(barBrush) painter.drawRect(barRect) painter.restore() # icon and title painter.save() painter.setFont(labelFont) painter.drawPixmap(innerRect.topLeft(), entry.icon.pixmap(self.iconSize, self.iconSize)) painter.setPen(textPen) painter.drawText( innerRect.translated(self.iconSize + self.vspace, 0), Qt.AlignVCenter, entry.label) # playtime painter.setFont(timeFont) painter.drawText(innerRect, Qt.AlignRight | Qt.AlignBottom, formatTime(entry.totalTime) + " played") painter.restore() painter.translate(0, entryHeight + self.vspace) iEntry += 1
def main(): threadCount = cvParam['threadCount'] profile = cvParam['profile'] trainFraction = cvParam.get('trainFraction', None) optimizeFun = cvParam['optimizeFun'] lossFun = cvParam['lossFun'] jrboost.setProfile(profile) jrboost.setNumThreads(threadCount) print(f'{threadCount} threads\n') (trainInDataFrame, trainOutDataSeries, trainWeightSeries, testInDataFrame, testOutDataSeries, validationInDataFrame, validationOutDataSeries) = loadData(trainFrac=trainFraction) trainSamples = trainInDataFrame.index testSamples = testInDataFrame.index validationSamples = validationInDataFrame.index trainInData = trainInDataFrame.to_numpy(dtype=np.float32) trainOutData = trainOutDataSeries.to_numpy(dtype=np.uint64) trainWeights = trainWeightSeries.to_numpy(dtype=np.float32) testInData = testInDataFrame.to_numpy(dtype=np.float32) testOutData = testOutDataSeries.to_numpy(dtype=np.uint64) validationInData = validationInDataFrame.to_numpy(dtype=np.float32) validationOutData = validationOutDataSeries.to_numpy(dtype=np.uint64) # make sure that total weight is the same for background and signal events trainWeights[trainOutData == 0] /= np.sum(trainWeights[trainOutData == 0]) trainWeights[trainOutData == 1] /= np.sum(trainWeights[trainOutData == 1]) # normalize so largest weight is 1 trainWeights /= np.max(trainWeights) print( f'{len(trainSamples)} train samples, {len(testSamples)} test samples, {len(validationSamples)} validation samples\n' ) #............................................................................... t = -time.time() PROFILE.PUSH(PROFILE.MAIN) #predOutDataFrame = pd.DataFrame(index = testSamples, columns = labels, dtype = np.uint64) bestOptList = optimizeFun( cvParam, lambda optionList: trainAndEval(trainInData, trainOutData, trainWeights, testInData, testOutData, optionList, lossFun)) print(formatOptions(bestOptList[0])) predOutData = trainAndPredict(trainInData, trainOutData, validationInData, bestOptList) estSignalRatio = sum(trainOutData) / len(trainOutData) estCutoff = np.quantile(predOutData, 1.0 - estSignalRatio) print(f'threshold = {estCutoff}') PROFILE.POP() t += time.time() PROFILE.PRINT() print(util.formatTime(t)) print() print() submission = pd.DataFrame(index=validationSamples, data={ 'P': predOutData, 'RankOrder': ranks(predOutData) + 1, 'Class': np.where(predOutData > estCutoff, 's', 'b') }) submission.to_csv('Higgs Submission.csv', sep=',') print("Done!")
import datetime def Start(): db = Connection(DB) try: daykey = formatTime() core_num = db.query(CORE_DELAY_SQL.format(daykey)) core_rate = db.query(CORE_DELAY_RATE_SQL.format(daykey)) full_num = db.query(FULL_DELAY_SQL.format(daykey)) full_rate = db.query(FULL_DELAY_RATE_SQL.format(daykey)) except Exception, e: print "query error!" raise e finally: db.close() for key, value in KeyMap.items(): data = DictObj() data.indexkey = value data.indextime = formatTime(0) data.indexvalue = eval(key) data = reqData(data) yield taskMonitor, data if __name__ == '__main__': pat = re.compile(r'\d{8}') if sys.argv[1] and pat.match(sys.argv[1]): daykey = sys.argv[1] nose.run()
def sign_transation(self, string): signingkey = self.sender.privatekey signature = signingkey.sign(string.encode('ascii')) self.timestamp = formatTime(datetime.now()) return signature
# Interpret the JSON response data = json.loads(resp.decode('utf8')) # Return the album object return data['ResultSet'][0] # Retrieve album with track information result = beginAlbumRetrieve('d9675b59-7b88-40aa-9909-4e638839c799', settings.applicationID, settings.applicationKey) # Output the results print('Name - ' + result['Name']) print('Artists - ' + result['Artists']) print('Disc Count - ' + str(result['DiscCount'])) print('Track Count - ' + str(result['TrackCount'])) print('Duration - ' + util.formatTime(result['TotalSeconds'])) try: print('Format - ' + result['Discs'][0]['MusicMedium']['Name']) except KeyError: pass try: externalIdentifiers = result['ExternalIdentifiers'] for externalIdentifier in externalIdentifiers: if externalIdentifier['ExternalDatabase']['Name'] == 'UPC Barcode': print('Barcode - ' + externalIdentifier['Identifier']) break except KeyError: pass
def UpdatePlaytime(self, time): self.totalTime.setText("Total playtime: <b>%s</b>" % formatTime(time).replace('<', '<'))
def main(): print(cvParam) print() threadCount = cvParam['threadCount'] profile = cvParam['profile'] dataFraction = cvParam['dataFraction'] optimizeFun = cvParam['optimizeFun'] lossFun = cvParam['lossFun'] innerFoldCount = cvParam['innerFoldCount'] jrboost.setProfile(profile) jrboost.setNumThreads(threadCount) print(f'{threadCount} threads\n') trainInDataFrame, trainOutDataFrame = loadTrainData(dataFraction) trainSamples = trainInDataFrame.index variables = trainInDataFrame.columns labels = trainOutDataFrame.columns testInDataFrame = loadTestData(0.01) testSamples = testInDataFrame.index assert (testInDataFrame.columns == variables).all print( f'{len(trainSamples)} train samples, {len(testSamples)} test samples\n' ) trainInData = trainInDataFrame.to_numpy(dtype=np.float32) testInData = testInDataFrame.to_numpy(dtype=np.float32) for i in itertools.count(): print(f'-------------------- {i} --------------------\n') t = -time.time() PROFILE.PUSH(PROFILE.MAIN) predOutDataFrame = pd.DataFrame(index=testSamples, columns=labels, dtype=np.uint64) for label in labels: trainOutData = trainOutDataFrame[label].to_numpy(dtype=np.uint64) bestOptList = optimizeFun( cvParam, lambda optionList: trainAndEval( trainInData, trainOutData, innerFoldCount, optionList, lossFun)) print(f'{label}: {formatOptions(bestOptList[0])}') predOutData = trainAndPredict(trainInData, trainOutData, testInData, bestOptList) predOutDataFrame[label] = predOutData PROFILE.POP() t += time.time() PROFILE.PRINT() print(util.formatTime(t)) print() print() predOuDataFrame = util.lorToProb(predOutDataFrame) predOutDataFrame.to_csv('result.csv', sep=',')
if rfid_tag_id == wait_for_valid_rfid(): new_user_nick = input("input your nick: ") if new_user_nick: users.add(new_user_nick, rfid_tag_id) log_action(new_user_nick, 'login') print('You now exist and are logged in! Dont forget to logout!') else: print('Provied nick empty blipp again.') else: print("Tagg not the same as earlier please try again") else: if user['isHere']: users.logout(rfid_tag_id) log_action(user['Nick'], 'logout') user = users.fetch(rfid_tag_id) print('Goodbye {Nick}, your highscore is: {totalTime}'.format( Nick = user['Nick'], totalTime = util.formatTime(user['totalTime']))) else: users.login(rfid_tag_id) log_action(user['Nick'], 'login') print("Welcome {Nick}!".format(**user)) print("-----------------------------------------------") trigger_random_sound()