content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
from django.forms import ( Form, CharField, Textarea, PasswordInput, ChoiceField, DateField, ImageField, BooleanField, IntegerField, MultipleChoiceField ) from django import forms from fb.models import UserProfile
[ 6738, 42625, 14208, 13, 23914, 1330, 357, 198, 220, 220, 220, 5178, 11, 3178, 15878, 11, 8255, 20337, 11, 30275, 20560, 11, 18502, 15878, 11, 7536, 15878, 11, 198, 220, 220, 220, 7412, 15878, 11, 41146, 15878, 11, 34142, 15878, 11, 20...
3.492308
65
# Simple implementation of GalaxyInvanders game # Rohan Roy (India) - 3 Nov 2013 # www.codeskulptor.org/#user23_fTVPDKIDhRdCfUp VER = "1.0" # "add various aliens" import simplegui, math, random, time #Global const FIELD_WIDTH = 850 FIELD_HEIGHT = 500 TOP_MARGIN = 75 LEFT_MARGIN = 25 ALIEN_WIDTH = 48 ALIEN_HEIGHT = 55 PLAYER_SPEED = 10 BULLET_SPEED = 10 BULLET_POWER = 1 BONUS_SPEED = 10 ALIEN_SPEED = [3, 5] # Images: pImage = simplegui.load_image('https://dl.dropbox.com/s/zhnjucatewcmfs4/player.png') aImages = [] for i in range(7): aImages.append([]) aImages[0].append(simplegui.load_image('https://dl.dropbox.com/s/0cck7w6r0mt8pzz/alien_1_1.png')) aImages[0].append(simplegui.load_image('https://dl.dropbox.com/s/j0kubnhzajbdngu/alien_1_2.png')) aImages[0].append(simplegui.load_image('https://dl.dropbox.com/s/zkeu6hqh9bakj25/alien_1_3.png')) aImages[1].append(simplegui.load_image('https://dl.dropbox.com/s/e75mkcylat70lnd/alien_2_1.png')) aImages[1].append(simplegui.load_image('https://dl.dropbox.com/s/pgjvaxg0z6rhco9/alien_2_2.png')) aImages[1].append(simplegui.load_image('https://dl.dropbox.com/s/en0hycfsi3cuzuo/alien_2_3.png')) aImages[2].append(simplegui.load_image('https://dl.dropbox.com/s/fu9weoll70acs8f/alien_3_1.png')) aImages[2].append(simplegui.load_image('https://dl.dropbox.com/s/b2rxru2nt5q2r1u/alien_3_2.png')) aImages[2].append(simplegui.load_image('https://dl.dropbox.com/s/x66vgj9fc2jlg53/alien_3_3.png')) aImages[3].append(simplegui.load_image('https://dl.dropbox.com/s/7o04ljg52kniyac/alien_4_1.png')) aImages[3].append(simplegui.load_image('https://dl.dropbox.com/s/b3v6tvami0rvl6r/alien_4_2.png')) aImages[3].append(simplegui.load_image('https://dl.dropbox.com/s/j451arcevsag36h/alien_4_3.png')) aImages[4].append(simplegui.load_image('https://dl.dropbox.com/s/jlhdigkm79nncnm/alien_5_1.png')) aImages[4].append(simplegui.load_image('https://dl.dropbox.com/s/wvlvjsa8yl6gka3/alien_5_2.png')) aImages[4].append(simplegui.load_image('https://dl.dropbox.com/s/rrg4y1tnsbrh04r/alien_5_3.png')) aImages[5].append(simplegui.load_image('https://dl.dropbox.com/s/oufyfy590tzf7cx/alien_6_1.png')) aImages[5].append(simplegui.load_image('https://dl.dropbox.com/s/p4ehd9f6mo2xfzc/alien_6_2.png')) aImages[5].append(simplegui.load_image('https://dl.dropbox.com/s/815gq3xyh6wmc0t/alien_6_3.png')) aImages[6].append(simplegui.load_image('https://dl.dropbox.com/s/bv4ycocuomsvj50/alien_7_1.png')) aImages[6].append(simplegui.load_image('https://dl.dropbox.com/s/krs2gtvdxxve79z/alien_7_2.png')) aImages[6].append(simplegui.load_image('https://dl.dropbox.com/s/v2wczi8lxwczq87/alien_7_3.png')) #backgrounds bckg = [] bckg.append(simplegui.load_image("https://dl.dropbox.com/s/ibfu2t9vrh4bhxd/back01.jpg")) bckg.append(simplegui.load_image("https://dl.dropbox.com/s/pcl8vzby25ovis8/back02.jpg")) bckg.append(simplegui.load_image("https://dl.dropbox.com/s/g8nwo1t9s4i9usg/back03.jpg")) bckg.append(simplegui.load_image("https://dl.dropbox.com/s/ee8oilluf7pe98h/back04.jpg")) bckg.append(simplegui.load_image("https://dl.dropbox.com/s/7jfgjoxinzwwlx4/back05.jpg")) bckg.append(simplegui.load_image("https://dl.dropbox.com/s/wh01g2q3607snvz/back06.jpg")) bckg.append(simplegui.load_image("https://dl.dropbox.com/s/b72ltp2xii9utnr/back07.jpg")) bckg.append(simplegui.load_image("https://dl.dropbox.com/s/av73jek8egezs1w/back08.jpg")) bckg.append(simplegui.load_image("https://dl.dropbox.com/s/ik54ttfklv3x3ai/back09.jpg")) bckg.append(simplegui.load_image("https://dl.dropbox.com/s/e9e6kpyg3yuoenc/back10.jpg")) bckg.append(simplegui.load_image("https://dl.dropbox.com/s/zrabwnnvlwvn7it/back11.jpg")) bckg.append(simplegui.load_image("https://dl.dropbox.com/s/a2infkx0rmn8b8m/back12.jpg")) # sounds sndPlayer = simplegui.load_sound('https://dl.dropbox.com/s/vl3as0o2m2wvlwu/player_shoot.wav') sndAlien = simplegui.load_sound('https://dl.dropbox.com/s/m4x0tldpze29hcr/alien_shoot.wav') sndPlayerExplosion = simplegui.load_sound('https://dl.dropbox.com/s/10fn2wh7kk7uoxh/explosion%2001.wav') sndAlienHit = simplegui.load_sound('https://dl.dropbox.com/s/80qdvup27n8j6r1/alien_hit.wav') sndAlienExplosion = simplegui.load_sound('https://dl.dropbox.com/s/qxm3je9vdlb469g/explosion_02.wav') sndBonus = simplegui.load_sound('https://dl.dropbox.com/s/tzp7e20e5v19l01/bonus.wav') sndPause = simplegui.load_sound('https://dl.dropbox.com/s/uzs9nixpd22asno/pause.wav') sndTheme = simplegui.load_sound('https://dl.dropbox.com/s/52zo892uemfkuzm/theme_01.mp3') sounds = [sndPlayer, sndAlien, sndPlayerExplosion, sndAlienExplosion, \ sndBonus, sndPause, sndTheme, sndAlienHit] #Global variables GameRunning = False GameEnded = False player_speed = 0 mes = "" timer_counter = 0 lives = 0 level = 1 scores = 0 killed = 0 current_back = 0 paused = False shoot_count = 0 level_time = [] ready, go = False, False #player = [FIELD_WIDTH //2, FIELD_HEIGHT - 30 + TOP_MARGIN] #game objects user_bullet = [] weapon_level = 1 weapon_speed = BULLET_SPEED alien_bullets = [] alien_fleet = None player = None frame = None aTimer = None dTimer = None bonuses = [] dCounter = 0 back = False bonus_count = [0, 0, 0, 0] player_killed = False player_killed_at = 0 level_map = [] for i in range(7): level_map.append([]) level_map[0] = [ 0, 0, 0, 0] level_map[1] = [129, 0, 0, 0] level_map[2] = [195, 129, 0, 0] level_map[3] = [255, 195, 60, 0] level_map[4] = [255, 231, 195, 195] level_map[5] = [255, 255, 231, 195] level_map[6] = [255, 255, 255, 231] #helper functions def dummy(key): return key def pause(): global paused paused = not paused sndPause.play() def draw_user_image(canvas, point): # draw a image of user ship # global player if pImage.get_width()==0: canvas.draw_circle(point, 12, 5, "Yellow") else: canvas.draw_image(pImage, (25, 36), (49, 72), point, (34, 50)) player.width = pImage.get_width() player.height = pImage.get_height() return canvas def draw_lives(canvas): # draw lives counter canvas.draw_text("Lives : ", [30, 25], 25, "Red") if player<>None: player.draw_lives_counter(canvas) return canvas def draw_weapons(canvas): canvas.draw_text("Weapon : ", [30, 60], 25, "Red") canvas.draw_text("Rocket lvl: "+str(int(weapon_level)), [135, 60], 25, "Yellow") canvas.draw_text("WS:"+str(weapon_speed/10.0), [280, 48], 10, "00c5fe") canvas.draw_text("WP:"+str(player.power), [280, 61], 10, "00c5fe") return canvas def draw_level(canvas): canvas.draw_text("Level : ", [FIELD_WIDTH-200, 50], 50, "Red") canvas.draw_text(str(level), [FIELD_WIDTH-50, 50], 50, "Yellow") return canvas def draw_scores(canvas): canvas.draw_text(str(int(scores)), [400, 50], 50, "LightBlue") return canvas def draw_screen(canvas): # border of board canvas.draw_image(bckg[current_back], (425, 250), (850, 500), \ (LEFT_MARGIN+FIELD_WIDTH//2, TOP_MARGIN+FIELD_HEIGHT//2),\ (FIELD_WIDTH, FIELD_HEIGHT)) canvas.draw_polygon([[LEFT_MARGIN, TOP_MARGIN], [LEFT_MARGIN, FIELD_HEIGHT+TOP_MARGIN], [FIELD_WIDTH+LEFT_MARGIN, FIELD_HEIGHT+TOP_MARGIN], [FIELD_WIDTH+LEFT_MARGIN, TOP_MARGIN]], 2, 'Orange') return canvas def draw_start_screen(canvas): img_count = 1 + len(aImages)*(len(aImages[0])) + len(bckg) loaded_img_count = 0 if pImage.get_width()<>0: loaded_img_count += 1 for bImage in bckg: if bImage.get_width()<>0: loaded_img_count += 1 for aImg in aImages: for img in aImg: if img.get_width()<>0: loaded_img_count += 1 loaded_sounds = 0 for snd in sounds: if snd <> None: loaded_sounds += 1 draw_text(canvas, "SPACE INVANDERS", [220, 150], 50, [3, 3], ["blue", "yellow"]) canvas.draw_text("ver. - "+VER, [600, 170], 20, "yellow") canvas.draw_text("03 nov. 2013", [600, 190], 20, "yellow") draw_text(canvas, "CONTROLS:", [110, 210], 24, [2, 2], ["green", "yellow"]) draw_text(canvas, "Arrows - to left and right, space - to fire, P to pause game", [110, 240], 24, [2, 2], ["green", "yellow"]) draw_text(canvas, "Bonuses: ", [110, 280], 24, [2, 2], ["green", "yellow"]) b = Bonus(0, [125, 310]) b.draw(canvas) draw_text(canvas, " - increase user's bullet speed", [150, 320], 24, [2, 2], ["green", "yellow"]) b = Bonus(1, [125, 350]) b.draw(canvas) draw_text(canvas, " - increase user's bullet number", [150, 360], 24, [2, 2], ["green", "yellow"]) b = Bonus(2, [125, 390]) b.draw(canvas) draw_text(canvas, " - add life", [150, 400], 24, [2, 2], ["green", "yellow"]) b = Bonus(3, [125, 430]) b.draw(canvas) draw_text(canvas, " - increase weapon power", [150, 440], 24, [2, 2], ["green", "yellow"]) if loaded_img_count<img_count: draw_text(canvas, "Please, wait for loading...", [280, 500], 40, [3, 3], ["Blue", "Yellow"]) s = "Loaded "+str(loaded_img_count)+" images of "+str(img_count) draw_text(canvas, s, [110, 550], 20, [2, 2], ["Blue", "yellow"]) s = "Loaded "+str(loaded_sounds)+" sounds of "+str(len(sounds)) draw_text(canvas, s, [510, 550], 20, [2, 2], ["Blue", "yellow"]) else: draw_text(canvas, "Click to start game", [300, 500], 40, [3, 3], ["Blue", "yellow"]) frame.set_mouseclick_handler(click_handler) return canvas def draw_end_screen(canvas): draw_text(canvas, "Game over!", [350, 180], 50, [2, 2], ["Blue", "Yellow"]) draw_text(canvas, "Your score is "+str(int(scores)), [330, 240], 35, [2, 2], ["blue", "Yellow"]) draw_text(canvas, "You shoot "+str(int(shoot_count))+" times", [150, 320], 24, [2, 2], ["blue", "Yellow"]) draw_text(canvas, "You kill a "+str(killed)+" aliens", [150, 360], 24, [2, 2], ["blue", "Yellow"]) if shoot_count == 0: s = "0" else: s = str(int(10000*float(killed)/shoot_count)/100.0) draw_text(canvas, "Your accuracy is "+s+"%", [150, 400], 24, [2, 2], ["blue", "Yellow"]) i = 0 for bc in bonus_count: b = Bonus(i, [505, 310 + 40*i]) b.draw(canvas) draw_text(canvas, " - used "+str(bonus_count[i])+" times", [530, 320+40*i], 24, [2, 2], ["blue", "yellow"]) i += 1 draw_text(canvas, "Click to start new game", [300, 500], 40, [2, 2], ["blue", "Yellow"]) canvas.draw_text("ver. - "+VER, [600, 540], 15, "yellow"); return canvas def draw_game_objects(canvas): player.draw(canvas) #draw_user_image(canvas, Player) for bullet in alien_bullets: bullet.draw(canvas) for bullet in user_bullet: bullet.draw(canvas) for bonus in bonuses: bonus.draw(canvas) alien_fleet.draw(canvas) readyGo() if paused: draw_text(canvas, "P A U S E", [380, 350], 50, [2, 2], ["Green", "Yellow"]) if ready: draw_text(canvas, "R E A D Y", [380, 350], 50, [2, 2], ["Green", "Yellow"]) if go: draw_text(canvas, "G O ! ! !", [380, 350], 50, [2, 2], ["Green", "Yellow"]) sndTheme.play() return canvas def moving_objects(): global timer_counter if not GameRunning: return None if paused or ready or go or player_killed: return None timer_counter += 1 player.move() for alien in alien_fleet.aliens: if alien.flying: alien.move([0,0]) if isBulletHit(alien, player): player.explode() if alien.y>FIELD_HEIGHT + TOP_MARGIN+20: alien.y = TOP_MARGIN for bonus in bonuses: bonus.move(); if bonus.y > FIELD_HEIGHT + TOP_MARGIN+20: bonuses.remove(bonus) if isBulletHit(bonus, player): bonus.execute() bonuses.remove(bonus) for bullet in user_bullet: bullet.move() alien_fleet.check_death() for bullet in user_bullet: if bullet.y<TOP_MARGIN+25: user_bullet.remove(bullet) # for bullet in alien_bullets: bullets_to_delete = [] for bullet in list(alien_bullets): bullet.move() if bullet.y > FIELD_HEIGHT + TOP_MARGIN -10: bullets_to_delete.append(bullet) if isBulletHit(bullet, player): player.explode() for bullet in bullets_to_delete: if bullet in alien_bullets: alien_bullets.remove(bullet) alien_fleet.make_shoot() alien_fleet.alien_fly() if level<30: x = 60 - level else: x = 1 if timer_counter % x == 0: alien_fleet.move_side() if timer_counter % (100 + x) == 0: alien_fleet.move_down() if alien_fleet.get_aliens_count() == 0: new_level() # Handler to draw on canvas #Initialization and start of game # Handler for mouse click #### keydown_handler #### keyup_handler to stop keydown # Create a frame and assign callbacks to event handlers frame = simplegui.create_frame("Galaxian", 900, 600, 0) frame.set_draw_handler(draw) frame.set_keydown_handler(keydown) frame.set_keyup_handler(keyup) aTimer = simplegui.create_timer(60, moving_objects) aTimer.start() # Start the frame animation frame.start()
[ 2, 17427, 7822, 286, 9252, 19904, 45070, 983, 201, 198, 2, 371, 22436, 9817, 357, 21569, 8, 532, 513, 5267, 2211, 201, 198, 2, 7324, 13, 40148, 74, 13327, 273, 13, 2398, 31113, 7220, 1954, 62, 69, 6849, 5760, 42, 2389, 71, 49, 67,...
2.080972
6,669
from flask import Flask, jsonify, request, render_template, redirect from flask_pymongo import PyMongo from werkzeug import secure_filename import base64 app = Flask(__name__) app.config['MONGO_DBNAME'] = 'restdb' app.config['MONGO_URI'] = 'mongodb://localhost:27017/restdb' mongo = PyMongo(app) if __name__ == '__main__': app.run(debug=True)
[ 6738, 42903, 1330, 46947, 11, 33918, 1958, 11, 2581, 11, 8543, 62, 28243, 11, 18941, 198, 6738, 42903, 62, 79, 4948, 25162, 1330, 9485, 44, 25162, 198, 6738, 266, 9587, 2736, 1018, 1330, 5713, 62, 34345, 198, 11748, 2779, 2414, 198, 1...
2.8
125
""" Utilities :Author: Jonathan Karr <karr@mssm.edu> :Date: 2016-11-10 :Copyright: 2016, Karr Lab :License: MIT """ from obj_tables import get_models as base_get_models from wc_lang import core from wc_lang import io from wc_utils.util import git def get_model_size(model): """ Get numbers of model components Args: model (:obj:`core.Model`): model Returns: :obj:`dict`: dictionary with numbers of each type of model component """ return { "submodels": len(model.get_submodels()), "compartments": len(model.get_compartments()), "species_types": len(model.get_species_types()), "species": len(model.get_species()), "parameters": len(model.get_parameters()), "references": len(model.get_references()), "reactions": len(model.get_reactions()), } def get_model_summary(model): """ Get textual summary of a model Args: model (:obj:`core.Model`): model Returns: :obj:`str`: textual summary of the model """ return "Model with:" \ + "\n{:d} submodels".format(len(model.get_submodels())) \ + "\n{:d} compartments".format(len(model.get_compartments())) \ + "\n{:d} species types".format(len(model.get_species_types())) \ + "\n{:d} species".format(len(model.get_species())) \ + "\n{:d} parameters".format(len(model.get_parameters())) \ + "\n{:d} references".format(len(model.get_references())) \ + "\n{:d} dFBA objective reactions".format(len(model.get_dfba_obj_reactions())) \ + "\n{:d} reactions".format(len(model.get_reactions())) \ + "\n{:d} rate laws".format(len(model.get_rate_laws())) def get_models(inline=True): """ Get list of models Args: inline (:obj:`bool`, optional): if true, return inline models Returns: :obj:`list` of :obj:`class`: list of models """ return base_get_models(module=core, inline=inline) def gen_ids(model): """ Generate ids for model objects Args: model (:obj:`core.Model`): model """ for obj in model.get_related(): if hasattr(obj, 'gen_id'): obj.id = obj.gen_id()
[ 37811, 41086, 198, 198, 25, 13838, 25, 11232, 509, 3258, 1279, 74, 3258, 31, 76, 824, 76, 13, 15532, 29, 198, 25, 10430, 25, 1584, 12, 1157, 12, 940, 198, 25, 15269, 25, 1584, 11, 509, 3258, 3498, 198, 25, 34156, 25, 17168, 198, ...
2.36246
927
import synapse.common as s_common import synapse.tests.utils as s_t_utils import synapse.tools.autodoc as s_autodoc
[ 11748, 6171, 7512, 13, 11321, 355, 264, 62, 11321, 198, 198, 11748, 6171, 7512, 13, 41989, 13, 26791, 355, 264, 62, 83, 62, 26791, 198, 198, 11748, 6171, 7512, 13, 31391, 13, 2306, 375, 420, 355, 264, 62, 2306, 375, 420, 198 ]
2.809524
42
# -*- coding: utf-8 -*- import pickle import os import jieba from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.externals import joblib from sklearn.metrics.pairwise import cosine_similarity
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 628, 198, 11748, 2298, 293, 198, 11748, 28686, 198, 198, 11748, 474, 494, 7012, 198, 6738, 1341, 35720, 13, 30053, 62, 2302, 7861, 13, 5239, 1330, 309, 69, 312, 69, 38469, ...
2.945946
74
""" Module for classifier Models (c) 2020 d373c7 """ import logging import torch import torch.nn as nn from .common import PyTorchModelException, ModelDefaults, _History, _ModelGenerated, _ModelStream from .encoders import GeneratedAutoEncoder from ..layers import LSTMBody, ConvolutionalBody1d, AttentionLastEntry, LinearEncoder, TensorDefinitionHead from ..layers import TransformerBody, TailBinary from ..loss import SingleLabelBCELoss from ...features import TensorDefinition, TensorDefinitionMulti from typing import List, Dict, Union logger = logging.getLogger(__name__)
[ 37811, 198, 26796, 329, 1398, 7483, 32329, 198, 7, 66, 8, 12131, 288, 34770, 66, 22, 198, 37811, 198, 11748, 18931, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 6738, 764, 11321, 1330, 9485, 15884, 354, 17633, 1...
3.570552
163
import re import numpy as np import pandas as pd import matplotlib as mpl mpl.use("pdf") import matplotlib.pyplot as plt from matplotlib import gridspec from peewee import AsIs, JOIN, prefetch, SQL from IPython import embed from bokeh.layouts import row, column from bokeh.plotting import figure, show, output_file from bokeh.transform import linear_cmap from bokeh.models import ( ColumnDataSource, Range1d, LabelSet, Label, Rect, HoverTool, Div, ) from qlknn.NNDB.model import ( Network, PureNetworkParams, PostprocessSlice, NetworkMetadata, TrainMetadata, Postprocess, db, Hyperparameters, ) from qlknn.plots.statistical_spread import get_base_stats from qlknn.misc.to_precision import to_precision # First, get some statistics target_names = ["efeTEM_GB"] hyperpars = ["cost_stable_positive_scale", "cost_l2_scale"] # hyperpars = ['cost_stable_positive_scale', 'cost_stable_positive_offset'] goodness_pars = [ "rms", "no_pop_frac", "no_thresh_frac", "pop_abs_mis_median", "thresh_rel_mis_median", "wobble_qlkunstab", ] try: report = get_base_stats(target_names, hyperpars, goodness_pars) except Network.DoesNotExist: report = pd.DataFrame(columns=goodness_pars, index=["mean", "stddev", "stderr"]) query = ( Network.select( Network.id.alias("network_id"), PostprocessSlice, Postprocess.rms, Hyperparameters, ) .join(PostprocessSlice, JOIN.LEFT_OUTER) .switch(Network) .join(Postprocess, JOIN.LEFT_OUTER) .switch(Network) .where(Network.target_names == target_names) .switch(Network) .join(PureNetworkParams) .join(Hyperparameters) .where(Hyperparameters.cost_stable_positive_offset.cast("numeric") == -5) .where(Hyperparameters.cost_stable_positive_function == "block") ) if query.count() > 0: results = list(query.dicts()) df = pd.DataFrame(results) # df['network'] = df['network'].apply(lambda el: 'pure_' + str(el)) # df['l2_norm'] = df['l2_norm'].apply(np.nanmean) df.drop(["id", "network"], inplace=True, axis="columns") df.set_index("network_id", inplace=True) stats = df stats = stats.applymap(np.array) stats = stats.applymap(lambda x: x[0] if isinstance(x, np.ndarray) and len(x) == 1 else x) stats.dropna(axis="columns", how="all", inplace=True) stats.dropna(axis="rows", how="all", inplace=True) stats = stats.loc[:, hyperpars + goodness_pars] stats.reset_index(inplace=True) # stats.set_index(hyperpars, inplace=True) # stats.sort_index(ascending=False, inplace=True) # stats = stats.groupby(level=list(range(len(stats.index.levels)))).mean() #Average equal hyperpars # stats.reset_index(inplace=True) aggdict = {"network_id": lambda x: tuple(x)} aggdict.update({name: "mean" for name in goodness_pars}) stats_mean = stats.groupby(hyperpars).agg(aggdict) aggdict.update({name: "std" for name in goodness_pars}) stats_std = stats.groupby(hyperpars).agg(aggdict) stats = stats_mean.merge(stats_std, left_index=True, right_index=True, suffixes=("", "_std")) stats.reset_index(inplace=True) for name in hyperpars: stats[name] = stats[name].apply(str) for name in goodness_pars: fmt = lambda x: "" if np.isnan(x) else to_precision(x, 4) fmt_mean = stats[name].apply(fmt) stats[name + "_formatted"] = fmt_mean fmt = lambda x: "" if np.isnan(x) else to_precision(x, 2) fmt_std = stats[name + "_std"].apply(fmt) prepend = lambda x: "+- " + x if x != "" else x stats[name + "_std_formatted"] = fmt_std.apply(prepend) x = np.unique(stats[hyperpars[1]].values) x = sorted(x, key=lambda x: float(x)) y = np.unique(stats[hyperpars[0]].values) y = sorted(y, key=lambda x: float(x)) source = ColumnDataSource(stats) plotmode = "bokehz" hover = HoverTool( tooltips=[ ("network_id", "@network_id"), (hyperpars[0], "@" + hyperpars[0]), (hyperpars[1], "@" + hyperpars[1]), ] ) plots = [] for statname in goodness_pars: fmt = lambda x: "" if np.isnan(x) else to_precision(x, 2) title = "{:s} (ref={:s}{:s})".format( statname, fmt(report[statname]["mean"]), fmt(report[statname]["stddev"] + report[statname]["stderr"]), ) p = figure(title=title, tools="tap", toolbar_location=None, x_range=x, y_range=y) p.add_tools(hover) color = linear_cmap(statname, "Viridis256", min(stats[statname]), max(stats[statname])) p.rect( x=hyperpars[1], y=hyperpars[0], width=1, height=1, source=source, fill_color=color, line_color=None, nonselection_fill_alpha=0.4, nonselection_fill_color=color, ) non_selected = Rect(fill_alpha=0.8) label_kwargs = dict( x=hyperpars[1], y=hyperpars[0], level="glyph", source=source, text_align="center", text_color="red", ) labels = LabelSet(text=statname + "_formatted", text_baseline="bottom", **label_kwargs) labels_std = LabelSet(text=statname + "_std_formatted", text_baseline="top", **label_kwargs) p.add_layout(labels) p.add_layout(labels_std) p.xaxis.axis_label = hyperpars[1] p.yaxis.axis_label = hyperpars[0] plots.append(p) from bokeh.layouts import layout, widgetbox title = Div(text=",".join(target_names)) l = layout([[title], [plots]]) show(l)
[ 11748, 302, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 2603, 29487, 8019, 355, 285, 489, 198, 198, 76, 489, 13, 1904, 7203, 12315, 4943, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 3...
2.377325
2,258
"""SharedBrandConfigs API Tests for Version 1.0. This is a testing template for the generated SharedBrandConfigsAPI Class. """ import unittest import requests import secrets from py3canvas.apis.shared_brand_configs import SharedBrandConfigsAPI from py3canvas.apis.shared_brand_configs import Sharedbrandconfig
[ 37811, 2484, 1144, 38416, 16934, 82, 7824, 30307, 329, 10628, 352, 13, 15, 13, 198, 198, 1212, 318, 257, 4856, 11055, 329, 262, 7560, 39403, 38416, 16934, 82, 17614, 5016, 13, 198, 37811, 198, 11748, 555, 715, 395, 198, 11748, 7007, 1...
3.586207
87
from abc import ABC, abstractmethod from django.test import TestCase from rest_framework.generics import GenericAPIView from rest_framework.test import APIRequestFactory from apps.cars.factory import UserFactory
[ 6738, 450, 66, 1330, 9738, 11, 12531, 24396, 198, 198, 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 198, 198, 6738, 1334, 62, 30604, 13, 8612, 873, 1330, 42044, 2969, 3824, 769, 198, 6738, 1334, 62, 30604, 13, 9288, 1330, 7824, 18...
3.857143
56
""" A simple templating tool for Dockerfiles """ import sys import os import click import jinja2 import yaml cli.add_command(from_yaml) if __name__ == '__main__': cli()
[ 37811, 198, 32, 2829, 2169, 489, 803, 2891, 329, 25716, 16624, 198, 37811, 198, 198, 11748, 25064, 198, 11748, 28686, 198, 198, 11748, 3904, 198, 11748, 474, 259, 6592, 17, 198, 11748, 331, 43695, 628, 628, 198, 44506, 13, 2860, 62, 2...
2.647059
68
"""File for holding the different verb forms for all of the verbs in the Total English book series.""" verb_forms = { 'become' : { 'normal' : 'become', 'present' : ['become','becomes'], 'past' : 'became', 'past participle' : 'become', 'gerund' : 'becoming', }, 'be': { 'normal' : 'be', 'present' : ['am','is','are'], 'past' : ['was', 'were'], 'past participle' : 'been', 'gerund' : 'being', }, 'begin': { 'normal' : 'begin', 'present' : ['begin','begins'], 'past' : 'began', 'past participle' : 'begun', 'gerund' : 'beginning', }, 'blow': { 'normal' : 'blow', 'present' : ['blow', 'blows'], 'past' : 'blew', 'past participle' : 'blown', 'gerund' : 'blowing', }, 'bring': { 'normal' : 'bring', 'present' : ['bring','brings'], 'past' : 'brought', 'past participle' : 'brought', 'gerund' : 'bringing', }, 'build': { 'normal' : 'build', 'present' : ['build','builds'], 'past' : 'built', 'past participle' : 'built', 'gerund' : 'building', }, 'burn': { 'normal' : 'burn', 'present' : ['burn','burns'], 'past' : ['burned','burnt'], 'past participle' : ['burned','burnt'], 'gerund' : 'burning', }, 'buy': { 'normal' : 'buy', 'present' : ['buy','buys'], 'past' : 'bought', 'past participle' : 'bought', 'gerund' : 'buying', }, 'catch': { 'normal' : 'catch', 'present' : ['catch','catches'], 'past' : 'caught', 'past participle' : 'caught', 'gerund' : 'catching', }, 'choose': { 'normal' : 'choose', 'present' : ['choose','chooses'], 'past' : 'chose', 'past participle' : 'chosen', 'gerund' : 'choosing', }, 'come': { 'normal' : 'come', 'present' : ['come','comes'], 'past' : 'came', 'past participle' : 'come', 'gerund' : 'coming', }, 'cut': { 'normal' : 'cut', 'present' : ['cut','cuts'], 'past' : 'cut', 'past participle' : 'cut', 'gerund' : 'cutting', }, 'do': { 'normal' : 'do', 'present' : ['do','does'], 'past' : 'did', 'past participle' : 'done', 'gerund' : 'doing', }, 'drink': { 'normal' : 'drink', 'present' : ['drink','drinks'], 'past' : 'drank', 'past participle' : 'drunk', 'gerund' : 'drinking', }, 'eat': { 'normal' : 'eat', 'present' : ['eat','eats'], 'past' : 'ate', 'past participle' : 'eaten', 'gerund' : 'eating', }, 'feel': { 'normal' : 'feel', 'present' : ['feel','feels'], 'past' : 'felt', 'past participle' : 'felt', 'gerund' : 'feeling', }, 'fight': { 'normal' : 'fight', 'present' : ['fight','fights'], 'past' : 'fought', 'past participle' : 'fought', 'gerund' : 'fighting', }, 'find': { 'normal' : 'find', 'present' : ['find','finds'], 'past' : 'found', 'past participle' : 'found', 'gerund' : 'finding', }, 'fly': { 'normal' : 'fly', 'present' : ['fly','flies'], 'past' : 'flew', 'past participle' : 'flown', 'gerund' : 'flying', }, 'forget': { 'normal' : 'forget', 'present' : ['forget','forgets'], 'past' : 'forgot', 'past participle' : ['forgotten','forgot'], 'gerund' : 'forgetting', }, 'get': { 'normal' : 'get', 'present' : ['get','gets'], 'past' : 'got', 'past participle' : ['gotten','got'], 'gerund' : 'getting', }, 'give': { 'normal' : 'give', 'present' : ['give','gives'], 'past' : 'gave', 'past participle' : 'given', 'gerund' : 'giving', }, 'go': { 'normal' : 'go', 'present' : ['go','goes'], 'past' : 'went', 'past participle' : 'gone', 'gerund' : 'going', }, 'grow': { 'normal' : 'grow', 'present' : ['grow','grows'], 'past' : 'grew', 'past participle' : 'grown', 'gerund' : 'growing', }, 'have': { 'normal' : 'have', 'present' : ['have','has'], 'past' : 'had', 'past participle' : 'had', 'gerund' : 'having', }, 'hear': { 'normal' : 'hear', 'present' : ['hear','hears'], 'past' : 'heard', 'past participle' : 'heard', 'gerund' : 'hearing', }, 'hit': { 'normal' : 'hit', 'present' : ['hit','hits'], 'past' : 'hit', 'past participle' : 'hit', 'gerund' : 'hitting', }, 'hold': { 'normal' : 'hold', 'present' : ['hold','holds'], 'past' : 'held', 'past participle' : 'held', 'gerund' : 'holding', }, 'hurt': { 'normal' : 'hurt', 'present' : ['hurt','hurts'], 'past' : 'hurt', 'past participle' : 'hurt', 'gerund' : 'hurting', }, 'keep': { 'normal' : 'keep', 'present' : ['keep','keeps'], 'past' : 'kept', 'past participle' : 'kept', 'gerund' : 'keeping', }, 'know': { 'normal' : 'know', 'present' : ['know','knows'], 'past' : 'knew', 'past participle' : 'known', 'gerund' : 'knowing', }, 'lead': { 'normal' : 'lead', 'present' : ['lead','leads'], 'past' : 'led', 'past participle' : 'led', 'gerund' : 'leading', }, 'leave': { 'normal' : 'leave', 'present' : ['leave','leaves'], 'past' : 'left', 'past participle' : 'left', 'gerund' : 'leaving', }, 'lend': { 'normal' : 'lend', 'present' : ['lend','lends'], 'past' : 'lent', 'past participle' : 'lent', 'gerund' : 'lending', }, 'lie': { 'normal' : 'lie', 'present' : ['lie','lies'], 'past' : 'lay', 'past participle' : 'lain', 'gerund' : 'lying', }, 'lose': { 'normal' : 'lose', 'present' : ['lose','loses'], 'past' : 'lost', 'past participle' : 'lost', 'gerund' : 'losing', }, 'make': { 'normal' : 'make', 'present' : ['make','makes'], 'past' : 'made', 'past participle' : 'made', 'gerund' : 'making', }, 'mean': { 'normal' : 'mean', 'present' : ['mean','means'], 'past' : 'meant', 'past participle' : 'meant', 'gerund' : 'meaning', }, 'meet': { 'normal' : 'meet', 'present' : ['meet','meets'], 'past' : 'met', 'past participle' : 'met', 'gerund' : 'meeting', }, 'put': { 'normal' : 'put', 'present' : ['put','puts'], 'past' : 'put', 'past participle' : 'put', 'gerund' : 'putting', }, 'read': { 'normal' : 'read', 'present' : ['read','reads'], 'past' : 'read', 'past participle' : 'read', 'gerund' : 'reading', }, 'ride': { 'normal' : 'ride', 'present' : ['ride','rides'], 'past' : 'rode', 'past participle' : 'ridden', 'gerund' : 'riding', }, 'ring': { 'normal' : 'ring', 'present' : ['ring','rings'], 'past' : 'rang', 'past participle' : 'rung', 'gerund' : 'ringing', }, 'run': { 'normal' : 'run', 'present' : ['run','runs'], 'past' : 'ran', 'past participle' : 'run', 'gerund' : 'running', }, 'say': { 'normal' : 'say', 'present' : ['say','says'], 'past' : 'said', 'past participle' : 'said', 'gerund' : 'saying', }, 'see': { 'normal' : 'see', 'present' : ['see','sees'], 'past' : 'saw', 'past participle' : 'seen', 'gerund' : 'seeing', }, 'sell': { 'normal' : 'sell', 'present' : ['sell','sells'], 'past' : 'sold', 'past participle' : 'sold', 'gerund' : 'selling', }, 'send': { 'normal' : 'send', 'present' : ['send','sends'], 'past' : 'sent', 'past participle' : 'sent', 'gerund' : 'sending', }, 'shake': { 'normal' : 'shake', 'present' : ['shake','shakes'], 'past' : 'shook', 'past participle' : 'shaken', 'gerund' : 'shaking', }, 'show': { 'normal' : 'show', 'present' : ['show','shows'], 'past' : 'showed', 'past participle' : 'shown', 'gerund' : 'showing', }, 'shut': { 'normal' : 'shut', 'present' : ['shut','shuts'], 'past' : 'shut', 'past participle' : 'shut', 'gerund' : 'shutting', }, 'sing': { 'normal' : 'sing', 'present' : ['sing','sings'], 'past' : 'sang', 'past participle' : 'sung', 'gerund' : 'singing', }, 'sit': { 'normal' : 'sit', 'present' : ['sit','sits'], 'past' : 'sat', 'past participle' : 'sat', 'gerund' : 'sitting', }, 'sleep': { 'normal' : 'sleep', 'present' : ['sleep','sleeps'], 'past' : 'slept', 'past participle' : 'slept', 'gerund' : 'sleeping', }, 'smell': { 'normal' : 'smell', 'present' : ['smell','smells'], 'past' : 'smelled,smelt', 'past participle' : 'smelled,smelt', 'gerund' : 'smelling', }, 'speak': { 'normal' : 'speak', 'present' : ['speak','speaks'], 'past' : 'spoke', 'past participle' : 'spoken', 'gerund' : 'speaking', }, 'spend': { 'normal' : 'spend', 'present' : ['spend','spends'], 'past' : 'spent', 'past participle' : 'spent', 'gerund' : 'spending', }, 'stand': { 'normal' : 'stand', 'present' : ['stand','stands'], 'past' : 'stood', 'past participle' : 'stood', 'gerund' : 'standing', }, 'swim': { 'normal' : 'swim', 'present' : ['swim','swims'], 'past' : 'swam', 'past participle' : 'swum', 'gerund' : 'swimming', }, 'take': { 'normal' : 'take', 'present' : ['take','takes'], 'past' : 'took', 'past participle' : 'taken', 'gerund' : 'taking', }, 'teach': { 'normal' : 'teach', 'present' : ['teach','teaches'], 'past' : 'taught', 'past participle' : 'taught', 'gerund' : 'teaching', }, 'tell': { 'normal' : 'tell', 'present' : ['tell','tells'], 'past' : 'told', 'past participle' : 'told', 'gerund' : 'telling', }, 'think': { 'normal' : 'think', 'present' : ['think','thinks'], 'past' : 'thought', 'past participle' : 'thought', 'gerund' : 'thinking', }, 'throw': { 'normal' : 'throw', 'present' : ['throw','throws'], 'past' : 'threw', 'past participle' : 'thrown', 'gerund' : 'throwing', }, 'understand': { 'normal' : 'understand', 'present' : ['understand','understands'], 'past' : 'understood', 'past participle' : 'understood', 'gerund' : 'unerstanding', }, 'wear': { 'normal' : 'wear', 'present' : ['wear','wears'], 'past' : 'wore', 'past participle' : 'worn', 'gerund' : 'wearing', }, 'win': { 'normal' : 'win', 'present' : ['win','wins'], 'past' : 'won', 'past participle' : 'won', 'gerund' : 'winning', }, 'write': { 'normal' : 'write', 'present' : ['write','writes'], 'past' : 'wrote', 'past participle' : 'written', 'gerund' : 'writing',},}
[ 37811, 8979, 329, 4769, 262, 1180, 15942, 5107, 329, 477, 286, 262, 41781, 287, 262, 7472, 198, 15823, 1492, 2168, 526, 15931, 198, 19011, 62, 23914, 796, 1391, 198, 220, 220, 220, 705, 9423, 462, 6, 1058, 198, 220, 220, 220, 1391, ...
1.985221
5,819
''' Provides API for loading themes ''' from __future__ import absolute_import from os.path import join from .theme import Theme default = Theme(json={}) del join
[ 7061, 6, 47081, 7824, 329, 11046, 13460, 198, 198, 7061, 6, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 6738, 28686, 13, 6978, 1330, 4654, 198, 198, 6738, 764, 43810, 1330, 26729, 198, 198, 12286, 796, 26729, 7, 177...
3.44898
49
# -*- coding: utf-8 -*- # # Copyright (C) 2015 Dirk Stcker <trac@dstoecker.de> # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.edgewall.com/license.html. # # This software consists of voluntary contributions made by many # individuals. For the exact contribution history, see the revision # history and logs, available at http://projects.edgewall.com/trac/. import hashlib import random import urllib2 from trac.config import Option from trac.core import Component, implements from trac.util.html import tag from tracspamfilter.api import user_agent from tracspamfilter.captcha import ICaptchaMethod
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 357, 34, 8, 1853, 42761, 520, 15280, 1279, 2213, 330, 31, 67, 301, 2577, 15280, 13, 2934, 29, 198, 2, 1439, 2489, 10395, 13, 198, 2, 198, 2, 770,...
3.514019
214
#!/usr/bin/env python # coding: utf-8 # In[18]: # this definition exposes all python module imports that should be available in all subsequent commands import json import numpy as np import pandas as pd from causalnex.structure import DAGRegressor from sklearn.model_selection import cross_val_score from sklearn.preprocessing import StandardScaler from sklearn.model_selection import KFold # ... # global constants MODEL_DIRECTORY = "/srv/app/model/data/" # In[22]: # this cell is not executed from MLTK and should only be used for staging data into the notebook environment # In[24]: # initialize your model # available inputs: data and parameters # returns the model object which will be used as a reference to call fit, apply and summary subsequently # In[26]: # train your model # returns a fit info json object and may modify the model object # In[28]: # apply your model # returns the calculated results # In[ ]: # save model to name in expected convention "<algo_name>_<model_name>" # In[ ]: # load model from name in expected convention "<algo_name>_<model_name>" # In[ ]: # return a model summary
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 19617, 25, 3384, 69, 12, 23, 628, 198, 220, 220, 220, 220, 198, 2, 554, 58, 1507, 5974, 628, 198, 2, 428, 6770, 32142, 477, 21015, 8265, 17944, 326, 815, 307, 1695, 287, 477, ...
3.191214
387
import matplotlib import matplotlib.pyplot as plt import matplotlib.animation as animation matplotlib.use('Agg') import math import numpy as np import sys from os.path import join, isfile import warnings warnings.filterwarnings("ignore") if __name__ == '__main__': main()
[ 11748, 2603, 29487, 8019, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 2603, 29487, 8019, 13, 11227, 341, 355, 11034, 198, 6759, 29487, 8019, 13, 1904, 10786, 46384, 11537, 198, 198, 11748, 10688, 198, 11748, ...
3.1
90
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import *
[ 2, 15069, 2211, 12, 42334, 13914, 45036, 3549, 2351, 4765, 11, 11419, 290, 584, 198, 2, 1338, 441, 4935, 34152, 13, 4091, 262, 1353, 12, 5715, 27975, 38162, 9947, 2393, 329, 3307, 13, 198, 2, 198, 2, 30628, 55, 12, 34156, 12, 33234,...
3.47619
63
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-11-21 23:50 from django.db import migrations
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 1157, 13, 22, 319, 2177, 12, 1157, 12, 2481, 2242, 25, 1120, 628, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 628 ]
2.477273
44
# SPDX-FileCopyrightText: 2020 The birch-books-smarthome Authors # SPDX-License-Identifier: MIT BOOKSTORE_GROUND_FLOOR = 0x0007 BOOKSTORE_FIRST_FLOOR = 0x0008 BOOKSTORE_TERRARIUM = 0x0010 BOOKSTORE_BEDROOM = 0x0020 HOUSE_BASEMENT = 0x0040 HOUSE_GROUND_FLOOR = 0x0380 HOUSE_BEDROOM_LIGHT = 0x0400 HOUSE_BEDROOM_LAMP = 0x0800 HOUSE_FIREPLACE_1 = 0x1000 HOUSE_FIREPLACE_2 = 0x2000 SCHEDULE = [ BOOKSTORE_BEDROOM | HOUSE_BEDROOM_LIGHT, BOOKSTORE_TERRARIUM | BOOKSTORE_BEDROOM | HOUSE_BEDROOM_LIGHT, BOOKSTORE_TERRARIUM | BOOKSTORE_FIRST_FLOOR | HOUSE_BEDROOM_LIGHT, BOOKSTORE_TERRARIUM | BOOKSTORE_GROUND_FLOOR | HOUSE_GROUND_FLOOR, BOOKSTORE_TERRARIUM | BOOKSTORE_GROUND_FLOOR | HOUSE_GROUND_FLOOR, BOOKSTORE_TERRARIUM | BOOKSTORE_GROUND_FLOOR, BOOKSTORE_TERRARIUM | BOOKSTORE_GROUND_FLOOR, BOOKSTORE_TERRARIUM | BOOKSTORE_GROUND_FLOOR, BOOKSTORE_TERRARIUM | BOOKSTORE_GROUND_FLOOR, BOOKSTORE_TERRARIUM | BOOKSTORE_GROUND_FLOOR | HOUSE_GROUND_FLOOR, BOOKSTORE_TERRARIUM | BOOKSTORE_FIRST_FLOOR | HOUSE_GROUND_FLOOR, BOOKSTORE_TERRARIUM | BOOKSTORE_FIRST_FLOOR | HOUSE_BASEMENT | HOUSE_BEDROOM_LIGHT, BOOKSTORE_TERRARIUM | BOOKSTORE_BEDROOM | HOUSE_BASEMENT | HOUSE_BEDROOM_LAMP, BOOKSTORE_BEDROOM | HOUSE_BEDROOM_LAMP, 0, 0, ] TEST_SCHEDULE = [ BOOKSTORE_GROUND_FLOOR, BOOKSTORE_FIRST_FLOOR, BOOKSTORE_TERRARIUM, BOOKSTORE_BEDROOM, HOUSE_BASEMENT, HOUSE_GROUND_FLOOR, HOUSE_BEDROOM_LIGHT, HOUSE_BEDROOM_LAMP, HOUSE_FIREPLACE_1, HOUSE_FIREPLACE_2, ]
[ 2, 30628, 55, 12, 8979, 15269, 8206, 25, 220, 12131, 383, 35122, 354, 12, 12106, 12, 82, 3876, 400, 462, 46665, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 17168, 198, 198, 39453, 2257, 6965, 62, 46025, 62, 3697, 46, 1581, ...
2.069241
751
import bcrypt salt = bcrypt.gensalt()
[ 11748, 275, 29609, 198, 198, 82, 2501, 796, 275, 29609, 13, 70, 641, 2501, 3419, 628 ]
2.5
16
from test.test_base import TestBase
[ 6738, 1332, 13, 9288, 62, 8692, 1330, 6208, 14881, 628 ]
3.7
10
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Jan-Piet Mens <jpmens()gmail.com>' __copyright__ = 'Copyright 2014 Jan-Piet Mens' __license__ = """Eclipse Public License - v 1.0 (http://www.eclipse.org/legal/epl-v10.html)""" import smtplib from email.mime.text import MIMEText
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 834, 9800, 834, 220, 220, 220, 796, 705, 12128, 12, 47, 1155, 43103, 1279, 73, 4426, 641, 3419, 14816, 13, 785, ...
2.446281
121
""" Module for Serialization and Deserialization of a KNX Disconnect Request information. Disconnect requests are used to disconnect a tunnel from a KNX/IP device. """ from __future__ import annotations from typing import TYPE_CHECKING from xknx.exceptions import CouldNotParseKNXIP from .body import KNXIPBody from .hpai import HPAI from .knxip_enum import KNXIPServiceType if TYPE_CHECKING: from xknx.xknx import XKNX
[ 37811, 198, 26796, 329, 23283, 1634, 290, 2935, 48499, 1634, 286, 257, 22466, 55, 3167, 8443, 19390, 1321, 13, 198, 198, 7279, 8443, 7007, 389, 973, 284, 22837, 257, 13275, 422, 257, 22466, 55, 14, 4061, 3335, 13, 198, 37811, 198, 673...
3.257576
132
from src.sqlite_helper import create_message_table, drop_message_table """ This script will create a SQLite table for you, and should be one time setup The table name is message which will store all the Post message """ create_message_table() """ If you need to drop the message table, un-comment the following code by removing the # sign in the beginning """ # # drop_message_table() #
[ 6738, 12351, 13, 25410, 578, 62, 2978, 525, 1330, 2251, 62, 20500, 62, 11487, 11, 4268, 62, 20500, 62, 11487, 198, 198, 37811, 198, 1212, 4226, 481, 2251, 257, 16363, 578, 3084, 329, 345, 11, 290, 815, 307, 530, 640, 9058, 198, 464,...
3.688679
106
from java.lang import String import threading import random import codecs import io import itertools import time import os import urllib2 import textwrap import socket import shutil ############################################################# # This is the ZOrba # ############################################################# # All bot specific configuration goes here. leftPort = "/dev/ttyACM1" rightPort = "/dev/ttyACM0" headPort = leftPort gesturesPath = "/home/pedro/Dropbox/pastaPessoal/3Dprinter/inmoov/scripts/zorba/gestures" botVoice = "WillBadGuy" #starting the INMOOV i01 = Runtime.createAndStart("i01", "InMoov") i01.setMute(True) ##############STARTING THE RIGHT HAND######### i01.rightHand = Runtime.create("i01.rightHand", "InMoovHand") #tweaking defaults settings of right hand i01.rightHand.thumb.setMinMax(20,155) i01.rightHand.index.setMinMax(30,130) i01.rightHand.majeure.setMinMax(38,150) i01.rightHand.ringFinger.setMinMax(30,170) i01.rightHand.pinky.setMinMax(30,150) i01.rightHand.thumb.map(0,180,20,155) i01.rightHand.index.map(0,180,30,130) i01.rightHand.majeure.map(0,180,38,150) i01.rightHand.ringFinger.map(0,180,30,175) i01.rightHand.pinky.map(0,180,30,150) ################# #################STARTING RIGHT ARM############### i01.startRightArm(rightPort) #i01.rightArm = Runtime.create("i01.rightArm", "InMoovArm") ## tweak default RightArm i01.detach() i01.rightArm.bicep.setMinMax(0,60) i01.rightArm.bicep.map(0,180,0,60) i01.rightArm.rotate.setMinMax(46,130) i01.rightArm.rotate.map(0,180,46,130) i01.rightArm.shoulder.setMinMax(0,155) i01.rightArm.shoulder.map(0,180,0,155) i01.rightArm.omoplate.setMinMax(8,85) i01.rightArm.omoplate.map(0,180,8,85) ########STARTING SIDE NECK CONTROL######## leftneckServo = Runtime.start("leftNeck","Servo") rightneckServo = Runtime.start("rightNeck","Servo") right = Runtime.start("i01.right", "Arduino") #right.connect(rightPort) leftneckServo.attach(right, 13) rightneckServo.attach(right, 12) restPos = 90 delta = 20 neckMoveTo(restPos,delta) #############STARTING THE HEAD############## i01.head = Runtime.create("i01.head", "InMoovHead") #weaking defaults settings of head i01.head.jaw.setMinMax(35,75) i01.head.jaw.map(0,180,35,75) i01.head.jaw.setRest(35) #tweaking default settings of eyes i01.head.eyeY.setMinMax(0,180) i01.head.eyeY.map(0,180,70,110) i01.head.eyeY.setRest(90) i01.head.eyeX.setMinMax(0,180) i01.head.eyeX.map(0,180,70,110) i01.head.eyeX.setRest(90) i01.head.neck.setMinMax(40,142) i01.head.neck.map(0,180,40,142) i01.head.neck.setRest(70) i01.head.rothead.setMinMax(21,151) i01.head.rothead.map(0,180,21,151) i01.head.rothead.setRest(88) #########STARTING MOUTH CONTROL############### i01.startMouthControl(leftPort) i01.mouthControl.setmouth(0,180) ###################################################################### # mouth service, speech synthesis mouth = Runtime.createAndStart("i01.mouth", "AcapelaSpeech") mouth.setVoice(botVoice) ###################################################################### # helper function help debug the recognized text from webkit/sphinx ###################################################################### ###################################################################### # Create ProgramAB chat bot ( This is the inmoov "brain" ) ###################################################################### zorba2 = Runtime.createAndStart("zorba", "ProgramAB") zorba2.startSession("Pedro", "zorba") ###################################################################### # Html filter to clean the output from programab. (just in case) htmlfilter = Runtime.createAndStart("htmlfilter", "HtmlFilter") ###################################################################### # the "ear" of the inmoov TODO: replace this with just base inmoov ear? ear = Runtime.createAndStart("i01.ear", "WebkitSpeechRecognition") ear.addListener("publishText", python.name, "heard"); ear.addMouth(mouth) ###################################################################### # MRL Routing webkitspeechrecognition/ear -> program ab -> htmlfilter -> mouth ###################################################################### ear.addTextListener(zorba) zorba2.addTextListener(htmlfilter) htmlfilter.addTextListener(mouth) #starting the INMOOV i01 = Runtime.createAndStart("i01", "InMoov") i01.setMute(True) i01.mouth = mouth ###################################################################### # Launch the web gui and create the webkit speech recognition gui # This service works in Google Chrome only with the WebGui ################################################################# webgui = Runtime.createAndStart("webgui","WebGui") ###################################################################### # Helper functions and various gesture definitions ###################################################################### i01.loadGestures(gesturesPath) ear.startListening() ###################################################################### # starting services ###################################################################### i01.startRightHand(rightPort) i01.detach() leftneckServo.detach() rightneckServo.detach() i01.startHead(leftPort) i01.detach()
[ 6738, 20129, 13, 17204, 1330, 10903, 198, 11748, 4704, 278, 198, 11748, 4738, 198, 11748, 40481, 82, 198, 11748, 33245, 198, 11748, 340, 861, 10141, 198, 11748, 640, 198, 11748, 28686, 198, 11748, 2956, 297, 571, 17, 198, 11748, 2420, 3...
3.141827
1,664
import os import pytest import yaml from pocs.core import POCS from pocs.observatory import Observatory from pocs.utils import error
[ 11748, 28686, 198, 11748, 12972, 9288, 198, 11748, 331, 43695, 198, 198, 6738, 279, 420, 82, 13, 7295, 1330, 350, 4503, 50, 198, 6738, 279, 420, 82, 13, 672, 3168, 2870, 1330, 25758, 198, 6738, 279, 420, 82, 13, 26791, 1330, 4049, 6...
3.066667
45
#!/usr/bin/env python3 ############################################################## ## Jose F. Sanchez & Alba Moya ## ## Copyright (C) 2020-2021 ## ############################################################## ''' Created on 28 oct. 2020 @author: alba Modified in March 2021 @author: Jose F. Sanchez-Herrero ''' ## useful imports import sys import os import pandas as pd import numpy as np import HCGB from Bio import SeqIO, Seq from Bio.SeqRecord import SeqRecord from BCBio import GFF from BacDup.scripts.functions import columns_annot_table ################################################## def gff_parser_caller(gff_file, ref_file, output_path, debug): '''This function calls the actual gff parser It serves as the entry point either from a module or system call ''' ## set output paths prot_file = os.path.abspath( os.path.join(output_path, 'proteins.fa')) csv_file = os.path.abspath( os.path.join(output_path, 'annot_df.csv')) csv_length = os.path.abspath( os.path.join(output_path, 'length_df.csv')) list_out_files = [prot_file, csv_file, csv_length] try: with open (ref_file) as in_handle: ref_recs = SeqIO.to_dict(SeqIO.parse(in_handle, "fasta")) ## debug messages if (debug): debug_message('GenBank record', 'yellow') print (ref_recs) ## parse with open(prot_file, "w") as out_handle: SeqIO.write(protein_recs(gff_file, ref_recs, list_out_files, debug=debug), out_handle, "fasta") ## return information return (list_out_files) except: return (False) ############################################################ ################################################################# def main (gff_file, ref_file, output_folder, debug=False): #get name base, ext = os.path.splitext(gff_file) gff_file = os.path.abspath(gff_file) #create folder output_path = HCGB.functions.file_functions.create_folder(output_path) if (debug): print ("## DEBUG:") print ("base:" , base) print ("ext:" , ext) print () gff_parser_caller(gff_file, ref_file, output_path, debug) ################################################################################ if __name__ == "__main__": if len(sys.argv) != 4: print (__doc__) print ("## Usage gff_parser") print ("python %s gff_file ref_fasta_file output_folder\n" %sys.argv[0]) sys.exit() main(*sys.argv[1:], debug=True) #main(*sys.argv[1:]) # la variable debug no es obligatoria. tiene un "por defecto definido" # Se utiliza el "=" para indicar el default.
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 29113, 14468, 7804, 4242, 2235, 198, 2235, 5264, 376, 13, 21909, 1222, 978, 7012, 337, 23790, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220,...
2.362817
1,221
import sys from distutils.core import setup import os from glob import glob import zipfile import shutil sys.path.insert(0, os.path.join('resources','library_patches')) sys.path.insert(0, os.path.join('..','..','pupy')) import pp import additional_imports import Crypto all_dependencies=set([x.split('.')[0] for x,m in sys.modules.iteritems() if not '(built-in)' in str(m) and x != '__main__']) print "ALLDEPS: ", all_dependencies zf = zipfile.ZipFile(os.path.join('resources','library.zip'), mode='w', compression=zipfile.ZIP_DEFLATED) try: for dep in all_dependencies: mdep = __import__(dep) print "DEPENDENCY: ", dep, mdep if hasattr(mdep, '__path__'): print('adding package %s'%dep) path, root = os.path.split(mdep.__path__[0]) for root, dirs, files in os.walk(mdep.__path__[0]): for f in list(set([x.rsplit('.',1)[0] for x in files])): found=False for ext in ('.pyc', '.so', '.pyo', '.py'): if ext == '.py' and found: continue if os.path.exists(os.path.join(root,f+ext)): zipname = os.path.join(root[len(path)+1:], f.split('.', 1)[0] + ext) print('adding file : {}'.format(zipname)) zf.write(os.path.join(root, f+ext), zipname) found=True else: if '<memimport>' in mdep.__file__: continue _, ext = os.path.splitext(mdep.__file__) print('adding %s -> %s'%(mdep.__file__, dep+ext)) zf.write(mdep.__file__, dep+ext) finally: zf.close()
[ 11748, 25064, 198, 6738, 1233, 26791, 13, 7295, 1330, 9058, 198, 11748, 28686, 198, 6738, 15095, 1330, 15095, 198, 11748, 19974, 7753, 198, 11748, 4423, 346, 198, 198, 17597, 13, 6978, 13, 28463, 7, 15, 11, 28686, 13, 6978, 13, 22179, ...
1.92539
898
import os import platform import unittest from conans.model.ref import ConanFileReference from conans.test.utils.tools import NO_SETTINGS_PACKAGE_ID, TestClient
[ 11748, 28686, 198, 11748, 3859, 198, 11748, 555, 715, 395, 198, 198, 6738, 369, 504, 13, 19849, 13, 5420, 1330, 31634, 8979, 26687, 198, 6738, 369, 504, 13, 9288, 13, 26791, 13, 31391, 1330, 8005, 62, 28480, 51, 20754, 62, 47, 8120, ...
3.326531
49
#-*- coding: utf-8 -*- # import os # from optparse import OptionParser # from pymongo import MongoClient, bulk # import json # import collections # import sys from import_hedgehogs import * HOST = '45.55.48.43' PORT = 27017 DB = 'SEC_EDGAR' if __name__ == "__main__": print("[WARNING] STILL UNDER DEVELOPMENT") main()
[ 2, 12, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 1330, 28686, 198, 2, 422, 2172, 29572, 1330, 16018, 46677, 198, 2, 422, 279, 4948, 25162, 1330, 42591, 11792, 11, 11963, 198, 2, 1330, 33918, 198, 2, 1330, 17268, 19...
2.66129
124
import torch import math import time import struct import argparse import numpy as np from collections import OrderedDict if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-model', required=True, help="trained model prefix, also include dir, e.g. ../data/model-100") args = parser.parse_args() model_path = args.model checkpoint = torch.load(model_path, map_location='cpu') assert 'args' in checkpoint assert 'model' in checkpoint args = checkpoint['args'] model = checkpoint['model'] checkpoint_new = {} model_new = {} e = [0, 0, 0, 0, 0, 0] d = [0, 0, 0, 0, 0, 0] for name, w in model.items(): if "decoder" in name: if "self_attn.in_proj" in name: layer = eval(name.split(".")[2]) wq, wk, wv = w.chunk(3, dim=0) assert args.encoder_embed_dim == args.decoder_embed_dim model_new[name] = torch.cat([wq[(args.encoder_embed_dim // 8 * e[layer]): (args.encoder_embed_dim // 8 * (e[layer] + 1))], wk[(args.encoder_embed_dim // 8 * e[layer]): (args.encoder_embed_dim // 8 * (e[layer] + 1))], wv[(args.encoder_embed_dim // 8 * e[layer]): (args.encoder_embed_dim // 8 * (e[layer] + 1))]], dim=0) elif "encoder_attn.in_proj" in name: layer = eval(name.split(".")[2]) wq, wk, wv = w.chunk(3, dim=0) assert args.encoder_embed_dim == args.decoder_embed_dim model_new[name] = torch.cat([wq[(args.encoder_embed_dim // 8 * d[layer]): (args.encoder_embed_dim // 8 * (d[layer] + 1))], wk[(args.encoder_embed_dim // 8 * d[layer]): (args.encoder_embed_dim // 8 * (d[layer] + 1))], wv[(args.encoder_embed_dim // 8 * d[layer]): (args.encoder_embed_dim // 8 * (d[layer] + 1))]], dim=0) elif "self_attn.out_proj.weight" in name: layer = eval(name.split(".")[2]) assert args.encoder_embed_dim == args.decoder_embed_dim model_new[name] = w[:, (args.encoder_embed_dim // 8 * e[layer]): (args.encoder_embed_dim // 8 * (e[layer] + 1))] elif "encoder_attn.out_proj.weight" in name: layer = eval(name.split(".")[2]) assert args.encoder_embed_dim == args.decoder_embed_dim model_new[name] = w[:, (args.encoder_embed_dim // 8 * d[layer]): (args.encoder_embed_dim // 8 * (d[layer] + 1))] else: model_new[name] = w else: model_new[name] = w checkpoint_new['args'] = args checkpoint_new['args'].arch = "transformer_singlehead_t2t_wmt_en_de" checkpoint_new['model'] = model_new # print(checkpoint_new['args'].arch) torch.save(checkpoint_new, 'checkpoint_singlehead.pt') print("finished!")
[ 11748, 28034, 198, 11748, 10688, 198, 11748, 640, 198, 11748, 2878, 198, 11748, 1822, 29572, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, ...
2.00403
1,489
import typing as t from typing import TYPE_CHECKING import numpy as np import torch import pytest import imageio from detectron2 import model_zoo from detectron2.data import transforms as T from detectron2.config import get_cfg from detectron2.modeling import build_model import bentoml if TYPE_CHECKING: from detectron2.config import CfgNode from bentoml._internal.types import Tag from bentoml._internal.models import ModelStore IMAGE_URL: str = "./tests/utils/_static/detectron2_sample.jpg" def prepare_image( original_image: "np.ndarray[t.Any, np.dtype[t.Any]]", ) -> "np.ndarray[t.Any, np.dtype[t.Any]]": """Mainly to test on COCO dataset""" _aug = T.ResizeShortestEdge([800, 800], 1333) image = _aug.get_transform(original_image).apply_image(original_image) return image.transpose(2, 0, 1)
[ 11748, 19720, 355, 256, 198, 6738, 19720, 1330, 41876, 62, 50084, 2751, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 11748, 12972, 9288, 198, 11748, 2939, 952, 198, 6738, 4886, 1313, 17, 1330, 2746, 62, 89, 2238, 198...
2.838384
297
"""Role testing files using testinfra""" def test_config_directory(host): """Check config directory""" f = host.file("/etc/influxdb") assert f.is_directory assert f.user == "influxdb" assert f.group == "root" assert f.mode == 0o775 def test_data_directory(host): """Check data directory""" d = host.file("/var/lib/influxdb") assert d.is_directory assert d.user == "influxdb" assert d.group == "root" assert d.mode == 0o700 def test_backup_directory(host): """Check backup directory""" b = host.file("/var/backups/influxdb") assert b.is_directory assert b.user == "influxdb" assert b.group == "root" assert b.mode == 0o775 def test_influxdb_service(host): """Check InfluxDB service""" s = host.service("influxdb") assert s.is_running assert s.is_enabled def test_influxdb_docker_container(host): """Check InfluxDB docker container""" d = host.docker("influxdb.service").inspect() assert d["HostConfig"]["Memory"] == 1073741824 assert d["Config"]["Image"] == "influxdb:latest" assert d["Config"]["Labels"]["maintainer"] == "me@example.com" assert "INFLUXD_REPORTING_DISABLED=true" in d["Config"]["Env"] assert "internal" in d["NetworkSettings"]["Networks"] assert \ "influxdb" in d["NetworkSettings"]["Networks"]["internal"]["Aliases"] def test_backup(host): """Check if the backup runs successfully""" cmd = host.run("/usr/local/bin/backup-influxdb.sh") assert cmd.succeeded def test_backup_cron_job(host): """Check backup cron job""" f = host.file("/var/spool/cron/crontabs/root") assert "/usr/local/bin/backup-influxdb.sh" in f.content_string def test_restore(host): """Check if the restore runs successfully""" cmd = host.run("/usr/local/bin/restore-influxdb.sh") assert cmd.succeeded
[ 37811, 47445, 4856, 3696, 1262, 1332, 10745, 430, 37811, 628, 198, 4299, 1332, 62, 11250, 62, 34945, 7, 4774, 2599, 198, 220, 220, 220, 37227, 9787, 4566, 8619, 37811, 198, 220, 220, 220, 277, 796, 2583, 13, 7753, 7203, 14, 14784, 14,...
2.56456
728
#!/usr/bin/env python import cayenne.client, datetime, time, serial # import random #Delay Start #print "Time now = ", datetime.datetime.now().strftime("%H-%M-%S") #time.sleep(60) #print "Starting now = ", datetime.datetime.now().strftime("%H-%M-%S") # Cayenne authentication info. This should be obtained from the Cayenne Dashboard. MQTT_USERNAME = "6375a470-cff9-11e7-86d0-83752e057225" MQTT_PASSWORD = "26e1dc13f900da7b30b24cad4b320f9bc6dd0d78" MQTT_CLIENT_ID = "157d1d10-69dd-11e8-84d1-4d9372e87a68" # Other settings that seem to be embedded in Cayenne's libraries # MQTT_URL = "mqtt.mydevices.com" # MQTT_PORT = "1883" # Default location of serial port on Pi models 1 and 2 #SERIAL_PORT = "/dev/ttyAMA0" # Default location of serial port on Pi models 3 and Zero SERIAL_PORT = "/dev/ttyS0" # How often shall we write values to Cayenne? (Seconds + 1) interval = 5 #This sets up the serial port specified above. baud rate is the bits per second timeout seconds #port = serial.Serial(SERIAL_PORT, baudrate=2400, timeout=5) #This sets up the serial port specified above. baud rate. This WAITS for any cr/lf (new blob of data from picaxe) port = serial.Serial(SERIAL_PORT, baudrate=2400) # The callback for when a message is received from Cayenne. client = cayenne.client.CayenneMQTTClient() client.on_message = on_message client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID) #Predefine Data Packet objects for python prior to trying to look for them :) node = ":01" channel = "A" data = 123 cs = 0 while True: try: rcv = port.readline() #read buffer until cr/lf #print("Serial Readline Data = " + rcv) rcv = rcv.rstrip("\r\n") node,channel,data,cs = rcv.split(",") #Test Point print("rcv.split Data = : " + node + channel + data + cs) if cs == '0': #if cs = Check Sum is good = 0 then do the following if channel == 'A': data = float(data)/1 client.virtualWrite(1, data, "analog_sensor", "null") client.loop() if channel == 'B': data = float(data)/1 client.virtualWrite(2, data, "analog_sensor", "null") client.loop() if channel == 'C': data = float(data)/1 client.virtualWrite(3, data, "analog_sensor", "null") client.loop() if channel == 'D': data = float(data)/1 client.virtualWrite(4, data, "analog_sensor", "null") client.loop() if channel == 'E': data = float(data)/1 client.virtualWrite(5, data, "analog_sensor", "null") client.loop() if channel == 'F': data = float(data)/1 client.virtualWrite(6, data, "analog_sensor", "null") client.loop() if channel == 'G': data = float(data)/1 client.virtualWrite(7, data, "analog_sensor", "null") client.loop() if channel == 'H': data = float(data)/1 client.virtualWrite(8, data, "analog_sensor", "null") client.loop() if channel == 'I': data = float(data)/1 client.virtualWrite(9, data, "analog_sensor", "null") client.loop() if channel == 'J': data = float(data)/1 client.virtualWrite(10, data, "analog_sensor", "null") client.loop() if channel == 'K': data = float(data)/1 client.virtualWrite(11, data, "analog_sensor", "null") client.loop() if channel == 'L': data = float(data)/1 client.virtualWrite(12, data, "analog_sensor", "null") client.loop() except ValueError: #if Data Packet corrupt or malformed then... print("Data Packet corrupt or malformed")
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 269, 323, 29727, 13, 16366, 11, 4818, 8079, 11, 640, 11, 11389, 198, 2, 1330, 4738, 198, 198, 2, 13856, 323, 7253, 198, 2, 4798, 366, 7575, 783, 796, 33172, 4818, 8079, 13, ...
2.389398
1,528
import unittest from mox3.mox import MoxTestBase, IsA from slimta.queue.proxy import ProxyQueue from slimta.smtp.reply import Reply from slimta.relay import Relay, TransientRelayError, PermanentRelayError from slimta.envelope import Envelope # vim:et:fdm=marker:sts=4:sw=4:ts=4
[ 198, 11748, 555, 715, 395, 198, 6738, 285, 1140, 18, 13, 76, 1140, 1330, 337, 1140, 14402, 14881, 11, 1148, 32, 198, 198, 6738, 18862, 8326, 13, 36560, 13, 36436, 1330, 38027, 34991, 198, 6738, 18862, 8326, 13, 5796, 34788, 13, 47768,...
2.747573
103
import pytest from pypospack.potential import EamPotential symbols = ['Al'] func_pair_name = "bornmayer" func_density_name = "eam_dens_exp" func_embedding_name = "fs" expected_parameter_names_pair_potential = [] expected_parameter_names_density_function = [] expected_parameter_names_embedding_function = [] expected_parameter_names = [ 'p_AlAl_phi0', 'p_AlAl_gamma', 'p_AlAl_r0', 'd_Al_rho0', 'd_Al_beta', 'd_Al_r0', 'e_Al_F0', 'e_Al_p', 'e_Al_q', 'e_Al_F1', 'e_Al_rho0'] print(80*'-') print("func_pair_name={}".format(func_pair_name)) print("func_density_name={}".format(func_density_name)) print("func_embedding_name={}".format(func_density_name)) print(80*'-') if __name__ == "__main__": # CONSTRUCTOR TEST pot = EamPotential(symbols=symbols, func_pair=func_pair_name, func_density=func_density_name, func_embedding=func_embedding_name) print('pot.potential_type == {}'.format(\ pot.potential_type)) print('pot.symbols == {}'.format(\ pot.symbols)) print('pot.parameter_names == {}'.format(\ pot.parameter_names)) print('pot.is_charge == {}'.format(\ pot.is_charge))
[ 11748, 12972, 9288, 198, 6738, 12972, 1930, 8002, 13, 13059, 1843, 1330, 412, 321, 25396, 1843, 198, 198, 1837, 2022, 10220, 796, 37250, 2348, 20520, 198, 20786, 62, 24874, 62, 3672, 796, 366, 6286, 76, 2794, 1, 198, 20786, 62, 43337, ...
2.195652
552
from typing import Dict from main.helpers.print_helper import PrintHelper
[ 6738, 19720, 1330, 360, 713, 198, 198, 6738, 1388, 13, 16794, 364, 13, 4798, 62, 2978, 525, 1330, 12578, 47429, 628 ]
3.619048
21
import tkinter as tk import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from pandastable import Table import util.generic as utl
[ 11748, 256, 74, 3849, 355, 256, 74, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 2603, 29487, 8019, 13, 1891, 2412, 13, 1891, 437, 62, 30488, 9460, 1330, 11291, 6090, 11017, 51, 74, 46384, 198, 6738, 19798,...
2.20202
99
import coloredlogs coloredlogs.install() custom_logger = logging.getLogger(name) coloredlogs.install(level="INFO", logger=custom_logger)
[ 11748, 16396, 6404, 82, 198, 198, 25717, 6404, 82, 13, 17350, 3419, 198, 23144, 62, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 7, 3672, 8, 198, 25717, 6404, 82, 13, 17350, 7, 5715, 2625, 10778, 1600, 49706, 28, 23144, 62, 6404, ...
3.066667
45
import os import versioneer from setuptools import setup, find_packages with open("README.md", "r") as fh: long_description = fh.read() if os.getenv('DEB_BUILD') == 'true' or os.getenv('USER') == 'root': "/usr/share/doc/linuxcnc/examples/sample-configs/sim" # list of (destination, source_file) tuples DATA_FILES = [ ('/usr/lib/x86_64-linux-gnu/qt5/plugins/designer/', [ 'pyqt5designer/Qt5.7.1-64bit/libpyqt5_py2.so', 'pyqt5designer/Qt5.7.1-64bit/libpyqt5_py3.so']), ] # list of (destination, source_dir) tuples DATA_DIRS = [ ('/usr/share/doc/linuxcnc/examples/sample-configs/sim', 'linuxcnc/configs'), ] if os.getenv('USER') == 'root': try: os.rename('/usr/lib/x86_64-linux-gnu/qt5/plugins/designer/libpyqt5.so', '/usr/lib/x86_64-linux-gnu/qt5/plugins/designer/libpyqt5.so.old') except: pass else: # list of (destination, source_file) tuples DATA_FILES = [ ('~/', ['scripts/.xsessionrc',]), ] # list of (destination, source_dir) tuples DATA_DIRS = [ ('~/linuxcnc/configs/sim.qtpyvcp', 'linuxcnc/configs/sim.qtpyvcp'), ('~/linuxcnc/nc_files/qtpyvcp', 'linuxcnc/nc_files/qtpyvcp'), # ('~/linuxcnc/vcps', 'examples'), ] data_files = [(os.path.expanduser(dest), src_list) for dest, src_list in DATA_FILES] data_files.extend(data_files_from_dirs(DATA_DIRS)) setup( name="qtpyvcp", version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), author="Kurt Jacobson", author_email="kcjengr@gmail.com", description="Qt and Python based Virtual Control Panel framework for LinuxCNC.", long_description=long_description, long_description_content_type="text/markdown", license="GNU General Public License v2 (GPLv2)", url="https://github.com/kcjengr/qtpyvcp", download_url="https://github.com/kcjengr/qtpyvcp/archive/master.zip", classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: Manufacturing', 'Intended Audience :: End Users/Desktop', 'Topic :: Software Development :: Widget Sets', 'Topic :: Software Development :: User Interfaces', 'License :: OSI Approved :: GNU General Public License v2 (GPLv2)', 'Programming Language :: Python :: 2.7', ], packages=find_packages(), data_files=data_files, include_package_data=True, install_requires=[ 'docopt', 'qtpy', 'pyudev', 'psutil', 'HiYaPyCo', 'pyopengl', 'vtk', 'pyqtgraph', 'oyaml', 'simpleeval', ], entry_points={ 'console_scripts': [ 'qtpyvcp=qtpyvcp.app:main', 'qcompile=qtpyvcp.tools.qcompile:main', 'editvcp=qtpyvcp.tools.editvcp:main', # example VCPs 'mini=examples.mini:main', 'brender=examples.brender:main', # test VCPs 'vtk_test=video_tests.vtk_test:main', 'opengl_test=video_tests.opengl_test:main', 'qtpyvcp_test=video_tests.qtpyvcp_test:main', ], 'qtpyvcp.example_vcp': [ 'mini=examples.mini', 'brender=examples.brender', 'actions=examples.actions', ], 'qtpyvcp.test_vcp': [ 'vtk_test=video_tests.vtk_test', 'opengl_test=video_tests.opengl_test', 'qtpyvcp_test=video_tests.qtpyvcp_test', ], }, )
[ 11748, 28686, 198, 11748, 2196, 28153, 198, 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 198, 4480, 1280, 7203, 15675, 11682, 13, 9132, 1600, 366, 81, 4943, 355, 277, 71, 25, 198, 220, 220, 220, 890, 62, 11213, 796, ...
2.050828
1,751
from enum import Enum as _Enum
[ 6738, 33829, 1330, 2039, 388, 355, 4808, 4834, 388, 628, 628 ]
3.090909
11
from reportlab.lib.pagesizes import A4 from reportlab.lib.units import cm from reportlab.lib.styles import getSampleStyleSheet from reportlab.platypus import BaseDocTemplate, Frame, PageTemplate, Paragraph
[ 6738, 989, 23912, 13, 8019, 13, 31126, 4340, 1330, 317, 19, 198, 6738, 989, 23912, 13, 8019, 13, 41667, 1330, 12067, 198, 6738, 989, 23912, 13, 8019, 13, 47720, 1330, 651, 36674, 21466, 3347, 316, 198, 6738, 989, 23912, 13, 489, 265, ...
3.631579
57
from datetime import datetime import uuid from sqlalchemy.exc import IntegrityError from dataservice.api.study.models import Study from dataservice.api.participant.models import Participant from dataservice.api.outcome.models import Outcome from dataservice.extensions import db from tests.utils import FlaskTestCase
[ 6738, 4818, 8079, 1330, 4818, 8079, 198, 11748, 334, 27112, 198, 198, 6738, 44161, 282, 26599, 13, 41194, 1330, 39348, 12331, 198, 198, 6738, 19395, 712, 501, 13, 15042, 13, 44517, 13, 27530, 1330, 12481, 198, 6738, 19395, 712, 501, 13,...
3.809524
84
import logging from werkzeug.utils import cached_property from wtforms import FormField, Form, StringField logger = logging.getLogger(__name__)
[ 11748, 18931, 198, 198, 6738, 266, 9587, 2736, 1018, 13, 26791, 1330, 39986, 62, 26745, 198, 6738, 266, 83, 23914, 1330, 5178, 15878, 11, 5178, 11, 10903, 15878, 198, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 7, 834, 3672, 8...
3.288889
45
#AFTER PREPROCESSING AND TARGETS DEFINITION newdataset.describe() LET_IS.value_counts() LET_IS.value_counts().plot(kind='bar', color='c') Y_unica.value_counts() Y_unica.value_counts().plot(kind='bar', color='c') ZSN.value_counts().plot(kind='bar', color='c') Survive.value_counts().plot(kind='bar', color='c')
[ 2, 8579, 5781, 22814, 4805, 4503, 7597, 2751, 5357, 309, 46095, 50, 5550, 20032, 17941, 198, 3605, 19608, 292, 316, 13, 20147, 4892, 3419, 198, 28882, 62, 1797, 13, 8367, 62, 9127, 82, 3419, 198, 28882, 62, 1797, 13, 8367, 62, 9127, ...
2.48
125
"""Confusion matrix calculation service.""" # coding=utf-8 # import relation package. from pandas_profiling import ProfileReport import pandas as pd import datetime import json # import project package. from config.config_setting import ConfigSetting
[ 37811, 18546, 4241, 17593, 17952, 2139, 526, 15931, 198, 2, 19617, 28, 40477, 12, 23, 198, 2, 1330, 8695, 5301, 13, 198, 6738, 19798, 292, 62, 5577, 4386, 1330, 13118, 19100, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 4818, 807...
4.015873
63
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # 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. # from .encryption_config import ( EncryptionConfiguration, ) from .model import ( DeleteModelRequest, GetModelRequest, ListModelsRequest, ListModelsResponse, Model, PatchModelRequest, ) from .model_reference import ( ModelReference, ) from .standard_sql import ( StandardSqlDataType, StandardSqlField, StandardSqlStructType, StandardSqlTableType, ) from .table_reference import ( TableReference, ) __all__ = ( "EncryptionConfiguration", "DeleteModelRequest", "GetModelRequest", "ListModelsRequest", "ListModelsResponse", "Model", "PatchModelRequest", "ModelReference", "StandardSqlDataType", "StandardSqlField", "StandardSqlStructType", "StandardSqlTableType", "TableReference", )
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 33160, 3012, 11419, 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, 2...
3.057395
453
from abc import abstractmethod, ABC from datetime import datetime, timezone from typing import Any, List, Tuple, Dict from blurr.core.base import BaseSchema from blurr.core.store_key import Key, KeyType def get_time_range(self, identity, group, start_time, end_time) -> List[Tuple[Key, Any]]: raise NotImplementedError() def get_count_range(self, identity, group, time, count): raise NotImplementedError()
[ 6738, 450, 66, 1330, 12531, 24396, 11, 9738, 198, 6738, 4818, 8079, 1330, 4818, 8079, 11, 640, 11340, 198, 6738, 19720, 1330, 4377, 11, 7343, 11, 309, 29291, 11, 360, 713, 198, 198, 6738, 23671, 81, 13, 7295, 13, 8692, 1330, 7308, 2...
2.939189
148
import time, copy import asyncio temprefmanager = TempRefManager() coro = temprefmanager.loop() import asyncio task = asyncio.ensure_future(coro) import atexit atexit.register(lambda *args, **kwargs: task.cancel())
[ 11748, 640, 11, 4866, 198, 11748, 30351, 952, 198, 198, 11498, 3866, 35826, 3536, 796, 24189, 8134, 13511, 3419, 198, 198, 10215, 78, 796, 2169, 3866, 35826, 3536, 13, 26268, 3419, 198, 11748, 30351, 952, 198, 35943, 796, 30351, 952, 13...
2.945946
74
############################################################################### # Name: choicedlg.py # # Purpose: Generic Choice Dialog # # Author: Cody Precord <cprecord@editra.org> # # Copyright: (c) 2008 Cody Precord <staff@editra.org> # # License: wxWindows License # ############################################################################### """ Editra Control Library: Choice Dialog A generic choice dialog that uses a wx.Choice control to display its choices. @summary: Generic Choice Dialog """ __author__ = "Cody Precord <cprecord@editra.org>" __svnid__ = "$Id: choicedlg.py 63820 2010-04-01 21:46:22Z CJP $" __revision__ = "$Revision: 63820 $" __all__ = ['ChoiceDialog',] #--------------------------------------------------------------------------# # Imports import wx #--------------------------------------------------------------------------# # Globals ChoiceDialogNameStr = u"ChoiceDialog" #--------------------------------------------------------------------------# #--------------------------------------------------------------------------# #--------------------------------------------------------------------------#
[ 29113, 29113, 7804, 4242, 21017, 198, 2, 6530, 25, 1727, 3711, 75, 70, 13, 9078, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 22...
2.916309
466
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: flower/proto/transport.proto from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name='flower/proto/transport.proto', package='flower.transport', syntax='proto3', serialized_options=None, serialized_pb=b'\n\x1c\x66lower/proto/transport.proto\x12\x10\x66lower.transport\"2\n\nParameters\x12\x0f\n\x07tensors\x18\x01 \x03(\x0c\x12\x13\n\x0btensor_type\x18\x02 \x01(\t\"\xb8\x05\n\rServerMessage\x12>\n\treconnect\x18\x01 \x01(\x0b\x32).flower.transport.ServerMessage.ReconnectH\x00\x12G\n\x0eget_parameters\x18\x02 \x01(\x0b\x32-.flower.transport.ServerMessage.GetParametersH\x00\x12\x39\n\x07\x66it_ins\x18\x03 \x01(\x0b\x32&.flower.transport.ServerMessage.FitInsH\x00\x12\x43\n\x0c\x65valuate_ins\x18\x04 \x01(\x0b\x32+.flower.transport.ServerMessage.EvaluateInsH\x00\x1a\x1c\n\tReconnect\x12\x0f\n\x07seconds\x18\x01 \x01(\x03\x1a\x0f\n\rGetParameters\x1a\xad\x01\n\x06\x46itIns\x12\x30\n\nparameters\x18\x01 \x01(\x0b\x32\x1c.flower.transport.Parameters\x12\x42\n\x06\x63onfig\x18\x02 \x03(\x0b\x32\x32.flower.transport.ServerMessage.FitIns.ConfigEntry\x1a-\n\x0b\x43onfigEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1a\xb7\x01\n\x0b\x45valuateIns\x12\x30\n\nparameters\x18\x01 \x01(\x0b\x32\x1c.flower.transport.Parameters\x12G\n\x06\x63onfig\x18\x02 \x03(\x0b\x32\x37.flower.transport.ServerMessage.EvaluateIns.ConfigEntry\x1a-\n\x0b\x43onfigEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x42\x05\n\x03msg\"\xbc\x04\n\rClientMessage\x12@\n\ndisconnect\x18\x01 \x01(\x0b\x32*.flower.transport.ClientMessage.DisconnectH\x00\x12G\n\x0eparameters_res\x18\x02 \x01(\x0b\x32-.flower.transport.ClientMessage.ParametersResH\x00\x12\x39\n\x07\x66it_res\x18\x03 \x01(\x0b\x32&.flower.transport.ClientMessage.FitResH\x00\x12\x43\n\x0c\x65valuate_res\x18\x04 \x01(\x0b\x32+.flower.transport.ClientMessage.EvaluateResH\x00\x1a\x36\n\nDisconnect\x12(\n\x06reason\x18\x01 \x01(\x0e\x32\x18.flower.transport.Reason\x1a\x41\n\rParametersRes\x12\x30\n\nparameters\x18\x01 \x01(\x0b\x32\x1c.flower.transport.Parameters\x1ak\n\x06\x46itRes\x12\x30\n\nparameters\x18\x01 \x01(\x0b\x32\x1c.flower.transport.Parameters\x12\x14\n\x0cnum_examples\x18\x02 \x01(\x03\x12\x19\n\x11num_examples_ceil\x18\x03 \x01(\x03\x1a\x31\n\x0b\x45valuateRes\x12\x14\n\x0cnum_examples\x18\x01 \x01(\x03\x12\x0c\n\x04loss\x18\x02 \x01(\x02\x42\x05\n\x03msg*R\n\x06Reason\x12\x0b\n\x07UNKNOWN\x10\x00\x12\r\n\tRECONNECT\x10\x01\x12\x16\n\x12POWER_DISCONNECTED\x10\x02\x12\x14\n\x10WIFI_UNAVAILABLE\x10\x03\x32_\n\rFlowerService\x12N\n\x04Join\x12\x1f.flower.transport.ClientMessage\x1a\x1f.flower.transport.ServerMessage\"\x00(\x01\x30\x01\x62\x06proto3' ) _REASON = _descriptor.EnumDescriptor( name='Reason', full_name='flower.transport.Reason', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='UNKNOWN', index=0, number=0, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='RECONNECT', index=1, number=1, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='POWER_DISCONNECTED', index=2, number=2, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='WIFI_UNAVAILABLE', index=3, number=3, serialized_options=None, type=None), ], containing_type=None, serialized_options=None, serialized_start=1376, serialized_end=1458, ) _sym_db.RegisterEnumDescriptor(_REASON) Reason = enum_type_wrapper.EnumTypeWrapper(_REASON) UNKNOWN = 0 RECONNECT = 1 POWER_DISCONNECTED = 2 WIFI_UNAVAILABLE = 3 _PARAMETERS = _descriptor.Descriptor( name='Parameters', full_name='flower.transport.Parameters', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='tensors', full_name='flower.transport.Parameters.tensors', index=0, number=1, type=12, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='tensor_type', full_name='flower.transport.Parameters.tensor_type', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=50, serialized_end=100, ) _SERVERMESSAGE_RECONNECT = _descriptor.Descriptor( name='Reconnect', full_name='flower.transport.ServerMessage.Reconnect', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='seconds', full_name='flower.transport.ServerMessage.Reconnect.seconds', index=0, number=1, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=385, serialized_end=413, ) _SERVERMESSAGE_GETPARAMETERS = _descriptor.Descriptor( name='GetParameters', full_name='flower.transport.ServerMessage.GetParameters', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=415, serialized_end=430, ) _SERVERMESSAGE_FITINS_CONFIGENTRY = _descriptor.Descriptor( name='ConfigEntry', full_name='flower.transport.ServerMessage.FitIns.ConfigEntry', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='key', full_name='flower.transport.ServerMessage.FitIns.ConfigEntry.key', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='value', full_name='flower.transport.ServerMessage.FitIns.ConfigEntry.value', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=b'8\001', is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=561, serialized_end=606, ) _SERVERMESSAGE_FITINS = _descriptor.Descriptor( name='FitIns', full_name='flower.transport.ServerMessage.FitIns', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='parameters', full_name='flower.transport.ServerMessage.FitIns.parameters', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='config', full_name='flower.transport.ServerMessage.FitIns.config', index=1, number=2, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[_SERVERMESSAGE_FITINS_CONFIGENTRY, ], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=433, serialized_end=606, ) _SERVERMESSAGE_EVALUATEINS_CONFIGENTRY = _descriptor.Descriptor( name='ConfigEntry', full_name='flower.transport.ServerMessage.EvaluateIns.ConfigEntry', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='key', full_name='flower.transport.ServerMessage.EvaluateIns.ConfigEntry.key', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='value', full_name='flower.transport.ServerMessage.EvaluateIns.ConfigEntry.value', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=b'8\001', is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=561, serialized_end=606, ) _SERVERMESSAGE_EVALUATEINS = _descriptor.Descriptor( name='EvaluateIns', full_name='flower.transport.ServerMessage.EvaluateIns', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='parameters', full_name='flower.transport.ServerMessage.EvaluateIns.parameters', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='config', full_name='flower.transport.ServerMessage.EvaluateIns.config', index=1, number=2, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[_SERVERMESSAGE_EVALUATEINS_CONFIGENTRY, ], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=609, serialized_end=792, ) _SERVERMESSAGE = _descriptor.Descriptor( name='ServerMessage', full_name='flower.transport.ServerMessage', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='reconnect', full_name='flower.transport.ServerMessage.reconnect', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='get_parameters', full_name='flower.transport.ServerMessage.get_parameters', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='fit_ins', full_name='flower.transport.ServerMessage.fit_ins', index=2, number=3, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='evaluate_ins', full_name='flower.transport.ServerMessage.evaluate_ins', index=3, number=4, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[_SERVERMESSAGE_RECONNECT, _SERVERMESSAGE_GETPARAMETERS, _SERVERMESSAGE_FITINS, _SERVERMESSAGE_EVALUATEINS, ], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ _descriptor.OneofDescriptor( name='msg', full_name='flower.transport.ServerMessage.msg', index=0, containing_type=None, fields=[]), ], serialized_start=103, serialized_end=799, ) _CLIENTMESSAGE_DISCONNECT = _descriptor.Descriptor( name='Disconnect', full_name='flower.transport.ClientMessage.Disconnect', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='reason', full_name='flower.transport.ClientMessage.Disconnect.reason', index=0, number=1, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1086, serialized_end=1140, ) _CLIENTMESSAGE_PARAMETERSRES = _descriptor.Descriptor( name='ParametersRes', full_name='flower.transport.ClientMessage.ParametersRes', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='parameters', full_name='flower.transport.ClientMessage.ParametersRes.parameters', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1142, serialized_end=1207, ) _CLIENTMESSAGE_FITRES = _descriptor.Descriptor( name='FitRes', full_name='flower.transport.ClientMessage.FitRes', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='parameters', full_name='flower.transport.ClientMessage.FitRes.parameters', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='num_examples', full_name='flower.transport.ClientMessage.FitRes.num_examples', index=1, number=2, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='num_examples_ceil', full_name='flower.transport.ClientMessage.FitRes.num_examples_ceil', index=2, number=3, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1209, serialized_end=1316, ) _CLIENTMESSAGE_EVALUATERES = _descriptor.Descriptor( name='EvaluateRes', full_name='flower.transport.ClientMessage.EvaluateRes', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='num_examples', full_name='flower.transport.ClientMessage.EvaluateRes.num_examples', index=0, number=1, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='loss', full_name='flower.transport.ClientMessage.EvaluateRes.loss', index=1, number=2, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1318, serialized_end=1367, ) _CLIENTMESSAGE = _descriptor.Descriptor( name='ClientMessage', full_name='flower.transport.ClientMessage', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='disconnect', full_name='flower.transport.ClientMessage.disconnect', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='parameters_res', full_name='flower.transport.ClientMessage.parameters_res', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='fit_res', full_name='flower.transport.ClientMessage.fit_res', index=2, number=3, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='evaluate_res', full_name='flower.transport.ClientMessage.evaluate_res', index=3, number=4, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[_CLIENTMESSAGE_DISCONNECT, _CLIENTMESSAGE_PARAMETERSRES, _CLIENTMESSAGE_FITRES, _CLIENTMESSAGE_EVALUATERES, ], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ _descriptor.OneofDescriptor( name='msg', full_name='flower.transport.ClientMessage.msg', index=0, containing_type=None, fields=[]), ], serialized_start=802, serialized_end=1374, ) _SERVERMESSAGE_RECONNECT.containing_type = _SERVERMESSAGE _SERVERMESSAGE_GETPARAMETERS.containing_type = _SERVERMESSAGE _SERVERMESSAGE_FITINS_CONFIGENTRY.containing_type = _SERVERMESSAGE_FITINS _SERVERMESSAGE_FITINS.fields_by_name['parameters'].message_type = _PARAMETERS _SERVERMESSAGE_FITINS.fields_by_name['config'].message_type = _SERVERMESSAGE_FITINS_CONFIGENTRY _SERVERMESSAGE_FITINS.containing_type = _SERVERMESSAGE _SERVERMESSAGE_EVALUATEINS_CONFIGENTRY.containing_type = _SERVERMESSAGE_EVALUATEINS _SERVERMESSAGE_EVALUATEINS.fields_by_name['parameters'].message_type = _PARAMETERS _SERVERMESSAGE_EVALUATEINS.fields_by_name['config'].message_type = _SERVERMESSAGE_EVALUATEINS_CONFIGENTRY _SERVERMESSAGE_EVALUATEINS.containing_type = _SERVERMESSAGE _SERVERMESSAGE.fields_by_name['reconnect'].message_type = _SERVERMESSAGE_RECONNECT _SERVERMESSAGE.fields_by_name['get_parameters'].message_type = _SERVERMESSAGE_GETPARAMETERS _SERVERMESSAGE.fields_by_name['fit_ins'].message_type = _SERVERMESSAGE_FITINS _SERVERMESSAGE.fields_by_name['evaluate_ins'].message_type = _SERVERMESSAGE_EVALUATEINS _SERVERMESSAGE.oneofs_by_name['msg'].fields.append( _SERVERMESSAGE.fields_by_name['reconnect']) _SERVERMESSAGE.fields_by_name['reconnect'].containing_oneof = _SERVERMESSAGE.oneofs_by_name['msg'] _SERVERMESSAGE.oneofs_by_name['msg'].fields.append( _SERVERMESSAGE.fields_by_name['get_parameters']) _SERVERMESSAGE.fields_by_name['get_parameters'].containing_oneof = _SERVERMESSAGE.oneofs_by_name['msg'] _SERVERMESSAGE.oneofs_by_name['msg'].fields.append( _SERVERMESSAGE.fields_by_name['fit_ins']) _SERVERMESSAGE.fields_by_name['fit_ins'].containing_oneof = _SERVERMESSAGE.oneofs_by_name['msg'] _SERVERMESSAGE.oneofs_by_name['msg'].fields.append( _SERVERMESSAGE.fields_by_name['evaluate_ins']) _SERVERMESSAGE.fields_by_name['evaluate_ins'].containing_oneof = _SERVERMESSAGE.oneofs_by_name['msg'] _CLIENTMESSAGE_DISCONNECT.fields_by_name['reason'].enum_type = _REASON _CLIENTMESSAGE_DISCONNECT.containing_type = _CLIENTMESSAGE _CLIENTMESSAGE_PARAMETERSRES.fields_by_name['parameters'].message_type = _PARAMETERS _CLIENTMESSAGE_PARAMETERSRES.containing_type = _CLIENTMESSAGE _CLIENTMESSAGE_FITRES.fields_by_name['parameters'].message_type = _PARAMETERS _CLIENTMESSAGE_FITRES.containing_type = _CLIENTMESSAGE _CLIENTMESSAGE_EVALUATERES.containing_type = _CLIENTMESSAGE _CLIENTMESSAGE.fields_by_name['disconnect'].message_type = _CLIENTMESSAGE_DISCONNECT _CLIENTMESSAGE.fields_by_name['parameters_res'].message_type = _CLIENTMESSAGE_PARAMETERSRES _CLIENTMESSAGE.fields_by_name['fit_res'].message_type = _CLIENTMESSAGE_FITRES _CLIENTMESSAGE.fields_by_name['evaluate_res'].message_type = _CLIENTMESSAGE_EVALUATERES _CLIENTMESSAGE.oneofs_by_name['msg'].fields.append( _CLIENTMESSAGE.fields_by_name['disconnect']) _CLIENTMESSAGE.fields_by_name['disconnect'].containing_oneof = _CLIENTMESSAGE.oneofs_by_name['msg'] _CLIENTMESSAGE.oneofs_by_name['msg'].fields.append( _CLIENTMESSAGE.fields_by_name['parameters_res']) _CLIENTMESSAGE.fields_by_name['parameters_res'].containing_oneof = _CLIENTMESSAGE.oneofs_by_name['msg'] _CLIENTMESSAGE.oneofs_by_name['msg'].fields.append( _CLIENTMESSAGE.fields_by_name['fit_res']) _CLIENTMESSAGE.fields_by_name['fit_res'].containing_oneof = _CLIENTMESSAGE.oneofs_by_name['msg'] _CLIENTMESSAGE.oneofs_by_name['msg'].fields.append( _CLIENTMESSAGE.fields_by_name['evaluate_res']) _CLIENTMESSAGE.fields_by_name['evaluate_res'].containing_oneof = _CLIENTMESSAGE.oneofs_by_name['msg'] DESCRIPTOR.message_types_by_name['Parameters'] = _PARAMETERS DESCRIPTOR.message_types_by_name['ServerMessage'] = _SERVERMESSAGE DESCRIPTOR.message_types_by_name['ClientMessage'] = _CLIENTMESSAGE DESCRIPTOR.enum_types_by_name['Reason'] = _REASON _sym_db.RegisterFileDescriptor(DESCRIPTOR) Parameters = _reflection.GeneratedProtocolMessageType('Parameters', (_message.Message,), { 'DESCRIPTOR' : _PARAMETERS, '__module__' : 'flower.proto.transport_pb2' # @@protoc_insertion_point(class_scope:flower.transport.Parameters) }) _sym_db.RegisterMessage(Parameters) ServerMessage = _reflection.GeneratedProtocolMessageType('ServerMessage', (_message.Message,), { 'Reconnect' : _reflection.GeneratedProtocolMessageType('Reconnect', (_message.Message,), { 'DESCRIPTOR' : _SERVERMESSAGE_RECONNECT, '__module__' : 'flower.proto.transport_pb2' # @@protoc_insertion_point(class_scope:flower.transport.ServerMessage.Reconnect) }) , 'GetParameters' : _reflection.GeneratedProtocolMessageType('GetParameters', (_message.Message,), { 'DESCRIPTOR' : _SERVERMESSAGE_GETPARAMETERS, '__module__' : 'flower.proto.transport_pb2' # @@protoc_insertion_point(class_scope:flower.transport.ServerMessage.GetParameters) }) , 'FitIns' : _reflection.GeneratedProtocolMessageType('FitIns', (_message.Message,), { 'ConfigEntry' : _reflection.GeneratedProtocolMessageType('ConfigEntry', (_message.Message,), { 'DESCRIPTOR' : _SERVERMESSAGE_FITINS_CONFIGENTRY, '__module__' : 'flower.proto.transport_pb2' # @@protoc_insertion_point(class_scope:flower.transport.ServerMessage.FitIns.ConfigEntry) }) , 'DESCRIPTOR' : _SERVERMESSAGE_FITINS, '__module__' : 'flower.proto.transport_pb2' # @@protoc_insertion_point(class_scope:flower.transport.ServerMessage.FitIns) }) , 'EvaluateIns' : _reflection.GeneratedProtocolMessageType('EvaluateIns', (_message.Message,), { 'ConfigEntry' : _reflection.GeneratedProtocolMessageType('ConfigEntry', (_message.Message,), { 'DESCRIPTOR' : _SERVERMESSAGE_EVALUATEINS_CONFIGENTRY, '__module__' : 'flower.proto.transport_pb2' # @@protoc_insertion_point(class_scope:flower.transport.ServerMessage.EvaluateIns.ConfigEntry) }) , 'DESCRIPTOR' : _SERVERMESSAGE_EVALUATEINS, '__module__' : 'flower.proto.transport_pb2' # @@protoc_insertion_point(class_scope:flower.transport.ServerMessage.EvaluateIns) }) , 'DESCRIPTOR' : _SERVERMESSAGE, '__module__' : 'flower.proto.transport_pb2' # @@protoc_insertion_point(class_scope:flower.transport.ServerMessage) }) _sym_db.RegisterMessage(ServerMessage) _sym_db.RegisterMessage(ServerMessage.Reconnect) _sym_db.RegisterMessage(ServerMessage.GetParameters) _sym_db.RegisterMessage(ServerMessage.FitIns) _sym_db.RegisterMessage(ServerMessage.FitIns.ConfigEntry) _sym_db.RegisterMessage(ServerMessage.EvaluateIns) _sym_db.RegisterMessage(ServerMessage.EvaluateIns.ConfigEntry) ClientMessage = _reflection.GeneratedProtocolMessageType('ClientMessage', (_message.Message,), { 'Disconnect' : _reflection.GeneratedProtocolMessageType('Disconnect', (_message.Message,), { 'DESCRIPTOR' : _CLIENTMESSAGE_DISCONNECT, '__module__' : 'flower.proto.transport_pb2' # @@protoc_insertion_point(class_scope:flower.transport.ClientMessage.Disconnect) }) , 'ParametersRes' : _reflection.GeneratedProtocolMessageType('ParametersRes', (_message.Message,), { 'DESCRIPTOR' : _CLIENTMESSAGE_PARAMETERSRES, '__module__' : 'flower.proto.transport_pb2' # @@protoc_insertion_point(class_scope:flower.transport.ClientMessage.ParametersRes) }) , 'FitRes' : _reflection.GeneratedProtocolMessageType('FitRes', (_message.Message,), { 'DESCRIPTOR' : _CLIENTMESSAGE_FITRES, '__module__' : 'flower.proto.transport_pb2' # @@protoc_insertion_point(class_scope:flower.transport.ClientMessage.FitRes) }) , 'EvaluateRes' : _reflection.GeneratedProtocolMessageType('EvaluateRes', (_message.Message,), { 'DESCRIPTOR' : _CLIENTMESSAGE_EVALUATERES, '__module__' : 'flower.proto.transport_pb2' # @@protoc_insertion_point(class_scope:flower.transport.ClientMessage.EvaluateRes) }) , 'DESCRIPTOR' : _CLIENTMESSAGE, '__module__' : 'flower.proto.transport_pb2' # @@protoc_insertion_point(class_scope:flower.transport.ClientMessage) }) _sym_db.RegisterMessage(ClientMessage) _sym_db.RegisterMessage(ClientMessage.Disconnect) _sym_db.RegisterMessage(ClientMessage.ParametersRes) _sym_db.RegisterMessage(ClientMessage.FitRes) _sym_db.RegisterMessage(ClientMessage.EvaluateRes) _SERVERMESSAGE_FITINS_CONFIGENTRY._options = None _SERVERMESSAGE_EVALUATEINS_CONFIGENTRY._options = None _FLOWERSERVICE = _descriptor.ServiceDescriptor( name='FlowerService', full_name='flower.transport.FlowerService', file=DESCRIPTOR, index=0, serialized_options=None, serialized_start=1460, serialized_end=1555, methods=[ _descriptor.MethodDescriptor( name='Join', full_name='flower.transport.FlowerService.Join', index=0, containing_service=None, input_type=_CLIENTMESSAGE, output_type=_SERVERMESSAGE, serialized_options=None, ), ]) _sym_db.RegisterServiceDescriptor(_FLOWERSERVICE) DESCRIPTOR.services_by_name['FlowerService'] = _FLOWERSERVICE # @@protoc_insertion_point(module_scope)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 262, 8435, 11876, 17050, 13, 220, 8410, 5626, 48483, 0, 198, 2, 2723, 25, 15061, 14, 1676, 1462, 14, 7645, 634, 13, 1676, 1462, 198, 198, 6738, 23...
2.421526
12,004
version_info = (4, 0, 1) __version__ = ".".join([str(v) for v in version_info])
[ 9641, 62, 10951, 796, 357, 19, 11, 657, 11, 352, 8, 198, 834, 9641, 834, 796, 366, 526, 13, 22179, 26933, 2536, 7, 85, 8, 329, 410, 287, 2196, 62, 10951, 12962, 198 ]
2.424242
33
from random import randint import pandas as pd # Class to calculate the check digit for 11 digit UPC's if __name__ == '__main__': test_upc = random_11_digit_upc() obj = CheckDigitCalculations() print(obj.get_full_upc(test_upc))
[ 6738, 4738, 1330, 43720, 600, 198, 11748, 19798, 292, 355, 279, 67, 628, 198, 2, 5016, 284, 15284, 262, 2198, 16839, 329, 1367, 16839, 471, 5662, 338, 628, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, ...
2.673913
92
import yaml import forest from forest import main def test_build_loader_given_files(): """replicate main.py as close as possible""" files = ["file_20190101T0000Z.nc"] args = main.parse_args.parse_args(files) config = forest.config.from_files(args.files, args.file_type) group = config.file_groups[0] loader = forest.Loader.group_args(group, args) assert isinstance(loader, forest.data.DBLoader) assert loader.locator.paths == files def test_build_loader_given_database(tmpdir): """replicate main.py as close as possible""" database_file = str(tmpdir / "database.db") config_file = str(tmpdir / "config.yml") settings = { "files": [ { "label": "UM", "pattern": "*.nc", "locator": "database" } ] } with open(config_file, "w") as stream: yaml.dump(settings, stream) args = main.parse_args.parse_args([ "--database", database_file, "--config-file", config_file]) config = forest.config.load_config(args.config_file) group = config.file_groups[0] database = forest.db.Database.connect(database_file) loader = forest.Loader.group_args(group, args, database=database) database.close() assert hasattr(loader.locator, "connection") assert loader.locator.directory is None
[ 11748, 331, 43695, 198, 11748, 8222, 198, 6738, 8222, 1330, 1388, 628, 198, 198, 4299, 1332, 62, 11249, 62, 29356, 62, 35569, 62, 16624, 33529, 198, 220, 220, 220, 37227, 35666, 5344, 1388, 13, 9078, 355, 1969, 355, 1744, 37811, 198, ...
2.466192
562
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from swagger_server.models.base_model_ import Model from swagger_server import util
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 4818, 8079, 1330, 3128, 11, 4818, 8079, 220, 1303, 645, 20402, 25, 376, 21844, 198, 198, 6738, 19720, 1330, 7343, 11, 360, 713, 220...
3.202703
74
import os import re import numpy as np # WARNING: this function overrides the mazes in sparse directory; don't run it # as the idea is that everyone test the same mazes def gen_sparses(dir_path): ''' Randomly remove points from dense instances ''' pattern = re.compile('^([0-9]+[a-zA-Z]+)') denses_fn = [x for x in os.listdir(dir_path + '/dense') if pattern.match(x)] print(denses_fn) for dense_fn in denses_fn: sparse = np.genfromtxt(dir_path + '/dense/' + dense_fn, dtype='str', delimiter=1) for r in range(0, len(sparse)): for c in range(0, len(sparse[0])): if sparse[r][c] == '.': sparse[r][c] = ' ' if bool(np.random.choice(np.arange(0,2), p=[0.25,0.75])) else '.' np.savetxt(dir_path + '/sparse/' + dense_fn, sparse, fmt='%s', delimiter='') gen_sparses('.')
[ 11748, 28686, 198, 11748, 302, 198, 11748, 299, 32152, 355, 45941, 198, 198, 2, 39410, 25, 428, 2163, 23170, 1460, 262, 285, 36096, 287, 29877, 8619, 26, 836, 470, 1057, 340, 198, 2, 355, 262, 2126, 318, 326, 2506, 1332, 262, 976, 2...
2.232558
387
""" Analyze JJ IV curve array (core) v.2 BB, 2016 """ import numpy as np from . import jjiv2 as jjiv import sys def fit2rsj_arr(iarr, varr, **kwargs): """Fit IV array to 2 Ic RSJ model and return arrays of fit params, error. Keyword arguments: guess: array of (Ic+, Ic-, Rn, Vo) io: fixed Io. updateguess: guess update ratio 0 to 1 """ if 'guess' in kwargs: kwargs['guess'] = np.array(kwargs['guess']) # array type update = kwargs.get('updateguess', 0.95) n = len(iarr) npopt = 4 popt_arr, pcov_arr = np.zeros((n, npopt)), np.zeros((n, npopt, npopt)) for k in range(n): try: done = False; l = 0 while not done: # fit popt, pcov = jjiv.fit2rsj(iarr[k], varr[k], **kwargs) # update guess if k == 0: kwargs['guess'] = popt else: kwargs['guess'] = (1-update)*kwargs['guess'] + update*popt # check if fit is good l += 1 if np.shape(pcov)==(4,4): perr = np.sqrt(np.diag(pcov)) else: perr = (np.inf, np.inf, np.inf, np.inf) if (np.amax(perr) < .05) or (l > 5): done = True popt_arr[k], pcov_arr[k] = popt, pcov else: print('Fit not good. Index: {}, Trial: {}'.format(k,l)) except RuntimeError: print('Can\'t fit. Index: {}!'.format(k)) return popt_arr, pcov_arr
[ 37811, 198, 37702, 2736, 38775, 8363, 12133, 7177, 357, 7295, 8, 410, 13, 17, 198, 198, 15199, 11, 1584, 198, 37811, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 764, 1330, 474, 73, 452, 17, 355, 474, 73, 452, 198, 11748, 250...
1.784753
892
from leetcode_tester import Tester from typing import Optional, List if __name__ == '__main__': solution = Solution() test = Tester(solution.maxProfit) test.addTest( [7, 1, 5, 3, 6, 4], 7 ) test.addTest( [1, 2, 3, 4, 5], 4 ) test.addTest( [7, 6, 4, 3, 1], 0 ) test.doTest()
[ 6738, 443, 316, 8189, 62, 4879, 353, 1330, 309, 7834, 198, 198, 6738, 19720, 1330, 32233, 11, 7343, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 4610, 796, 28186, 3419, 198, 220, 220, ...
2.005917
169
import torch import json import os from torch.utils.data import DataLoader,Dataset import torchvision.transforms as transforms from PIL import Image import numpy as np data_folder = "./dataset/images" press_times = json.load(open("./dataset/dataset.json")) image_roots = [os.path.join(data_folder,image_file) \ for image_file in os.listdir(data_folder)]
[ 11748, 28034, 198, 11748, 33918, 198, 11748, 28686, 198, 6738, 28034, 13, 26791, 13, 7890, 1330, 6060, 17401, 11, 27354, 292, 316, 198, 11748, 28034, 10178, 13, 7645, 23914, 355, 31408, 198, 6738, 350, 4146, 1330, 7412, 198, 11748, 299, ...
2.798507
134
import json from grafana_backup.dashboardApi import create_snapshot
[ 11748, 33918, 198, 6738, 7933, 69, 2271, 62, 1891, 929, 13, 42460, 3526, 32, 14415, 1330, 2251, 62, 45380, 9442, 628 ]
3.285714
21
""" Test case for Keras """ from perceptron.zoo.ssd_300.keras_ssd300 import SSD300 from perceptron.models.detection.keras_ssd300 import KerasSSD300Model from perceptron.utils.image import load_image from perceptron.benchmarks.brightness import BrightnessMetric from perceptron.utils.criteria.detection import TargetClassMiss from perceptron.utils.tools import bcolors from perceptron.utils.tools import plot_image_objectdetection # instantiate the model from keras applications ssd300 = SSD300() # initialize the KerasResNet50RetinaNetModel kmodel = KerasSSD300Model(ssd300, bounds=(0, 255)) # get source image and label # the model expects values in [0, 1], and channles_last image = load_image(shape=(300, 300), bounds=(0, 255), fname='car.png') metric = BrightnessMetric(kmodel, criterion=TargetClassMiss(7)) print(bcolors.BOLD + 'Process start' + bcolors.ENDC) adversary = metric(image, unpack=False) print(bcolors.BOLD + 'Process finished' + bcolors.ENDC) if adversary.image is None: print(bcolors.WARNING + 'Warning: Cannot find an adversary!' + bcolors.ENDC) exit(-1) ################### print summary info ##################################### keywords = ['Keras', 'SSD300', 'TargetClassMiss', 'BrightnessMetric'] print(bcolors.HEADER + bcolors.UNDERLINE + 'Summary:' + bcolors.ENDC) print('Configuration:' + bcolors.CYAN + ' --framework %s ' '--model %s --criterion %s ' '--metric %s' % tuple(keywords) + bcolors.ENDC) print('Minimum perturbation required: %s' % bcolors.BLUE + str(adversary.distance) + bcolors.ENDC) print('\n') # print the original image and the adversary plot_image_objectdetection(adversary, kmodel, bounds=(0, 255), title=", ".join(keywords), figname='examples/images/%s.png' % '_'.join(keywords))
[ 37811, 6208, 1339, 329, 17337, 292, 37227, 201, 198, 201, 198, 6738, 34953, 1313, 13, 89, 2238, 13, 824, 67, 62, 6200, 13, 6122, 292, 62, 824, 67, 6200, 1330, 21252, 6200, 201, 198, 6738, 34953, 1313, 13, 27530, 13, 15255, 3213, 13,...
2.536842
760
import sys
[ 11748, 25064, 628, 198 ]
3.25
4
from .build import build_transforms from .pre_augmentation_transforms import Resize from .target_transforms import PanopticTargetGenerator, SemanticTargetGenerator
[ 6738, 764, 11249, 1330, 1382, 62, 7645, 23914, 198, 6738, 764, 3866, 62, 559, 5154, 341, 62, 7645, 23914, 1330, 1874, 1096, 198, 6738, 764, 16793, 62, 7645, 23914, 1330, 5961, 8738, 291, 21745, 8645, 1352, 11, 12449, 5109, 21745, 8645, ...
3.813953
43
""" Routines for the analysis of proton radiographs. These routines can be broadly classified as either creating synthetic radiographs from prescribed fields or methods of 'inverting' experimentally created radiographs to reconstruct the original fields (under some set of assumptions). """ __all__ = [ "SyntheticProtonRadiograph", ] import astropy.constants as const import astropy.units as u import numpy as np import sys import warnings from tqdm import tqdm from plasmapy import particles from plasmapy.formulary.mathematics import rot_a_to_b from plasmapy.particles import Particle from plasmapy.plasma.grids import AbstractGrid from plasmapy.simulation.particle_integrators import boris_push def _coerce_to_cartesian_si(pos): """ Takes a tuple of `astropy.unit.Quantity` values representing a position in space in either Cartesian, cylindrical, or spherical coordinates, and returns a numpy array representing the same point in Cartesian coordinates and units of meters. """ # Auto-detect geometry based on units geo_units = [x.unit for x in pos] if geo_units[2].is_equivalent(u.rad): geometry = "spherical" elif geo_units[1].is_equivalent(u.rad): geometry = "cylindrical" else: geometry = "cartesian" # Convert geometrical inputs between coordinates systems pos_out = np.zeros(3) if geometry == "cartesian": x, y, z = pos pos_out[0] = x.to(u.m).value pos_out[1] = y.to(u.m).value pos_out[2] = z.to(u.m).value elif geometry == "cylindrical": r, t, z = pos r = r.to(u.m) t = t.to(u.rad).value z = z.to(u.m) pos_out[0] = (r * np.cos(t)).to(u.m).value pos_out[1] = (r * np.sin(t)).to(u.m).value pos_out[2] = z.to(u.m).value elif geometry == "spherical": r, t, p = pos r = r.to(u.m) t = t.to(u.rad).value p = p.to(u.rad).value pos_out[0] = (r * np.sin(t) * np.cos(p)).to(u.m).value pos_out[1] = (r * np.sin(t) * np.sin(p)).to(u.m).value pos_out[2] = (r * np.cos(t)).to(u.m).value return pos_out def _coast_to_grid(self): r""" Coasts all particles to the timestep when the first particle should be entering the grid. Doing in this in one step (rather than pushing the particles through zero fields) saves computation time. """ # Distance from the source to the nearest gridpoint dist = np.min(np.linalg.norm(self.grid_arr - self.source, axis=3)) # Find the particle with the highest speed towards the grid vmax = np.max(np.dot(self.v, self.src_n)) # Time for fastest possible particle to reach the grid. t = dist / vmax # Coast the particles to the advanced position self.x = self.x + self.v * t def _coast_to_plane(self, center, hdir, vdir, x=None): """ Calculates the positions where the current trajectories of each particle impact a plane, described by the plane's center and horizontal and vertical unit vectors. Returns an [nparticles, 3] array of the particle positions in the plane By default this function does not alter self.x. The optional keyword x can be used to pass in an output array that will used to hold the positions in the plane. This can be used to directly update self.x as follows: self._coast_to_plane(self.detector, self.det_hdir, self.det_vdir, x = self.x) """ normal = np.cross(hdir, vdir) # Calculate the time required to evolve each particle into the # plane t = np.inner(center[np.newaxis, :] - self.x, normal) / np.inner(self.v, normal) # Calculate particle positions in the plane if x is None: # If no output array is provided, preallocate x = np.empty_like(self.x) x[...] = self.x + self.v * t[:, np.newaxis] # Check that all points are now in the plane # (Eq. of a plane is nhat*x + d = 0) plane_eq = np.dot(x - center, normal) assert np.allclose(plane_eq, 0, atol=1e-6) return x def _remove_deflected_particles(self): r""" Removes any particles that have been deflected away from the detector plane (eg. those that will never hit the grid) """ dist_remaining = np.dot(self.x, self.det_n) + np.linalg.norm(self.detector) v_towards_det = np.dot(self.v, -self.det_n) # If particles have not yet reached the detector plane and are moving # away from it, they will never reach the detector. # So, we can remove them from the arrays # Find the indices of all particles that we should keep: # i.e. those still moving towards the detector. ind = np.logical_not((v_towards_det < 0) & (dist_remaining > 0)).nonzero()[0] # Drop the other particles self.x = self.x[ind, :] self.v = self.v[ind, :] self.v_init = self.v_init[ind, :] self.nparticles_grid = self.x.shape[0] # Store the number of particles deflected self.fract_deflected = (self.nparticles - ind.size) / self.nparticles # Warn the user if a large number of particles are being deflected if self.fract_deflected > 0.05: warnings.warn( f"{100*self.fract_deflected:.1f}% particles have been " "deflected away from the detector plane. The fields " "provided may be too high to successfully radiograph " "with this particle energy.", RuntimeWarning, ) def _push(self): r""" Advance particles using an implementation of the time-centered Boris algorithm """ # Get a list of positions (input for interpolator) pos = self.x[self.grid_ind, :] * u.m # Update the list of particles on and off the grid self.on_grid = self.grid.on_grid(pos) # entered_grid is zero at the end if a particle has never # entered the grid self.entered_grid += self.on_grid # Estimate the E and B fields for each particle # Note that this interpolation step is BY FAR the slowest part of the push # loop. Any speed improvements will have to come from here. if self.field_weighting == "volume averaged": Ex, Ey, Ez, Bx, By, Bz = self.grid.volume_averaged_interpolator( pos, "E_x", "E_y", "E_z", "B_x", "B_y", "B_z", persistent=True, ) elif self.field_weighting == "nearest neighbor": Ex, Ey, Ez, Bx, By, Bz = self.grid.nearest_neighbor_interpolator( pos, "E_x", "E_y", "E_z", "B_x", "B_y", "B_z", persistent=True, ) # Create arrays of E and B as required by push algorithm E = np.array( [Ex.to(u.V / u.m).value, Ey.to(u.V / u.m).value, Ez.to(u.V / u.m).value] ) E = np.moveaxis(E, 0, -1) B = np.array([Bx.to(u.T).value, By.to(u.T).value, Bz.to(u.T).value]) B = np.moveaxis(B, 0, -1) # Calculate the adaptive timestep from the fields currently experienced # by the particles # If user sets dt explicitly, that's handled in _adpative_dt dt = self._adaptive_dt(Ex, Ey, Ez, Bx, By, Bz) # TODO: Test v/c and implement relativistic Boris push when required # vc = np.max(v)/_c x = self.x[self.grid_ind, :] v = self.v[self.grid_ind, :] boris_push(x, v, B, E, self.q, self.m, dt) self.x[self.grid_ind, :] = x self.v[self.grid_ind, :] = v def _stop_condition(self): r""" The stop condition is that most of the particles have entered the grid and almost all have now left it. """ # Count the number of particles who have entered, which is the # number of non-zero entries in entered_grid self.num_entered = np.nonzero(self.entered_grid)[0].size # How many of the particles have entered the grid self.fract_entered = np.sum(self.num_entered) / self.nparticles_grid # Of the particles that have entered the grid, how many are currently # on the grid? # if/else avoids dividing by zero if np.sum(self.num_entered) > 0: still_on = np.sum(self.on_grid) / np.sum(self.num_entered) else: still_on = 0.0 if self.fract_entered > 0.1 and still_on < 0.001: # Warn user if < 10% of the particles ended up on the grid if self.num_entered < 0.1 * self.nparticles: warnings.warn( f"Only {100*self.num_entered/self.nparticles:.2f}% of " "particles entered the field grid: consider " "decreasing the max_theta to increase this " "number.", RuntimeWarning, ) return True else: return False def run( self, dt=None, field_weighting="volume averaged", ): r""" Runs a particle-tracing simulation. Timesteps are adaptively calculated based on the local grid resolution of the particles and the electric and magnetic fields they are experiencing. After all particles have left the grid, they are advanced to the detector plane where they can be used to construct a synthetic diagnostic image. Parameters ---------- dt : `~astropy.units.Quantity`, optional An explicitly set timestep in units convertable to seconds. Setting this optional keyword overrules the adaptive time step capability and forces the use of this timestep throughout. If a tuple of timesteps is provided, the adaptive timstep will be clamped between the first and second values. field_weighting : str String that selects the field weighting algorithm used to determine what fields are felt by the particles. Options are: * 'nearest neighbor': Particles are assigned the fields on the grid vertex closest to them. * 'volume averaged' : The fields experienced by a particle are a volume-average of the eight grid points surrounding them. The default is 'volume averaged'. Returns ------- None. """ # Load and validate inputs field_weightings = ["volume averaged", "nearest neighbor"] if field_weighting in field_weightings: self.field_weighting = field_weighting else: raise ValueError( f"{field_weighting} is not a valid option for ", "field_weighting. Valid choices are", f"{field_weightings}", ) if dt is None: # Set dt as an infinite range by default (auto dt with no restrictions) self.dt = np.array([0.0, np.inf]) * u.s else: self.dt = dt self.dt = (self.dt).to(u.s).value # Check to make sure particles have already been generated if not hasattr(self, "x"): raise ValueError( "Either the create_particles or load_particles method must be " "called before running the particle tracing algorithm." ) # If meshes have been added, apply them now for mesh in self.mesh_list: self._apply_wire_mesh(**mesh) # Store a copy of the initial velocity distribution in memory # This will be used later to calculate the maximum deflection self.v_init = np.copy(self.v) # Calculate the maximum velocity # Used for determining the grid crossing maximum timestep self.vmax = np.max(np.linalg.norm(self.v, axis=-1)) # Determine which particles should be tracked # This array holds the indices of all particles that WILL hit the grid # Only these particles will actually be pushed through the fields self.grid_ind = np.where(self.theta < self.max_theta_hit_grid)[0] self.nparticles_grid = len(self.grid_ind) self.fract_tracked = self.nparticles_grid / self.nparticles # Create flags for tracking when particles during the simulation # on_grid -> zero if the particle is off grid, 1 self.on_grid = np.zeros([self.nparticles_grid]) # Entered grid -> non-zero if particle EVER entered the grid self.entered_grid = np.zeros([self.nparticles_grid]) # Generate a null distribution of points (the result in the absence of # any fields) for statistical comparison self.x0 = self._coast_to_plane(self.detector, self.det_hdir, self.det_vdir) # Advance the particles to the near the start of the grid self._coast_to_grid() # Initialize a "progress bar" (really more of a meter) # Setting sys.stdout lets this play nicely with regular print() pbar = tqdm( initial=0, total=self.nparticles_grid + 1, disable=not self.verbose, desc="Particles on grid", unit="particles", bar_format="{l_bar}{bar}{n:.1e}/{total:.1e} {unit}", file=sys.stdout, ) # Push the particles until the stop condition is satisfied # (no more particles on the simulation grid) while not self._stop_condition(): n_on_grid = np.sum(self.on_grid) pbar.n = n_on_grid pbar.last_print_n = n_on_grid pbar.update() self._push() pbar.close() # Remove particles that will never reach the detector self._remove_deflected_particles() # Advance the particles to the image plane self._coast_to_plane(self.detector, self.det_hdir, self.det_vdir, x=self.x) # Log a summary of the run self._log("Run completed") self._log("Fraction of particles tracked: " f"{self.fract_tracked*100:.1f}%") self._log( "Fraction of tracked particles that entered the grid: " f"{self.fract_entered*100:.1f}%" ) self._log( "Fraction of tracked particles deflected away from the " "detector plane: " f"{self.fract_deflected*100}%" ) # ************************************************************************* # Synthetic diagnostic methods (creating output) # ************************************************************************* def synthetic_radiograph( self, size=None, bins=[200, 200], ignore_grid=False, optical_density=False ): r""" Calculate a "synthetic radiograph" (particle count histogram in the image plane). Parameters ---------- size : `~astropy.units.Quantity`, shape (2,2) The size of the detector array, specified as the minimum and maximum values included in both the horizontal and vertical directions in the detector plane coordinates. Shape is [[hmin,hmax], [vmin, vmax]]. Units must be convertable to meters. bins : array of integers, shape (2) The number of bins in each direction in the format [hbins, vbins]. The default is [200,200]. ignore_grid: bool If True, returns the intensity in the image plane in the absence of simulated fields. optical_density: bool If True, return the optical density rather than the intensity .. math:: OD = -log_{10}(Intensity/I_0) where I_O is the intensity on the detector plane in the absence of simulated fields. Default is False. Returns ------- hax : `~astropy.units.Quantity` array shape (hbins,) The horizontal axis of the synthetic radiograph in meters. vax : `~astropy.units.Quantity` array shape (vbins, ) The vertical axis of the synthetic radiograph in meters. intensity : ndarray, shape (hbins, vbins) The number of particles counted in each bin of the histogram. """ # Note that, at the end of the simulation, all particles were moved # into the image plane. # If ignore_grid is True, use the predicted positions in the absence of # simulated fields if ignore_grid: x = self.x0 else: x = self.x # Determine locations of points in the detector plane using unit # vectors xloc = np.dot(x - self.detector, self.det_hdir) yloc = np.dot(x - self.detector, self.det_vdir) if size is None: # If a detector size is not given, choose lengths based on the # dimensions of the grid w = self.mag * np.max( [ np.max(np.abs(self.grid.pts0.to(u.m).value)), np.max(np.abs(self.grid.pts1.to(u.m).value)), np.max(np.abs(self.grid.pts2.to(u.m).value)), ] ) # The factor of 5 here is somewhat arbitrary: we just want a # region a few times bigger than the image of the grid on the # detector, since particles could be deflected out size = 5 * np.array([[-w, w], [-w, w]]) * u.m # Generate the histogram intensity, h, v = np.histogram2d( xloc, yloc, range=size.to(u.m).value, bins=bins ) # h, v are the bin edges: compute the centers to produce arrays # of the right length (then trim off the extra point) h = ((h + np.roll(h, -1)) / 2)[0:-1] v = ((v + np.roll(v, -1)) / 2)[0:-1] # Throw a warning if < 50% of the particles are included on the # histogram percentage = np.sum(intensity) / self.nparticles if percentage < 0.5: warnings.warn( f"Only {percentage:.2%} of the particles are shown " "on this synthetic radiograph. Consider increasing " "the size to include more.", RuntimeWarning, ) if optical_density: # Generate the null radiograph x, y, I0 = self.synthetic_radiograph(size=size, bins=bins, ignore_grid=True) # Calculate I0 as the mean of the non-zero values in the null # histogram. Zeros are just outside of the illuminate area. I0 = np.mean(I0[I0 != 0]) # Overwrite any zeros in intensity to avoid log10(0) intensity[intensity == 0] = 1 # Calculate the optical_density intensity = -np.log10(intensity / I0) return h * u.m, v * u.m, intensity
[ 37811, 198, 49, 448, 1127, 329, 262, 3781, 286, 386, 1122, 19772, 33492, 13, 2312, 31878, 460, 307, 18633, 198, 31691, 355, 2035, 4441, 18512, 19772, 33492, 422, 14798, 7032, 393, 198, 24396, 82, 286, 705, 259, 48820, 6, 6306, 453, 27...
2.32087
8,184
# switch_start.py # Adding another switch statement # Authors : Seoyeon Hwang import string import random
[ 2, 5078, 62, 9688, 13, 9078, 201, 198, 2, 18247, 1194, 5078, 2643, 201, 198, 2, 46665, 1058, 1001, 726, 23277, 367, 47562, 201, 198, 201, 198, 11748, 4731, 201, 198, 11748, 4738, 201 ]
3.294118
34
from numpy import array, rad2deg, pi, mgrid, argmin from matplotlib.pylab import contour import matplotlib.pyplot as plt import mplstereonet from obspy.imaging.beachball import aux_plane from focal_mech.lib.classify_mechanism import classify, translate_to_sphharm from focal_mech.io.read_hash import read_demo, read_hash_solutions from focal_mech.util.hash_routines import hash_to_classifier from focal_mech.lib.sph_harm import get_sph_harm from focal_mech.lib.correlate import corr_shear hash_solns = read_hash_solutions("example1.out") # we want solutions that are symetric polarity_data = read_demo("north1.phase", "scsn.reverse", reverse=True) inputs = hash_to_classifier(polarity_data, parity=1) event = 3146815 result = classify(*inputs[event], kernel_degree=2) Alm = translate_to_sphharm(*result, kernel_degree=2) coeffs = array([Alm[0,0], Alm[1,-1], Alm[1,0], Alm[1,1], Alm[2,-2], Alm[2,-1], Alm[2,0], Alm[2,1], Alm[2,2]]) svm_soln, f = corr_shear(Alm) resolution = (200,400) longi, lati, Z = get_sph_harm(resolution=resolution) mech = coeffs.dot(Z).real longi.shape = resolution lati.shape = resolution mech.shape = resolution c = contour(longi, lati, mech, [0]) pth1 = c.collections[0].get_paths()[0].vertices pth1 = rad2deg(pth1) pth2 = c.collections[0].get_paths()[1].vertices pth2 = rad2deg(pth2) hash_focal = rad2deg(hash_solns[event]) event2 = 3158361 result = classify(*inputs[event2], kernel_degree=2) Alm = translate_to_sphharm(*result, kernel_degree=2) coeffs = array([Alm[0,0], Alm[1,-1], Alm[1,0], Alm[1,1], Alm[2,-2], Alm[2,-1], Alm[2,0], Alm[2,1], Alm[2,2]]) svm_soln2, f = corr_shear(Alm) resolution = (200,400) longi, lati, Z = get_sph_harm(resolution=resolution) mech = coeffs.dot(Z).real longi.shape = resolution lati.shape = resolution mech.shape = resolution c = contour(longi, lati, mech, [0]) pth3 = c.collections[0].get_paths()[0].vertices pth3 = rad2deg(pth3) pth4 = c.collections[0].get_paths()[1].vertices pth4 = rad2deg(pth4) hash_focal2 = rad2deg(hash_solns[event2]) event3 = 3153955 result = classify(*inputs[event3], kernel_degree=2) Alm = translate_to_sphharm(*result, kernel_degree=2) coeffs = array([Alm[0,0], Alm[1,-1], Alm[1,0], Alm[1,1], Alm[2,-2], Alm[2,-1], Alm[2,0], Alm[2,1], Alm[2,2]]) svm_soln3, f = corr_shear(Alm) resolution = (200,400) longi, lati, Z = get_sph_harm(resolution=resolution) mech = coeffs.dot(Z).real longi.shape = resolution lati.shape = resolution mech.shape = resolution c = contour(longi, lati, mech, [0]) pth5 = c.collections[0].get_paths()[0].vertices pth5 = rad2deg(pth5) pth6 = c.collections[0].get_paths()[1].vertices pth6 = rad2deg(pth6) hash_focal3 = rad2deg(hash_solns[event3]) fig = plt.figure(facecolor="white", figsize=(10,20)) ax = fig.add_subplot(221, projection='stereonet') ax.rake(pth1[:,0], pth1[:,1] +90.0, 90.0, ':', color='red', linewidth=3) ax.rake(pth2[:,0], pth2[:,1] +90.0, 90.0, ':', color='red', linewidth=3) strike, dip, rake = svm_soln ax.plane(strike, dip, '-r', linewidth=2) strike, dip, rake = aux_plane(*svm_soln) ax.plane(strike, dip, '-r', linewidth=2) strike, dip, rake = hash_focal ax.plane(strike-90, dip, 'g-', linewidth=2) strike, dip, rake = aux_plane(*hash_focal) ax.plane(strike-90, dip,'g-', linewidth=2) azi = rad2deg(polarity_data[event][:,0]) toa = rad2deg(polarity_data[event][:,1]) polarity = polarity_data[event][:,2] for a, t, p in zip(azi, toa, polarity): if p > 0: ax.pole(a, t,'o', markeredgecolor='red', markerfacecolor='red') else: ax.pole(a, t,'o', markeredgecolor='blue', markerfacecolor='white') ax.grid() ax = fig.add_subplot(222, projection='stereonet') ax.rake(pth3[:,0], pth3[:,1] +90.0, 90.0, ':', color='red', linewidth=3) ax.rake(pth4[:,0], pth4[:,1] +90.0, 90.0, ':', color='red', linewidth=3) strike, dip, rake = svm_soln2 ax.plane(strike, dip, '-r', linewidth=2) strike, dip, rake = aux_plane(*svm_soln2) ax.plane(strike, dip, '-r', linewidth=2) strike, dip, rake = hash_focal2 ax.plane(strike-90, dip, 'g-', linewidth=2) strike, dip, rake = aux_plane(*hash_focal2) ax.plane(strike-90, dip,'g-', linewidth=2) azi = rad2deg(polarity_data[event2][:,0]) toa = rad2deg(polarity_data[event2][:,1]) polarity = polarity_data[event2][:,2] for a, t, p in zip(azi, toa, polarity): if p > 0: ax.pole(a, t,'o', markeredgecolor='red', markerfacecolor='red') else: ax.pole(a, t,'o', markeredgecolor='blue', markerfacecolor='white') ax.grid() ax = fig.add_subplot(224, projection='stereonet') ax.rake(pth5[:,0], pth5[:,1] +90.0, 90.0, ':', color='red', linewidth=3) ax.rake(pth6[:,0], pth6[:,1] +90.0, 90.0, ':', color='red', linewidth=3) strike, dip, rake = svm_soln3 ax.plane(strike, dip, '-r', linewidth=2) strike, dip, rake = aux_plane(*svm_soln3) ax.plane(strike, dip, '-r', linewidth=2) strike, dip, rake = hash_focal3 ax.plane(strike-90, dip, 'g-', linewidth=2) strike, dip, rake = aux_plane(*hash_focal3) ax.plane(strike-90, dip,'g-', linewidth=2) azi = rad2deg(polarity_data[event3][:,0]) toa = rad2deg(polarity_data[event3][:,1]) polarity = polarity_data[event3][:,2] for a, t, p in zip(azi, toa, polarity): if p > 0: ax.pole(a, t,'o', markeredgecolor='red', markerfacecolor='red') else: ax.pole(a, t,'o', markeredgecolor='blue', markerfacecolor='white') ax.grid() plt.tight_layout(pad=4.0, h_pad=20.0) plt.show()
[ 6738, 299, 32152, 1330, 7177, 11, 2511, 17, 13500, 11, 31028, 11, 285, 25928, 11, 1822, 1084, 198, 198, 6738, 2603, 29487, 8019, 13, 79, 2645, 397, 1330, 542, 454, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 1...
2.187102
2,512
# Copyright (c) 2017 FlashX, LLC # # 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. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import requests import json
[ 2, 15069, 357, 66, 8, 2177, 9973, 55, 11, 11419, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 198, 2, 286, 428, 3788, 290, 3917, 10314, 3696, 357, 1169, 366, 25423, 12340...
3.862069
290
import numpy as np import pandas as pd import matplotlib.pyplot as plt import sklearn.ensemble import sklearn.metrics import sklearn import progressbar import sklearn.model_selection from plotnine import * import pdb import sys sys.path.append("smooth_rf/") import smooth_base import smooth_level # function def average_depth(random_forest, data): """ calculate the average depth of each point (average across trees) Arguments: ---------- random_forest : sklearn random forest model (fit) data : array (n, p) data frame that can be predicted from random_forest Returns: -------- average_depth : array (n,) vector of average depth in forest of each data point """ # test: #rf_fit #smooth_rf_opt #d1 = average_depth(rf_fit, data) #d2 = average_depth(smooth_rf_opt, data) #np.all(d1 == d2) n_trees = len(random_forest.estimators_) n_obs = data.shape[0] depth = np.zeros(n_obs) for t in random_forest.estimators_: d_path = t.decision_path(data) depth = depth + np.array(d_path.sum(axis = 1)).ravel() return depth / n_trees # start of analysis data, y = smooth_base.generate_data(large_n = 650) data_vis = pd.DataFrame(data = {"x1":data[:,0], "x2":data[:,1], "y":y}, columns = ["x1","x2","y"]) ggout = ggplot(data_vis) +\ geom_point(aes(x = "x1",y ="x2", color = "factor(y)")) +\ theme_minimal() +\ labs(x= "X1", y = "X2", color = "value (minus 100)") rf = sklearn.ensemble.RandomForestRegressor(n_estimators = 300) rf_fit = rf.fit(data,y) smooth_rf_opt, smooth_rf_last ,_, _ = smooth_base.smooth( rf_fit, X_trained = data, y_trained = y.ravel(), X_tune = None, y_tune = None, resample_tune= False, # oob no_constraint = False, subgrad_max_num = 10000, subgrad_t_fix = 1, parents_all=True, verbose = True, all_trees = False, initial_lamb_seed = None) # test data data_test, y_test = smooth_base.generate_data(large_n = 10000) reorder = np.random.choice(data_test.shape[0], size = data_test.shape[0], replace= False) data_test = data_test[reorder,:] y_test = y_test[reorder] yhat_base = rf_fit.predict(data_test) yhat_smooth = smooth_rf_opt.predict(data_test) base_mse = sklearn.metrics.mean_squared_error(y_true = y_test, y_pred = yhat_base) smooth_mse = sklearn.metrics.mean_squared_error(y_true = y_test, y_pred = yhat_smooth) error_base = np.abs(yhat_base - y_test) error_smooth = np.abs(yhat_smooth - y_test) extreme_binary = np.max([np.max(np.abs(error_base)), np.max(np.abs(error_smooth))]) col_vis = error_base - error_smooth extreme = np.max(np.abs(col_vis)) mean_depth_test = average_depth(rf_fit,data_test) data_vis = pd.DataFrame(data = {"X1":data_test[:,0], "X2":data_test[:,1], "y": y_test.ravel(), "error_base":error_base.copy(), "error_smooth":error_smooth.copy(), "error":col_vis.copy(), "mean_depth":mean_depth_test.copy()}, columns = ["X1","X2","y","error", "error_base","error_smooth", "mean_depth"]) a = ggplot(data_vis) +\ geom_point(aes(x = "X1", y="X2", color = "error"), size = .5) +\ scale_color_continuous(name = "bwr", limits= [-extreme, extreme]) +\ theme_bw() +\ labs(color = "Difference in Error", title = r'Difference in Error ($Error_{base} - Error_{smooth}$)') b = ggplot(data_vis) +\ geom_point(aes(x = "X1", y="X2", color = "error_base"), size = .5) +\ scale_color_continuous(name = "binary", limits= [0, extreme_binary]) +\ theme_bw() +\ labs(color = "Error", title = "Error from Base Random Forest") c = ggplot(data_vis) +\ geom_point(aes(x = "X1", y="X2", color = "error_smooth"), size = .5) +\ scale_color_continuous(name = "binary", limits= [0, extreme_binary]) +\ theme_bw() +\ labs(color = "Error", title = "Error from Smoothed Random Forest") d = ggplot(data_vis) +\ geom_point(aes(x = "X1", y="X2", color = "factor(y)"), size = .5) +\ theme_bw() +\ labs(color = "True Value (discrete)", title = "Test Set True Values") e = ggplot(data_vis,aes(x = "mean_depth", y = "error")) +\ geom_point(alpha = .1) +\ theme_bw() +\ labs(x = "Mean depth in Forest", y = "Difference in Error", title = "Lack of relationship between diff in errors and depth") f = ggplot(data_vis, aes(x = "X1", y = "X2", color = "mean_depth")) +\ geom_point() +\ scale_color_continuous(name = "Blues") +\ theme_bw() +\ labs(color = "Mean depth in Forest", title = "Mean depth in Forest (Depth averaged across trees)") g = ggplot(data_vis) +\ geom_point(aes(x = "error_base", y = "error_smooth"), alpha = .05) +\ geom_abline(intercept = 0, slope = 1) +\ theme_bw() +\ labs(x = "Error from Random Forest", y = "Error from Smooth Random Forest", title = "Comparing Errors Between Models", subtitle = r"(total error: rf: %f vs srf: %f)" %\ (base_mse, smooth_mse)) save_as_pdf_pages([a + theme(figure_size = (8,6))], filename = "images/diff_error"+"_understanding_smoothing.pdf") save_as_pdf_pages([b + theme(figure_size = (8,6))], filename = "images/error_base"+"_understanding_smoothing.pdf") save_as_pdf_pages([c + theme(figure_size = (8,6))], filename = "images/error_smooth"+"_understanding_smoothing.pdf") save_as_pdf_pages([d + theme(figure_size = (8,6))], filename = "images/truth"+"_understanding_smoothing.pdf") save_as_pdf_pages([e + theme(figure_size = (8,6))], filename = "images/mean_depth_diff_error"+"_understanding_smoothing.pdf") save_as_pdf_pages([f + theme(figure_size = (8,6))], filename = "images/mean_depth"+"_understanding_smoothing.pdf") save_as_pdf_pages([g + theme(figure_size = (8,6))], filename = "images/error_vs_error"+"_understanding_smoothing.pdf") save_as_pdf_pages([a + theme(figure_size = (8,6)), b + theme(figure_size = (8,6)), c + theme(figure_size = (8,6)), d + theme(figure_size = (8,6)), e + theme(figure_size = (8,6)), f + theme(figure_size = (8,6)), g + theme(figure_size = (8,6))], filename = "images/understanding_smoothing.pdf") # some of these observations might be due to the decision on the values of the classes # we'll see
[ 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 1341, 35720, 13, 1072, 11306, 198, 11748, 1341, 35720, 13, 4164, 10466, 198, 11748, 1341, 357...
1.977549
3,697
import numpy as np def CCC(y_true, y_pred): """ Calculate the CCC for two numpy arrays. """ x = y_true y = y_pred xMean = x.mean() yMean = y.mean() xyCov = (x * y).mean() - (xMean * yMean) # xyCov = ((x-xMean) * (y-yMean)).mean() xVar = x.var() yVar = y.var() return 2 * xyCov / (xVar + yVar + (xMean - yMean) ** 2) def MSE(y_true, y_pred): """ Calculate the Mean Square Error for two numpy arrays. """ mse = (np.square(y_true - y_pred)).mean(axis=0) return mse def RMSE(y_true, y_pred): """ Calculate the Mean Square Error for two numpy arrays. """ return np.sqrt(MSE(y_true, y_pred)) def perfMeasure(y_actual, y_pred): """ Calculate the confusion matrix for two numpy arrays. """ TP = 0 FP = 0 TN = 0 FN = 0 for i in range(len(y_pred)): if y_actual[i]==y_pred[i]==1: TP += 1 if y_pred[i]==1 and y_actual[i]!=y_pred[i]: FP += 1 if y_actual[i]==y_pred[i]==-1: TN += 1 if y_pred[i]==-1 and y_actual[i]!=y_pred[i]: FN += 1 return (TP, FP, TN, FN)
[ 11748, 299, 32152, 355, 45941, 198, 198, 4299, 327, 4093, 7, 88, 62, 7942, 11, 331, 62, 28764, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 27131, 378, 262, 327, 4093, 329, 734, 299, 32152, 26515, 13, 198, 220, 220, 220, 3...
1.921273
597
# Copyright (c) 2015 Niklas Rosenstein # # 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. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import abc import six import time import threading import warnings from .lowlevel.enums import EventType, Pose, Arm, XDirection from .utils.threading import TimeoutClock from .vector import Vector from .quaternion import Quaternion def __init__(self): super(Feed, self).__init__() self.synchronized = threading.Condition() self._myos = {} def get_devices(self): """ get_devices() -> list of Feed.MyoProxy Returns a list of paired and connected Myo's. """ with self.synchronized: return list(self._myos.values()) def get_connected_devices(self): """ get_connected_devices(self) -> list of Feed.MyoProxy Returns a list of connected Myo's. """ with self.synchronized: return [myo for myo in self._myos.values() if myo.connected] def wait_for_single_device(self, timeout=None, interval=0.5): """ wait_for_single_device(timeout) -> Feed.MyoProxy or None Waits until a Myo is was paired **and** connected with the Hub and returns it. If the *timeout* is exceeded, returns None. This function will not return a Myo that is only paired but not connected. :param timeout: The maximum time to wait for a device. :param interval: The interval at which the function should exit sleeping. We can not sleep endlessly, otherwise the main thread can not be exit, eg. through a KeyboardInterrupt. """ timer = TimeoutClock(timeout) start = time.time() with self.synchronized: # As long as there are no Myo's connected, wait until we # get notified about a change. while not timer.exceeded: # Check if we found a Myo that is connected. for myo in six.itervalues(self._myos): if myo.connected: return myo remaining = timer.remaining if interval is not None and remaining > interval: remaining = interval self.synchronized.wait(remaining) return None # DeviceListener
[ 2, 15069, 357, 66, 8, 1853, 220, 11271, 21921, 41916, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 198, 2, 286, 428, 3788, 290, 3917, 10314, 3696, 357, 1169, 366, 25423, ...
2.720588
1,224
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Aug 12 13:34:49 2020 @author: lukepinkel """ import numpy as np import scipy as sp import scipy.special
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 3300, 2447, 1105, 1511, 25, 2682, 25, 2920, 12131, 198, 198, 31, 9800, 25, 300, 4649, 116...
2.457143
70
''' Created on Sep 29, 2021 @author: thomas ''' import ImageNetTools import sys import getopt main(sys.argv[1:])
[ 7061, 6, 198, 41972, 319, 8621, 2808, 11, 33448, 198, 198, 31, 9800, 25, 294, 16911, 198, 7061, 6, 198, 198, 11748, 7412, 7934, 33637, 198, 11748, 25064, 198, 11748, 651, 8738, 198, 220, 220, 220, 220, 198, 12417, 7, 17597, 13, 853,...
2.479167
48
""" $ pytest -s -v test_results_render.py """ import logging import pytest from sagas.nlu.results_render import ResultsRender
[ 37811, 198, 3, 12972, 9288, 532, 82, 532, 85, 1332, 62, 43420, 62, 13287, 13, 9078, 198, 37811, 198, 11748, 18931, 198, 11748, 12972, 9288, 198, 198, 6738, 45229, 292, 13, 77, 2290, 13, 43420, 62, 13287, 1330, 15691, 45819, 628, 628 ]
3.095238
42
import json import math from HistoricalTweetDataFetcher import getHistoricalData joelsarray = getHistoricalData(0) arrs = [] arrm = [] arrp = [] arrsTotal = 0 arrmTotal = 0 ncount = 0 ccount = 0 lcount = 0 time = joelsarray[0]["h"] for dictionary in joelsarray: arrs.append(dictionary["s"]) arrm.append(dictionary["m"]) arrp.append(dictionary["p"]) for x in range(len(arrs)): arrsTotal += arrs[x] arrmTotal += arrm[x] if arrp[x]=='l': lcount += 1 elif arrp[x]=='c': ccount += 1 elif arrp[x]=='n': ncount += 1 arrsAvg = arrsTotal/len(arrs)#sentiment value arrmAvg = arrmTotal/len(arrm)#magnitude value #print(arrsTotal) #print(len(arrs)) #rint(arrsAvg) #print(arrmAvg) #print(lcount) #print(ccount) ################################################################### filename2 = "weather_us.json" if filename2: with open(filename2, 'r') as f: weatherstore = json.load(f) for x in range(50): statearray = list(weatherstore.keys()) statesAverage = 0 for state in statearray: for x in range(50): temptemp = float(weatherstore[state]["temperature"]) temphigh = float(weatherstore[state]["average_monthly_high"]) templow = float(weatherstore[state]["average_monthly_low"]) statesAverage+=((temptemp-temphigh)*(templow-temptemp))/(math.pow(((temphigh+templow)/2),2)) statesAverage = statesAverage/50 #this is the average tempeature multiplyer print(statesAverage) ##################################################################################### filename3 = "sp500_price.json" if filename3: with open(filename3, 'r') as f: stockdata = json.load(f) stockpricecurrent = stockdata["current_price"] stockpricechange = stockdata["percent_change"]#percent change of S&P500 if stockpricechange <= 0.73 and stockpricechange >=-0.73: stockmultiply = 0; else: stockmultiply = stockpricechange*0.5*0.73 print(stockpricechange) ######################################################################################### filename4 = "trump_approval_rating.json" if filename4: with open(filename4, 'r') as f: approvalratingdata = json.load(f) approveAvg = approvalratingdata["approve_avg"]#approval average data currentApproval = approvalratingdata["approve"]#current approval percentage ######################################################################################## my_list = equation(arrsAvg, stockmultiply, currentApproval, approveAvg, statesAverage, 0, 0, lcount, ccount, 17, 70, 60, 50, 45, 25)
[ 11748, 33918, 201, 198, 11748, 10688, 201, 198, 6738, 23121, 47845, 6601, 37, 316, 2044, 1330, 651, 13749, 12409, 6601, 201, 198, 201, 198, 7639, 1424, 18747, 796, 651, 13749, 12409, 6601, 7, 15, 8, 201, 198, 3258, 82, 796, 17635, 201...
2.647944
997
from decimal import Decimal as D, ROUND_DOWN, ROUND_UP import math import datetime from django.core import exceptions from django.template.defaultfilters import slugify from django.db import models from django.utils.translation import ungettext, ugettext as _ from django.utils.importlib import import_module from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from django.conf import settings from oscar.apps.offer.managers import ActiveOfferManager from oscar.templatetags.currency_filters import currency from oscar.models.fields import PositiveDecimalField, ExtendedURLField # ========== # Conditions # ========== # ======== # Benefits # ======== # ================= # Shipping benefits # =================
[ 6738, 32465, 1330, 4280, 4402, 355, 360, 11, 371, 15919, 62, 41925, 11, 371, 15919, 62, 8577, 198, 11748, 10688, 198, 11748, 4818, 8079, 198, 198, 6738, 42625, 14208, 13, 7295, 1330, 13269, 198, 6738, 42625, 14208, 13, 28243, 13, 12286,...
3.609302
215
#!/usr/local/bin/python # coding: latin-1 #if you use this code give me credit @tuf_unkn0wn #i do not give you permission to show / edit this script without my credit #to ask questions or report a problem message me on instagram @tuf_unkn0wn """ """ import os import sys import random lred = '\033[91m' lblue = '\033[94m' lgreen = '\033[92m' yellow = '\033[93m' cyan = '\033[1;36m' purple = '\033[95m' red = '\033[31m' green = '\033[32m' blue = '\033[34m' orange = '\033[33m' colorlist = [red, blue, green, yellow, lblue, purple, cyan, lred, lgreen, orange] randomcolor = random.choice(colorlist) banner3list = [red, blue, green, purple] helpbanner()
[ 2, 48443, 14629, 14, 12001, 14, 8800, 14, 29412, 198, 2, 19617, 25, 3042, 259, 12, 16, 198, 2, 361, 345, 779, 428, 2438, 1577, 502, 3884, 2488, 83, 3046, 62, 2954, 77, 15, 675, 198, 2, 72, 466, 407, 1577, 345, 7170, 284, 905, ...
1.801205
498
d_soldiers = []
[ 67, 62, 24120, 3183, 796, 17635, 628, 197, 628 ]
2.222222
9
from dzTrafico.BusinessEntities.Simulation import Simulation import lxml.etree as etree
[ 6738, 288, 89, 15721, 69, 3713, 13, 24749, 14539, 871, 13, 8890, 1741, 1330, 41798, 198, 11748, 300, 19875, 13, 316, 631, 355, 2123, 631, 198 ]
3.384615
26
#!/usr/bin/env python3 import collections import logging import os import typing import unicodedata from janome.tokenizer import Tokenizer from transformers.file_utils import cached_path from transformers.models.bert.tokenization_bert import BertTokenizer, WordpieceTokenizer, load_vocab import bunkai.constant """ The original source code is from cl-tohoku/bert-japanese. https://github.com/cl-tohoku/bert-japanese/blob/master/tokenization.py The original source code is under Apache-2.0 License. """ logger = logging.getLogger(__name__) KNOWN_PRETRAINED_VOCABS = { "cl-tohoku/bert-base-japanese", "cl-tohoku/bert-base-japanese-whole-word-masking", "cl-tohoku/bert-base-japanese-char", "cl-tohoku/bert-base-japanese-char-whole-word-masking", }
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 17268, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 19720, 198, 11748, 28000, 9043, 1045, 198, 198, 6738, 42897, 462, 13, 30001, 7509, 1330, 29130, 7509, 198, 6738, ...
2.730496
282
import unittest from datetime import datetime import os import sys from api.exchanges.exchange import ExchangeAPICallFailedException from api.exchanges.gdax_exchange import GdaxExchange from api.exchanges.kraken_exchange import KrakenExchange from api.exchanges.bitstamp_exchange import BitstampExchange from api.exchanges.bitfinex_exchange import BitfinexExchange if __name__ == '__main__': unittest.main(exit=False)
[ 11748, 555, 715, 395, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 11748, 28686, 198, 11748, 25064, 198, 198, 6738, 40391, 13, 1069, 36653, 13, 1069, 3803, 1330, 12516, 2969, 2149, 439, 37, 6255, 16922, 198, 6738, 40391, 13, 1069, 3665...
3.115942
138
from sklearn.cluster import KMeans import image_processing import numpy as np import some_analysis from sklearn.manifold import TSNE import matplotlib.pyplot as plt from autoencoder import ConvAutoencoder input_path = './bin' output_shape = (32, 48) processing_output = './processed/results_processing' data = image_processing.get_data_from_images(processing_output) data = data[:, :, :, :-1] encoder, _, _ = ConvAutoencoder.build(32, 48, 3, filters=(32, 64), latentDim=512) encoder.load_weights('encoder.h5') data_encoded = encoder.predict(data) #data_reshaped = data.reshape((data.shape[0], -1)) n_clusters = 200 # Runs in parallel 4 CPUs kmeans = KMeans(n_clusters=n_clusters, n_init=15, n_jobs=8) # Train K-Means. y_pred_kmeans = kmeans.fit_predict(data_encoded) data += 1.0 data *= 127.5 array = np.empty((n_clusters), dtype=object) for i in range(n_clusters): array[i] = [] for cluster, idx in zip(y_pred_kmeans, range(data.shape[0])): array[cluster].append(idx) i = 1 for l in array: cluster = data[l] some_analysis.make_preview(cluster, f'./previews/cluster_v3_{i}.png', n_cols=5) i += 1 ''' data_embedded = TSNE(learning_rate=200).fit_transform(data_reshaped) plt.scatter(data_embedded[:, 0], data_embedded[:, 1]) '''
[ 6738, 1341, 35720, 13, 565, 5819, 1330, 509, 5308, 504, 198, 11748, 2939, 62, 36948, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 617, 62, 20930, 198, 6738, 1341, 35720, 13, 805, 361, 727, 1330, 26136, 12161, 198, 11748, 2603, 29487,...
2.278438
589
""" Modifique as funes que foram criadas no desafio 107 para que elas aceitem um parametro a mais, informando se o valor retornado por elas vai ser ou no formatado pela funo moeda(), desenvolvida no desafio 108. """ from Aula22.ex109 import moeda from Aula22.ex109.titulo import titulo preco = float(input("Preo: R$")) titulo('Informaes Calculadas: ') print(f"Metade: {moeda.metade(preco, True)}") print(f"Dobro: {moeda.dobro(preco, True)}") print(f"10% Acrscimo: {moeda.aumentar(preco, 10, True)}") print(f"10% Desconto: {moeda.diminuir(preco, 10, True)}")
[ 37811, 198, 5841, 361, 2350, 355, 1257, 274, 8358, 329, 321, 269, 21244, 292, 645, 748, 1878, 952, 16226, 31215, 198, 4188, 1288, 292, 31506, 9186, 23781, 5772, 316, 305, 257, 285, 15152, 11, 4175, 25440, 384, 267, 1188, 273, 198, 118...
2.405983
234
from mocu.utils.toysystems import * import matplotlib.pyplot as plt import matplotlib.cm as cm if __name__ == '__main__': main()
[ 6738, 285, 420, 84, 13, 26791, 13, 83, 726, 10057, 82, 1330, 1635, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 2603, 29487, 8019, 13, 11215, 355, 12067, 628, 628, 220, 220, 220, 220, 198, 361, 11593, 36...
2.370968
62
""" Several methods for generating graphs from the stochastic block model. """ import itertools import math import random import scipy.sparse import numpy as np def _get_num_pos_edges(c1_size, c2_size, same_cluster, self_loops, directed): """ Compute the number of possible edges between two clusters. :param c1_size: The size of the first cluster :param c2_size: The size of the second cluster :param same_cluster: Whether these are the same cluster :param self_loops: Whether we will generate self loops :param directed: Whether we are generating a directed graph :return: the number of possible edges between these clusters """ if not same_cluster: # The number is simply the product of the number of vertices return c1_size * c2_size else: # The base number is n choose 2 possible_edges_between_clusters = int((c1_size * (c1_size - 1)) / 2) # If we are allowed self-loops, then add them on if self_loops: possible_edges_between_clusters += c1_size # The number is normally the same for undirected and directed graphs, unless the clusters are the same, in which # case the number for the directed graph is double since we need to consider both directions of each edge. if directed: possible_edges_between_clusters *= 2 # But if we are allowed self-loops, then we shouldn't double them since there is only one 'direction'. if directed and self_loops: possible_edges_between_clusters -= c1_size return possible_edges_between_clusters def _get_number_of_edges(c1_size, c2_size, prob, same_cluster, self_loops, directed): """ Compute the number of edges there will be between two clusters. :param c1_size: The size of the first cluster :param c2_size: The size of the second cluster :param prob: The probability of an edge between the clusters :param same_cluster: Whether these are the same cluster :param self_loops: Whether we will generate self loops :param directed: Whether we are generating a directed graph :return: the number of edges to generate between these clusters """ # We need to compute the number of possible edges possible_edges_between_clusters = _get_num_pos_edges(c1_size, c2_size, same_cluster, self_loops, directed) # Sample the number of edges from the binomial distribution return np.random.binomial(possible_edges_between_clusters, prob) def sbm_adjmat(cluster_sizes, prob_mat_q, directed=False, self_loops=False): """ Generate a graph from the stochastic block model. The list cluster_sizes gives the number of vertices inside each cluster and the matrix Q gives the probability of each edge between pairs of clusters. For two vertices u and v where u is in cluster i and v is in cluster j, there is an edge between u and v with probability Q_{i, j}. For the undirected case, we assume that the matrix Q is symmetric (and in practice look only at the upper triangle). For the directed case, we generate edges (u, v) and (v, u) with probabilities Q_{i, j} and Q_{j, i} respectively. Returns the adjacency matrix of the graph as a sparse scipy matrix in the CSR format. :param cluster_sizes: The number of vertices in each cluster. :param prob_mat_q: A square matrix where Q_{i, j} is the probability of each edge between clusters i and j. Should be symmetric in the undirected case. :param directed: Whether to generate a directed graph (default is false). :param self_loops: Whether to generate self-loops (default is false). :return: The sparse adjacency matrix of the graph. """ # Initialize the adjacency matrix adj_mat = scipy.sparse.lil_matrix((sum(cluster_sizes), sum(cluster_sizes))) # Generate the edges in the graph for (u, v) in _generate_sbm_edges(cluster_sizes, prob_mat_q, directed=directed): if u != v or self_loops: # Add this edge to the adjacency matrix. adj_mat[u, v] = 1 if not directed: adj_mat[v, u] = 1 # Reformat the output matrix to the CSR format return adj_mat.tocsr() def sbm_adjmat_equal_clusters(n, k, prob_mat_q, directed=False): """ Generate a graph from the general stochastic block model. Generates a graph with n vertices and k clusters. Every cluster will have floor(n/k) vertices. The probability of each edge inside a cluster is given by the probability matrix Q. :param n: The number of vertices in the graph. :param k: The number of clusters. :param prob_mat_q: q[i][j] gives the probability of an edge between clusters i and j :param directed: Whether to generate a directed graph. :return: The sparse adjacency matrix of the graph. """ return sbm_adjmat([int(n/k)] * k, prob_mat_q, directed=directed) def ssbm_adjmat(n, k, p, q, directed=False): """ Generate a graph from the symmetric stochastic block model. Generates a graph with n vertices and k clusters. Every cluster will have floor(n/k) vertices. The probability of each edge inside a cluster is given by p. The probability of an edge between two different clusters is q. :param n: The number of vertices in the graph. :param k: The number of clusters. :param p: The probability of an edge inside a cluster. :param q: The probability of an edge between clusters. :param directed: Whether to generate a directed graph. :return: The sparse adjacency matrix of the graph. """ # Every cluster has the same size. cluster_sizes = [int(n/k)] * k # Construct the k*k probability matrix Q. The off-diagonal entries are all q and the diagonal entries are all p. prob_mat_q = [] for row_num in range(k): new_row = [q] * k new_row[row_num] = p prob_mat_q.append(new_row) # Call the general sbm method. return sbm_adjmat(cluster_sizes, prob_mat_q, directed=directed)
[ 37811, 198, 14945, 5050, 329, 15453, 28770, 422, 262, 3995, 354, 3477, 2512, 2746, 13, 198, 37811, 198, 11748, 340, 861, 10141, 198, 11748, 10688, 198, 11748, 4738, 198, 11748, 629, 541, 88, 13, 82, 29572, 198, 11748, 299, 32152, 355, ...
2.938805
2,059
#!/usr/bin/python3 """ | --------------------- Py include <Mauro Balads> --------------------- | ___ _ _ _ __ _ _ ___ ____ | | |_) \ \_/ | | | |\ | / /` | | | | | | | \ | |_ | |_| |_| |_| |_| \| \_\_, |_|__ \_\_/ |_|_/ |_|__ | ---------------------------------------------------------------------- | MIT License | | Copyright (c) 2022 Mauro Balads | | 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. | | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | SOFTWARE. | """ from pathlib import Path import sys def include(*args, **kwargs): """Here is where all the magic ocour. This function takes an infinite amount of paths and they are being executend to feel like user imported it. Note: It can also be used to store it into a variable if user needs it. This can be done by adding the argument `ret` to True (more detail in #Args). Note: Please note how (for the import statement) you will need a `__init__.py` and paths separated by dots. With py-include, you don't need. Py-include will make your path supported by the current platform and it will open it's content and execute it, so you don't need a path divided by `.` or a `__init__.py` Args: files [list(str)]: A list of paths to include. ret [bool]: If it is set to True, return the module (defaults to False). Note: If `ret` is set to `True`, the function will return all modules as user will need to unpack them. """ # Get the value whether user whan't to execute # the module or to return it. (defaults to False) ret = kwargs.get("ret", False) # Check if user inserted `ret` as True. If it not, # we will open the file and execute it's content. # If it is True, we will return the module they # whanted to import. if not ret: _exec_modules(*args, **kwargs) return _ret_modules(*args, **kwargs)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 198, 37811, 198, 91, 41436, 12, 9485, 2291, 1279, 44, 559, 305, 8528, 5643, 29, 41436, 12, 198, 91, 220, 46444, 220, 220, 4808, 220, 220, 220, 220, 220, 220, 220, 220, 4808, 220, 220,...
3.161504
904
import pyensembl import sys import sqlite3 import boto3 import pickle dynamodb = boto3.resource('dynamodb') table_agfusion_gene_synonyms = dynamodb.Table('agfusion_gene_synonyms') table_agfusion_genes = dynamodb.Table('agfusion_genes') table_agfusion_sequences = dynamodb.Table('agfusion_sequences') # process_data('homo_sapiens', 94, '/Users/charliemurphy/Downloads/agfusion.homo_sapiens.94.db') # process_data('homo_sapiens', 75, 'GRCh37', '/Users/charliemurphy/Downloads/agfusion.homo_sapiens.75.db') # process_data('mus_musculus', 92, 'GRCm38', '/Users/charliemurphy/Downloads/agfusion.mus_musculus.92.db')
[ 11748, 12972, 1072, 2022, 75, 198, 11748, 25064, 198, 11748, 44161, 578, 18, 198, 11748, 275, 2069, 18, 198, 11748, 2298, 293, 198, 198, 67, 4989, 375, 65, 796, 275, 2069, 18, 13, 31092, 10786, 67, 4989, 375, 65, 11537, 198, 11487, ...
2.46
250
# Copyright 2017 Google Inc. All Rights Reserved. # # 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. # """Mutiple files/file patterns source. Multiple File source, which reads the union of multiple files and/or file patterns. """ from apache_beam import coders from apache_beam.io import iobase from apache_beam.io.filesystem import CompressionTypes from apache_beam.io.iobase import Read from apache_beam.io.range_trackers import OffsetRangeTracker from apache_beam.io.textio import _TextSource as TextSource from apache_beam.io.tfrecordio import _TFRecordSource as TFRecordSource from apache_beam.transforms import PTransform from apache_beam.transforms.display import DisplayDataItem # pylint: disable=g-import-not-at-top try: from apache_beam.options.value_provider import ValueProvider from apache_beam.options.value_provider import StaticValueProvider except ImportError: from apache_beam.utils.value_provider import ValueProvider from apache_beam.utils.value_provider import StaticValueProvider # pylint: enable=g-import-not-at-top FILE_LIST_SEPARATOR = ',' # TODO(user): currently compression_type is not a ValueProvider valure in # filebased_source, thereby we have to make seperate classes for # non-compressed and compressed version of TFRecord sources. Consider to # make the compression_type a ValueProvider in filebased_source.
[ 2, 15069, 2177, 3012, 3457, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 393, 517, 198, 2, 18920, 5964, 11704, 13, 220, 4091, 262, 28536, 2393, 9387, 351, 198, 2, 428,...
3.69788
566
import numpy as np import matplotlib.pyplot as plt import glob, os, time from ..lib import manageevent as me from ..lib import readECF as rd from ..lib import sort_nicely as sn from ..lib import util, logedit from . import parameters as p from . import lightcurve as lc from . import models as m from .utils import get_target_data #FINDME: Keep reload statements for easy testing from importlib import reload reload(p) reload(m) reload(lc) def fitJWST(eventlabel, s4_meta=None): '''Fits 1D spectra with various models and fitters. Parameters ---------- eventlabel: str The unique identifier for these data. s4_meta: MetaClass The metadata object from Eureka!'s S4 step (if running S4 and S5 sequentially). Returns ------- meta: MetaClass The metadata object with attributes added by S5. Notes ------- History: - November 12-December 15, 2021 Megan Mansfield Original version - December 17-20, 2021 Megan Mansfield Connecting S5 to S4 outputs - December 17-20, 2021 Taylor Bell Increasing connectedness of S5 and S4 ''' print("\nStarting Stage 5: Light Curve Fitting\n") # Initialize a new metadata object meta = MetaClass() meta.eventlabel = eventlabel # Load Eureka! control file and store values in Event object ecffile = 'S5_' + eventlabel + '.ecf' ecf = rd.read_ecf(ecffile) rd.store_ecf(meta, ecf) # load savefile if s4_meta == None: # Search for the S2 output metadata in the inputdir provided in # First just check the specific inputdir folder rootdir = os.path.join(meta.topdir, *meta.inputdir.split(os.sep)) if rootdir[-1]!='/': rootdir += '/' files = glob.glob(rootdir+'S4_'+meta.eventlabel+'*_Meta_Save.dat') if len(files)==0: # There were no metadata files in that folder, so let's see if there are in children folders files = glob.glob(rootdir+'**/S4_'+meta.eventlabel+'*_Meta_Save.dat', recursive=True) files = sn.sort_nicely(files) if len(files)==0: # There may be no metafiles in the inputdir - raise an error and give a helpful message raise AssertionError('Unable to find an output metadata file from Eureka!\'s S4 step ' +'in the inputdir: \n"{}"!'.format(rootdir)) elif len(files)>1: # There may be multiple runs - use the most recent but warn the user print('WARNING: There are multiple metadata save files in your inputdir: \n"{}"\n'.format(rootdir) +'Using the metadata file: \n{}\n'.format(files[-1]) +'and will consider aperture ranges listed there. If this metadata file is not a part\n' +'of the run you intended, please provide a more precise folder for the metadata file.') fname = files[-1] # Pick the last file name (should be the most recent or only file) fname = fname[:-4] # Strip off the .dat ending s4_meta = me.loadevent(fname) # Need to remove the topdir from the outputdir s4_outputdir = s4_meta.outputdir[len(s4_meta.topdir):] if s4_outputdir[0]=='/': s4_outputdir = s4_outputdir[1:] s4_allapers = s4_meta.allapers # Overwrite the temporary meta object made above to be able to find s4_meta meta = s4_meta # Load Eureka! control file and store values in the S4 metadata object ecffile = 'S5_' + eventlabel + '.ecf' ecf = rd.read_ecf(ecffile) rd.store_ecf(meta, ecf) # Overwrite the inputdir with the exact output directory from S4 meta.inputdir = s4_outputdir meta.old_datetime = s4_meta.datetime # Capture the date that the meta.datetime = None # Reset the datetime in case we're running this on a different day meta.inputdir_raw = meta.inputdir meta.outputdir_raw = meta.outputdir if (not s4_allapers) or (not meta.allapers): # The user indicated in the ecf that they only want to consider one aperture # in which case the code will consider only the one which made s4_meta. # Alternatively, S4 was run without allapers, so S5's allapers will only conside that one meta.spec_hw_range = [meta.spec_hw,] meta.bg_hw_range = [meta.bg_hw,] run_i = 0 for spec_hw_val in meta.spec_hw_range: for bg_hw_val in meta.bg_hw_range: t0 = time.time() meta.spec_hw = spec_hw_val meta.bg_hw = bg_hw_val # Do some folder swapping to be able to reuse this function to find S4 outputs tempfolder = meta.outputdir_raw meta.outputdir_raw = meta.inputdir_raw meta.inputdir = util.pathdirectory(meta, 'S4', meta.runs[run_i], old_datetime=meta.old_datetime, ap=spec_hw_val, bg=bg_hw_val) meta.outputdir_raw = tempfolder run_i += 1 if meta.testing_S5: # Only fit a single channel while testing chanrng = [0] else: chanrng = range(meta.nspecchan) for channel in chanrng: # Create directories for Stage 5 processing outputs run = util.makedirectory(meta, 'S5', ap=spec_hw_val, bg=bg_hw_val, ch=channel) meta.outputdir = util.pathdirectory(meta, 'S5', run, ap=spec_hw_val, bg=bg_hw_val, ch=channel) # Copy existing S4 log file and resume log meta.s5_logname = meta.outputdir + 'S5_' + meta.eventlabel + ".log" log = logedit.Logedit(meta.s5_logname, read=meta.s4_logname) log.writelog("\nStarting Channel {} of {}\n".format(channel+1, meta.nspecchan)) log.writelog(f"Input directory: {meta.inputdir}") log.writelog(f"Output directory: {meta.outputdir}") # Copy ecf (and update outputdir in case S5 is being called sequentially with S4) log.writelog('Copying S5 control file') # shutil.copy(ecffile, meta.outputdir) new_ecfname = meta.outputdir + ecffile.split('/')[-1] with open(new_ecfname, 'w') as new_file: with open(ecffile, 'r') as file: for line in file.readlines(): if len(line.strip())==0 or line.strip()[0]=='#': new_file.write(line) else: line_segs = line.strip().split() if line_segs[0]=='inputdir': new_file.write(line_segs[0]+'\t\t/'+meta.inputdir+'\t'+' '.join(line_segs[2:])+'\n') else: new_file.write(line) # Set the intial fitting parameters params = p.Parameters(param_file=meta.fit_par) # Subtract off the zeroth time value to avoid floating point precision problems when fitting for t0 t_offset = int(np.floor(meta.bjdtdb[0])) t_mjdtdb = meta.bjdtdb - t_offset params.t0.value -= t_offset # Get the flux and error measurements for the current channel flux = meta.lcdata[channel,:] flux_err = meta.lcerr[channel,:] # Normalize flux and uncertainties to avoid large flux values flux_err /= flux.mean() flux /= flux.mean() if meta.testing_S5: # FINDME: Use this area to add systematics into the data # when testing new systematics models. In this case, I'm # introducing an exponential ramp to test m.ExpRampModel(). log.writelog('****Adding exponential ramp systematic to light curve****') fakeramp = m.ExpRampModel(parameters=params, name='ramp', fmt='r--') fakeramp.coeffs = np.array([-1,40,-3, 0, 0, 0]) flux *= fakeramp.eval(time=t_mjdtdb) # Load the relevant values into the LightCurve model object lc_model = lc.LightCurve(t_mjdtdb, flux, channel, meta.nspecchan, unc=flux_err, name=eventlabel, time_units=f'MJD_TDB = BJD_TDB - {t_offset}') # Make the astrophysical and detector models modellist=[] if 'transit' in meta.run_myfuncs: t_model = m.TransitModel(parameters=params, name='transit', fmt='r--') modellist.append(t_model) if 'polynomial' in meta.run_myfuncs: t_polynom = m.PolynomialModel(parameters=params, name='polynom', fmt='r--') modellist.append(t_polynom) if 'expramp' in meta.run_myfuncs: t_ramp = m.ExpRampModel(parameters=params, name='ramp', fmt='r--') modellist.append(t_ramp) model = m.CompositeModel(modellist) # Fit the models using one or more fitters log.writelog("=========================") if 'lsq' in meta.fit_method: log.writelog("Starting lsq fit.") model.fitter = 'lsq' lc_model.fit(model, meta, fitter='lsq') log.writelog("Completed lsq fit.") log.writelog("-------------------------") if 'emcee' in meta.fit_method: log.writelog("Starting emcee fit.") model.fitter = 'emcee' lc_model.fit(model, meta, fitter='emcee') log.writelog("Completed emcee fit.") log.writelog("-------------------------") if 'dynesty' in meta.fit_method: log.writelog("Starting dynesty fit.") model.fitter = 'dynesty' lc_model.fit(model, meta, fitter='dynesty') log.writelog("Completed dynesty fit.") log.writelog("-------------------------") if 'lmfit' in meta.fit_method: log.writelog("Starting lmfit fit.") model.fitter = 'lmfit' lc_model.fit(model, meta, fitter='lmfit') log.writelog("Completed lmfit fit.") log.writelog("-------------------------") log.writelog("=========================") # Plot the results from the fit(s) if meta.isplots_S5 >= 1: lc_model.plot(meta) return meta, lc_model
[ 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 15095, 11, 28686, 11, 640, 198, 6738, 11485, 8019, 1330, 6687, 15596, 355, 502, 198, 6738, 11485, 8019, 1330, 1100, 2943, 37, 355, ...
2.078504
5,159
# Copyright 2021 Sony Semiconductors Israel, Inc. All rights reserved. # # 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. # ============================================================================== from typing import Any, List from model_compression_toolkit.common.graph.base_node import BaseNode from model_compression_toolkit.common.matchers import node_matcher, walk_matcher, edge_matcher
[ 2, 15069, 33448, 10184, 311, 5314, 12920, 669, 2692, 11, 3457, 13, 1439, 2489, 10395, 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, ...
4.017857
224
#!/usr/bin/env python # -*- coding: utf-8 -*- """ The next steps use just in case to recreate the already existing DB Backup and Delete the folder "migrations" Backup and Delete the file "app.db" Execute the next console commands Linux (venv) $ export FLASK_APP=microblog.py MS Windows (venv) $ set FLASK_APP=microblog.py (venv) $ flask db init (venv) $ flask db migrate -m "initialization" (venv) $ python initialize_app_db.py ### (venv) $ flask shell (venv) $ flask run http://localhost:5000/ http://localhost:5000/index Use the function "initialize_data_into_db()" for data recreation. Use the function "remove_data_from_db()" for data deletion. Then you can simply use again the function "initialize_data_into_db()" for data recreation. """ from datetime import datetime, timedelta from app import create_app, db from app.models import User, Post from config import Config def remove_data_from_db(): """ In case of removing data... """ app = create_app(Config) app_context = app.app_context() app_context.push() db.create_all() db.session.remove() db.drop_all() app_context.pop() if __name__ == '__main__': initialize_data_into_db() # remove_data_from_db()
[ 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, 464, 1306, 4831, 779, 655, 287, 1339, 284, 32049, 262, 1541, 4683, 20137, 198, 7282, 929, 290, 23520, ...
2.850816
429
#!/usr/bin/env python3 from .kernel import Kernel from ..functions import RBFCovariance
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 6738, 764, 33885, 1330, 32169, 198, 6738, 11485, 12543, 2733, 1330, 17986, 4851, 709, 2743, 590, 628, 198 ]
3.137931
29
# -*- coding: utf-8 -*- """dependenpy finder module.""" from importlib.util import find_spec from os.path import basename, exists, isdir, isfile, join, splitext
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 45841, 268, 9078, 1064, 263, 8265, 526, 15931, 198, 198, 6738, 1330, 8019, 13, 22602, 1330, 1064, 62, 16684, 198, 6738, 28686, 13, 6978, 1330, 1615, 12453, 1...
2.8
60
import math
[ 11748, 10688, 628, 198 ]
3.5
4
# Generic/Built-in import datetime import math import os import numpy as np import matplotlib.pyplot as plt import pandas as pd import pvlib from dataclasses_json import dataclass_json from typing import Optional from dataclasses import dataclass from functools import lru_cache from hisim.simulationparameters import SimulationParameters # Owned from hisim import component as cp from hisim import loadtypes as lt from hisim import utils from hisim import log from hisim.components.weather import Weather __authors__ = "Vitor Hugo Bellotto Zago" __copyright__ = "Copyright 2021, the House Infrastructure Project" __credits__ = ["Noah Pflugradt"] __license__ = "MIT" __version__ = "0.1" __maintainer__ = "Vitor Hugo Bellotto Zago" __email__ = "vitor.zago@rwth-aachen.de" __status__ = "development" """ The functions cited in this module are at some degree based on the tsib project: [tsib-kotzur]: Kotzur, Leander, Detlef Stolten, and Hermann-Josef Wagner. Future grid load of the residential building sector. No. RWTH-2018-231872. Lehrstuhl fr Brennstoffzellen (FZ Jlich), 2019. ID: http://hdl.handle.net/2128/21115 http://nbn-resolving.org/resolver?verb=redirect&identifier=urn:nbn:de:0001-2019020614 The implementation of the tsib project can be found under the following repository: https://github.com/FZJ-IEK3-VSA/tsib """ temp_model = pvlib.temperature.TEMPERATURE_MODEL_PARAMETERS["sapm"]["open_rack_glass_glass"] def simPhotovoltaicSimple( dni_extra=None, DNI=None, DHI=None, GHI=None, azimuth=None, apparent_zenith=None, temperature=None, wind_speed=None, surface_tilt=30, surface_azimuth=180, albedo=0.2): """ Simulates a defined PV array with the Sandia PV Array Performance Model. The implementation is done in accordance with following tutorial: https://github.com/pvlib/pvlib-python/blob/master/docs/tutorials/tmy_to_power.ipynb Based on the tsib project @[tsib-kotzur] (Check header) Parameters ---------- tmy_data: pandas.DataFrame(), required Weatherfile in the format of a tmy file. surface_tilt: int or float, optional (default:30) Tilt angle of of the array in degree. surface_azimuth: int or float, optional (default:180) Azimuth angle of of the array in degree. 180 degree means south, 90 degree east and 270 west. albedo: float, optional (default: 0.2) Reflection coefficient of the surrounding area. losses: float, optional (default: 0.1) Losses due to soiling, mismatch, diode connections, dc wiring etc. load_module_data: Boolean, optional (default: False) If True the module data base is loaded from the Sandia Website. Otherwise it is loaded from this relative path '\\profiles\\PV-Modules\\sandia_modules.csv'. module_name: str, optional (default:'Hanwha_HSL60P6_PA_4_250T__2013_') Module name. The string must be existens in Sandia Module database. integrateInverter: bool, optional (default: True) If an inverter shall be added to the simulation, providing the photovoltaic output after the inverter. inverter_name: str, optional (default: 'ABB__MICRO_0_25_I_OUTD_US_208_208V__CEC_2014_') Type of inverter. Returns -------- """ # automatic pd time series in future pvlib version # calculate airmass airmass = pvlib.atmosphere.get_relative_airmass(apparent_zenith) # use perez model to calculate the plane of array diffuse sky radiation poa_sky_diffuse = pvlib.irradiance.perez( surface_tilt, surface_azimuth, DHI, np.float64(DNI), dni_extra, apparent_zenith, azimuth, airmass, ) # calculate ground diffuse with specified albedo poa_ground_diffuse = pvlib.irradiance.get_ground_diffuse( surface_tilt, GHI, albedo=albedo ) # calculate angle of incidence aoi = pvlib.irradiance.aoi(surface_tilt, surface_azimuth, apparent_zenith, azimuth) # calculate plane of array irradiance poa_irrad = pvlib.irradiance.poa_components(aoi, np.float64(DNI), poa_sky_diffuse, poa_ground_diffuse) # calculate pv cell and module temperature temp_model = pvlib.temperature.TEMPERATURE_MODEL_PARAMETERS["sapm"]["open_rack_glass_glass"] pvtemps = pvlib.temperature.sapm_cell(poa_irrad["poa_global"], temperature, wind_speed, **temp_model) pv_dc = pvlib.pvsystem.pvwatts_dc(poa_irrad["poa_global"], temp_cell=pvtemps, pdc0=1, gamma_pdc=-0.002, temp_ref=25.0) if math.isnan(pv_dc): pv_dc = 0 return pv_dc def readTRY(location="Aachen", year=2010): """ Reads a test reference year file and gets the GHI, DHI and DNI from it. Based on the tsib project @[tsib-kotzur] (Check header) Parameters ------- try_num: int (default: 4) The region number of the test reference year. year: int (default: 2010) The year. Only data for 2010 and 2030 available """ # get the correct file path filepath = os.path.join(utils.HISIMPATH["weather"][location]) # get the geoposition with open(filepath + ".dat", encoding="utf-8") as fp: lines = fp.readlines() location_name = lines[0].split(maxsplit=2)[2].replace('\n', '') lat = float(lines[1][20:37]) lon = float(lines[2][15:30]) location = {"name": location_name, "latitude": lat, "longitude": lon} # check if time series data already exists as .csv with DNI if os.path.isfile(filepath + ".csv"): data = pd.read_csv(filepath + ".csv", index_col=0, parse_dates=True,sep=";",decimal=",") data.index = pd.to_datetime(data.index, utc=True).tz_convert("Europe/Berlin") # else read from .dat and calculate DNI etc. else: # get data data = pd.read_csv( filepath + ".dat", sep=r"\s+", skiprows=([i for i in range(0, 31)]) ) data.index = pd.date_range( "{}-01-01 00:00:00".format(year), periods=8760, freq="H", tz="Europe/Berlin" ) data["GHI"] = data["D"] + data["B"] data = data.rename(columns={"D": "DHI", "t": "T", "WG": "WS"}) # calculate direct normal data["DNI"] = calculateDNI(data["B"], lon, lat) # data["DNI"] = data["B"] # save as .csv #data.to_csv(filepath + ".csv",sep=";",decimal=",") return data, location def calculateDNI(directHI, lon, lat, zenith_tol=87.0): """ Calculates the direct NORMAL irradiance from the direct horizontal irradiance with the help of the PV lib. Based on the tsib project @[tsib-kotzur] (Check header) Parameters ---------- directHI: pd.Series with time index Direct horizontal irradiance lon: float Longitude of the location lat: float Latitude of the location zenith_tol: float, optional Avoid cosines of values above a certain zenith angle of in order to avoid division by zero. Returns ------- DNI: pd.Series """ solarPos = pvlib.solarposition.get_solarposition(directHI.index, lat, lon) solarPos["apparent_zenith"][solarPos.apparent_zenith > zenith_tol] = zenith_tol DNI = directHI.div(solarPos["apparent_zenith"].apply(math.radians).apply(math.cos)) DNI = DNI.fillna(0) if DNI.isnull().values.any(): raise ValueError("Something went wrong...") return DNI
[ 2, 42044, 14, 39582, 12, 259, 198, 11748, 4818, 8079, 198, 11748, 10688, 198, 11748, 28686, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 19798, 292, 355, 279, 67, 198, 1...
2.488971
2,992
""" //////////////////////////////////////////////////////////////////////////// // // Copyright (C) NVIDIA Corporation. All rights reserved. // // NVIDIA Sample Code // // Please refer to the NVIDIA end user license agreement (EULA) associated // with this source code for terms and conditions that govern your use of // this software. Any use, reproduction, disclosure, or distribution of // this software and related documentation outside the terms of the EULA // is strictly prohibited. // //////////////////////////////////////////////////////////////////////////// """ from .loadCsvNode import LoadCsvNode from .bootstrapNode import BootstrapNode from .logReturnNode import LogReturnNode from .distanceNode import DistanceNode from .hierarchicalClusteringNode import HierarchicalClusteringNode from .hrpWeight import HRPWeightNode from .portfolioNode import PortfolioNode from .performanceMetricNode import PerformanceMetricNode from .nrpWeightNode import NRPWeightNode from .maxDrawdownNode import MaxDrawdownNode from .featureNode import FeatureNode from .aggregateTimeFeature import AggregateTimeFeatureNode from .mergeNode import MergeNode from .diffNode import DiffNode from .rSquaredNode import RSquaredNode from .shapSummaryPlotNode import ShapSummaryPlotPlotNode from .leverageNode import LeverageNode from .rawDataNode import RawDataNode from .transactionCostNode import TransactionCostNode __all__ = ["LoadCsvNode", "BootstrapNode", "LogReturnNode", "DistanceNode", "HierarchicalClusteringNode", "HRPWeightNode", "PortfolioNode", "PerformanceMetricNode", "NRPWeightNode", "MaxDrawdownNode", "FeatureNode", "AggregateTimeFeatureNode", "MergeNode", "DiffNode", "RSquaredNode", "ShapSummaryPlotPlotNode", "LeverageNode", "RawDataNode", "TransactionCostNode"]
[ 37811, 198, 3373, 49704, 49704, 16150, 1003, 198, 3373, 198, 3373, 15069, 357, 34, 8, 15127, 10501, 13, 220, 1439, 2489, 10395, 13, 198, 3373, 198, 3373, 15127, 27565, 6127, 198, 3373, 198, 3373, 4222, 3522, 284, 262, 15127, 886, 2836, ...
3.745935
492
#from http://rosettacode.org/wiki/Greatest_subsequential_sum#Python #pythran export maxsum(int list) #pythran export maxsumseq(int list) #pythran export maxsumit(int list) #runas maxsum([0, 1, 0]) #runas maxsumseq([-1, 2, -1, 3, -1]) #runas maxsumit([-1, 1, 2, -5, -6]) def maxsum(sequence): """Return maximum sum.""" maxsofar, maxendinghere = 0, 0 for x in sequence: # invariant: ``maxendinghere`` and ``maxsofar`` are accurate for ``x[0..i-1]`` maxendinghere = max(maxendinghere + x, 0) maxsofar = max(maxsofar, maxendinghere) return maxsofar
[ 2, 6738, 2638, 1378, 305, 17744, 330, 1098, 13, 2398, 14, 15466, 14, 13681, 395, 62, 7266, 3107, 1843, 62, 16345, 2, 37906, 198, 2, 79, 5272, 2596, 10784, 3509, 16345, 7, 600, 1351, 8, 198, 2, 79, 5272, 2596, 10784, 3509, 16345, 4...
2.363636
253
__all__ = ["Binwalk"] import os import re import time import magic from binwalk.compat import * from binwalk.config import * from binwalk.update import * from binwalk.filter import * from binwalk.parser import * from binwalk.plugins import * from binwalk.plotter import * from binwalk.hexdiff import * from binwalk.entropy import * from binwalk.extractor import * from binwalk.prettyprint import * from binwalk.smartstrings import * from binwalk.smartsignature import * from binwalk.common import file_size, unique_file_name, BlockFile
[ 834, 439, 834, 796, 14631, 33, 259, 11152, 8973, 198, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 640, 198, 11748, 5536, 198, 6738, 9874, 11152, 13, 5589, 265, 1330, 1635, 198, 6738, 9874, 11152, 13, 11250, 1330, 1635, 198, 6738, ...
3.426752
157
def task_clean_junk(): """Remove junk file""" return { 'actions': ['rm -rdf $(find . | grep pycache)'], 'clean': True, }
[ 4299, 4876, 62, 27773, 62, 73, 2954, 33529, 198, 220, 220, 220, 37227, 27914, 18556, 2393, 37811, 198, 220, 220, 220, 1441, 1391, 198, 220, 220, 220, 220, 220, 220, 220, 705, 4658, 10354, 37250, 26224, 532, 4372, 69, 29568, 19796, 764...
2.223881
67
#Uses python3 import sys if __name__ == '__main__': #input = sys.stdin.read() data = input().split(' ') a = data[1:] print(largest_number(a))
[ 2, 5842, 274, 21015, 18, 198, 198, 11748, 25064, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1303, 15414, 796, 25064, 13, 19282, 259, 13, 961, 3419, 198, 220, 220, 220, 1366, 796, 5128, 22...
2.2
75
import logging import subprocess profiles = { 'none': ScreenBlankProfileNone(), 'balanced': ScreenBlankProfileBalanced(), 'onoff': ScreenBlankProfileOnWhenPlaying() }
[ 11748, 18931, 198, 11748, 850, 14681, 628, 628, 628, 628, 198, 5577, 2915, 796, 1391, 198, 220, 220, 220, 705, 23108, 10354, 15216, 3629, 962, 37046, 14202, 22784, 198, 220, 220, 220, 705, 27753, 10354, 15216, 3629, 962, 37046, 24597, 2...
3.065574
61