def ask_the_oracle(): o = oracle.Oracle() a = acolyte.Acolyte() while True: answer = 0 print("Ask the Oracle a [L]ikely, [N]eutral, or [U]likely Question") print("Seek a [P]ortent or consult the [T]WENE") print("or [D]epart in peace.") print("\n") inquiry = input('What knowledge do you seek: ') if inquiry == 'L' or inquiry == 'l': print("The Oracle responds to your LIKELY inquiry: ") answer = o.ask("Advantage") print(str(a.interpret(answer)) + '\n') elif inquiry == 'N' or inquiry == 'n': print("The Oracle responds to your NEUTRAL inquiry: ") answer = o.ask('N') print("\033[31m" + str(a.interpret(answer)) + "\033[37m" + "\n") elif inquiry == 'U' or inquiry == 'u': print("The Oracle responds to your UNLIKELY inquiry: ") answer = o.ask("Disadvantage") print(str(a.interpret(answer)) + '\n') elif inquiry == 'P' or inquiry == 'p': print("PORTENT") elif inquiry == 'T' or inquiry == 't': print("TWENE") elif inquiry == 'D' or inquiry == 'd': print("May Wisdom light your footsteps Adventurer!") return False else: print( "The Acolyte is uncertain how to explain your inquiry. Try again." )
def main(): #assert(b64encode(encrypt(IV, pad(flag))) == b"XmmSv7+azqHCSPwBYfsVKVoqq+NpOaWrRHOYlLn3GlRAg4kdAVmEdc5L9koCHcxl5U0Ee28wMqTNdZYzd/BOaynUpmthknT0QdVGLXpx5Oko7QiK7+I0UVFhi8MP0+YFigbKhXMGzuv7ySqhnakeaRhaRGjRvVShMmjL0vitvuw=") cipher = b64encode(encrypt(IV, pad(flag))) out = out_message(IV, pad(flag)) o = oracle.Oracle(IV, cipher, 'YES', 'NO') o.setGuessfunc(checkmsg) print('plain = '+o.attack())
def oracle_learn(): state = HexapawnState(5) red = oracle.Oracle() blue = oracle.Oracle() for i in range(100): while not state.check_gameover(): move = red.consult(state) try: state.make_move(move) state.alternate_turn() except oracle.GameoverException: state.winner = label.BLUE red.loss(state, move) break if state.check_gameover(): break move = blue.consult(state) try: state.make_move(move) state.alternate_turn() except oracle.GameoverException: state.winner = label.RED blue.loss(state, move) break if state.winner == label.RED: print('Winner is RED player') else: print('Winner is BLUE player') state.draw_board() for state, moves in red.learned.items(): print(state, moves, os.linesep) for state, moves in blue.learned.items(): print(state, moves, os.linesep)
def factory(**connection): """ фабрика для инстанса бд :param connection: **dict :return: instance :raise ValueError: """ conn_type = int(connection.get('conn_type', '')) del connection['conn_type'] if conn_type == ConnectionChoices.POSTGRESQL: return postgresql.Postgresql(connection) elif conn_type == ConnectionChoices.MYSQL: return mysql.Mysql(connection) elif conn_type == ConnectionChoices.MS_SQL: import mssql return mssql.MsSql(connection) elif conn_type == ConnectionChoices.ORACLE: import oracle return oracle.Oracle(connection) else: raise ValueError("Неизвестный тип подключения!")
def __init__(self, regions, ua, debug=False): """ Provides interactive Oracle functionality. This can be used to create bots and user interfaces. :param regions: Path to NationStates regional data dump. Can be a string or file object. :param ua: User agent string that identifies the operator, as required by NS TOS :return: """ self.debug = debug self.regions = regions self.ua = ua self.oracle = oracle.Oracle(regions, ua) self.time_now = datetime.datetime.utcnow().replace(tzinfo=UTC()) self.time_base = datetime.datetime.utcnow().replace(tzinfo=UTC(), hour=0, minute=0, second=0, microsecond=0) # determine start time of closest update # 16h = minor # 4h = major # easy: anything less than 16h is major (we don't really care about weird exception cases anyhow) if self.time_now < self.time_base + datetime.timedelta(hours=16): self.mode = "major" else: self.mode = "minor" self.tracking = False self.target = "" self.runner = threading.Thread(target=self._runner, daemon=True) self.runner.start() self.log = []
def main(): np.seterr(divide='ignore', invalid='ignore') #ignore divide by 0 warnings orcl = oracle.Oracle("data4.npz") print("loaded:", orcl.get_filename(), "gamma = ", orcl.get_gamma()) num_iterations = 20 lower_limit_eta = 1 step = 5 upper_limit_eta = min( int(orcl.get_num_samples() / orcl.get_num_clusters()), 50) xs = [] ys = [] for eta in range(lower_limit_eta, upper_limit_eta, step): success = 0 total_queries = 0 total_cost = 0 for i in range(num_iterations): predicted_clustering, queries = clusterise(orcl, eta) total_queries += queries if orcl.check_predicted_clustering(predicted_clustering): success += 1 total_cost += find_cost(orcl, predicted_clustering) average_queries = total_queries / num_iterations average_cost = total_cost / num_iterations xs.append(average_queries) ys.append(average_cost / orcl.get_cost()) print("eta = ", eta, ", success rate:", success, "/", num_iterations, "av. cost = ", average_cost, ", av. queries = ", average_queries, ", av.cost/oracle_cost = ", average_cost / orcl.get_cost()) #Plot the graph of cost relative to underlying clustering vs number of queries taken plt.xlabel('num_queries') plt.ylabel('predicted_cluster_cost/oracle_cluster_cost') plt.ylim([0.99, 1.01]) plt.plot(xs, ys) plt.savefig('graphs/dataset4.png')
try: configfilename = sys.argv[1] except IndexError: sys.stderr.write("usage: trainer_slave.py config-file [options...]\n") sys.exit(1) if log.level >= 1: log.write("Reading configuration from %s\n" % configfilename) execfile(configfilename) opts, args = optparser.parse_args(args=sys.argv[2:]) maxmargin.watch_features = watch_features theoracle = oracle.Oracle(order=4, variant=opts.bleuvariant, oracledoc_size=10) thedecoder = make_decoder() thelearner = Learner() weight_stack = [] if log.level >= 1: gc.collect() log.write("all structures loaded, memory=%s\n" % (monitor.memory())) comm = MPI.Comm.Get_parent() log.prefix = '[%s] ' % (comm.Get_rank(), ) instances = [] while True: msg = comm.recv()
import os import oracle from ucca import diffutil, ioutil, textutil, layer1, evaluation from pdb import set_trace files = [ '../ucca_corpus_pickle/' + f for f in os.listdir('../ucca_corpus_pickle') ] passages = list(ioutil.read_files_and_dirs(files)) passage = passages[0] ora = oracle.Oracle(passage) set_trace()
def make_oracle(): return oracle.Oracle(order=4, variant=opts.bleuvariant, oracledoc_size=10)
def qk_means(mixture, numOracles, numClusters, qubitStringLen, qGenerations, dim, timeDB=False, earlyStop=0): # matrix for fitness evolution; # +1 for the column that indicates the best score in each gen fitnessEvolution = np.zeros((qGenerations,numOracles+1)) if earlyStop != 0: useEarlyStop=True earlyStopCounter=0 else: useEarlyStop=False if timeDB: db_timings = list() #timing list for Davies-Bouldin index computation qk_timings_cg = list() start = datetime.now() best = 0 #index of best oracle (starts at 0) oras = list() qk_centroids = [0]*numOracles qk_estimator = [0]*numOracles qk_assignment = [0]*numOracles for i in range(0,numOracles): oras.append(oracle.Oracle()) oras[i].initialization(numClusters*dim,qubitStringLen) oras[i].collapse() qk_timings_cg.append((datetime.now() - start).total_seconds()) start = datetime.now() for qGen_ in range(0,qGenerations): ## Clustering step for i,ora in enumerate(oras): if qGen_ != 0 and i == best: # current best shouldn't be modified continue qk_centroids[i] = np.vstack(np.hsplit(ora.getIntArrays(),numClusters)) qk_estimator[i] = KMeans(n_clusters=numClusters,init=qk_centroids[i],n_init=1) qk_assignment[i] = qk_estimator[i].fit_predict(mixture) qk_centroids[i] = qk_estimator[i].cluster_centers_ ora.setIntArrays(np.concatenate(qk_centroids[i])) ## Compute fitness # start DB timing if timeDB: db_start = datetime.now() # compute DB score = DaviesBouldin.DaviesBouldin(mixture,qk_centroids[i],qk_assignment[i]) ora.score = score.eval() # save timing if timeDB: db_timings.append((datetime.now() - db_start).total_seconds()) ## Store best from this generation for i in range(1,numOracles): if oras[i].score < oras[best].score: best = i ## Quantum Rotation Gate for i in range(0,numOracles): if i == best: continue oras[i].QuantumGateStep(oras[best]) ## Collapse qubits oras[i].collapse() qk_timings_cg.append((datetime.now() - start).total_seconds()) for i in range(0,numOracles): fitnessEvolution[qGen_,i]=oras[i].score fitnessEvolution[qGen_,-1]=best # check early stop if useEarlyStop: # increment counter if this generetion's fitness is the same as last if oras[best].score == fitnessEvolution[qGen_,fitnessEvolution[qGen_-1,-1]]: earlyStopCounter += 1 else: earlyStopCounter == 0 if earlyStopCounter == earlyStop: break start = datetime.now() # delete empty rows on fitness matrix emptyRows=range(qGen_+1,qGenerations) fitnessEvolution=np.delete(fitnessEvolution,emptyRows,axis=0) if timeDB: return qk_centroids,qk_assignment,fitnessEvolution,qk_timings_cg,db_timings return qk_centroids,qk_assignment,fitnessEvolution,qk_timings_cg
import oracle as o import vueworks as vw v = vw.VUEWorks() O = o.Oracle() for x in O.incidents['items']: invw = v.checkVUEWorks(x['id']) if not invw['in']: incident = O.getIncidentData(x['id']) if incident["customFields"]["c"]["latitude"] is not None and incident[ "customFields"]["c"]["longitude"] is not None: result = v.createSR(x['id'], incident["customFields"]["c"]["latitude"], incident["customFields"]["c"]["longitude"]) print "created Service Request: " + result else: print "In VUEWorks already"
import sym import svector import sgml # usage: hope.py <forest> <source> <ref>+ optparser = optparse.OptionParser() optparser.add_option("-w", "--weights", dest="weights", help="weights") opts, args = optparser.parse_args() # Feature weights weights = svector.Vector("lm1=0.1 gt_prob=0.1") if opts.weights: weights = svector.Vector(opts.weights) theoracle = oracle.Oracle(4, variant="ibm") srcfilename = args[1] forestfilename = args[0] reffilenames = args[2:] srcfile = open(srcfilename) forestfile = open(forestfilename) if forestfilename != "-" else sys.stdin reffiles = [open(reffilename) for reffilename in reffilenames] def output(f): deriv = f.viterbi_deriv() hypv = deriv.vector() hyp = deriv.english() return "hyp={{{%s}}} derivation={{{%s}}} %s" % (" ".join(sym.tostring(e) for e in hyp), deriv, hypv)
import json, discord, os, string, re, random, hashlib, unicodedata, urllib.request import fetcher, oracle, config # Globals legal_cards = [] client = discord.Client() config = config.Config() oracle = oracle.Oracle() def init(): update_legality() client.run(config.get("token")) def update_legality(): global legal_cards legal_cards = fetcher.Fetcher().legal_cards() print("Legal cards: {0}".format(str(len(legal_cards)))) def normalize_filename(str_input): # Remove spaces str_input = '-'.join(str_input.split(' ')).lower() # Remove Pipes str_input = '-'.join(str_input.split('|')).lower() # Remove nasty accented characters. return ''.join((c for c in unicodedata.normalize('NFD', str_input) if unicodedata.category(c) != 'Mn'))