content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
#!/usr/bin/env python """ Retrieve intraday stock data from Google Finance. """ import csv import datetime import re import pandas as pd import requests def intradaystockprices(ticker, period=60, days=1): """ Retrieve intraday stock data from Google Finance. Parameters ---------- ticker : str Company ticker symbol. period : int Interval between stock values in seconds. days : int Number of days of data to retrieve. Returns ------- df : pandas.DataFrame DataFrame containing the opening price, high price, low price, closing price, and volume. The index contains the times associated with the retrieved price values. """ #import pytz #localtz = pytz.timezone('America/Los_Angeles') uri = 'https://finance.google.com/finance/getprices?q={ticker}&x=&p={days}d&i={period}&f=d,c,o,h,l,v'.format( ticker=ticker, period=str(period), days=str(days) ) ## uri = 'http://www.google.com/finance/getprices?i={period}&p={days}d&f=d,o,h,l,c,v&df=cpct&q={ticker}'.format( ## ticker=ticker, ## period=period, ## days=days ## ) #uri= 'http://www.google.com/finance/getprices?q=GOOG&x=NASD&i=86400&p=40Y&f=d,c,v,k,o,h,l&df=cpct&auto=0&ei=Ef6XUYDfCqSTiAKEMg' #uri= 'http://www.google.com/finance/getprices?q=MSFT&x=&i=86400&p=3d&f=d,c,v,k,o,h,l&df=cpct&auto=0&ei=Ef6XUYDfCqSTiAKEMg' #uri = 'https://finance.google.com/finance/getprices?q=BX&x=&p=1d&i=60&f=d,c,o,h,l,v' page = requests.get(uri) #print uri reader = csv.reader(page.content.splitlines()) columns = ['Open', 'High', 'Low', 'Close', 'Volume'] rows = [] times = [] for row in reader: #print row if re.match('^[a\d]', row[0]): if row[0].startswith('a'): start = datetime.datetime.fromtimestamp(int(row[0][1:])) times.append(start) else: times.append(start+datetime.timedelta(seconds=period*int(row[0]))) rows.append(map(float, row[1:])) if len(rows): df_final = pd.DataFrame(rows, index=pd.DatetimeIndex(times, name='Date'),columns=columns) #return pd.DataFrame(rows, index=pd.DatetimeIndex(times, name='Date'),columns=columns) else: df_final = pd.DataFrame(rows, index=pd.DatetimeIndex(times, name='Date')) #return pd.DataFrame(rows, index=pd.DatetimeIndex(times, name='Date')) df_final['Ticker']=ticker df_final.sort_index(inplace=True) return df_final if __name__=='__main__': df = intradaystockprices(ticker='BX',period=60, days=1) print df
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 220, 198, 37811, 198, 9781, 30227, 493, 6335, 323, 4283, 1366, 422, 3012, 15007, 13, 198, 37811, 198, 198, 11748, 269, 21370, 198, 11748, 4818, 8079, 198, 11748, 302, 198, 198, 11748, 19798, ...
1.777961
1,815
#!/usr/bin/env python import os import sys import json from argparse import ArgumentParser ROOT = os.path.dirname(os.path.abspath(__file__)) DB_FILE = os.path.join(ROOT, 'problems.json') def parse_args(): """Parse CLI tool options. """ parser = ArgumentParser() parser.add_argument('problem_id', type=int) parser.add_argument('--field', type=str, help='extract field value') parser.add_argument('--markdown', type=bool, default=False, help='print markdown content') parser.add_argument('--context', type=str, help='additional context to lookup') return parser.parse_args() if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 33918, 198, 6738, 1822, 29572, 1330, 45751, 46677, 198, 198, 13252, 2394, 796, 28686, 13, 6978, 13, 15908, 3672, 7, 418, 13, 6978, 13, ...
2.218391
348
from __future__ import annotations # Fixes an issue with some annotations from .ascii_box import Light, LineChar from .ascii_drawing import DrawingChar
[ 6738, 11593, 37443, 834, 1330, 37647, 220, 1303, 34258, 281, 2071, 351, 617, 37647, 198, 198, 6738, 764, 292, 979, 72, 62, 3524, 1330, 4401, 11, 6910, 12441, 198, 6738, 764, 292, 979, 72, 62, 19334, 278, 1330, 40027, 12441, 628, 628, ...
3.674419
43
import numpy as np import matplotlib.pyplot as plt # NTC103F397F datasheet d_T = np.array(np.arange(-40, 121, 5)) d_R = np.array([333.110, 240.704, 175.794, 129.707, 96.646, 72.691, 55.169, 42.234, 32.6, 25.364, 19.886, 15.705, 12.490, 10.0, 8.0584, 6.5341, 5.3297, 4.3722, 3.6065, 2.9906, 2.4925, 2.0875, 1.7565, 1.4848, 1.2605, 1.0746, 0.91983, 0.79042, 0.68178, 0.59020, 0.51271, 0.44690, 0.39080]) d_B = 3970 d_T0 = 273.15 + 25 d_R0 = 10 # B parameter equation b_T = 1/d_T0 - (1/d_B)*np.log(d_R0) + (1/d_B)*np.log(d_R) # SteinhartHart equation s_T = b_T + 0.000000254 * (np.log(d_R)**3) s_T = 1/s_T - 273.15 b_T = 1/b_T - 273.15 # B, SH plt.figure(1) plt.plot(d_T, d_R, label="datasheet", marker='*') plt.plot(b_T, d_R, label="B equ") plt.plot(s_T, d_R, label="SH equ") plt.yscale('log') plt.grid() plt.legend() plt.xlabel(r"$\degree C$") plt.ylabel(r"$k\Omega$") # find optimal resistan plt.figure(2) for R in [3, 5, 10, 20]: T_v = d_R*5/(R+d_R) plt.plot(d_T, T_v, label=r"{0} $k\Omega$".format(R)) plt.xticks(np.arange(-40, 121, 10)) plt.yticks(np.arange(0, 5.1, 0.2)) plt.grid() plt.xlabel(r"$\degree C$") plt.ylabel("V") plt.legend() plt.show()
[ 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 2, 399, 4825, 15197, 37, 33372, 37, 19395, 25473, 198, 67, 62, 51, 796, 45941, 13, 18747, 7, 37659, 13, 283, 858, 32590, 1821, 11...
1.763425
689
from abc import ABC, abstractmethod from collections import defaultdict from functools import partial from auxiliary import default
[ 6738, 450, 66, 1330, 9738, 11, 12531, 24396, 198, 6738, 17268, 1330, 4277, 11600, 198, 6738, 1257, 310, 10141, 1330, 13027, 198, 198, 6738, 37419, 1330, 4277, 628, 628, 628 ]
4.6
30
from . import anasysfile from . import anasysdoc from . import heightmap from . import irspectra from . import anasysio
[ 6738, 764, 1330, 281, 292, 893, 7753, 198, 6738, 764, 1330, 281, 292, 893, 15390, 198, 6738, 764, 1330, 6001, 8899, 198, 6738, 764, 1330, 4173, 4443, 430, 198, 6738, 764, 1330, 281, 292, 893, 952, 198 ]
3.243243
37
import os import sys import time import numpy as np from sklearn.metrics import accuracy_score from utils.config import TRANSFORMATION from utils.ensemble import load_models, prediction, ensemble_defenses_util BSLabelFP=sys.argv[1] samplesDir=sys.argv[2] modelsDir=sys.argv[3] AETypes = { "biml2": ["bim_ord2_nbIter100_eps1000", "bim_ord2_nbIter100_eps250", "bim_ord2_nbIter100_eps500"], "bimli":["bim_ordinf_nbIter100_eps100", "bim_ordinf_nbIter100_eps90", "bim_ordinf_nbIter100_eps75"], "cwl2":["cw_l2_lr350_maxIter100", "cw_l2_lr500_maxIter100", "cw_l2_lr700_maxIter100"], "dfl2":["deepfool_l2_overshoot20", "deepfool_l2_overshoot30", "deepfool_l2_overshoot50"], "fgsm":["fgsm_eps100", "fgsm_eps250", "fgsm_eps300"], "jsma":["jsma_theta30_gamma50", "jsma_theta50_gamma50", "jsma_theta50_gamma70"], "mim":["mim_eps20_nbIter1000", "mim_eps30_nbIter1000", "mim_eps50_nbIter1000"], "op":["onepixel_pxCount15_maxIter30_popsize100", "onepixel_pxCount30_maxIter30_popsize100", "onepixel_pxCount5_maxIter30_popsize100"], "pgd":["pgd_eps250", "pgd_eps100", "pgd_eps300"] } sampleSubDirs=[ "legitimates"#, "fgsm" #"biml2", "bimli", "cwl2", "dfl2" #"fgsm", "jsma", "mim", "op", "pgd" ] # (nSamples, <sample dimension>, nChannels) # (nClasses) trueLabelVec=np.load(BSLabelFP) trueLabels = np.argmax(trueLabelVec, axis=1) nClasses = trueLabelVec.shape[1] EnsembleIDs=[0,1,2,3] rows=0 cols=1+len(EnsembleIDs) if "legitimates" in sampleSubDirs: rows=1+3*(len(sampleSubDirs) - 1) else: rows=3*len(sampleSubDirs) accs = np.zeros((rows, cols)) modelFilenamePrefix="mnist-cnn" # dataset name and network architecture # include "clean" type: no transformation. # transformationList[0] is "clean" transformationList=TRANSFORMATION.supported_types() # remove "clean" because the correspondingly model will not be used in ensemble transformationList.remove("clean") nTrans = len(transformationList) transTCs_Prob = np.zeros((rows, nTrans)) transTCs_Logit = np.zeros((rows, nTrans)) predTCs_Prob = np.zeros((rows, nTrans)) predTCs_Logit = np.zeros((rows, nTrans)) ensembleTCs = np.zeros((rows, 5)) rowIdx=0 rowHeaders=[] AEFilenamePrefix="test_AE-mnist-cnn-clean" datasetFilePaths = [] for subDirName in sampleSubDirs: if subDirName == "legitimates": # BS datasetFilePaths.append( os.path.join(os.path.join(samplesDir, subDirName), "test_BS-mnist-clean.npy")) rowHeaders.append("BS") else: # AE AETags = AETypes[subDirName] for AETag in AETags: datasetFilePaths.append( os.path.join(os.path.join(samplesDir, subDirName), AEFilenamePrefix+"-"+AETag+".npy")) rowHeaders.append(AETag) useLogit = False print("Loading prob models") models = load_models(modelsDir, modelFilenamePrefix, transformationList, convertToLogit=useLogit) for datasetFilePath in datasetFilePaths: accs[rowIdx, 0:4], transTCs_Prob[rowIdx], predTCs_Prob[rowIdx], ensembleTCs[rowIdx, 0:4] = testOneData( datasetFilePath, models, nClasses, transformationList, EnsembleIDs, trueLabels, useLogit=useLogit ) rowIdx+=1 del models useLogit=True print("Loading logit models") logitModels = load_models(modelsDir, modelFilenamePrefix, transformationList, convertToLogit=useLogit) rowIdx=0 for datasetFilePath in datasetFilePaths: accs[rowIdx, 4], transTCs_Logit[rowIdx], predTCs_Logit[rowIdx], ensembleTCs[rowIdx, 4] = testOneData( datasetFilePath, logitModels, nClasses, transformationList, EnsembleIDs, trueLabels, useLogit=useLogit ) rowIdx+=1 del logitModels np.save("acc_ensemble_test.npy", accs) with open("acc_ensemble_test.txt", "w") as fp: fp.write("Acc\tRD\tMV\tAVEP\tT2MV\tAVEL\n") for ridx in range(len(rowHeaders)): fp.write("{}\t{}\t{}\t{}\t{}\t{}\n".format( rowHeaders[ridx], accs[ridx, 0], accs[ridx, 1], accs[ridx, 2], accs[ridx, 3], accs[ridx, 4])) transTCs = (transTCs_Prob + transTCs_Logit)/2 np.save("transTCs.npy", transTCs) np.save("predTCs_Prob.npy", predTCs_Prob) np.save("predTCs_Logit.npy", predTCs_Logit) np.save("ensembleTCs.npy", ensembleTCs)
[ 11748, 28686, 198, 11748, 25064, 198, 11748, 640, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 1341, 35720, 13, 4164, 10466, 1330, 9922, 62, 26675, 198, 198, 6738, 3384, 4487, 13, 11250, 1330, 44069, 35036, 198, 6738, 3384, 4487, ...
2.10033
2,123
from django.shortcuts import render, redirect from django.contrib.admin.views.decorators import staff_member_required from django.views.decorators.csrf import csrf_exempt from django.contrib.auth import authenticate, login, logout from django.http import HttpResponse from ems.models import Score, Level, Judge, Label, Team from Event.models import Event from registration.models import Participant from django.contrib.auth.models import User # Create your views here. EMSADMINS = [ # have access to all events 'admin', 'controls', 'webmasterdvm', 'deepak' ] def events_levels(request, eventid): event = Event.objects.get(id=eventid) levels = Level.objects.filter(event=event) emsadmin = True if request.user.username in EMSADMINS else False if request.method == 'POST': if 'delete-level' in request.POST: levelid = request.POST['delete-level'] level = Level.objects.get(id=levelid) level.teams.clear() level.delete() if 'delete-judge' in request.POST: judgeid = request.POST['delete-judge'] judge = Judge.objects.get(id=judgeid) judge.level_set.clear() judge.user.delete() judge.delete() if 'delete-label' in request.POST: labelid = request.POST['delete-label'] label = Label.objects.get(id=labelid) label.delete() context = { 'event' : event, 'levels' : levels, 'emsadmin' : emsadmin, } return render(request, 'ems/events_levels.html', context) def events_levels_add(request, eventid): event = Event.objects.get(id=eventid) levels = Level.objects.filter(event=event) emsadmin = True if request.user.username in EMSADMINS else False if request.method == 'POST': if 'add' in request.POST: name = request.POST['name'] position = int(request.POST['position']) level = Level.objects.create(name=name, position=position, event=event) if 'judgesheet' in request.POST: labelid = request.POST['label'] label = Label.objects.get(id=labelid) level.label = label level.save() judges = request.POST.getlist('judge') for judgeid in judges: judge = Judge.objects.get(id=judgeid) level.judges.add(judge) return redirect('ems:events_levels', event.id) context = { 'event' : event, 'levels' : levels, 'emsadmin' : emsadmin, } return render(request, 'ems/events_levels_add.html', context) def events_labels_add(request, eventid): event = Event.objects.get(id=eventid) levels = Level.objects.filter(event=event) emsadmin = True if request.user.username in EMSADMINS else False if request.method == 'POST': if 'add' in request.POST: names = request.POST.getlist("name") maxvalues = request.POST.getlist("max") label = Label(event=event) for i, name in enumerate(names): attr = "var" + str(i+1) + "name" setattr(label, attr, name) for i, maxvalue in enumerate(maxvalues): attr = "var" + str(i+1) + "max" setattr(label, attr, maxvalue) label.save() return redirect('ems:events_levels', event.id) context = { 'event' : event, 'levels' : levels, 'emsadmin' : emsadmin, } return render(request, 'ems/events_labels_add.html', context) def events_judges_add(request, eventid): event = Event.objects.get(id=eventid) levels = Level.objects.filter(event=event) emsadmin = True if request.user.username in EMSADMINS else False if request.method == 'POST': if 'add' in request.POST: name = request.POST['name'] username = request.POST['username'] password = request.POST['password'] try: user = User.objects.create_user(username=username, password=password) except: return HttpResponse("Please use a different username. Press the back button to continue") judge = Judge.objects.create(name=name, event=event, user=user) judge.user = user judge.save() return redirect('ems:events_levels', event.id) context = { 'event' : event, 'levels' : levels, 'emsadmin' : emsadmin, } return render(request, 'ems/events_judges_add.html', context) def events_levels_edit(request, eventid, levelid): emsadmin = True if request.user.username in EMSADMINS else False event = Event.objects.get(id=eventid) level = Level.objects.get(id=levelid) if 'save' in request.POST: name = request.POST['name'] position = int(request.POST['position']) level.name = name level.position = position level.label = None level.save() level.judges.clear() if 'judgesheet' in request.POST: labelid = request.POST['label'] label = Label.objects.get(id=labelid) level.label = label level.save() judges = request.POST.getlist('judge') for judgeid in judges: judge = Judge.objects.get(id=judgeid) level.judges.add(judge) return redirect('ems:events_levels', event.id) if 'delete' in request.POST: level.delete() return redirect('ems:events_home', event.id) context = { 'event' : event, 'level' : level, 'emsadmin' : emsadmin, } return render(request, 'ems/events_levels_edit.html', context) def events_judge_home(request, eventid): event = Event.objects.get(id=eventid) context = { 'event' : event, } return render(request, 'ems/events_judge_home.html', context) def events_judge_login(request, eventid, levelid, judgeid): event = Event.objects.get(id=eventid) judge = Judge.objects.get(id=judgeid) level = Level.objects.get(id=levelid) context = { 'event' : event, 'level' : level, 'judge' : judge, } if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active and user == judge.user: login(request, user) return redirect('ems:events_levels_judge', event.id, level.id, judge.id) else: context['status'] = 0 return render(request, 'ems/login.html', context) def events_levels_judge(request, eventid, levelid, judgeid): event = Event.objects.get(id=eventid) level = Level.objects.get(id=levelid) judge = Judge.objects.get(id=judgeid) emsadmin = True if request.user.username in EMSADMINS else False if not emsadmin and request.user != judge.user: return redirect('ems:events_judge_login', event.id, level.id, judge.id) if request.method == 'POST': if 'leave' in request.POST: for team in level.teams.all(): try: score = Score.objects.get(level=level, team=team, judge=judge) if not score.is_frozen: score.delete() score = Score.objects.create(level=level, team=team, judge=judge) score.is_frozen = True score.save() except: score = Score.objects.create(level=level, team=team, judge=judge) score.is_frozen = True score.save() elif "save" or "freeze" in request.POST: for team in level.teams.all(): scores = request.POST.getlist(str(team.id)) try: score = Score.objects.get(level=level, team=team, judge=judge) except: score = Score.objects.create(level=level, team=team, judge=judge) for i, val in enumerate(scores): attr = 'var' + str(i+1) if val == '': val = None setattr(score, attr, val) comments = request.POST['comment-'+str(team.id)] score.comments = comments if "freeze" in request.POST: score.is_frozen = True score.save() teams = [] for team in level.teams.all(): try: score = Score.objects.get(level=level, team=team, judge=judge) team.score = score total = 0 for x in range(1, 11): attr = 'var' + str(x) try: val = getattr(score, attr) total += val except: pass team.score.total = total except: pass teams.append(team) context = { 'event' : event, 'level' : level, 'judge' : judge, 'teams' : teams, 'emsadmin' : emsadmin, } return render(request, 'ems/events_judge_edit.html', context) def events_participants(request, eventid): event = Event.objects.get(id=eventid) emsadmin = True if request.user.username in EMSADMINS else False if event.is_team: return redirect('ems:events_teams', event.id) teams = Team.objects.filter(event=event) if request.method == 'POST': if 'delete-team' in request.POST: teamid = request.POST['delete-team'] team = Team.objects.get(id=teamid) team.delete() context = { 'event' : event, 'teams' : teams, 'emsadmin' : emsadmin, } return render(request, 'ems/events_participants.html', context) def events_participants_add(request, eventid): event = Event.objects.get(id=eventid) emsadmin = True if request.user.username in EMSADMINS else False parts = [] if request.method == 'POST': if 'fetch' in request.POST: partid = request.POST['aadhaar'] partids = map(lambda s:s.strip().replace("BITS", "").replace("MSPS", ""), partid.split()) print partids for partid in partids: try: part = Participant.bitsians.get(uniqueid__iexact=partid) parts.append(part) except: pass try: part = Participant.objects.get(id__iexact=partid) parts.append(part) except: pass if 'add' in request.POST: partids = request.POST.getlist('part') for partid in partids: part = Participant.objects.get(id=partid) try: team = Team.objects.get(leader=part, event=event, members=None) except: team = Team.objects.create(leader=part, event=event) registered = Level.objects.get(name="Registered", event=event) team.levels.add(registered) return redirect('ems:events_participants', event.id) context = { 'event' : event, 'parts' : parts, 'emsadmin' : emsadmin, } return render(request, 'ems/events_participants_add.html', context) def events_teams(request, eventid): event = Event.objects.get(id=eventid) emsadmin = True if request.user.username in EMSADMINS else False if not event.is_team: return redirect('ems:events_participants', event.id) teams = Team.objects.filter(event=event) if request.method == 'POST': if 'delete-team' in request.POST: teamid = request.POST['delete-team'] team = Team.objects.get(id=teamid) team.delete() context = { 'event' : event, 'teams' : teams, 'emsadmin' : emsadmin, } return render(request, 'ems/events_teams.html', context) def events_teams_add(request, eventid): event = Event.objects.get(id=eventid) parts = [] select = [] errors = [] if request.method == 'POST': if 'fetch' in request.POST: partid = request.POST['aadhaar'] if ";" in partid: existingteams = Team.objects.filter(event=event) newteams = partid.split(";") for newteam in newteams: team_parts = [] team_partids = map(lambda s:s.strip().replace("BITS", "").replace("MSPS", ""), newteam.split()) for team_partid in team_partids: try: part = Participant.bitsians.get(uniqueid__iexact=team_partid) parts.append(part) except: pass try: part = Participant.objects.get(id__iexact=team_partid) team_parts.append(part) except: pass if team_parts: leader = team_parts[0] team = Team.objects.create(leader=leader, event=event) members = team_parts[1:] for member in members: team.members.add(member) registered = Level.objects.get(name="Registered", event=event) team.levels.add(registered) return redirect('ems:events_participants', event.id) else: partids = partid.split() partids = map(lambda s:s.strip().replace("BITS", "").replace("MSPS", ""), partids) for partid in partids: try: part = Participant.bitsians.get(uniqueid__iexact=partid) parts.append(part) except: pass try: part = Participant.objects.get(id__iexact=partid) parts.append(part) except: pass if 'next' in request.POST: teams = event.team_set.all() partids = request.POST.getlist('part') for partid in partids: part = Participant.objects.get(id=partid) if not errors: for partid in partids: part = Participant.objects.get(id=partid) select.append(part) if "add" in request.POST: teams = event.team_set.all() partids = request.POST.getlist('part') leaderid = request.POST['leader'] name = request.POST['name'] comments = request.POST['comments'] leader = Participant.objects.get(id=leaderid) team = Team.objects.create(leader=leader, event=event, name=name, comments=comments) for partid in partids: if partid != leaderid: part = Participant.objects.get(id=partid) team.members.add(part) registered = Level.objects.get(name="Registered", event=event) team.levels.add(registered) return redirect('ems:events_participants', event.id) context = { 'event' : event, 'parts' : parts, 'select' : select, 'errors' : errors, } return render(request, 'ems/events_teams_add.html', context) def events_teams_edit(request, eventid, teamid): event = Event.objects.get(id=eventid) team = Team.objects.get(id=teamid) if request.method == 'POST': if 'save' in request.POST: name = request.POST['team_name'] comments = request.POST['comments'] position = request.POST['position'] team.name = name team.comments = comments team.position = position team.save() context = { 'event' : event, 'team' : team, } return render(request, 'ems/events_teams_edit.html', context)
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 11, 18941, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 28482, 13, 33571, 13, 12501, 273, 2024, 1330, 3085, 62, 19522, 62, 35827, 198, 6738, 42625, 14208, 13, 33571, 13, 12501, 273, 2024,...
2.529604
5,202
from msedge.selenium_tools import Edge, EdgeOptions from lxml import html import time import curses stdscr = curses.initscr() max_y = stdscr.getmaxyx()[0] - 1 if max_y < 16: raise Exception("Terminal row size must be more then 17, but now it is %d." % (max_y + 1)) # changelog: more OOP. # class: illust,illustName,picList(made up of pic classes) stdscr.addstr("Config R18?\nWarning: you must quit all edge browsers and kill their process in task manager!") # When getstr(), auto-refresh f0_config = bytes.decode(stdscr.getstr()) if f0_config == 'Y' or f0_config == 'y' or f0_config == '': driver = driver_init() driver.get("https://www.pixiv.net/setting_user.php") etree = html.etree initial_page = driver.page_source initial_dom = etree.HTML(initial_page) r18Switch = initial_dom.xpath( '//input[(@name="r18" or @name="r18g") and @checked]/@value') if r18Switch[0] == 'hide': stdscr.addstr('R-18 disabled.\n') else: stdscr.addstr('R-18 enabled.\n') if r18Switch[1] == '1': stdscr.addstr('R-18G disabled.\n') else: stdscr.addstr('R-18G enabled.\n') stdscr.refresh() stdscr.addstr( 'Do you want confirm the r-18 settings?\nPress Y or Enter to navigate you to the settings page, or by default ' 'NO.\n') f1_config = bytes.decode(stdscr.getstr()) if f1_config == 'y' or f1_config == 'Y' or f1_config == '': stdscr.addstr('Unleash R-18?\n') r18Config = bytes.decode(stdscr.getstr()) stdscr.addstr('Unleash R-18G?\n') r18gConfig = bytes.decode(stdscr.getstr()) if r18Config == 'y' or r18Config == 'Y' or r18Config == '': driver.find_element_by_xpath( '//input[@name="r18" and @value="show"]').click() stdscr.addstr('R-18 has been ON.\n') else: driver.find_element_by_xpath( '//input[@name="r18" and @value="hide"]').click() stdscr.addstr('R-18 is now OFF.\n') # Give a timely feedback stdscr.refresh() if r18gConfig == 'Y' or r18gConfig == 'y' or r18gConfig == '': driver.find_element_by_xpath( '//input[@name="r18g" and @value="2"]').click() stdscr.addstr('R-18G has been ON.\n') else: driver.find_element_by_xpath( '//input[@name="r18g" and @value="1"]').click() stdscr.addstr('R-18G is now OFF.\n') stdscr.refresh() driver.find_element_by_xpath('//input[@name="submit"]').click() time.sleep(2) stdscr.addstr('Config saved. Now refreshing...\n') stdscr.refresh() driver.refresh() driver.quit()
[ 6738, 13845, 14907, 13, 741, 47477, 62, 31391, 1330, 13113, 11, 13113, 29046, 201, 198, 6738, 300, 19875, 1330, 27711, 201, 198, 11748, 640, 201, 198, 11748, 43878, 201, 198, 19282, 1416, 81, 796, 43878, 13, 259, 896, 6098, 3419, 201, ...
2.050296
1,352
from geo.position import Location import geo.helper
[ 6738, 40087, 13, 9150, 1330, 13397, 198, 11748, 40087, 13, 2978, 525, 628, 628 ]
3.928571
14
from django_tables2 import tables, Column from profiles.models import TeamRoleBinding
[ 6738, 42625, 14208, 62, 83, 2977, 17, 1330, 8893, 11, 29201, 198, 6738, 16545, 13, 27530, 1330, 4816, 47445, 33, 6020, 628 ]
3.954545
22
# Script: bubble_sort_recursive.py # Author: Joseph L. Crandal # Purpose: Demonstrate bubble sort with recursion # data will be the list to be sorted data = [ 0, 5, 2, 3, 10, 123, -53, 23, 9, 2 ] dataOrig = [ 0, 5, 2, 3, 10, 123, -53, 23, 9, 2 ] # In a bubble sort you will work your way through the dataset # and move the elements that are adjacent # Recursive functions call on themselves to process data until a goal has been met or it runs out of items to process # In this example it continues to go over the dataset until it doesn't see any further change in position from sorting # Execute the sort bubbleSort(data) # Show sorted array versus original print("Unsorted array: ") for i in range(len(dataOrig)): print(dataOrig[i]) print("Sorted array: ") for i in range(len(data)): print(data[i])
[ 2, 12327, 25, 14310, 62, 30619, 62, 8344, 30753, 13, 9078, 198, 2, 6434, 25, 7212, 406, 13, 3864, 7642, 198, 2, 32039, 25, 7814, 23104, 14310, 3297, 351, 664, 24197, 198, 198, 2, 1366, 481, 307, 262, 1351, 284, 307, 23243, 198, 78...
3.217391
253
# Copyright 2015-2016 Mirantis, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import ConfigParser import datetime import json import logging import os.path import subprocess import traceback from oslo_config import cfg from mcv_consoler.common.config import DEFAULT_CIRROS_IMAGE from mcv_consoler.common.config import MOS_TEMPEST_MAP from mcv_consoler.common.config import TIMES_DB_PATH from mcv_consoler.common.errors import TempestError from mcv_consoler.plugins.rally import runner as rrunner from mcv_consoler import utils LOG = logging.getLogger(__name__) CONF = cfg.CONF tempest_additional_conf = { 'compute': {'fixed_network_name': CONF.networking.network_ext_name}, 'object-storage': {'operator_role': 'admin', 'reseller_admin_role': 'admin'}, 'auth': {} }
[ 2, 220, 220, 220, 15069, 1853, 12, 5304, 7381, 20836, 11, 3457, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220, 220, 407, 779, 428, ...
2.988889
450
# THIS FILE IS GENERATED FROM NUMPY SETUP.PY # # To compare versions robustly, use `numpy_demo.lib.NumpyVersion` short_version = '1.29.0' version = '1.29.0' full_version = '1.29.0' git_revision = 'dd8e9be4d35e25e795d8d139ff4658715767c211' release = True if not release: version = full_version
[ 198, 2, 12680, 45811, 3180, 24700, 1137, 11617, 16034, 399, 20476, 56, 25823, 8577, 13, 47, 56, 198, 2, 198, 2, 1675, 8996, 6300, 12373, 306, 11, 779, 4600, 77, 32152, 62, 9536, 78, 13, 8019, 13, 45, 32152, 14815, 63, 198, 19509, ...
2.373016
126
""" ################# Hammersley Sphere ################# """ import numpy as np from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D def return_point(m, n, p): """ m is the index number of the Hammersley point to calculate n is the maximun number of points p is the order of the Hammersley point, 1,2,3,4,... etc l is the power of x to go out to and is hard coded to 10 in this example :return type double """ if p == 1: return m / float(n) v = 0.0 for j in range(10, -1, -1): num = m // p ** j if num > 0: m -= num * p ** j v += num / (p ** (j + 1)) return (v) if __name__ == "__main__": npts = 500 h_1 = np.zeros(npts) h_7 = np.zeros(npts) for m in range(npts): h_1[m] = return_point(m, npts, 1) h_7[m] = return_point(m, npts, 7) phirad = h_1 * 2.0 * np.pi h7 = 2.0 * h_7 - 1.0 # map from [0,1] to [-1,1] st = np.sqrt(1.0 - h7 * h7) xxx = st * np.cos(phirad) yyy = st * np.sin(phirad) zzz = h7 fig = plt.figure() ax = fig.gca(projection='3d') ax.plot(xxx, yyy, zzz, '.') ax.set_xticks([-1.0, -0.5, 0.0, 0.5, 1.0]); ax.set_yticks([-1.0, -0.5, 0.0, 0.5, 1.0]); ax.set_zticks([-1.0, -0.5, 0.0, 0.5, 1.0]); ax.set_title("Ham Points, 1 and 7", fontsize=14) plt.show()
[ 37811, 198, 14468, 2, 198, 39, 36846, 1636, 31798, 198, 14468, 2, 198, 37811, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 2603, 29487, 8019, 1330, 12972, 29487, 355, 458, 83, 198, 6738, 285, 489, 62, 25981, 74, 896, 13, 76, 29487, ...
1.975749
701
import enum import json import os import requests import yaml import socket import sqlite3 import traceback from org.heather.api.tools import Tools from org.heather.api.log import Log, LogLevel
[ 11748, 33829, 198, 11748, 33918, 198, 11748, 28686, 198, 11748, 7007, 198, 11748, 331, 43695, 198, 11748, 17802, 198, 11748, 44161, 578, 18, 198, 11748, 12854, 1891, 198, 198, 6738, 8745, 13, 258, 1032, 13, 15042, 13, 31391, 1330, 20003, ...
3.119403
67
import math import sys import time from nltk import word_tokenize import numpy as np
[ 11748, 10688, 198, 11748, 25064, 198, 11748, 640, 198, 198, 6738, 299, 2528, 74, 1330, 1573, 62, 30001, 1096, 198, 11748, 299, 32152, 355, 45941, 198, 220, 220, 220, 220, 198 ]
2.935484
31
from pwn import * shellcode = "\x31\xc0\x31\xdb\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x53\x89\xe1\x31\xd2\xb0\x0b\x51\x52\x55\x89\xe5\x0f\x34\x31\xc0\x31\xdb\xfe\xc0\x51\x52\x55\x89\xe5\x0f\x34" HOST = 'pwn2.jarvisoj.com' PORT = 9877 PrettyTommy(HOST,PORT)
[ 6738, 279, 675, 1330, 1635, 201, 198, 29149, 8189, 796, 37082, 87, 3132, 59, 25306, 15, 59, 87, 3132, 59, 87, 9945, 59, 87, 1120, 59, 87, 3104, 59, 87, 17, 69, 59, 87, 17, 69, 59, 87, 4790, 59, 87, 3104, 59, 87, 3104, 59, 87...
1.479167
192
"""Definition for "invalid bot credentials" error.""" from typing import NoReturn from botx.clients.methods.base import APIErrorResponse, BotXMethod from botx.clients.types.http import HTTPResponse from botx.exceptions import BotXAPIError def handle_error(method: BotXMethod, response: HTTPResponse) -> NoReturn: """Handle "invalid bot credentials" error response. Arguments: method: method which was made before error. response: HTTP response from BotX API. Raises: InvalidBotCredentials: raised always. """ APIErrorResponse[dict].parse_obj(response.json_body) raise InvalidBotCredentials( url=method.url, method=method.http_method, response_content=response.json_body, status_content=response.status_code, bot_id=method.bot_id, # type: ignore )
[ 37811, 36621, 329, 366, 259, 12102, 10214, 18031, 1, 4049, 526, 15931, 198, 6738, 19720, 1330, 1400, 13615, 198, 198, 6738, 10214, 87, 13, 565, 2334, 13, 24396, 82, 13, 8692, 1330, 7824, 12331, 31077, 11, 18579, 55, 17410, 198, 6738, ...
2.77377
305
# This file has a lot going on in it because really ties the game together, # just like The Dude's rug. You can probably read it start to finish, but # by all means start jumping around from here. # Dependencies for rendering the UI from clubsandwich.ui import ( LabelView, LayoutOptions, UIScene, ) # including some ones written specifically for this game from .views import ProgressBarView, GameView, StatsView # Whenever you go to another "screen," you're visiting a scene. These are the # scenes you can get to from the game scene. from .scenes import PauseScene, WinScene, LoseScene # This object stores the state of the whole game, so we're definitely gonna # need that. from .game_state import GameState # When keys are pressed, we'll call these functions to have the player do # things. from .actions import ( action_throw, action_close, action_move, action_pickup_item, ) # When things happen, we need to show status messages at the bottom of the # screen. Since more than one thing can happen in a frame, there's some # subtle logic encapsulated in this Logger object. from .logger import Logger # Constructing arbitrary English sentences from component parts is not always # simple. This function makes it read nicer in code. from .sentences import simple_declarative_sentence # There are four tracks that can play at any given time. Pyglet (the library # used for audio) doesn't have easy "fade" support, so this object tracks and # modifies volumes for each track per frame. from .music import NTrackPlayer # const.py does some interesting things that you should look at when you're # interested. For now, here are some hints: from .const import ( # Enums are collections of unique identifiers. In roguelikes it's usually # better to keep everything in data files, but for a small game like this # it's not a big deal to have a few small ones. EnumEventNames, EnumFeature, EnumMonsterMode, # These are collections of values from data files: verbs, # from verbs.csv key_bindings, # from key_bindings.csv # This is a reverse mapping of key_bindings.csv so we can turn # a raw key value into a usable command. BINDINGS_BY_KEY, # Map of key binding ID to a clubsandwich.geom.Point object representing a # direction. KEYS_TO_DIRECTIONS, ) # At some point this game was slow. This flag enables profiling. You can # ignore it. DEBUG_PROFILE = False if DEBUG_PROFILE: import cProfile pr = cProfile.Profile() # All game scenes share an instance of the player because the audio should be # continuous. It's a bit of a hack that it's a global variable, but this was a # 48-hour game, so deal with it. N_TRACK_PLAYER = NTrackPlayer(['Q1.mp3', 'Q2.mp3', 'Q3.mp3', 'Q4.mp3']) # This is the text that appears at the bottom left of the screen. TEXT_HELP = """ ======= Keys ======= Move: arrows, numpad hjklyubn Get rock: g Throw rock: t Close: c """.strip() # While you're playing the game, there are actually 3 modes of input: # # * Normal: move, wait, get, close, throw # * Prompting for throw direction # * Prompting for close direction # # These states were originally handled with a "mode" property, but it turns out # to be MUCH simpler if there are just 3 completely different scenes for these # things that happen to draw the screen the same way. That way you never have # any "if mode == PROMPT_THROW_DIRECTION" blocks or anything. # # So those 3 scenes all inherit from this base class. # This is another abstract base class, subclassing the one above. Two of the # three game scenes are just waiting for a single keystroke for input. This # class abstracts that behavior. # Finally, some real action! This is the main game scene, as the name says. # This object has a lot of responsibilities: # # * Reset things for a new game # * Display world events to the user # * Act on main game input # * Assorted hacks # # Let's dive in! # At this point, you should be able to read the last two classes yourself # without my help. From here, you should jump around to whatever interests you! # I would suggest a reading order of something like: # * const.py # * entity.py # * game_state.py # * level_state.py # * behavior.py # * actions.py # * level_generator.py # * views.py # * draw_game.py
[ 2, 770, 2393, 468, 257, 1256, 1016, 319, 287, 340, 780, 1107, 8470, 262, 983, 1978, 11, 198, 2, 655, 588, 383, 40628, 338, 14477, 13, 921, 460, 2192, 1100, 340, 923, 284, 5461, 11, 475, 198, 2, 416, 477, 1724, 923, 14284, 1088, ...
3.410095
1,268
import os import shutil import argparse from pathlib import Path from time import time from collections import defaultdict import torch import numpy as np import pandas as pd torch.manual_seed(0) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Null') parser.add_argument('path', help='path of experiment, must contain config.py') parser.add_argument('--test', action='store_true', help='test only') args = parser.parse_args() os.environ['CONFIG_LOCAL_DIR'] = args.path # variables defined here are global/model level save_dir = Path(args.path) if not os.path.isfile(os.path.join(save_dir, 'config.py')): raise Exception('{}: wrong path or no local config'.format(save_dir)) from config_global import epoch, net, optimizer, criterion, data, online_train if not args.test: train() net, optimizer, criterion = load_model(save_dir.joinpath('state.pt')) test()
[ 11748, 28686, 198, 11748, 4423, 346, 198, 11748, 1822, 29572, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 640, 1330, 640, 198, 6738, 17268, 1330, 4277, 11600, 198, 11748, 28034, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 29...
2.926154
325
# from __future__ import unicode_literals import frappe, erpnext from frappe import _ import json from frappe.utils import flt, cstr, nowdate, nowtime from six import string_types
[ 2, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 11748, 5306, 27768, 11, 1931, 79, 19545, 198, 6738, 5306, 27768, 1330, 4808, 198, 11748, 33918, 198, 6738, 5306, 27768, 13, 26791, 1330, 781, 83, 11, 269, 2536, ...
3.232143
56
import json import subprocess PACMAN_SYNC_DB_COMMAND = 'sudo pacman --noconfirm -Sy' AUR_HELPER_COMMAND = 'paru --noconfirm -S {}' PACMAN_COMMAND = 'sudo pacman --noconfirm -S {}' with open('./config.json') as f: config = json.load(f) packages_raw = config.get('packages', {}) setup_raw = config.get('setup', {}) pacman_packages = set() aur_packages = set() scripts = [] for package_raw in packages_raw: # TODO: select with maybe website? or fzf? if package_raw.get('name') not in ['', None, 'custom dmenu', 'custom dwm']: if package_raw.get('script'): scripts.append(package_raw.get('script', ['echo error'])) pacman_packages.update(package_raw.get('pacman', [])) aur_packages.update(package_raw.get('aur', [])) pacman_packages_str = ' '.join(pacman_packages) aur_packages_str = ' '.join(aur_packages) run_cmds([ PACMAN_SYNC_DB_COMMAND, # Synchronize package database PACMAN_COMMAND.format(pacman_packages_str), # Install Pacman packages AUR_HELPER_COMMAND.format(aur_packages_str), # Install AUR packages ]) for script in scripts: run_cmds(script) for package_name, cmds in setup_raw.items(): if package_name in pacman_packages or package_name in aur_packages: run_cmds(cmds)
[ 11748, 33918, 198, 11748, 850, 14681, 198, 198, 44938, 10725, 62, 23060, 7792, 62, 11012, 62, 9858, 44, 6981, 796, 705, 24032, 23503, 805, 1377, 77, 36221, 69, 2533, 532, 13940, 6, 198, 32, 4261, 62, 39, 3698, 18973, 62, 9858, 44, 6...
2.546371
496
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField, SelectMultipleField, HiddenField from flask_pagedown.fields import PageDownField from wtforms import validators
[ 6738, 42903, 62, 86, 27110, 1330, 46947, 8479, 198, 6738, 266, 83, 23914, 1330, 10903, 15878, 11, 30275, 15878, 11, 39900, 15878, 11, 9683, 31217, 15878, 11, 20458, 15878, 198, 6738, 42903, 62, 79, 1886, 593, 13, 25747, 1330, 7873, 8048...
4.019608
51
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/8/18 9:50 # @Author : Matrix # @Github : https://github.com/blackmatrix7/ # @Blog : http://www.cnblogs.com/blackmatrix/ # @File : retry.py # @Software: PyCharm import time from functools import wraps __author__ = 'blackmatrix' """ """ def retry(max_retries: int =5, delay: (int, float) =0, step: (int, float) =0, exceptions: (BaseException, tuple, list) =BaseException, sleep=time.sleep, callback=None, validate=None): """ :param max_retries: :param delay: :param step: :param exceptions: tuplelist :param sleep: time.sleep tornadotime.sleep time.sleep :param callback: True True :param validate: False False :return: """ return wrapper if __name__ == '__main__': pass
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2488, 7575, 1058, 2177, 14, 23, 14, 1507, 860, 25, 1120, 198, 2, 2488, 13838, 1058, 24936, 198, 2, 2488, 38, 100...
2.25323
387
# -*- coding: utf-8 -*- # @Time : 2021/01/02 16:26 # @Author : lishijie import torch from torch.utils import data from torch.utils.data import DataLoader import torchvision from torchvision.transforms.transforms import Resize from .databases import *
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2488, 7575, 220, 220, 220, 220, 1058, 33448, 14, 486, 14, 2999, 1467, 25, 2075, 198, 2, 2488, 13838, 220, 220, 1058, 300, 680, 2926, 494, 198, 11748, 28034, 198, ...
2.988372
86
import pyeccodes.accessors as _
[ 11748, 279, 5948, 535, 4147, 13, 15526, 669, 355, 4808, 628 ]
3
11
# apetools Libraries from apetools.baseclass import BaseClass from apetools.builders import builder from apetools.lexicographers.lexicographer import Lexicographer # end SetUp
[ 198, 2, 2471, 316, 10141, 46267, 198, 6738, 2471, 316, 10141, 13, 8692, 4871, 1330, 7308, 9487, 198, 6738, 2471, 316, 10141, 13, 50034, 1330, 27098, 198, 6738, 2471, 316, 10141, 13, 2588, 291, 34063, 13, 2588, 291, 18539, 1330, 17210, ...
3.56
50
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Sentence level and Corpus level BLEU score calculation tool """ from __future__ import division, print_function import io import os import math import sys import argparse from fractions import Fraction from collections import Counter from functools import reduce from operator import or_ try: from nltk import ngrams except: def chen_and_cherry(references, hypothesis, p_n, hyp_len, smoothing=0, epsilon=0.1, alpha=5, k=5): """ Boxing Chen and Collin Cherry (2014) A Systematic Comparison of Smoothing Techniques for Sentence-Level BLEU. In WMT14. """ # No smoothing. if smoothing == 0: return p_n # Smoothing method 1: Add *epsilon* counts to precision with 0 counts. if smoothing == 1: return [Fraction(p_i.numerator + epsilon, p_i.denominator) if p_i.numerator == 0 else p_i for p_i in p_n] # Smoothing method 2: Add 1 to both numerator and denominator (Lin and Och 2004) if smoothing == 2: return [Fraction(p_i.numerator + 1, p_i.denominator + 1) for p_i in p_n] # Smoothing method 3: NIST geometric sequence smoothing # The smoothing is computed by taking 1 / ( 2^k ), instead of 0, for each # precision score whose matching n-gram count is null. # k is 1 for the first 'n' value for which the n-gram match count is null/ # For example, if the text contains: # - one 2-gram match # - and (consequently) two 1-gram matches # the n-gram count for each individual precision score would be: # - n=1 => prec_count = 2 (two unigrams) # - n=2 => prec_count = 1 (one bigram) # - n=3 => prec_count = 1/2 (no trigram, taking 'smoothed' value of 1 / ( 2^k ), with k=1) # - n=4 => prec_count = 1/4 (no fourgram, taking 'smoothed' value of 1 / ( 2^k ), with k=2) if smoothing == 3: incvnt = 1 # From the mteval-v13a.pl, it's referred to as k. for i, p_i in enumerate(p_n): if p_i == 0: p_n[i] = 1 / 2**incvnt incvnt+=1 return p_n # Smoothing method 4: # Shorter translations may have inflated precision values due to having # smaller denominators; therefore, we give them proportionally # smaller smoothed counts. Instead of scaling to 1/(2^k), Chen and Cherry # suggests dividing by 1/ln(len(T), where T is the length of the translation. if smoothing == 4: incvnt = 1 for i, p_i in enumerate(p_n): if p_i == 0: p_n[i] = incvnt * k / math.log(hyp_len) # Note that this K is different from the K from NIST. incvnt+=1 return p_n # Smoothing method 5: # The matched counts for similar values of n should be similar. To a # calculate the n-gram matched count, it averages the n1, n and n+1 gram # matched counts. if smoothing == 5: m = {} # Requires an precision value for an addition ngram order. p_n_plus5 = p_n + [modified_precision(references, hypothesis, 5)] m[-1] = p_n[0] + 1 for i, p_i in enumerate(p_n): p_n[i] = (m[i-1] + p_i + p_n_plus5[i+1]) / 3 m[i] = p_n[i] return p_n # Smoothing method 6: # Interpolates the maximum likelihood estimate of the precision *p_n* with # a prior estimate *pi0*. The prior is estimated by assuming that the ratio # between pn and pn1 will be the same as that between pn1 and pn2. if smoothing == 6: for i, p_i in enumerate(p_n): if i in [1,2]: # Skips the first 2 orders of ngrams. continue else: pi0 = p_n[i-1]**2 / p_n[i-2] # No. of ngrams in translation. l = sum(1 for _ in ngrams(hypothesis, i+1)) p_n[i] = (p_i + alpha * pi0) / (l + alpha) return p_n # Smoothing method if smoothing == 7: p_n = chen_and_cherry(references, hypothesis, p_n, hyp_len, smoothing=4) p_n = chen_and_cherry(references, hypothesis, p_n, hyp_len, smoothing=5) return p_n if __name__ == '__main__': parser = argparse.ArgumentParser(description='Arguments for calculating BLEU') parser.add_argument('-t', '--translation', type=str, required=True, help="translation file or string") parser.add_argument('-r', '--reference', type=str, required=True, help="reference file or string") parser.add_argument('-s', '--smooth', type=int, default=3, metavar='INT', required=False, help="smoothing method type (default: %(default)s)") parser.add_argument('-w', '--weights', type=str, default='0.25 0.25 0.25 0.25', help="weights for ngram (default: %(default)s)") parser.add_argument('-sl', '--sentence-level', action='store_true', help="print sentence level BLEU score (default: %(default)s)") parser.add_argument('-se', '--smooth-epsilon', type=float, default=0.1, help="empirical smoothing parameter for method 1 (default: %(default)s)") parser.add_argument('-sk', '--smooth-k', type=int, default=5, help="empirical smoothing parameter for method 4 (default: %(default)s)") parser.add_argument('-sa', '--smooth-alpha', type=int, default=5, help="empirical smoothing parameter for method 6 (default: %(default)s)") args = parser.parse_args() hypothesis_file = args.translation reference_file = args.reference weights = tuple(map(float, args.weights.split())) segment_level = args.sentence_level smoothing_method = args.smooth epsilon = args.smooth_epsilon alpha = args.smooth_alpha k = args.smooth_k # Calculate BLEU scores. # Set --sentence-level and other params to calc sentence-level BLEU in a FILE or string if os.path.isfile(reference_file): with io.open(reference_file, 'r', encoding='utf8') as reffin, \ io.open(hypothesis_file, 'r', encoding='utf8') as hypfin: list_of_references = ((r.split(),) for r in reffin) hypotheses = (h.split() for h in hypfin) corpus_bleu(list_of_references, hypotheses, weights=weights, segment_level=segment_level, smoothing=smoothing_method, epsilon=epsilon, alpha=alpha, k=k) else: reffin = [reference_file] hypfin = [hypothesis_file] list_of_references = ((r.split(),) for r in reffin) hypotheses = (h.split() for h in hypfin) corpus_bleu(list_of_references, hypotheses, weights=weights, segment_level=True, smoothing=smoothing_method, epsilon=epsilon, alpha=alpha, k=k)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 31837, 594, 1241, 290, 44874, 1241, 347, 2538, 52, 4776, 17952, 2891, 198, 37811, 198, 198, 6738, 1159...
2.254082
3,062
DSN = 'postgresql://edward:edward@postgres:5432/chat'
[ 5258, 45, 796, 705, 7353, 34239, 13976, 1378, 276, 904, 25, 276, 904, 31, 7353, 34239, 25, 4051, 2624, 14, 17006, 6, 198 ]
2.347826
23
from sqlite_framework.sql.item.base import SqlItem from sqlite_framework.sql.item.column import Column
[ 6738, 44161, 578, 62, 30604, 13, 25410, 13, 9186, 13, 8692, 1330, 311, 13976, 7449, 198, 6738, 44161, 578, 62, 30604, 13, 25410, 13, 9186, 13, 28665, 1330, 29201, 628, 198 ]
3.387097
31
from .report_group import GroupReport from .report_single import SingleReport
[ 6738, 764, 13116, 62, 8094, 1330, 4912, 19100, 198, 6738, 764, 13116, 62, 29762, 1330, 14206, 19100, 198 ]
4.333333
18
""" Mixin for returning history frames. """ from collections import deque from typing import Deque from rx.core.typing import Observable from baboon_tracking.models.frame import Frame
[ 37811, 201, 198, 35608, 259, 329, 8024, 2106, 13431, 13, 201, 198, 37811, 201, 198, 201, 198, 6738, 17268, 1330, 390, 4188, 201, 198, 6738, 19720, 1330, 1024, 4188, 201, 198, 6738, 374, 87, 13, 7295, 13, 774, 13886, 1330, 19243, 540, ...
3.229508
61
import json import html from pathlib import Path from elm_doc.utils import Namespace # Note: title tag is omitted, as the Elm app sets the title after # it's initialized. PAGE_TEMPLATE = ''' <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link rel="shortcut icon" size="16x16, 32x32, 48x48, 64x64, 128x128, 256x256" href="{mount_point}/assets/favicon.ico"> <link rel="stylesheet" href="{mount_point}/assets/style.css"> <script src="{mount_point}/artifacts/elm.js"></script> <script src="{mount_point}/assets/highlight/highlight.pack.js"></script> <link rel="stylesheet" href="{mount_point}/assets/highlight/styles/default.css"> </head> <body> <script> try {{ const fontsLink = document.createElement("link"); fontsLink.href = "{mount_point}/assets/fonts/" + ((navigator.userAgent.indexOf("Macintosh") > -1) ? "_hints_off.css" : "_hints_on.css"); fontsLink.rel = "stylesheet"; document.head.appendChild(fontsLink); }} catch(e) {{ // loading the font is not essential; log the error and move on console.log(e); }} Elm.Main.init({init}); </script> </body> </html> ''' # noqa: E501
[ 11748, 33918, 198, 11748, 27711, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 6738, 1288, 76, 62, 15390, 13, 26791, 1330, 28531, 10223, 628, 198, 2, 5740, 25, 3670, 7621, 318, 22532, 11, 355, 262, 35189, 598, 5621, 262, 3670, 706, 19...
2.551948
462
''' v1.0 2021.1 01Studio www.01Studio.org ''' # import time from machine import Pin,SoftI2C,ADC from ssd1306 import SSD1306_I2C #oled i2c = SoftI2C(scl=Pin(10), sda=Pin(11)) #I2Cscl--> 10, sda --> 11 oled = SSD1306_I2C(128, 64, i2c, addr=0x3c) #OLED128*64,OLEDI2C0x3c #ADC1,Pin=27 Water_level = ADC(1) while True: oled.fill(0) # oled.text('01Studio', 0, 0) # 01Studio oled.text('Water Level test', 0, 15) # value=Water_level.read_u16() #ADC # oled.text(str(value)+' (65535)',0,40) #0-40950-3V'%.2f'%2 oled.text(str('%.2f'%(value/65535*3.3))+' V',0,55) #50-4cm if 0 <= value <=9602: oled.text('0cm', 60, 55) if 9602 < value <= 14403: oled.text('1cm', 60, 55) if 14403 < value <= 19204: oled.text('2cm', 60, 55) if 19204 < value <= 20804: oled.text('3cm', 60, 55) if 20804 < value: oled.text('4cm', 60, 55) oled.show() time.sleep_ms(1000)
[ 7061, 6, 198, 198, 85, 16, 13, 15, 198, 1238, 2481, 13, 16, 198, 486, 41501, 7324, 13, 486, 41501, 13, 2398, 198, 198, 7061, 6, 198, 198, 2, 198, 11748, 640, 198, 6738, 4572, 1330, 13727, 11, 18380, 40, 17, 34, 11, 2885, 34, 1...
1.975771
454
from typing import Annotated Problem = Annotated[str, "code cfs problems have, ex. 1348B"] ProblemWidth = int CFSSectionsData = tuple[int, ...]
[ 6738, 19720, 1330, 1052, 1662, 515, 628, 198, 40781, 796, 1052, 1662, 515, 58, 2536, 11, 366, 8189, 269, 9501, 2761, 423, 11, 409, 13, 1511, 2780, 33, 8973, 198, 40781, 30916, 796, 493, 198, 22495, 5432, 478, 507, 6601, 796, 46545, ...
3.0625
48
import pandas as pd import numpy as np import matplotlib.pyplot as plt ### import nltk from nltk.corpus import stopwords from nltk.tokenize import word_tokenize # from nltk.stem import WordNetLemmatizer from nltk.stem import PorterStemmer ### from sklearn.naive_bayes import MultinomialNB from sklearn.metrics import confusion_matrix, classification_report from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import CountVectorizer ### from loadRandom import loadRandom2 ps = PorterStemmer() # lemmatizer = WordNetLemmatizer() if __name__ == '__main__': _seed = 123 _observations = 1e4 _subsets = [1, 2, 3, 4] location = '/Users/caitchison/Documents/Yelp/yelp_dataset/restaurants_only.csv' data = loadRandom2(location, _observations, seed=_seed, n=3778803).loc[:, ('text', 'useful', 'cool', 'funny', 'stars_x')] # Calculate "interaction" score data['interactions'] = data.useful + data.cool + data.funny data = data[data['interactions'] >= _subsets[0]].dropna() # Subset to get equal amounts of low-useful and high-useful masks = [data.interactions == x for x in _subsets] masks.append(data.interactions > _subsets[-1]) subsetSize = min([sum(mask) for mask in masks]) print("Creating subsets of size %i" % subsetSize) newData = pd.DataFrame([]) for mask in masks: df = data[mask].sample(n=subsetSize, random_state=_seed) newData = newData.append(df) data = newData # Split interactions into quantiles (5) data['group'] = pd.qcut(data['interactions'], q=5, labels=False) print(pd.qcut(data['interactions'], q=5).cat.categories) data.rename(columns={"stars_x": "stars"}) # Create a bag of words and convert the text to a sparse matrix text = np.array(data['text']) bow = CountVectorizer(analyzer=textProcess).fit(text) print("Unique (Not Stop) Words:", len(bow.vocabulary_)) text = bow.transform(text) # Split into features for testing and training at 30% xTrain, xTest, yTrain, yTest = train_test_split( text, np.array(data['group']), test_size=0.3, random_state=_seed) # Train model (Multinomial Naive Bayes) nb = MultinomialNB() nb.fit(xTrain, yTrain) # Test and Evaluate Model preds = nb.predict(xTest) print(confusion_matrix(yTest, preds)) print('\n') print(classification_report(yTest, preds))
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 21017, 198, 11748, 299, 2528, 74, 198, 6738, 299, 2528, 74, 13, 10215, 79, 385, 1330, 2245, 10879,...
2.533062
983
# -*- coding: utf-8 -*- import csv import json outdirectory = "outputCSV/" tweetsFile = "tweets.txt"; outputFile = "mostUsedHasgtags.csv"; tweetsList = [] #List that contains all the tweets readed from a file hashtagTable = {}; # Dictionary with key= hashtags and value= frecuency for this hashtag """ Returns a list of tweets readen from a file. if there's a problem None object will be returned """ """ Creates a hasmap frecuency table where keys are the hashtags and values are the number or appeareances of that hashtag in all the twetts. Returns None if we coudn't create the Hashmap and a dictionary if everything works""" """ Returns a ordered hasmap, where the sorting was made taking into acccount the value of each key on the hasmap and desdending order. """ """ This function writes header and data to a .csv file pass by value If the outputFile passed is not a .csv type. A failure will returned (False) """ tweetsList = loadTweets(tweetsFile); #Loading a list of twetts from a file if (tweetsList != None): print "Loading twetts from file...[OK]" else: "Loading twetts from file...[ERROR]" hashtagTable = createHashtagFrecuencyTable(tweetsList); if (hashtagTable != None): print "Creating hashtags table with its frecuencies...[OK]" else: "Creating hashtags table with its frecuencies...[ERROR]" orderedHashtagTable = orderHashtagTable(hashtagTable) if (orderedHashtagTable != None): print "Ordering hashtags table in desdending order...[OK]" else: "Ordering hashtags table in desdending order...[ERROR]" headerList = ["hashtag", "frecuency"] # .csv header to write on the file if (writeFile(headerList, orderedHashtagTable[:10], outputFile)): print "Writing csv file with top used hashtags...[OK]" else: "Writing csv file with top used hashtags...[ERROR]"
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 269, 21370, 198, 11748, 33918, 198, 198, 448, 34945, 220, 197, 28, 366, 22915, 7902, 53, 30487, 198, 83, 732, 1039, 8979, 220, 197, 197, 28, 366, 83, 732, 1039,...
3.379699
532
import time import json import argparse import websocket import requests import github MY_NAME = 'kit' # should be able to avoid this in the future TOKEN = 'XXXXXXX' GITHUB_USERNAME_BY_SLACK_USERNAME = { "adam": "adamsmith", # XXXXXXX ... } channel_ids_by_name = {} channel_names_by_id = {} next_id = 0 if __name__ == '__main__': try: main() except KeyboardInterrupt: pass
[ 11748, 640, 198, 11748, 33918, 198, 11748, 1822, 29572, 198, 198, 11748, 2639, 5459, 198, 11748, 7007, 198, 198, 11748, 33084, 198, 198, 26708, 62, 20608, 796, 705, 15813, 6, 220, 1303, 815, 307, 1498, 284, 3368, 428, 287, 262, 2003, ...
2.637584
149
import discord import requests from discord.ext import commands
[ 11748, 36446, 198, 11748, 7007, 198, 6738, 36446, 13, 2302, 1330, 9729 ]
5.25
12
target_num = 0 j = 0 while target_num == 0: pent_ind = float((1 + ( 1 + 24*j*(2*j-1))**.5)/6) tri_ind = float((-1 + (1+8*j*(2*j-1)))/2) if pent_ind.is_integer() and tri_ind.is_integer(): num = j*(2*j-1) if num != 1 and num != 40755: target_num = num j += 1 print(target_num) # 1533776805 """ I had a brute force solution, but it was a bit over a minute. By solving for the index values of pentagon and triangle numbers in terms of the index value of the hexagon numbers, the formulas in pent_ind and tri_ind pop out of the quadratic equation. Basically those variables will only be integers if j is a valid index for a pentagon number and triangle number as well. """
[ 16793, 62, 22510, 796, 657, 198, 73, 796, 657, 198, 198, 4514, 2496, 62, 22510, 6624, 657, 25, 198, 220, 220, 220, 28145, 62, 521, 796, 12178, 19510, 16, 1343, 357, 352, 1343, 1987, 9, 73, 9, 7, 17, 9, 73, 12, 16, 4008, 1174, ...
2.626374
273
#!/usr/bin/python # -*- coding: utf-8 -*- # Importo les llibreries import socket import RPi.GPIO as GPIO import time # Faig la configuraci bsica del GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) # Noms utilitzo el 18. Es podria fer un bucle per activar-ne diversos alhora. # Indico la IP del servidor i el port de comunicaci host = "PLACE_YOUR_SERVER_IP_HERE" port = 12345 # Inicio un bucle infinit while 1: s = socket.socket() # Creo el socket s.connect((host, port)) # Connecto al servidor data = s.recv(1024) # Rebo dades GPIO.output(int(data), GPIO.HIGH) # La dada rebuda indica el pin del gpio que es far UP time.sleep(1) # S'espera 1 segon GPIO.output(int(data), GPIO.LOW) # Fa un DOWN del pin s.close() # Tanca la connexi
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 17267, 78, 10287, 32660, 571, 260, 1678, 198, 11748, 17802, 198, 11748, 25812, 72, 13, 16960, 9399, 355, 50143, 198, ...
2.476636
321
## ------------------------------------------------------------------------------------------------- ## -- Project : MLPro - A Synoptic Framework for Standardized Machine Learning Tasks ## -- Package : mlpro.rl.envmodels ## -- Module : mlp_robotinhtm ## ------------------------------------------------------------------------------------------------- ## -- History : ## -- yyyy-mm-dd Ver. Auth. Description ## -- 2021-12-17 0.0.0 MRD Creation ## -- 2021-12-17 1.0.0 MRD Released first version ## -- 2021-12-20 1.0.1 DA Replaced 'done' by 'success' ## -- 2021-12-21 1.0.2 DA Class MLPEnvMdel: renamed method reset() to _reset() ## -- 2022-01-02 2.0.0 MRD Refactoring due to the changes on afct pool on ## -- TorchAFctTrans ## -- 2022-02-25 2.0.1 SY Refactoring due to auto generated ID in class Dimension ## ------------------------------------------------------------------------------------------------- """ Ver. 2.0.1 (2022-02-25) This module provides Environment Model based on MLP Neural Network for robotinhtm environment. """ import torch import transformations from mlpro.rl.models import * from mlpro.rl.pool.envs.robotinhtm import RobotArm3D from mlpro.rl.pool.envs.robotinhtm import RobotHTM from mlpro.sl.pool.afct.afctrans_pytorch import TorchAFctTrans from torch.utils.data.sampler import SubsetRandomSampler from collections import deque # Buffer
[ 2235, 16529, 3880, 12, 198, 2235, 1377, 4935, 1058, 10373, 2964, 532, 317, 16065, 8738, 291, 25161, 329, 8997, 1143, 10850, 18252, 309, 6791, 198, 2235, 1377, 15717, 1058, 25962, 1676, 13, 45895, 13, 24330, 27530, 198, 2235, 1377, 19937, ...
3.064449
481
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Author : # @Email : 877362867@qq.com # @Date : 2021/02/22 10:29 """ icdar2013 zip """ import re from pyxllib.xl import File, Dir, shorten
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2488, 13838, 1058, 220, 198, 2, 2488, 15333, 220, 1058, 807, 3324, 2623, 2078, 3134, 31, 38227, 13, 785, 198, ...
2.186813
91
import os import numpy as np import torch from transformers import BertTokenizer from tensorflow.keras.utils import to_categorical from NewDataLoader import * from config import * import warnings
[ 11748, 28686, 198, 11748, 299, 32152, 355, 45941, 198, 198, 11748, 28034, 198, 6738, 6121, 364, 1330, 22108, 30642, 7509, 198, 198, 6738, 11192, 273, 11125, 13, 6122, 292, 13, 26791, 1330, 284, 62, 66, 2397, 12409, 198, 6738, 968, 6601,...
3.703704
54
from airflow import DAG from operators import LoadDimensionOperator def load_dim_subdag( parent_dag_name: str, task_id: str, redshift_conn_id: str, sql_statement: str, do_truncate: bool, table_name: str, **kwargs, ): """ Airflow's subdag wrapper. Implements LoadDimensionOperator operator. Subdag's name will be f'{parent_dag_name}.{task_id}' Subdag related keyword arguments: - parent_dag_name -- Parent DAG name - task_id -- Task ID for the subdag to use Keyword arguments: redshift_conn_id -- Airflow connection name for Redshift detail sql_statement -- SQL statement to run do_truncate -- Does the table need to be truncated before running SQL statement table_name -- Dimension table name All keyword arguments will be passed to LoadDimensionOperator """ dag = DAG(f'{parent_dag_name}.{task_id}', **kwargs) load_dimension_table = LoadDimensionOperator( task_id=task_id, dag=dag, redshift_conn_id=redshift_conn_id, sql_query=sql_statement, do_truncate=do_truncate, table_name=table_name, ) load_dimension_table return dag
[ 6738, 45771, 1330, 360, 4760, 198, 6738, 12879, 1330, 8778, 29271, 3004, 18843, 1352, 628, 198, 4299, 3440, 62, 27740, 62, 7266, 67, 363, 7, 198, 220, 220, 220, 2560, 62, 67, 363, 62, 3672, 25, 965, 11, 198, 220, 220, 220, 4876, 6...
2.394175
515
# coding: utf-8 from __future__ import print_function from __future__ import absolute_import from __future__ import division from src.yolo_net import YoloTest, Yolo import torch import cv2 import numpy as np # net = Yolo(10177) # state_dict = torch.load('trained_models\\only_params_trained_yolo_coco') # net.load_state_dict(state_dict) # net.eval() # img10 = readImage('D:\\dev\\dataset\\CASIA-WebFace\\0000045\\001.jpg') # img11 = readImage('D:\\dev\\dataset\\CASIA-WebFace\\0000045\\002.jpg') # img21 = readImage('D:\\dev\\dataset\\CASIA-WebFace\\0000099\\001.jpg') # # logits = net(img10) # print(logits.view(1, 5, -1, 49).shape) # output10 = net(img10).reshape((1024*7*7,)).detach().numpy() # output11 = net(img11).reshape((1024*7*7,)).detach().numpy() # output21 = net(img21).reshape((1024*7*7,)).detach().numpy() # dis11 = np.linalg.norm(output10 - output11) # dis21 = np.linalg.norm(output10 - output21) # # print(dis11) # print(dis21) # # # def cosdis(vec1, vec2): # return np.dot(vec1,vec2)/(np.linalg.norm(vec1)*(np.linalg.norm(vec2))) # # cosdis11 = cosdis(output10, output11) # cosdis21 = cosdis(output10, output21) # print(cosdis11) # print(cosdis21)
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 198, 6738, 12351, 13, 88, 14057, 62, 3262, ...
2.425358
489
# coding=utf-8 """ Google Earth Engine MODIS Collections """ from . import Collection, TODAY, Band from functools import partial IDS = [ 'MODIS/006/MOD09GQ', 'MODIS/006/MYD09GQ', 'MODIS/006/MOD09GA', 'MODIS/006/MYD09GA', 'MODIS/006/MOD13Q1', 'MODIS/006/MYD13Q1' ] START = { 'MODIS/006/MOD09GQ': '2000-02-24', 'MODIS/006/MYD09GQ': '2000-02-24', 'MODIS/006/MOD09GA': '2000-02-24', 'MODIS/006/MYD09GA': '2000-02-24', 'MODIS/006/MOD13Q1': '2000-02-18', 'MODIS/006/MYD13Q1': '2000-02-18', } END = { 'MODIS/006/MOD09GQ': TODAY, 'MODIS/006/MYD09GQ': TODAY, 'MODIS/006/MOD09GA': TODAY, 'MODIS/006/MYD09GA': TODAY, 'MODIS/006/MOD13Q1': TODAY, 'MODIS/006/MYD13Q1': TODAY, }
[ 2, 19617, 28, 40477, 12, 23, 198, 37811, 3012, 3668, 7117, 19164, 1797, 50004, 37227, 198, 198, 6738, 764, 1330, 12251, 11, 20092, 11, 10243, 198, 6738, 1257, 310, 10141, 1330, 13027, 198, 198, 14255, 796, 685, 198, 220, 220, 220, 705...
1.97027
370
""" This module provides a method to generate a random number between 0 and the specified number """ import random import math def random_num(max): """ Generates a random number Parameters: max(int): the range upper limit Returns: int: the random number """ return math.floor(random.random() * max)
[ 37811, 770, 8265, 3769, 257, 2446, 284, 7716, 257, 4738, 1271, 1022, 657, 290, 262, 7368, 1271, 37227, 198, 11748, 4738, 198, 11748, 10688, 628, 198, 4299, 4738, 62, 22510, 7, 9806, 2599, 198, 220, 220, 220, 37227, 220, 198, 220, 220,...
3.219048
105
import math import numpy as np
[ 11748, 10688, 198, 11748, 299, 32152, 355, 45941, 628 ]
3.555556
9
import ctypes import struct from .dave_define import * from .dave_enum import * from .dave_msg_id import * from .dave_msg_struct import * from .dave_struct import *
[ 11748, 269, 19199, 198, 11748, 2878, 628, 198, 6738, 764, 67, 1015, 62, 13086, 1330, 1635, 198, 6738, 764, 67, 1015, 62, 44709, 1330, 1635, 198, 6738, 764, 67, 1015, 62, 19662, 62, 312, 1330, 1635, 198, 6738, 764, 67, 1015, 62, 1966...
2.964286
56
# -*- coding: utf-8 -*- """@package Methods.Machine.Conductor.check Check that the Conductor is correct @date Created on Thu Jan 22 17:50:02 2015 @copyright (C) 2015-2016 EOMYS ENGINEERING. @author pierre_b """ from pyleecan.Methods.Machine.LamSlotWind.check import Lam_WindCheckError def check(self): """Check that the Conductor object is correct Parameters ---------- self : Conductor A Conductor object Returns ------- None """ pass
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 31, 26495, 25458, 13, 37573, 13, 25559, 33029, 13, 9122, 198, 9787, 326, 262, 9724, 33029, 318, 3376, 198, 31, 4475, 15622, 319, 26223, 2365, 2534, 1596, 25, 1120...
2.777143
175
from pathlib import Path from typing import List import cv2 import numpy as np from shapely import geometry from shapely.strtree import STRtree from wholeslidedata.annotation.structures import Annotation, Point, Polygon from wholeslidedata.image.wholeslideimage import WholeSlideImage from wholeslidedata.image.wholeslideimagewriter import WholeSlideMaskWriter from wholeslidedata.samplers.utils import shift_coordinates
[ 6738, 3108, 8019, 1330, 10644, 198, 6738, 19720, 1330, 7343, 198, 198, 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 5485, 306, 1330, 22939, 198, 6738, 5485, 306, 13, 2536, 21048, 1330, 19269, 21048, 198, 6738, 1795...
3.601695
118
import pytest from ..slicing_tuples import tuple_slice
[ 11748, 12972, 9288, 198, 6738, 11485, 82, 677, 278, 62, 28047, 2374, 1330, 46545, 62, 48369, 628 ]
3.294118
17
# -*- coding: utf-8 -*- """This class maintains the internal dfTimewolf state. Use it to track errors, abort on global failures, clean up after modules, etc. """ from dataclasses import dataclass from concurrent.futures import ThreadPoolExecutor, Future import importlib import logging import threading import traceback from typing import TYPE_CHECKING, Callable, Dict, List, Sequence, Type, Any, TypeVar, cast # pylint: disable=line-too-long from dftimewolf.cli import curses_display_manager as cdm from dftimewolf.config import Config from dftimewolf.lib import errors, utils from dftimewolf.lib.containers.interface import AttributeContainer from dftimewolf.lib.errors import DFTimewolfError from dftimewolf.lib.modules import manager as modules_manager from dftimewolf.lib.module import ThreadAwareModule, BaseModule if TYPE_CHECKING: from dftimewolf.lib import module as dftw_module from dftimewolf.lib.containers import interface T = TypeVar("T", bound="interface.AttributeContainer") # pylint: disable=invalid-name,line-too-long # TODO(tomchop): Consider changing this to `dftimewolf.state` if we ever need # more granularity. logger = logging.getLogger('dftimewolf') NEW_ISSUE_URL = 'https://github.com/log2timeline/dftimewolf/issues/new'
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 1212, 1398, 16047, 262, 5387, 47764, 14967, 413, 4024, 1181, 13, 198, 198, 11041, 340, 284, 2610, 8563, 11, 15614, 319, 3298, 15536, 11, 3424, 510, 706, 13103, 11...
3.165829
398
### Implements database management for Authentication Server and TGS ### from Query import * from sqlite3 import * from config import *
[ 21017, 1846, 1154, 902, 6831, 4542, 329, 48191, 9652, 290, 309, 14313, 44386, 198, 198, 6738, 43301, 1330, 1635, 198, 6738, 44161, 578, 18, 1330, 1635, 198, 6738, 4566, 1330, 1635, 628, 198, 197, 197 ]
4.028571
35
from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from .models import Person from .serializers import PersonSerializer
[ 6738, 1334, 62, 30604, 13, 12501, 273, 2024, 1330, 40391, 62, 1177, 198, 6738, 1334, 62, 30604, 13, 26209, 1330, 18261, 198, 6738, 1334, 62, 30604, 1330, 3722, 198, 198, 6738, 764, 27530, 1330, 7755, 198, 6738, 764, 46911, 11341, 1330, ...
4.255319
47
import numpy as np import matplotlib.pyplot as plt field_width = 396 #cm field_hight = 180 #cm goal_length = 180 #cm threshold = 36 field_width_threshold_num = field_width / threshold + 1 field_width_threshold = [Y * threshold - field_width / 2.0 for Y in xrange(field_width_threshold_num)] field_hight_threshold_num = field_hight / threshold + 1 field_hight_threshold = [X * threshold for X in xrange(field_hight_threshold_num)] ball_velo_x_threshold = [X * 100.0 for X in [-1.0, -0.8, -0.6, -0.4, -0.2, 0.0]] ball_velo_x_threshold_num = len(ball_velo_x_threshold) + 1 ball_velo_y_threshold = [Y * 50.0 for Y in [-1.0, -0.8, -0.6, -0.4, -0.2, 0.0, 0.2, 0.4, 0.6, 0.8, 1.0]] ball_velo_y_threshold_num = len(ball_velo_y_threshold) + 1 tau = 0.2 #sec fall_time = 10 robot_states = 3 #epsilon = 0.1 epsilon = 0.00001 alpha = 0.5 gamma = 0.5 STAND, LEFT, RIGHT, BALL = range(4) COMPLETED = "COMPLETED" FAILED = "FAILED" ACTIVE = "ACTIVE" if __name__ == '__main__': #Soccer(max_episode=100, plot=True) Soccer(max_episode=10000000, plot=False)
[ 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 3245, 62, 10394, 796, 48758, 1303, 11215, 198, 3245, 62, 71, 432, 796, 11546, 1303, 11215, 198, 35231, 62, 13664, 796, 11546, 1303, ...
2.256959
467
from pytest import raises from gsea_api.molecular_signatures_db import MolecularSignaturesDatabase
[ 6738, 12972, 9288, 1330, 12073, 198, 198, 6738, 308, 8583, 62, 15042, 13, 76, 2305, 10440, 62, 12683, 6691, 62, 9945, 1330, 38275, 11712, 6691, 38105, 628, 198 ]
3.642857
28
from django.contrib import admin, auth from django.contrib.auth.models import Group from django.shortcuts import get_object_or_404, redirect, render from django.urls import path, reverse, reverse_lazy from django.utils.translation import gettext_lazy as _ from adminsortable2.admin import SortableAdminMixin from froide.api import api_router from froide.follow.admin import FollowerAdmin from froide.helper.admin_utils import make_choose_object_action, make_emptyfilter from froide.helper.widgets import TagAutocompleteWidget from froide.organization.models import Organization from .api_views import GovernmentPlanViewSet from .auth import get_allowed_plans, has_limited_access from .forms import ( GovernmentPlanForm, GovernmentPlanUpdateAcceptProposalForm, GovernmentPlanUpdateForm, ) from .models import ( Government, GovernmentPlan, GovernmentPlanFollower, GovernmentPlanSection, GovernmentPlanUpdate, ) User = auth.get_user_model() api_router.register(r"governmentplan", GovernmentPlanViewSet, basename="governmentplan") def execute_assign_organization(admin, request, queryset, action_obj): queryset.update(organization=action_obj) def execute_assign_group(admin, request, queryset, action_obj): queryset.update(group=action_obj) PLAN_ACTIONS = { "assign_organization": make_choose_object_action( Organization, execute_assign_organization, _("Assign organization...") ), "assign_group": make_choose_object_action( Group, execute_assign_group, _("Assign permission group...") ), } admin.site.register(Government, GovernmentAdmin) admin.site.register(GovernmentPlan, GovernmentPlanAdmin) admin.site.register(GovernmentPlanUpdate, GovernmentPlanUpdateAdmin) admin.site.register(GovernmentPlanSection, GovernmentPlanSectionAdmin) admin.site.register(GovernmentPlanFollower, FollowerAdmin) govplan_admin_site = GovPlanAdminSite(name="govplanadmin") govplan_admin_site.register(GovernmentPlan, GovernmentPlanAdmin) govplan_admin_site.register(GovernmentPlanUpdate, GovernmentPlanUpdateAdmin)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 11, 6284, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 4912, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 651, 62, 15252, 62, 273, 62, 26429, 11, 18941, 11, 85...
3.268025
638
try: import unittest2 as unittest except: import unittest from mpegdash.parser import MPEGDASHParser
[ 28311, 25, 198, 220, 220, 220, 1330, 555, 715, 395, 17, 355, 555, 715, 395, 198, 16341, 25, 198, 220, 220, 220, 1330, 555, 715, 395, 198, 198, 6738, 285, 431, 21287, 1077, 13, 48610, 1330, 41203, 35, 11211, 46677, 628 ]
2.707317
41
arr = [3, 5, 8, 10, 12, 15, 18, 20, 20, 50, 60] low = 1 high = 11 key = 50 index = BinarySearchIt(arr, low, high, key) if index != -1: print ("Element", key,"is present at index %d" %(index)) else: print ("Element %d is not present" %(key))
[ 198, 198, 3258, 796, 685, 18, 11, 642, 11, 807, 11, 838, 11, 1105, 11, 1315, 11, 1248, 11, 1160, 11, 1160, 11, 2026, 11, 3126, 60, 198, 9319, 796, 352, 198, 8929, 796, 1367, 198, 2539, 796, 2026, 198, 198, 9630, 796, 45755, 1824...
2.436893
103
#--- Day 2: Bathroom Security --- from typing import List test_data = """ULL RRDDD LURDL UUUUD""" assert solve1(test_data) == '1985' assert solve2(test_data) == '5DB3' if __name__ == '__main__': from aocd.models import Puzzle puzzle = Puzzle(2016, 2) answer_1 = solve1(puzzle.input_data) print(answer_1) puzzle.answer_a = answer_1 answer_2 = solve2(puzzle.input_data) puzzle.answer_b = answer_2
[ 2, 6329, 3596, 362, 25, 24967, 3823, 4765, 11420, 198, 6738, 19720, 1330, 7343, 628, 628, 198, 198, 9288, 62, 7890, 796, 37227, 9994, 198, 21095, 16458, 35, 198, 43, 4261, 19260, 198, 30100, 52, 8322, 37811, 198, 198, 30493, 8494, 16,...
2.468571
175
#!/usr/bin/python3 import argparse import koji import os from pprint import pprint if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 11748, 1822, 29572, 198, 11748, 479, 31370, 198, 11748, 28686, 198, 198, 6738, 279, 4798, 1330, 279, 4798, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220...
2.659574
47
# -*- coding: utf-8 -*- """Main module {{cookiecutter.project_name}} """ from __future__ import absolute_import from __future__ import unicode_literals
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 13383, 8265, 22935, 44453, 8968, 353, 13, 16302, 62, 3672, 11709, 37227, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 133...
3.122449
49
from config import * from utils import * import datetime import pickle indir_vocab_jnames = VOCAB_JNAMES indir_bio_srt = BIO_SRT indir_sorted_fperson_fname = SORTED_FPERSON_FNAME indir_sorted_lperson_fname = SORTED_LPERSON_FNAME print indir_vocab_jnames with open(indir_vocab_jnames,'rb') as v: all_vocab=pickle.load(v) with open(indir_bio_srt,'rb') as v: all_bio_vocab=pickle.load(v) all_bio_vocab = [a.decode('utf-8') for a in all_bio_vocab] sorted_fname= read_sorted_file_into_array(indir_sorted_fperson_fname) sorted_lname= read_sorted_file_into_array(indir_sorted_lperson_fname) #test()
[ 6738, 4566, 1330, 1635, 198, 198, 6738, 3384, 4487, 1330, 1635, 198, 11748, 4818, 8079, 198, 11748, 2298, 293, 198, 198, 521, 343, 62, 18893, 397, 62, 73, 14933, 796, 569, 4503, 6242, 62, 41, 45, 29559, 198, 521, 343, 62, 65, 952, ...
2.18705
278
from rich.console import Console from rich.table import Table from rich.progress import track from time import sleep import sys
[ 6738, 5527, 13, 41947, 1330, 24371, 198, 6738, 5527, 13, 11487, 1330, 8655, 198, 6738, 5527, 13, 33723, 1330, 2610, 198, 6738, 640, 1330, 3993, 198, 11748, 25064, 628 ]
4.448276
29
# coding: utf-8 import datetime from flask_login import login_required, current_user from flask import Blueprint, request from app.libs.http import jsonify, error_jsonify from app.libs.db import session from app.serializer.notice import NoticeParaSchema from app.model.notice import Notice bp_admin_notification = Blueprint('admin_notification', __name__, url_prefix='/admin/notification')
[ 2, 220, 19617, 25, 3384, 69, 12, 23, 198, 11748, 4818, 8079, 198, 198, 6738, 42903, 62, 38235, 1330, 17594, 62, 35827, 11, 1459, 62, 7220, 198, 198, 6738, 42903, 1330, 39932, 11, 2581, 198, 198, 6738, 598, 13, 8019, 82, 13, 4023, ...
3.410256
117
from fixture.orm import ORMfixture from model.group import Group from model.contact import Contact import random db = ORMfixture(host='127.0.0.1', name='addressbook', user='root', password='')
[ 6738, 29220, 13, 579, 1330, 6375, 44, 69, 9602, 198, 6738, 2746, 13, 8094, 1330, 4912, 198, 6738, 2746, 13, 32057, 1330, 14039, 198, 198, 11748, 4738, 198, 198, 9945, 796, 6375, 44, 69, 9602, 7, 4774, 11639, 16799, 13, 15, 13, 15, ...
3.266667
60
from django.urls import reverse_lazy from django.contrib.auth import get_user_model from django.views.generic import CreateView from . import forms User = get_user_model()
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 9575, 62, 75, 12582, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 651, 62, 7220, 62, 19849, 198, 6738, 42625, 14208, 13, 33571, 13, 41357, 1330, 13610, 7680, 198, 198, 6738, 764, 133...
3.240741
54
#!/usr/bin/env python # -*- encoding: utf-8 -*- from torch.nn import Module from torch.nn.modules.loss import _Loss from torch.optim import Optimizer from colossalai.builder import build_gradient_handler from colossalai.context import ParallelMode from colossalai.core import global_context as gpc from colossalai.logging import get_global_dist_logger from colossalai.nn import (ZeroRedundancyOptimizer_Level_2, ZeroRedundancyOptimizer_Level_3) from .schedule import BaseSchedule def train(self): """Sets the model to training mode. """ self.training = True self._model.train() def eval(self): """Sets the model to evaluation mode. """ self.training = False self._model.eval() def step(self, data_iter, is_last_iteration: bool = False, return_loss=True): """A running step based on the schedule. Usually, it runs a training or evaluation over a batch of dataset. :param data_iter: Data iterator of the dataset :param is_last_iteration: If True, this iteration is the last iteration in the epoch :param return_loss: loss will be returned if True :type data_iter: Iterator :type is_last_iteration: bool, optional :type return_loss: bool, optional :return: (output, lablel, loss) """ if self.training: self._optimizer.zero_grad() # differentiate training and eval with grad accum if self.training: for i in range(self._grad_accum_size): output, label, loss = self._schedule.forward_backward_step( data_iter, self._model, self._criterion, self._optimizer, forward_only=False, grad_accum_size=self._grad_accum_size, return_loss=return_loss) if i == self._grad_accum_size - 1: # all reduce gradients self.handle_gradient() self._schedule.optimizer_step(self._model, self._optimizer, self._grad_clip) else: output, label, loss = self._schedule.forward_backward_step( data_iter, self._model, self._criterion, self._optimizer, forward_only=True, grad_accum_size=1, return_loss=return_loss) # consume the remaining dataset left out due to gradient accumulation if is_last_iteration: while True: try: _ = next(data_iter) except StopIteration: break return output, label, loss
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 21004, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 28034, 13, 20471, 1330, 19937, 198, 6738, 28034, 13, 20471, 13, 18170, 13, 22462, 1330, 4808, 43, 793, 198, ...
2.20684
1,228
import numpy as np import cv2 cap = cv2.VideoCapture('motion.avi') ret, frame = cap.read() gs_im0 = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) points_prev = cv2.goodFeaturesToTrack(gs_im0, 100, 0.03, 9.0, False) while(cap.isOpened()): ret, frame = cap.read() gs_im1 = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Call tracker. points, st, err = cv2.calcOpticalFlowPyrLK(gs_im0, gs_im1, points_prev, None, (3,3)) for i,p in enumerate(points): a,b = p.ravel() frame = cv2.circle(frame,(a,b),3,(255,255,255),-1) cv2.imshow('frame',frame) points_prev = points gs_im0 = gs_im1 if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
[ 11748, 299, 32152, 355, 45941, 198, 11748, 269, 85, 17, 198, 198, 11128, 796, 269, 85, 17, 13, 10798, 49630, 10786, 38714, 13, 15820, 11537, 198, 198, 1186, 11, 5739, 796, 1451, 13, 961, 3419, 198, 14542, 62, 320, 15, 796, 269, 85, ...
2
359
import math def make_circle(radius = 10, res = 20, filled = True): points = [] for i in range(res): ang = 2*math.pi * i / res points.append((math.cos(ang) * radius, math.sin(ang) * radius) ) if filled: return FilledPolygon(points) else: return PolyLine(points, True)
[ 11748, 10688, 628, 198, 4299, 787, 62, 45597, 7, 42172, 796, 838, 11, 581, 796, 1160, 11, 5901, 796, 6407, 2599, 198, 220, 220, 220, 2173, 796, 17635, 198, 220, 220, 220, 329, 1312, 287, 2837, 7, 411, 2599, 198, 220, 220, 220, 220...
2.358209
134
"""Tests for the servo classes.""" from typing import List, Optional, Type import pytest from j5.backends import Backend from j5.boards import Board from j5.components.servo import Servo, ServoInterface, ServoPosition def test_servo_interface_implementation(): """Test that we can implement the ServoInterface.""" MockServoDriver() def test_servo_interface_class(): """Test that the interface class is ServoInterface.""" assert Servo.interface_class() is ServoInterface def test_servo_instantiation(): """Test that we can instantiate a Servo.""" Servo(0, MockServoBoard(), MockServoDriver()) def test_servo_get_position(): """Test that we can get the position of a servo.""" servo = Servo(2, MockServoBoard(), MockServoDriver()) assert type(servo.position) is float assert servo.position == 0.5 def test_servo_set_position(): """Test that we can set the position of a servo.""" servo = Servo(2, MockServoBoard(), MockServoDriver()) servo.position = 0.6 def test_servo_set_position_none(): """Test that we can set the position of a servo to None.""" servo = Servo(2, MockServoBoard(), MockServoDriver()) servo.position = None def test_servo_set_position_out_of_bounds(): """Test that we cannot set < -1 or > 1.""" servo = Servo(2, MockServoBoard(), MockServoDriver()) with pytest.raises(ValueError): servo.position = 2 with pytest.raises(ValueError): servo.position = -2
[ 37811, 51, 3558, 329, 262, 1113, 78, 6097, 526, 15931, 198, 6738, 19720, 1330, 7343, 11, 32233, 11, 5994, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 474, 20, 13, 1891, 2412, 1330, 5157, 437, 198, 6738, 474, 20, 13, 12821, 1330, 5...
2.857692
520
frase = str(input('Digite uma frase: ')).lower() print('Sobre a letra "a": \nQuantas vezes ela aparece? {} vezes;'.format(frase.count('a'))) print('Em que posio ela aparece pela primeira vez? {};'.format(frase.strip().index('a')+1)) print('Em que posio ela aparece pela ltima vez? {}.'.format(frase.strip().rfind('a')+1))
[ 8310, 589, 796, 965, 7, 15414, 10786, 19511, 578, 334, 2611, 1216, 589, 25, 705, 29720, 21037, 3419, 198, 4798, 10786, 50, 672, 260, 257, 1309, 430, 366, 64, 1298, 3467, 77, 24915, 292, 1569, 12271, 1288, 64, 2471, 533, 344, 30, 238...
2.439394
132
from django.contrib.auth.mixins import LoginRequiredMixin from django.views import View from django.views.generic import ListView from django.utils.http import is_safe_url from django.contrib import messages from rest_framework import status from django.core.exceptions import ObjectDoesNotExist from django.shortcuts import redirect, render from mama_cas.models import ServiceTicket from mama_cas.utils import redirect as cas_redirect from mama_cas.utils import to_bool from rest_framework.response import Response from decimal import Decimal from django.urls import reverse import urllib from pinax.stripe.mixins import CustomerMixin from pinax.stripe.models import Charge from pinax.stripe.actions import charges from stripe.error import CardError from rest_framework_jwt.settings import api_settings from unfold.transactions.models import Purchase, Article from unfold.transactions.admin import PurchaseForm from unfold.users.models import User jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
[ 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 19816, 1040, 1330, 23093, 37374, 35608, 259, 198, 6738, 42625, 14208, 13, 33571, 1330, 3582, 198, 6738, 42625, 14208, 13, 33571, 13, 41357, 1330, 7343, 7680, 198, 6738, 42625, 14208, 13, ...
3.560403
298
"""InterviewBit. Programming > Arrays > Rotate Matrix. """ matrices = [ [ [1] ], [ [1, 2], [3, 4] ], [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ], [ ['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l'], ['m', 'n', 'o', 'p'], ], [ [str(x).zfill(2) for x in range(1, 6)], [str(x).zfill(2) for x in range(6, 11)], [str(x).zfill(2) for x in range(11, 16)], [str(x).zfill(2) for x in range(16, 21)], [str(x).zfill(2) for x in range(21, 26)] ], [ [str(x).zfill(2) for x in range(1, 7)], [str(x).zfill(2) for x in range(7, 13)], [str(x).zfill(2) for x in range(13, 19)], [str(x).zfill(2) for x in range(19, 25)], [str(x).zfill(2) for x in range(25, 31)], [str(x).zfill(2) for x in range(31, 37)] ] ] solution = Solution() for matrix in matrices: print("Matrix before rotation:") for row in matrix: print('\t', row) print("Matrix after rotation:") for row in solution.rotate(matrix): print('\t', row) print('\n' * 3)
[ 37811, 39945, 13128, 13, 198, 198, 15167, 2229, 1875, 943, 20477, 1875, 18481, 378, 24936, 13, 198, 37811, 628, 198, 198, 6759, 45977, 796, 685, 198, 220, 220, 220, 685, 198, 220, 220, 220, 220, 220, 220, 220, 685, 16, 60, 198, 220,...
1.765861
662
# Copyright (c) 2019, 2020, Oracle Corporation and/or its affiliates. # Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. connect('weblogic', 'welcome1', 't3://DOMAINNAME-admin-server:7001') # get all JDBC Properties dsCounter = 0 allJDBCResources = cmo.getJDBCSystemResources() for jdbcResource in allJDBCResources: dsCounter = dsCounter + 1 dsname = jdbcResource.getName() dsResource = jdbcResource.getJDBCResource() dsJNDIname = dsResource.getJDBCDataSourceParams().getJNDINames()#[0] dsDriver = dsResource.getJDBCDriverParams().getDriverName() conn = dsResource.getJDBCDriverParams().getUrl() dsInitialCap = dsResource.getJDBCConnectionPoolParams().getInitialCapacity() dsMaxCap = dsResource.getJDBCConnectionPoolParams().getMaxCapacity() dsParams = dsResource.getJDBCDataSourceParams() dsProps = dsResource.getJDBCDriverParams().getProperties() dsParams = dsResource.getJDBCConnectionPoolParams() user = get("/JDBCSystemResources/"+ dsname +"/Resource/" + dsname + "/JDBCDriverParams/" + dsname + "/Properties/" + dsname + "/Properties/user/Value") readTimeOut = get("/JDBCSystemResources/"+ dsname +"/Resource/" + dsname + "/JDBCDriverParams/" + dsname + "/Properties/" + dsname + "/Properties/oracle.jdbc.ReadTimeout/Value") connTimeOut = get("/JDBCSystemResources/"+ dsname +"/Resource/" + dsname + "/JDBCDriverParams/" + dsname + "/Properties/" + dsname + "/Properties/oracle.net.CONNECT_TIMEOUT/Value") print 'datasource.name.' + str(dsCounter) +'=' + str(dsname) print 'datasource.jndiname.' + str(dsCounter) + '=' + str(dsJNDIname) print 'datasource.driver.class.' + str(dsCounter) + '=' + dsDriver print 'datasource.url.' + str(dsCounter) + '=' + conn print 'datasource.initialCapacity.' + str(dsCounter) + '=' + str(dsInitialCap) print 'datasource.maxCapacity.' + str(dsCounter) + '=' + str(dsMaxCap) print 'datasource.readTimeout.' + str(dsCounter) + '=' + readTimeOut print 'datasource.connectionTimeout.' + str(dsCounter) + '=' + connTimeOut print 'datasource.username.' + str(dsCounter) + '=' + str(user) print 'datasource.dsProps.' + str(dsCounter) + '=' + str(dsProps) print 'datasource.dsParams.' + str(dsCounter) + '=' + str(dsParams) disconnect() exit()
[ 2, 15069, 357, 66, 8, 13130, 11, 12131, 11, 18650, 10501, 290, 14, 273, 663, 29116, 13, 198, 2, 49962, 739, 262, 14499, 2448, 33532, 13789, 410, 352, 13, 15, 355, 3402, 379, 3740, 1378, 793, 13, 273, 6008, 13, 785, 14, 677, 4541, ...
2.698266
865
from rdr_service import clock from rdr_service.dao.biobank_stored_sample_dao import BiobankStoredSampleDao from rdr_service.dao.participant_dao import ParticipantDao from rdr_service.model.biobank_stored_sample import BiobankStoredSample from rdr_service.model.participant import Participant from tests.helpers.unittest_base import BaseTestCase
[ 6738, 374, 7109, 62, 15271, 1330, 8801, 198, 6738, 374, 7109, 62, 15271, 13, 67, 5488, 13, 8482, 672, 962, 62, 301, 1850, 62, 39873, 62, 67, 5488, 1330, 8436, 672, 962, 1273, 1850, 36674, 35, 5488, 198, 6738, 374, 7109, 62, 15271, ...
3.145455
110
import socket, os, atexit from flask import Flask, jsonify, request from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask.helpers import send_from_directory, url_for from zeroconf import ServiceInfo, Zeroconf from pantryflask.config import FlaskConfig from pantryflask.auth import token_auth, generate_pairing_code, generate_user_token from pantryflask.models import AuthToken from pantryflask.db import db from pantryflask.pantry_api import bp as pantry_bp from pantryflask.robot_api import bp as robot_bp from pantryflask.util import bp as util_bp ip = os.environ.get('LISTEN_IP') httpZconf = ServiceInfo( "_http._tcp.local.", "intpantry._http._tcp.local.", addresses=[socket.inet_aton(ip)], port=5000) httpsZconf = ServiceInfo( "_https._tcp.local.", "intpantry._https._tcp.local.", addresses=[socket.inet_aton(ip)], port=5443) zc = Zeroconf() zc.register_service(httpZconf) print('Service Registered:', httpZconf) app, db, migrate = app_factory()
[ 11748, 17802, 11, 28686, 11, 379, 37023, 198, 6738, 42903, 1330, 46947, 11, 33918, 1958, 11, 2581, 198, 6738, 42903, 62, 25410, 282, 26599, 1330, 16363, 2348, 26599, 198, 6738, 42903, 62, 76, 42175, 1330, 337, 42175, 198, 6738, 42903, 1...
2.694872
390
# # Copyright 2017 Mycroft AI Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """ Parse functions for Basque (eu) TODO: numbers greater than 999999 """ from datetime import datetime from dateutil.relativedelta import relativedelta from dateutil.tz import gettz from lingua_franca.lang.format_eu import pronounce_number_eu from lingua_franca.lang.parse_common import * from lingua_franca.lang.common_data_eu import _NUM_STRING_EU def isFractional_eu(input_str): """ This function takes the given text and checks if it is a fraction. Args: text (str): the string to check if fractional Returns: (bool) or (float): False if not a fraction, otherwise the fraction """ if input_str.endswith('s', -1): input_str = input_str[:len(input_str) - 1] # e.g. "fifths" aFrac = {"erdia": 2, "erdi": 2, "heren": 3, "laurden": 4, "laurdena": 4, "bosten": 5, "bostena": 5, "seiren": 6, "seirena": 6, "zazpiren": 7, "zapirena": 7, "zortziren": 8, "zortzirena": 8, "bederatziren": 9, "bederatzirena": 9, "hamarren": 10, "hamarrena": 10, "hamaikaren": 11, "hamaikarena": 11, "hamabiren": 12, "hamabirena": 12} if input_str.lower() in aFrac: return 1.0 / aFrac[input_str] if (input_str == "hogeiren" or input_str == "hogeirena"): return 1.0 / 20 if (input_str == "hogeita hamarren" or input_str == "hogeita hamarrena"): return 1.0 / 30 if (input_str == "ehunen" or input_str == "ehunena"): return 1.0 / 100 if (input_str == "milaren" or input_str == "milarena"): return 1.0 / 1000 return False # TODO: short_scale and ordinals don't do anything here. # The parameters are present in the function signature for API compatibility # reasons. # # Returns incorrect output on certain fractional phrases like, "cuarto de dos" def extract_number_eu(text, short_scale=True, ordinals=False): """ This function prepares the given text for parsing by making numbers consistent, getting rid of contractions, etc. Args: text (str): the string to normalize Returns: (int) or (float): The value of extracted number """ aWords = text.lower().split() count = 0 result = None while count < len(aWords): val = 0 word = aWords[count] next_next_word = None if count + 1 < len(aWords): next_word = aWords[count + 1] if count + 2 < len(aWords): next_next_word = aWords[count + 2] else: next_word = None # is current word a number? if word in _NUM_STRING_EU: val = _NUM_STRING_EU[word] elif word.isdigit(): # doesn't work with decimals val = int(word) elif is_numeric(word): val = float(word) elif isFractional_eu(word): if next_word in _NUM_STRING_EU: # erdi bat, heren bat, etab result = _NUM_STRING_EU[next_word] # hurrengo hitza (bat, bi, ...) salto egin next_word = None count += 2 elif not result: result = 1 count += 1 result = result * isFractional_eu(word) continue if not val: # look for fractions like "2/3" aPieces = word.split('/') # if (len(aPieces) == 2 and is_numeric(aPieces[0]) # and is_numeric(aPieces[1])): if look_for_fractions(aPieces): val = float(aPieces[0]) / float(aPieces[1]) if val: if result is None: result = 0 # handle fractions if next_word == "en" or next_word == "ren": result = float(result) / float(val) else: result = val if next_word is None: break # number word and fraction ands = ["eta"] if next_word in ands: zeros = 0 if result is None: count += 1 continue newWords = aWords[count + 2:] newText = "" for word in newWords: newText += word + " " afterAndVal = extract_number_eu(newText[:-1]) if afterAndVal: if result < afterAndVal or result < 20: while afterAndVal > 1: afterAndVal = afterAndVal / 10.0 for word in newWords: if word == "zero" or word == "0": zeros += 1 else: break for _ in range(0, zeros): afterAndVal = afterAndVal / 10.0 result += afterAndVal break elif next_next_word is not None: if next_next_word in ands: newWords = aWords[count + 3:] newText = "" for word in newWords: newText += word + " " afterAndVal = extract_number_eu(newText[:-1]) if afterAndVal: if result is None: result = 0 result += afterAndVal break decimals = ["puntu", "koma", ".", ","] if next_word in decimals: zeros = 0 newWords = aWords[count + 2:] newText = "" for word in newWords: newText += word + " " for word in newWords: if word == "zero" or word == "0": zeros += 1 else: break afterDotVal = str(extract_number_eu(newText[:-1])) afterDotVal = zeros * "0" + afterDotVal result = float(str(result) + "." + afterDotVal) break count += 1 # Return the $str with the number related words removed # (now empty strings, so strlen == 0) # aWords = [word for word in aWords if len(word) > 0] # text = ' '.join(aWords) if "." in str(result): integer, dec = str(result).split(".") # cast float to int if dec == "0": result = int(integer) return result or False # TODO Not parsing 'cero' def extract_numbers_eu(text, short_scale=True, ordinals=False): """ Takes in a string and extracts a list of numbers. Args: text (str): the string to extract a number from short_scale (bool): Use "short scale" or "long scale" for large numbers -- over a million. The default is short scale, which is now common in most English speaking countries. See https://en.wikipedia.org/wiki/Names_of_large_numbers ordinals (bool): consider ordinal numbers, e.g. third=3 instead of 1/3 Returns: list: list of extracted numbers as floats """ return extract_numbers_generic(text, pronounce_number_eu, extract_number_eu, short_scale=short_scale, ordinals=ordinals) def normalize_eu(text, remove_articles=True): """ Basque string normalization """ words = text.split() # this also removed extra spaces normalized = "" i = 0 while i < len(words): word = words[i] # Convert numbers into digits r = eu_number_parse(words, i) if r: v, i = r normalized += " " + str(v) continue normalized += " " + word i += 1 return normalized[1:] # strip the initial space return text # TODO MycroftAI/mycroft-core#2348
[ 2, 198, 2, 15069, 2177, 2011, 36714, 9552, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13...
2.102281
3,901
# Defines a velocity profile, which is the big object we've been # working towards. from math import sqrt, ceil import json
[ 2, 2896, 1127, 257, 15432, 7034, 11, 543, 318, 262, 1263, 2134, 356, 1053, 587, 198, 2, 1762, 3371, 13, 198, 6738, 10688, 1330, 19862, 17034, 11, 2906, 346, 198, 198, 11748, 33918, 198 ]
3.676471
34
import os import subprocess test_set_path = '/Users/runelangergaard/Documents/SmartAnnotation/data/test_set' test_imgs = os.listdir(test_set_path) test_imgs cwd_path = '/Users/runelangergaard' os.chdir(cwd_path) for img in test_imgs: full_path = os.path.join(test_set_path, img) subprocess.run([ "scp", "-i", "coco-anno.pem", full_path, "ec2-user@ec2-34-211-193-133.us-west-2.compute.amazonaws.com:/datasets/tmp" ])
[ 11748, 28686, 198, 11748, 850, 14681, 198, 9288, 62, 2617, 62, 6978, 796, 31051, 14490, 14, 5143, 417, 2564, 36232, 14, 38354, 14, 25610, 2025, 38983, 14, 7890, 14, 9288, 62, 2617, 6, 198, 9288, 62, 9600, 82, 796, 28686, 13, 4868, 1...
2.079295
227
import random import grom grom.debug(False) dirName = "dump\\" inputName = "example.bmp" outputName = "output.bmp" g = grom.Genome(dirName + inputName, partition=[ ('head', 0x76), ('raw') ]) print(g) print(g.partition) g.apply(lambda x: 255 - x, ['raw']) g(dirName + outputName, pause=False)
[ 11748, 4738, 198, 11748, 308, 398, 198, 70, 398, 13, 24442, 7, 25101, 8, 198, 198, 15908, 5376, 796, 366, 39455, 6852, 1, 198, 15414, 5376, 796, 366, 20688, 13, 65, 3149, 1, 198, 22915, 5376, 796, 366, 22915, 13, 65, 3149, 1, 198,...
2.412698
126
################################################################################ # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ################################################################################ import typing from statefun.core import ValueSpec from statefun.context import Context from statefun.messages import Message from statefun.storage import make_address_storage_spec, StorageSpec import inspect
[ 29113, 29113, 14468, 198, 2, 220, 49962, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 198, 2, 220, 393, 517, 18920, 5964, 11704, 13, 220, 4091, 262, 28536, 2393, 198, 2, 220, 9387, 351, 428, 670, 329, 3224, 1321, 198, ...
4.448669
263
""" Problem: You are given a list of N points (x1, y1), (x2, y2), ..., (xN, yN) representing a polygon. You can assume these points are given in order; that is, you can construct the polygon by connecting point 1 to point 2, point 2 to point 3, and so on, finally looping around to connect point N to point 1. Determine if a new point p lies inside this polygon. (If p is on the boundary of the polygon, you should return False). """ from typing import List, Tuple Point = Tuple[int, int] if __name__ == "__main__": print(is_inside([(4, 3), (5, 4), (6, 3), (5, 2)], (3, 3))) print(is_inside([(4, 3), (5, 4), (6, 3), (5, 2)], (5, 3))) """ SPECS: TIME COMPLEXITY: O(n) SPACE COMPLEXITY: O(n) """
[ 37811, 198, 40781, 25, 198, 198, 1639, 389, 1813, 257, 1351, 286, 399, 2173, 357, 87, 16, 11, 331, 16, 828, 357, 87, 17, 11, 331, 17, 828, 2644, 11, 357, 87, 45, 11, 331, 45, 8, 10200, 257, 198, 35428, 14520, 13, 921, 460, 704...
2.666667
267
# Copyright 2021 Alexis Lopez Zubieta # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. from appimagebuilder.modules.generate.package_managers.apt import ( PackageRepositoryResolver, )
[ 2, 220, 15069, 220, 33448, 31078, 22593, 47828, 1155, 64, 198, 2, 198, 2, 220, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 198, 2, 220, 4866, 286, 428, 3788, 290, 3917, 10314, 3696, 357, 1169, ...
4.124294
177
# Author: Fabio Rodrigues Pereira # E-mail: fabior@uio.no # Author: Per Morten Halvorsen # E-mail: pmhalvor@uio.no # Author: Eivind Grnlie Guren # E-mail: eivindgg@ifi.uio.no try: from Oblig3.packages.preprocess import load_raw_data, filter_raw_data, pad from Oblig3.packages.preprocess import OurCONLLUDataset from Oblig3.packages.model import Transformer except: from packages.preprocess import load_raw_data, filter_raw_data, pad from packages.preprocess import OurCONLLUDataset from packages.model import Transformer from sklearn.model_selection import train_test_split from torch.utils.data import DataLoader from transformers import BertTokenizer import torch # first step # datapath = '/cluster/projects/nn9851k/IN5550/norne-nb-in5550-train.conllu' # NORBERT = '/cluster/shared/nlpl/data/vectors/latest/216' datapath = 'Oblig3/saga/norne-nb-in5550-train.conllu' NORBERT = 'Oblig3/saga/216/' device = "cuda" if torch.cuda.is_available() else "cpu" torch.cuda.empty_cache() if torch.cuda.is_available() else None # loading raw data con_df = load_raw_data(datapath=datapath) con_df = filter_raw_data(df=con_df, min_entities=5) # splitting data train_df, val_df = train_test_split( con_df, # train_size=0.50, test_size=0.25, random_state=1, shuffle=True, ) tokenizer = BertTokenizer.from_pretrained(NORBERT) # creating data sets train_dataset = OurCONLLUDataset( df=train_df, tokenizer=tokenizer, device=device ) val_dataset = OurCONLLUDataset( df=val_df, tokenizer=tokenizer, label_vocab=train_dataset.label_vocab, device=device ) # creating data loaders train_loader = DataLoader( train_dataset, batch_size=32, collate_fn=lambda batch: pad(batch, train_dataset.IGNORE_ID) ) val_loader = DataLoader( val_dataset, batch_size=len(val_dataset), collate_fn=lambda batch: pad(batch, train_dataset.IGNORE_ID) ) # calling transformer model transformer = Transformer( NORBERT=NORBERT, num_labels=len(train_dataset.label_indexer), NOT_ENTITY_ID=train_dataset.label_indexer['O'], device=device, epochs=100, # 12 for the optimal lr_scheduler=False, factor=0.1, patience=2, loss_funct='cross-entropy', random_state=1, verbose=True, lr=0.01, momentum=0.9, epoch_patience=1, # 0 for the optimal label_indexer=train_dataset.label_indexer ) transformer.fit( loader=train_loader, test=val_loader, verbose=True ) torch.save(transformer, "transformer_benchmark_12ep.pt")
[ 2, 6434, 25, 14236, 952, 16114, 947, 17229, 8704, 198, 2, 412, 12, 4529, 25, 7843, 1504, 31, 84, 952, 13, 3919, 198, 198, 2, 6434, 25, 2448, 10788, 268, 11023, 85, 669, 268, 198, 2, 412, 12, 4529, 25, 9114, 14201, 20867, 31, 84,...
2.416904
1,053
import logging import os import random import string import unittest import warnings from boxsdk.exception import BoxAPIException, BoxOAuthException from parsons.box import Box from parsons.etl import Table """Prior to running, you should ensure that the relevant environment variables have been set, e.g. via # Note: these are fake keys, provided as examples. export BOX_CLIENT_ID=txqedp4rqi0cz5qckz361fziavdtdwxz export BOX_CLIENT_SECRET=bk264KHMDLVy89TeuUpSRa4CN5o35u9h export BOX_ACCESS_TOKEN=boK97B39m3ozIGyTcazbWRbi5F2SSZ5J """ TEST_CLIENT_ID = os.getenv('BOX_CLIENT_ID') TEST_BOX_CLIENT_SECRET = os.getenv('BOX_CLIENT_SECRET') TEST_ACCESS_TOKEN = os.getenv('BOX_ACCESS_TOKEN') def generate_random_string(length): """Utility to generate random alpha string for file/folder names""" return ''.join(random.choice(string.ascii_letters) for i in range(length))
[ 11748, 18931, 198, 11748, 28686, 198, 11748, 4738, 198, 11748, 4731, 198, 11748, 555, 715, 395, 198, 11748, 14601, 198, 198, 6738, 3091, 21282, 74, 13, 1069, 4516, 1330, 8315, 17614, 16922, 11, 8315, 23621, 1071, 16922, 198, 198, 6738, ...
2.752351
319
import matplotlib.pyplot as plt import numpy as np import cv2 '''Erosion Method''' '''Point Detection Method''' img = cv2.imread("point.jpg",0) sample = img kernel = np.array([[-1,-1,-1], [-1,8,-1], [-1,-1,-1]]) output, co_ord = point_detection(img, kernel) output = output*255 output = np.asarray(output, np.uint8) cv2.rectangle(output,(424,230),(464,272),(255,255,255),2) cv2.imwrite("res_point.jpg",output) '''Code for segmenting the object from the background''' img2 = cv2.imread("segment.jpg", 0) seg = check_segment(img2) seg = np.asarray(seg, np.uint8) cv2.rectangle(seg,(155,115),(208,172),(255,255,255),2) cv2.rectangle(seg,(245,68),(300,223),(255,255,255),2) cv2.rectangle(seg,(322,13),(370,291),(255,255,255),2) cv2.rectangle(seg,(382,33),(430,264),(255,255,255),2) '''Observed co-ordinates of bounding boxes, in col, row format''' print("1st box: ") print("Upper left: (155,115)") print("Upper right: (208,115)") print("Bottom left: (155,172)") print("Bottom right: (208,172)\n") print("2nd box: ") print("Upper left: (245,68)") print("Upper right: (300,68)") print("Bottom left: (245,223)") print("Bottom right: (300,223)\n") print("3rd box: ") print("Upper left: (322,13)") print("Upper right: (370,13)") print("Bottom left: (322,291)") print("Bottom right: (370,291)\n") print("4th box: ") print("Upper left: (382,33)") print("Upper right: (430,33)") print("Bottom left: (382,264)") print("Bottom right: (430,264)") cv2.imwrite("res_segment.jpg",seg) '''Plotting Histogram''' my_dict = {} for i in range(np.unique(img2).shape[0]): a = np.unique(img2)[i] count = np.sum(img2 == a) my_dict[a] = count sorted_by_value = sorted(my_dict.items(), key=lambda kv: kv[1]) uniq = list(np.unique(img2)) val = list(my_dict.values()) plt.plot(uniq[1:],val[1:]) plt.show()
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 11748, 269, 85, 17, 201, 198, 201, 198, 7061, 6, 36, 4951, 295, 11789, 7061, 6, 201, 198, 201, 198, 7061, 6, 12727, 46254, ...
2.125277
902
# Generated by Django 3.1.5 on 2021-02-07 08:19 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 20, 319, 33448, 12, 2999, 12, 2998, 8487, 25, 1129, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) lm = LoginManager(app) from app import views, models, oauth
[ 6738, 42903, 1330, 46947, 198, 6738, 42903, 62, 25410, 282, 26599, 1330, 16363, 2348, 26599, 198, 6738, 42903, 62, 38235, 1330, 23093, 13511, 198, 198, 1324, 796, 46947, 7, 834, 3672, 834, 8, 198, 1324, 13, 11250, 13, 6738, 62, 15252, ...
3.22973
74
""" https://leetcode.com/problems/to-lower-case/ Difficulty: Easy Given a string s, return the string after replacing every uppercase letter with the same lowercase letter. Example 1: Input: s = "Hello" Output: "hello" Example 2: Input: s = "here" Output: "here" Example 3: Input: s = "LOVELY" Output: "lovely" Constraints: 1 <= s.length <= 100 s consists of printable ASCII characters. """
[ 37811, 198, 5450, 1378, 293, 316, 8189, 13, 785, 14, 1676, 22143, 14, 1462, 12, 21037, 12, 7442, 14, 198, 28813, 22402, 25, 16789, 198, 198, 15056, 257, 4731, 264, 11, 1441, 262, 4731, 706, 13586, 790, 334, 39921, 589, 3850, 351, 26...
2.764706
153
import align_tools as at import matplotlib.pyplot as plt import numpy as np from collections import Counter if __name__ == '__main__': main()
[ 11748, 10548, 62, 31391, 355, 379, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 17268, 1330, 15034, 628, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, ...
3.125
48
from django.apps import AppConfig
[ 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 628 ]
3.888889
9
import os from pygears.hdl.sv import SVModuleInst from .ip_resolver import IPResolver
[ 11748, 28686, 198, 6738, 12972, 70, 4127, 13, 71, 25404, 13, 21370, 1330, 20546, 26796, 6310, 198, 6738, 764, 541, 62, 411, 14375, 1330, 314, 4805, 274, 14375, 628 ]
3
29
import shutil import tempfile from pathlib import Path from typing import Dict import click from commodore.config import Config from .parameters import ClassNotFound, InventoryFactory, InventoryFacts
[ 11748, 4423, 346, 198, 11748, 20218, 7753, 198, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 19720, 1330, 360, 713, 198, 198, 11748, 3904, 198, 198, 6738, 13088, 382, 13, 11250, 1330, 17056, 198, 198, 6738, 764, 17143, 7307, 1330, 501...
3.961538
52
begin_unit comment|'# Copyright (c) 2013 Intel, Inc.' nl|'\n' comment|'# Copyright (c) 2013 OpenStack Foundation' nl|'\n' comment|'# All Rights Reserved.' nl|'\n' comment|'#' nl|'\n' comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may' nl|'\n' comment|'# not use this file except in compliance with the License. You may obtain' nl|'\n' comment|'# a copy of the License at' nl|'\n' comment|'#' nl|'\n' comment|'# http://www.apache.org/licenses/LICENSE-2.0' nl|'\n' comment|'#' nl|'\n' comment|'# Unless required by applicable law or agreed to in writing, software' nl|'\n' comment|'# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT' nl|'\n' comment|'# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the' nl|'\n' comment|'# License for the specific language governing permissions and limitations' nl|'\n' comment|'# under the License.' nl|'\n' nl|'\n' name|'import' name|'copy' newline|'\n' nl|'\n' name|'from' name|'oslo_config' name|'import' name|'cfg' newline|'\n' name|'from' name|'oslo_log' name|'import' name|'log' name|'as' name|'logging' newline|'\n' name|'import' name|'six' newline|'\n' nl|'\n' name|'from' name|'nova' name|'import' name|'exception' newline|'\n' name|'from' name|'nova' op|'.' name|'i18n' name|'import' name|'_LE' newline|'\n' name|'from' name|'nova' name|'import' name|'objects' newline|'\n' name|'from' name|'nova' op|'.' name|'objects' name|'import' name|'fields' newline|'\n' name|'from' name|'nova' op|'.' name|'objects' name|'import' name|'pci_device_pool' newline|'\n' name|'from' name|'nova' op|'.' name|'pci' name|'import' name|'utils' newline|'\n' name|'from' name|'nova' op|'.' name|'pci' name|'import' name|'whitelist' newline|'\n' nl|'\n' nl|'\n' DECL|variable|CONF name|'CONF' op|'=' name|'cfg' op|'.' name|'CONF' newline|'\n' DECL|variable|LOG name|'LOG' op|'=' name|'logging' op|'.' name|'getLogger' op|'(' name|'__name__' op|')' newline|'\n' nl|'\n' nl|'\n' DECL|class|PciDeviceStats name|'class' name|'PciDeviceStats' op|'(' name|'object' op|')' op|':' newline|'\n' nl|'\n' indent|' ' string|'"""PCI devices summary information.\n\n According to the PCI SR-IOV spec, a PCI physical function can have up to\n 256 PCI virtual functions, thus the number of assignable PCI functions in\n a cloud can be big. The scheduler needs to know all device availability\n information in order to determine which compute hosts can support a PCI\n request. Passing individual virtual device information to the scheduler\n does not scale, so we provide summary information.\n\n Usually the virtual functions provided by a host PCI device have the same\n value for most properties, like vendor_id, product_id and class type.\n The PCI stats class summarizes this information for the scheduler.\n\n The pci stats information is maintained exclusively by compute node\n resource tracker and updated to database. The scheduler fetches the\n information and selects the compute node accordingly. If a compute\n node is selected, the resource tracker allocates the devices to the\n instance and updates the pci stats information.\n\n This summary information will be helpful for cloud management also.\n """' newline|'\n' nl|'\n' DECL|variable|pool_keys name|'pool_keys' op|'=' op|'[' string|"'product_id'" op|',' string|"'vendor_id'" op|',' string|"'numa_node'" op|',' string|"'dev_type'" op|']' newline|'\n' nl|'\n' DECL|member|__init__ name|'def' name|'__init__' op|'(' name|'self' op|',' name|'stats' op|'=' name|'None' op|',' name|'dev_filter' op|'=' name|'None' op|')' op|':' newline|'\n' indent|' ' name|'super' op|'(' name|'PciDeviceStats' op|',' name|'self' op|')' op|'.' name|'__init__' op|'(' op|')' newline|'\n' comment|'# NOTE(sbauza): Stats are a PCIDevicePoolList object' nl|'\n' name|'self' op|'.' name|'pools' op|'=' op|'[' name|'pci_pool' op|'.' name|'to_dict' op|'(' op|')' nl|'\n' name|'for' name|'pci_pool' name|'in' name|'stats' op|']' name|'if' name|'stats' name|'else' op|'[' op|']' newline|'\n' name|'self' op|'.' name|'pools' op|'.' name|'sort' op|'(' name|'key' op|'=' name|'lambda' name|'item' op|':' name|'len' op|'(' name|'item' op|')' op|')' newline|'\n' name|'self' op|'.' name|'dev_filter' op|'=' name|'dev_filter' name|'or' name|'whitelist' op|'.' name|'Whitelist' op|'(' nl|'\n' name|'CONF' op|'.' name|'pci_passthrough_whitelist' op|')' newline|'\n' nl|'\n' DECL|member|_equal_properties dedent|'' name|'def' name|'_equal_properties' op|'(' name|'self' op|',' name|'dev' op|',' name|'entry' op|',' name|'matching_keys' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'all' op|'(' name|'dev' op|'.' name|'get' op|'(' name|'prop' op|')' op|'==' name|'entry' op|'.' name|'get' op|'(' name|'prop' op|')' nl|'\n' name|'for' name|'prop' name|'in' name|'matching_keys' op|')' newline|'\n' nl|'\n' DECL|member|_find_pool dedent|'' name|'def' name|'_find_pool' op|'(' name|'self' op|',' name|'dev_pool' op|')' op|':' newline|'\n' indent|' ' string|'"""Return the first pool that matches dev."""' newline|'\n' name|'for' name|'pool' name|'in' name|'self' op|'.' name|'pools' op|':' newline|'\n' indent|' ' name|'pool_keys' op|'=' name|'pool' op|'.' name|'copy' op|'(' op|')' newline|'\n' name|'del' name|'pool_keys' op|'[' string|"'count'" op|']' newline|'\n' name|'del' name|'pool_keys' op|'[' string|"'devices'" op|']' newline|'\n' name|'if' op|'(' name|'len' op|'(' name|'pool_keys' op|'.' name|'keys' op|'(' op|')' op|')' op|'==' name|'len' op|'(' name|'dev_pool' op|'.' name|'keys' op|'(' op|')' op|')' name|'and' nl|'\n' name|'self' op|'.' name|'_equal_properties' op|'(' name|'dev_pool' op|',' name|'pool_keys' op|',' name|'dev_pool' op|'.' name|'keys' op|'(' op|')' op|')' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'pool' newline|'\n' nl|'\n' DECL|member|_create_pool_keys_from_dev dedent|'' dedent|'' dedent|'' name|'def' name|'_create_pool_keys_from_dev' op|'(' name|'self' op|',' name|'dev' op|')' op|':' newline|'\n' indent|' ' string|'"""create a stats pool dict that this dev is supposed to be part of\n\n Note that this pool dict contains the stats pool\'s keys and their\n values. \'count\' and \'devices\' are not included.\n """' newline|'\n' comment|"# Don't add a device that doesn't have a matching device spec." nl|'\n' comment|'# This can happen during initial sync up with the controller' nl|'\n' name|'devspec' op|'=' name|'self' op|'.' name|'dev_filter' op|'.' name|'get_devspec' op|'(' name|'dev' op|')' newline|'\n' name|'if' name|'not' name|'devspec' op|':' newline|'\n' indent|' ' name|'return' newline|'\n' dedent|'' name|'tags' op|'=' name|'devspec' op|'.' name|'get_tags' op|'(' op|')' newline|'\n' name|'pool' op|'=' op|'{' name|'k' op|':' name|'getattr' op|'(' name|'dev' op|',' name|'k' op|')' name|'for' name|'k' name|'in' name|'self' op|'.' name|'pool_keys' op|'}' newline|'\n' name|'if' name|'tags' op|':' newline|'\n' indent|' ' name|'pool' op|'.' name|'update' op|'(' name|'tags' op|')' newline|'\n' dedent|'' name|'return' name|'pool' newline|'\n' nl|'\n' DECL|member|add_device dedent|'' name|'def' name|'add_device' op|'(' name|'self' op|',' name|'dev' op|')' op|':' newline|'\n' indent|' ' string|'"""Add a device to its matching pool."""' newline|'\n' name|'dev_pool' op|'=' name|'self' op|'.' name|'_create_pool_keys_from_dev' op|'(' name|'dev' op|')' newline|'\n' name|'if' name|'dev_pool' op|':' newline|'\n' indent|' ' name|'pool' op|'=' name|'self' op|'.' name|'_find_pool' op|'(' name|'dev_pool' op|')' newline|'\n' name|'if' name|'not' name|'pool' op|':' newline|'\n' indent|' ' name|'dev_pool' op|'[' string|"'count'" op|']' op|'=' number|'0' newline|'\n' name|'dev_pool' op|'[' string|"'devices'" op|']' op|'=' op|'[' op|']' newline|'\n' name|'self' op|'.' name|'pools' op|'.' name|'append' op|'(' name|'dev_pool' op|')' newline|'\n' name|'self' op|'.' name|'pools' op|'.' name|'sort' op|'(' name|'key' op|'=' name|'lambda' name|'item' op|':' name|'len' op|'(' name|'item' op|')' op|')' newline|'\n' name|'pool' op|'=' name|'dev_pool' newline|'\n' dedent|'' name|'pool' op|'[' string|"'count'" op|']' op|'+=' number|'1' newline|'\n' name|'pool' op|'[' string|"'devices'" op|']' op|'.' name|'append' op|'(' name|'dev' op|')' newline|'\n' nl|'\n' dedent|'' dedent|'' op|'@' name|'staticmethod' newline|'\n' DECL|member|_decrease_pool_count name|'def' name|'_decrease_pool_count' op|'(' name|'pool_list' op|',' name|'pool' op|',' name|'count' op|'=' number|'1' op|')' op|':' newline|'\n' indent|' ' string|'"""Decrement pool\'s size by count.\n\n If pool becomes empty, remove pool from pool_list.\n """' newline|'\n' name|'if' name|'pool' op|'[' string|"'count'" op|']' op|'>' name|'count' op|':' newline|'\n' indent|' ' name|'pool' op|'[' string|"'count'" op|']' op|'-=' name|'count' newline|'\n' name|'count' op|'=' number|'0' newline|'\n' dedent|'' name|'else' op|':' newline|'\n' indent|' ' name|'count' op|'-=' name|'pool' op|'[' string|"'count'" op|']' newline|'\n' name|'pool_list' op|'.' name|'remove' op|'(' name|'pool' op|')' newline|'\n' dedent|'' name|'return' name|'count' newline|'\n' nl|'\n' DECL|member|remove_device dedent|'' name|'def' name|'remove_device' op|'(' name|'self' op|',' name|'dev' op|')' op|':' newline|'\n' indent|' ' string|'"""Remove one device from the first pool that it matches."""' newline|'\n' name|'dev_pool' op|'=' name|'self' op|'.' name|'_create_pool_keys_from_dev' op|'(' name|'dev' op|')' newline|'\n' name|'if' name|'dev_pool' op|':' newline|'\n' indent|' ' name|'pool' op|'=' name|'self' op|'.' name|'_find_pool' op|'(' name|'dev_pool' op|')' newline|'\n' name|'if' name|'not' name|'pool' op|':' newline|'\n' indent|' ' name|'raise' name|'exception' op|'.' name|'PciDevicePoolEmpty' op|'(' nl|'\n' name|'compute_node_id' op|'=' name|'dev' op|'.' name|'compute_node_id' op|',' name|'address' op|'=' name|'dev' op|'.' name|'address' op|')' newline|'\n' dedent|'' name|'pool' op|'[' string|"'devices'" op|']' op|'.' name|'remove' op|'(' name|'dev' op|')' newline|'\n' name|'self' op|'.' name|'_decrease_pool_count' op|'(' name|'self' op|'.' name|'pools' op|',' name|'pool' op|')' newline|'\n' nl|'\n' DECL|member|get_free_devs dedent|'' dedent|'' name|'def' name|'get_free_devs' op|'(' name|'self' op|')' op|':' newline|'\n' indent|' ' name|'free_devs' op|'=' op|'[' op|']' newline|'\n' name|'for' name|'pool' name|'in' name|'self' op|'.' name|'pools' op|':' newline|'\n' indent|' ' name|'free_devs' op|'.' name|'extend' op|'(' name|'pool' op|'[' string|"'devices'" op|']' op|')' newline|'\n' dedent|'' name|'return' name|'free_devs' newline|'\n' nl|'\n' DECL|member|consume_requests dedent|'' name|'def' name|'consume_requests' op|'(' name|'self' op|',' name|'pci_requests' op|',' name|'numa_cells' op|'=' name|'None' op|')' op|':' newline|'\n' indent|' ' name|'alloc_devices' op|'=' op|'[' op|']' newline|'\n' name|'for' name|'request' name|'in' name|'pci_requests' op|':' newline|'\n' indent|' ' name|'count' op|'=' name|'request' op|'.' name|'count' newline|'\n' name|'spec' op|'=' name|'request' op|'.' name|'spec' newline|'\n' comment|'# For now, keep the same algorithm as during scheduling:' nl|'\n' comment|'# a spec may be able to match multiple pools.' nl|'\n' name|'pools' op|'=' name|'self' op|'.' name|'_filter_pools_for_spec' op|'(' name|'self' op|'.' name|'pools' op|',' name|'spec' op|')' newline|'\n' name|'if' name|'numa_cells' op|':' newline|'\n' indent|' ' name|'pools' op|'=' name|'self' op|'.' name|'_filter_pools_for_numa_cells' op|'(' name|'pools' op|',' name|'numa_cells' op|')' newline|'\n' dedent|'' name|'pools' op|'=' name|'self' op|'.' name|'_filter_non_requested_pfs' op|'(' name|'request' op|',' name|'pools' op|')' newline|'\n' comment|'# Failed to allocate the required number of devices' nl|'\n' comment|'# Return the devices already allocated back to their pools' nl|'\n' name|'if' name|'sum' op|'(' op|'[' name|'pool' op|'[' string|"'count'" op|']' name|'for' name|'pool' name|'in' name|'pools' op|']' op|')' op|'<' name|'count' op|':' newline|'\n' indent|' ' name|'LOG' op|'.' name|'error' op|'(' name|'_LE' op|'(' string|'"Failed to allocate PCI devices for instance."' nl|'\n' string|'" Unassigning devices back to pools."' nl|'\n' string|'" This should not happen, since the scheduler"' nl|'\n' string|'" should have accurate information, and allocation"' nl|'\n' string|'" during claims is controlled via a hold"' nl|'\n' string|'" on the compute node semaphore"' op|')' op|')' newline|'\n' name|'for' name|'d' name|'in' name|'range' op|'(' name|'len' op|'(' name|'alloc_devices' op|')' op|')' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'add_device' op|'(' name|'alloc_devices' op|'.' name|'pop' op|'(' op|')' op|')' newline|'\n' dedent|'' name|'return' name|'None' newline|'\n' dedent|'' name|'for' name|'pool' name|'in' name|'pools' op|':' newline|'\n' indent|' ' name|'if' name|'pool' op|'[' string|"'count'" op|']' op|'>=' name|'count' op|':' newline|'\n' indent|' ' name|'num_alloc' op|'=' name|'count' newline|'\n' dedent|'' name|'else' op|':' newline|'\n' indent|' ' name|'num_alloc' op|'=' name|'pool' op|'[' string|"'count'" op|']' newline|'\n' dedent|'' name|'count' op|'-=' name|'num_alloc' newline|'\n' name|'pool' op|'[' string|"'count'" op|']' op|'-=' name|'num_alloc' newline|'\n' name|'for' name|'d' name|'in' name|'range' op|'(' name|'num_alloc' op|')' op|':' newline|'\n' indent|' ' name|'pci_dev' op|'=' name|'pool' op|'[' string|"'devices'" op|']' op|'.' name|'pop' op|'(' op|')' newline|'\n' name|'self' op|'.' name|'_handle_device_dependents' op|'(' name|'pci_dev' op|')' newline|'\n' name|'pci_dev' op|'.' name|'request_id' op|'=' name|'request' op|'.' name|'request_id' newline|'\n' name|'alloc_devices' op|'.' name|'append' op|'(' name|'pci_dev' op|')' newline|'\n' dedent|'' name|'if' name|'count' op|'==' number|'0' op|':' newline|'\n' indent|' ' name|'break' newline|'\n' dedent|'' dedent|'' dedent|'' name|'return' name|'alloc_devices' newline|'\n' nl|'\n' DECL|member|_handle_device_dependents dedent|'' name|'def' name|'_handle_device_dependents' op|'(' name|'self' op|',' name|'pci_dev' op|')' op|':' newline|'\n' indent|' ' string|'"""Remove device dependents or a parent from pools.\n\n In case the device is a PF, all of it\'s dependent VFs should\n be removed from pools count, if these are present.\n When the device is a VF, it\'s parent PF pool count should be\n decreased, unless it is no longer in a pool.\n """' newline|'\n' name|'if' name|'pci_dev' op|'.' name|'dev_type' op|'==' name|'fields' op|'.' name|'PciDeviceType' op|'.' name|'SRIOV_PF' op|':' newline|'\n' indent|' ' name|'vfs_list' op|'=' name|'objects' op|'.' name|'PciDeviceList' op|'.' name|'get_by_parent_address' op|'(' nl|'\n' name|'pci_dev' op|'.' name|'_context' op|',' nl|'\n' name|'pci_dev' op|'.' name|'compute_node_id' op|',' nl|'\n' name|'pci_dev' op|'.' name|'address' op|')' newline|'\n' name|'if' name|'vfs_list' op|':' newline|'\n' indent|' ' name|'for' name|'vf' name|'in' name|'vfs_list' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'remove_device' op|'(' name|'vf' op|')' newline|'\n' dedent|'' dedent|'' dedent|'' name|'elif' name|'pci_dev' op|'.' name|'dev_type' op|'==' name|'fields' op|'.' name|'PciDeviceType' op|'.' name|'SRIOV_VF' op|':' newline|'\n' indent|' ' name|'try' op|':' newline|'\n' indent|' ' name|'parent' op|'=' name|'pci_dev' op|'.' name|'get_by_dev_addr' op|'(' name|'pci_dev' op|'.' name|'_context' op|',' nl|'\n' name|'pci_dev' op|'.' name|'compute_node_id' op|',' nl|'\n' name|'pci_dev' op|'.' name|'parent_addr' op|')' newline|'\n' comment|'# Make sure not to decrease PF pool count if this parent has' nl|'\n' comment|'# been already removed from pools' nl|'\n' name|'if' name|'parent' name|'in' name|'self' op|'.' name|'get_free_devs' op|'(' op|')' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'remove_device' op|'(' name|'parent' op|')' newline|'\n' dedent|'' dedent|'' name|'except' name|'exception' op|'.' name|'PciDeviceNotFound' op|':' newline|'\n' indent|' ' name|'return' newline|'\n' nl|'\n' dedent|'' dedent|'' dedent|'' op|'@' name|'staticmethod' newline|'\n' DECL|member|_filter_pools_for_spec name|'def' name|'_filter_pools_for_spec' op|'(' name|'pools' op|',' name|'request_specs' op|')' op|':' newline|'\n' indent|' ' name|'return' op|'[' name|'pool' name|'for' name|'pool' name|'in' name|'pools' nl|'\n' name|'if' name|'utils' op|'.' name|'pci_device_prop_match' op|'(' name|'pool' op|',' name|'request_specs' op|')' op|']' newline|'\n' nl|'\n' dedent|'' op|'@' name|'staticmethod' newline|'\n' DECL|member|_filter_pools_for_numa_cells name|'def' name|'_filter_pools_for_numa_cells' op|'(' name|'pools' op|',' name|'numa_cells' op|')' op|':' newline|'\n' comment|"# Some systems don't report numa node info for pci devices, in" nl|'\n' comment|'# that case None is reported in pci_device.numa_node, by adding None' nl|'\n' comment|'# to numa_cells we allow assigning those devices to instances with' nl|'\n' comment|'# numa topology' nl|'\n' indent|' ' name|'numa_cells' op|'=' op|'[' name|'None' op|']' op|'+' op|'[' name|'cell' op|'.' name|'id' name|'for' name|'cell' name|'in' name|'numa_cells' op|']' newline|'\n' comment|'# filter out pools which numa_node is not included in numa_cells' nl|'\n' name|'return' op|'[' name|'pool' name|'for' name|'pool' name|'in' name|'pools' name|'if' name|'any' op|'(' name|'utils' op|'.' name|'pci_device_prop_match' op|'(' nl|'\n' name|'pool' op|',' op|'[' op|'{' string|"'numa_node'" op|':' name|'cell' op|'}' op|']' op|')' nl|'\n' name|'for' name|'cell' name|'in' name|'numa_cells' op|')' op|']' newline|'\n' nl|'\n' DECL|member|_filter_non_requested_pfs dedent|'' name|'def' name|'_filter_non_requested_pfs' op|'(' name|'self' op|',' name|'request' op|',' name|'matching_pools' op|')' op|':' newline|'\n' comment|'# Remove SRIOV_PFs from pools, unless it has been explicitly requested' nl|'\n' comment|'# This is especially needed in cases where PFs and VFs has the same' nl|'\n' comment|'# product_id.' nl|'\n' indent|' ' name|'if' name|'all' op|'(' name|'spec' op|'.' name|'get' op|'(' string|"'dev_type'" op|')' op|'!=' name|'fields' op|'.' name|'PciDeviceType' op|'.' name|'SRIOV_PF' name|'for' nl|'\n' name|'spec' name|'in' name|'request' op|'.' name|'spec' op|')' op|':' newline|'\n' indent|' ' name|'matching_pools' op|'=' name|'self' op|'.' name|'_filter_pools_for_pfs' op|'(' name|'matching_pools' op|')' newline|'\n' dedent|'' name|'return' name|'matching_pools' newline|'\n' nl|'\n' dedent|'' op|'@' name|'staticmethod' newline|'\n' DECL|member|_filter_pools_for_pfs name|'def' name|'_filter_pools_for_pfs' op|'(' name|'pools' op|')' op|':' newline|'\n' indent|' ' name|'return' op|'[' name|'pool' name|'for' name|'pool' name|'in' name|'pools' nl|'\n' name|'if' name|'not' name|'pool' op|'.' name|'get' op|'(' string|"'dev_type'" op|')' op|'==' name|'fields' op|'.' name|'PciDeviceType' op|'.' name|'SRIOV_PF' op|']' newline|'\n' nl|'\n' DECL|member|_apply_request dedent|'' name|'def' name|'_apply_request' op|'(' name|'self' op|',' name|'pools' op|',' name|'request' op|',' name|'numa_cells' op|'=' name|'None' op|')' op|':' newline|'\n' comment|'# NOTE(vladikr): This code maybe open to race conditions.' nl|'\n' comment|'# Two concurrent requests may succeed when called support_requests' nl|'\n' comment|'# because this method does not remove related devices from the pools' nl|'\n' indent|' ' name|'count' op|'=' name|'request' op|'.' name|'count' newline|'\n' name|'matching_pools' op|'=' name|'self' op|'.' name|'_filter_pools_for_spec' op|'(' name|'pools' op|',' name|'request' op|'.' name|'spec' op|')' newline|'\n' name|'if' name|'numa_cells' op|':' newline|'\n' indent|' ' name|'matching_pools' op|'=' name|'self' op|'.' name|'_filter_pools_for_numa_cells' op|'(' name|'matching_pools' op|',' nl|'\n' name|'numa_cells' op|')' newline|'\n' dedent|'' name|'matching_pools' op|'=' name|'self' op|'.' name|'_filter_non_requested_pfs' op|'(' name|'request' op|',' nl|'\n' name|'matching_pools' op|')' newline|'\n' name|'if' name|'sum' op|'(' op|'[' name|'pool' op|'[' string|"'count'" op|']' name|'for' name|'pool' name|'in' name|'matching_pools' op|']' op|')' op|'<' name|'count' op|':' newline|'\n' indent|' ' name|'return' name|'False' newline|'\n' dedent|'' name|'else' op|':' newline|'\n' indent|' ' name|'for' name|'pool' name|'in' name|'matching_pools' op|':' newline|'\n' indent|' ' name|'count' op|'=' name|'self' op|'.' name|'_decrease_pool_count' op|'(' name|'pools' op|',' name|'pool' op|',' name|'count' op|')' newline|'\n' name|'if' name|'not' name|'count' op|':' newline|'\n' indent|' ' name|'break' newline|'\n' dedent|'' dedent|'' dedent|'' name|'return' name|'True' newline|'\n' nl|'\n' DECL|member|support_requests dedent|'' name|'def' name|'support_requests' op|'(' name|'self' op|',' name|'requests' op|',' name|'numa_cells' op|'=' name|'None' op|')' op|':' newline|'\n' indent|' ' string|'"""Check if the pci requests can be met.\n\n Scheduler checks compute node\'s PCI stats to decide if an\n instance can be scheduled into the node. Support does not\n mean real allocation.\n If numa_cells is provided then only devices contained in\n those nodes are considered.\n """' newline|'\n' comment|'# note (yjiang5): this function has high possibility to fail,' nl|'\n' comment|'# so no exception should be triggered for performance reason.' nl|'\n' name|'pools' op|'=' name|'copy' op|'.' name|'deepcopy' op|'(' name|'self' op|'.' name|'pools' op|')' newline|'\n' name|'return' name|'all' op|'(' op|'[' name|'self' op|'.' name|'_apply_request' op|'(' name|'pools' op|',' name|'r' op|',' name|'numa_cells' op|')' nl|'\n' name|'for' name|'r' name|'in' name|'requests' op|']' op|')' newline|'\n' nl|'\n' DECL|member|apply_requests dedent|'' name|'def' name|'apply_requests' op|'(' name|'self' op|',' name|'requests' op|',' name|'numa_cells' op|'=' name|'None' op|')' op|':' newline|'\n' indent|' ' string|'"""Apply PCI requests to the PCI stats.\n\n This is used in multiple instance creation, when the scheduler has to\n maintain how the resources are consumed by the instances.\n If numa_cells is provided then only devices contained in\n those nodes are considered.\n """' newline|'\n' name|'if' name|'not' name|'all' op|'(' op|'[' name|'self' op|'.' name|'_apply_request' op|'(' name|'self' op|'.' name|'pools' op|',' name|'r' op|',' name|'numa_cells' op|')' nl|'\n' name|'for' name|'r' name|'in' name|'requests' op|']' op|')' op|':' newline|'\n' indent|' ' name|'raise' name|'exception' op|'.' name|'PciDeviceRequestFailed' op|'(' name|'requests' op|'=' name|'requests' op|')' newline|'\n' nl|'\n' DECL|member|__iter__ dedent|'' dedent|'' name|'def' name|'__iter__' op|'(' name|'self' op|')' op|':' newline|'\n' comment|"# 'devices' shouldn't be part of stats" nl|'\n' indent|' ' name|'pools' op|'=' op|'[' op|']' newline|'\n' name|'for' name|'pool' name|'in' name|'self' op|'.' name|'pools' op|':' newline|'\n' indent|' ' name|'tmp' op|'=' op|'{' name|'k' op|':' name|'v' name|'for' name|'k' op|',' name|'v' name|'in' name|'six' op|'.' name|'iteritems' op|'(' name|'pool' op|')' name|'if' name|'k' op|'!=' string|"'devices'" op|'}' newline|'\n' name|'pools' op|'.' name|'append' op|'(' name|'tmp' op|')' newline|'\n' dedent|'' name|'return' name|'iter' op|'(' name|'pools' op|')' newline|'\n' nl|'\n' DECL|member|clear dedent|'' name|'def' name|'clear' op|'(' name|'self' op|')' op|':' newline|'\n' indent|' ' string|'"""Clear all the stats maintained."""' newline|'\n' name|'self' op|'.' name|'pools' op|'=' op|'[' op|']' newline|'\n' nl|'\n' DECL|member|__eq__ dedent|'' name|'def' name|'__eq__' op|'(' name|'self' op|',' name|'other' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'cmp' op|'(' name|'self' op|'.' name|'pools' op|',' name|'other' op|'.' name|'pools' op|')' op|'==' number|'0' newline|'\n' nl|'\n' DECL|member|__ne__ dedent|'' name|'def' name|'__ne__' op|'(' name|'self' op|',' name|'other' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'not' op|'(' name|'self' op|'==' name|'other' op|')' newline|'\n' nl|'\n' DECL|member|to_device_pools_obj dedent|'' name|'def' name|'to_device_pools_obj' op|'(' name|'self' op|')' op|':' newline|'\n' indent|' ' string|'"""Return the contents of the pools as a PciDevicePoolList object."""' newline|'\n' name|'stats' op|'=' op|'[' name|'x' name|'for' name|'x' name|'in' name|'self' op|']' newline|'\n' name|'return' name|'pci_device_pool' op|'.' name|'from_pci_stats' op|'(' name|'stats' op|')' newline|'\n' dedent|'' dedent|'' endmarker|'' end_unit
[ 27471, 62, 20850, 198, 23893, 91, 6, 2, 15069, 357, 66, 8, 2211, 8180, 11, 3457, 2637, 198, 21283, 91, 6, 59, 77, 6, 198, 23893, 91, 6, 2, 15069, 357, 66, 8, 2211, 4946, 25896, 5693, 6, 198, 21283, 91, 6, 59, 77, 6, 198, 238...
1.940863
13,122
"""Variational autoencoder model.""" from typing import Tuple import torch from torch import nn from torch.nn import functional as F
[ 37811, 23907, 864, 1960, 6571, 66, 12342, 2746, 526, 15931, 198, 198, 6738, 19720, 1330, 309, 29291, 198, 198, 11748, 28034, 198, 6738, 28034, 1330, 299, 77, 198, 6738, 28034, 13, 20471, 1330, 10345, 355, 376, 628, 198 ]
3.605263
38
from django.http.response import HttpResponse from rest_framework import serializers, viewsets from rest_framework.decorators import action from rest_framework.permissions import IsAuthenticated from .excel import Excel XLSX_MIME = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
[ 6738, 42625, 14208, 13, 4023, 13, 26209, 1330, 367, 29281, 31077, 198, 6738, 1334, 62, 30604, 1330, 11389, 11341, 11, 5009, 1039, 198, 6738, 1334, 62, 30604, 13, 12501, 273, 2024, 1330, 2223, 198, 6738, 1334, 62, 30604, 13, 525, 8481, ...
3.619048
84