def setup(): """Setup for upstream plugin""" models.setup() utils.setup() addbook.setup() covers.setup() merge_authors.setup() import data data.setup() # setup template globals from openlibrary.i18n import ugettext, ungettext, gettext_territory web.template.Template.globals.update({ "gettext": ugettext, "ugettext": ugettext, "_": ugettext, "ungettext": ungettext, "gettext_territory": gettext_territory, "random": random.Random(), "commify": web.commify, "group": web.group, "storage": web.storage, "all": all, "any": any, "locals": locals }); import jsdef web.template.STATEMENT_NODES["jsdef"] = jsdef.JSDefNode setup_jquery_urls()
def game_loop(self): """The main game loop. This is where your hivemind code goes.""" # Setting up rate limiter. rate_limit = rate_limiter.RateLimiter(120) # Setting up data. field_info = FieldInfoPacket() self.game_interface.update_field_info_packet(field_info) packet = GameTickPacket() self.game_interface.update_live_data_packet(packet) data.setup(self, packet, field_info, self.running_indices) self.ball.predict = BallPrediction() # https://github.com/RLBot/RLBotPythonExample/wiki/Ball-Path-Prediction # MAIN LOOP: while True: # Updating the game packet from the game. self.game_interface.update_live_data_packet(packet) # Processing packet. data.process(self, packet) # Ball prediction. self.game_interface.update_ball_prediction(self.ball.predict) # Planning. brain.plan(self) # Rendering. self.render_debug(self.game_interface.renderer) # For each drone under the hivemind's control, do something. for drone in self.drones: # The controls are reset each frame. drone.ctrl = PlayerInput( ) # Basically the same as SimpleControllerState(). # Role execution. if drone.role is not None: drone.role.execute(self, drone) self.render_role(self.game_interface.renderer, drone) # Send the controls to the bots. self.game_interface.update_player_input( drone.ctrl, drone.index) # Rate limit sleep. rate_limit.acquire()
def gif_route(): gif="" if request.form.get("selGif") is not None: print("Selected: " + request.form.get("selGif")) gif=request.form.get("selGif") update_stats("giftype") return render_template("gif.html", gif=gif, projects=data.setup())
def run(self): self.process_args() pofilesA = data.setup(self.t25l, self._dataset) if pofilesA is None: raise TaskError("%s: no %r data set" % (self.NAME, self._dataset)) pofilesB = PoFileSet.from_dir(self._podir) pofilesB.merge(pofilesA, self._merge_options) pofilesB.dump(self._merge_options)
def setup(): logging.debug('Running process setup.') logging.debug('Changing working directory.') os.chdir('./secner') graph = data.setup(config.NEO4J_SERVER) ftp_server = scraping.setup(config.SEC_SERVER) nlp.setup() return graph, ftp_server
def setup(): """Setup for upstream plugin""" models.setup() utils.setup() addbook.setup() covers.setup() merge_authors.setup() import data data.setup() # Types for upstream paths types.register_type('^/authors/[^/]*$', '/type/author') types.register_type('^/books/[^/]*$', '/type/edition') types.register_type('^/languages/[^/]*$', '/type/language') types.register_type('^/subjects/places/[^/]*$', '/type/place') types.register_type('^/subjects/people/[^/]*$', '/type/person') types.register_type('^/subjects/[^/]*$', '/type/subject') # fix photo/cover url pattern ol_code.Author.photo_url_patten = "%s/photo" ol_code.Edition.cover_url_patten = "%s/cover" # setup template globals from openlibrary.i18n import ugettext, ungettext web.template.Template.globals.update({ "gettext": ugettext, "ugettext": ugettext, "_": ugettext, "ungettext": ungettext, "random": random.Random(), "commify": web.commify, "group": web.group, "storage": web.storage, "all": all, "any": any, "locals": locals }); import jsdef web.template.STATEMENT_NODES["jsdef"] = jsdef.JSDefNode setup_jquery_urls()
def graph_ql(): date = datetime.now() log = open('calls.log', 'a') log_val = '' + str(date) + '-' + request.path + '\n' log.write(log_val) setup() client = Client(schema) query = """ query FetchIdQuery($id: String!){ student(id: $id){ name } } """ params = {"id": "1"} result = client.execute(query, variables=params) return result
def bi_route(): dec = 0 print("n bi") print(request.form.get("bi")) if request.form.get("bi") is not None and request.form.get("bi") != "": print(request.form.get("bi")) bin=request.form.get("bi") print('binary; ' + bi) dec=int(bi, 2) print(dec) return render_template("jaideepminilab.html", decimal=dec, projects=data.setup())
def bin_route(): dec = 0 print("n bin") print(request.form.get("bin")) if request.form.get("bin") is not None and request.form.get("bin") != "": print(request.form.get("bin")) bin=request.form.get("bin") print('binary; ' + bin) dec=int(bin, 2) print(dec) return render_template("lightbulb.html", decimal=dec, projects=data.setup())
def game_loop(self): """The main game loop. This is where your hivemind code goes.""" # Setting up rate limiter. rate_limit = rate_limiter.RateLimiter(120) # Setting up data. field_info = FieldInfoPacket() self.game_interface.update_field_info_packet(field_info) packet = GameTickPacket() self.game_interface.update_live_data_packet(packet) data.setup(self, packet, field_info, self.running_indices) self.ball.predict = BallPrediction() # MAIN LOOP: while True: # Updating the game packet from the game. self.game_interface.update_live_data_packet(packet) # Processing packet. data.process(self, packet) # Ball prediction. self.game_interface.update_ball_prediction(self.ball.predict) brain.think(self) for drone in self.drones: drone.ctrl = PlayerInput() if drone.role is not None: drone.role.execute(self, drone) self.game_interface.update_player_input( drone.ctrl, drone.index) self.draw_debug() # Rate limit sleep. rate_limit.acquire()
def example_route(): # first get the form data if request.form.get("txt") is not None and request.form.get("txt") != "": print("text: " + request.form.get("txt")) strTxt = request.form.get("txt") # now format it - the Markup import formats the HTML correctly example = Markup("<b><i>" + strTxt + "</i></b>") else: strTxt = "" example = strTxt # next format it # then return the parameter to the page return render_template("example.html", strTxt=strTxt, example=example, projects=data.setup())
def get_output(self, packet: GameTickPacket) -> SimpleControllerState: # Runs setup. if self.need_setup: field_info = self.get_field_info() data.setup(self, packet, field_info) self.need_setup = False # Preprocessing. data.process(self, packet) self.ctrl = SimpleControllerState() # Handle states. self.checkState() # Execute state. if not self.state.expired: self.state.execute(self) # Render. self.render(self.renderer) return self.ctrl
def playlist_route(): return render_template("pop.html", projects=data.setup())
def repo_route(): return render_template("repo.html", projects=data.setup())
def animation_route(): return render_template("animation.html", projects=data.setup())
def playlist_route(): return render_template("playlist.html", datalist=data.playlist(), projects=data.setup())
def home(): return render_template("home.html", projects=data.setup(), data=data.runtime())
def home_route(): return render_template("home.html", title = data.setup())
from sklearn.datasets import load_digits from data import setup x, y = load_digits(return_X_y=True) x_train, x_test, y_train, y_test = setup(x, y) best_params_dt = {'max_depth': 13, 'max_leaf_nodes': 93} best_params_knn = {'metric': 'manhattan', 'n_neighbors': 3} best_params_nn = { 'alpha': 1e-05, 'hidden_layer_sizes': (100, ), 'learning_rate': 'invscaling' }
def home_route(): return render_template("home.html", projects=data.setup())
from sklearn import cross_validation from sklearn.feature_selection import SelectPercentile, f_classif from sklearn.feature_extraction.text import TfidfVectorizer #from sklearn import svm from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix # project functions from data import setup, read_labels, read_samples from preprocessor import purge_HTML, html2txt, count_links, avg_sentence_len # Setup setup(dataDir) nTrain = 700 nTest = 500 # Build dataset labels = read_labels() pos = [k for k, v in labels.items() if v] neg = [k for k, v in labels.items() if not v] random.shuffle(pos) random.shuffle(neg) balanced_labels = {k: True for k in pos[:nTrain]} balanced_labels.update({k: False for k in neg[:nTest]}) trainId, testId = cross_validation.train_test_split( np.array(list(balanced_labels.keys())),
def resolve_rebels(self, info): return get_rebels() def resolve_empire(self, info): return get_empire() class Mutation(graphene.ObjectType): introduce_ship = IntroduceShip.Field() schema = graphene.Schema(query=Query, mutation=Mutation) if __name__ == "__main__": setup() query = """ query RebelsShipsQuery { rebels { name, ships(first: 1) { pageInfo { startCursor endCursor hasNextPage hasPreviousPage } edges { cursor node {
def char_route(): # get value sent by form, and format them print("Ascii" + str(request.form.get("ASCIICode"))) # first the ascii code if request.form.get("ASCIICode") is not None: strAscii = Markup("&#" + request.form.get("ASCIICode") + ";") else: strAscii = "" # second the unicode code if request.form.get("UnicodeCode") is not None: strUnicode = Markup("&#" + request.form.get("UnicodeCode") + ";") else: strUnicode = "" # return the page, sending ASCII and Unicode parameters return render_template("char_codes.html", asciicode=strAscii, unicode=strUnicode, projects=data.setup())
def jazz_route(): return render_template("jazz.html", projects=data.setup())
def flask_route(): return render_template("flask.html", projects=data.setup())
setattr(self, a, [obj(x) if isinstance(x, dict) else x for x in b]) else: setattr(self, a, obj(b) if isinstance(b, dict) else b) app = Flask(__name__) log = logging.getLogger('werkzeug') log.setLevel(logging.DEBUG) '''readonly url, create your own if you want to write''' dbUrl = 'https://rapgraphdb.firebaseio.com/' '''genius api token''' token = '' data = setup(db=dbUrl, token=token) @app.route('/') def index(): global data query = ''' query songQuery { songs { edges { node { id title url primaryartist {
def train(params, model): criterion = get_criterion(params) optimizer = optim.Adam(model.parameters(), lr=params.lr) # Temp file for storing the best model temp_file_name = str(int(np.random.rand() * int(time.time()))) params.best_model_file = os.path.join('tmp', temp_file_name) train_generator, test_generator = chooseReader.setup(params) best_test_loss = 99999 for i in range(params.epochs): print('epoch: ', i) model.train() with tqdm(total=params.batch_size * len(train_generator)) as pbar: time.sleep(0.05) # Training for _i, _data in enumerate(train_generator): #_i,_data = next(iter(enumerate(train_generator))) x_train = _data[:, :-1].to(params.device) y_train = _data[:, -1].to(params.device) optimizer.zero_grad() predictions = model(x_train).squeeze(-1) loss = get_loss(params, criterion, predictions, y_train) loss.backward() nn.utils.clip_grad_norm_(model.parameters(), params.clip) optimizer.step() # Compute Training Accuracy n_total = len(predictions) if params.label == 'sentiment': n_correct = ((predictions >= 0.5).type( torch.float) == y_train).sum().item() train_acc = n_correct / n_total #Update Progress Bar pbar.update(params.batch_size) ordered_dict = {'acc': train_acc, 'loss': loss.item()} pbar.set_postfix(ordered_dict=ordered_dict) #################### Compute Validation Performance################## model.eval() with torch.set_grad_enabled(False): pred_test, y_test = get_predictions(model, params, test_generator) test_loss = get_loss(params, criterion, pred_test, y_test) print('Test Performance:') performances = evaluate(params, pred_test, y_test) print('val_acc = {}, val_loss = {}'.format(performances['acc'], test_loss)) if test_loss < best_test_loss: best_test_loss = test_loss torch.save(model, params.best_model_file) print('The best model up till now. Saved to File.')
def rock_route(): return render_template("rock.html", projects=data.setup())
def rgb_route(): codeRed=255 codeGreen=255 codeBlue=255 if request.form.get("codeRed") is not None: codeRed=request.form.get("codeRed") if request.form.get("codeGreen") is not None: codeGreen=request.form.get("codeGreen") if request.form.get("codeBlue") is not None: codeBlue=request.form.get("codeBlue") # update the count for rgb update_stats("rgb") return render_template("rgb.html", red=codeRed, green=codeGreen, blue=codeBlue, projects=data.setup())
def hello_rooute(): return render_template("hello.html", projects=data.setup())
def hello_route(): print('In PaulN') user = Users.query.filter_by(UserID=1).first() print(user.username) return render_template("PaulN.html", projects=data.setup())
def home(): return render_template("index.html", data=data.setup())
def ducks_route(): return render_template("p2-ducks.html", projects=data.setup())