content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
from django.shortcuts import render, render_to_response, redirect from django.http import HttpResponse, HttpResponseRedirect, JsonResponse, FileResponse from django.urls import reverse import os from django.contrib.auth import authenticate, login, logout # from django.contrib import auth from django.template import RequestContext from .forms import LoginForm, RegistrationForm from django.contrib.auth.models import User import hashlib # python from django.contrib.auth.hashers import make_password, check_password # Django from django.core.mail import send_mail import imghdr # import time, datetime from django.conf import settings from .models import Pictures # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_DIR = "common_static" GPU_ISACTIVATED = True # Create your views here. # ip # # #
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 11, 8543, 62, 1462, 62, 26209, 11, 18941, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 31077, 11, 367, 29281, 31077, 7738, 1060, 11, 449, 1559, 31077, 11, 9220, 31077, 198, 6738,...
3.195876
291
#!/usr/bin/env python3 from Spot import * import time from bosdyn.client import math_helpers if __name__ == '__main__': spot = Spot() try: # It's ALIVE! spot.power_on() spot.move_to(1.0, 0.0, 0.0, math_helpers.Quat(), duration=5.0) time.sleep(5.0) spot.move_to(0.0, 1.0, 0.0, math_helpers.Quat(), duration=5.0) time.sleep(5.0) spot.move_to(-1.0, 0.0, 0.0, math_helpers.Quat(), duration=5.0) time.sleep(5.0) spot.move_to(0.0, -1.0, 0.0, math_helpers.Quat(), duration=5.0) time.sleep(5.0) # Power down spot.estop(graceful=True) except: print('Exception') print('Trying to make Python GC the Spot object') spot = None time.sleep(5.0) exit(0)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 6738, 15899, 1330, 1635, 198, 11748, 640, 198, 6738, 37284, 67, 2047, 13, 16366, 1330, 10688, 62, 16794, 364, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 1035...
1.947631
401
import pytest from tennis_probability import set, InvalidInput, InvalidProbability, NegativeNumber
[ 11748, 12972, 9288, 198, 6738, 20790, 62, 1676, 65, 1799, 1330, 900, 11, 17665, 20560, 11, 17665, 2964, 65, 1799, 11, 36183, 15057, 628 ]
4.166667
24
from abc import ABC, abstractmethod from typing import Dict, Any, Callable from kombu import Message from classic.components import component MessageBody = Dict[str, Any]
[ 6738, 450, 66, 1330, 9738, 11, 12531, 24396, 198, 6738, 19720, 1330, 360, 713, 11, 4377, 11, 4889, 540, 198, 198, 6738, 479, 2381, 84, 1330, 16000, 198, 198, 6738, 6833, 13, 5589, 3906, 1330, 7515, 628, 198, 12837, 25842, 796, 360, ...
3.54
50
""" byceps.services.shop.order.event_service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from __future__ import annotations from datetime import datetime from typing import Sequence from ....database import db from .dbmodels.order_event import OrderEvent as DbOrderEvent, OrderEventData from .transfer.models import OrderID def create_event( event_type: str, order_id: OrderID, data: OrderEventData ) -> None: """Create an order event.""" event = build_event(event_type, order_id, data) db.session.add(event) db.session.commit() def create_events( event_type: str, order_id: OrderID, datas: Sequence[OrderEventData] ) -> None: """Create a sequence of order events.""" events = [build_event(event_type, order_id, data) for data in datas] db.session.add_all(events) db.session.commit() def build_event( event_type: str, order_id: OrderID, data: OrderEventData ) -> DbOrderEvent: """Assemble, but not persist, an order event.""" now = datetime.utcnow() return DbOrderEvent(now, event_type, order_id, data) def get_events_for_order(order_id: OrderID) -> list[DbOrderEvent]: """Return the events for that order.""" return db.session \ .query(DbOrderEvent) \ .filter_by(order_id=order_id) \ .order_by(DbOrderEvent.occurred_at) \ .all()
[ 37811, 198, 1525, 344, 862, 13, 30416, 13, 24643, 13, 2875, 13, 15596, 62, 15271, 198, 27156, 27156, 15116, 198, 198, 25, 15269, 25, 4793, 12, 1238, 2481, 449, 420, 831, 509, 7211, 364, 354, 21184, 198, 25, 34156, 25, 31492, 347, 10...
2.823529
510
from attr import attrs, attrib import enum from .enum import EnumColumn
[ 6738, 708, 81, 1330, 708, 3808, 11, 708, 822, 198, 11748, 33829, 198, 198, 6738, 764, 44709, 1330, 2039, 388, 39470, 198 ]
3.318182
22
import config import os import pandas as pd import numpy as np from torch.utils.data import Dataset, DataLoader from PIL import Image from tqdm import tqdm if __name__ == "__main__": """ Test if everything works ok """ dataset = DRDataset( images_folder="/data/images_resized_650", path_to_csv="/data/trainLabels.csv", transform = config.val_transforms ) loader = DataLoader( dataset=dataset, batch_size=32, num_workers=6, shuffle=True, pin_memory=True ) for x, label, file in tqdm(loader): print(x.shape) print(label.shape) import sys sys.exit
[ 11748, 4566, 198, 11748, 28686, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 28034, 13, 26791, 13, 7890, 1330, 16092, 292, 316, 11, 6060, 17401, 198, 6738, 350, 4146, 1330, 7412, 198, 6738, 256, ...
2.373626
273
from flask import Flask, request, jsonify import util app= Flask(__name__) if __name__ == "__main__": print("Starting Python Flask Server For Celebrity Image Classification") util.load_saved_artifacts() app.run(port=5000)
[ 6738, 42903, 1330, 46947, 11, 2581, 11, 33918, 1958, 201, 198, 11748, 7736, 201, 198, 1324, 28, 46947, 7, 834, 3672, 834, 8, 201, 198, 201, 198, 201, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 201, 198, 220, 220, ...
2.872093
86
from blogsley_site.app import create_app
[ 6738, 19118, 1636, 62, 15654, 13, 1324, 1330, 2251, 62, 1324, 198 ]
3.416667
12
# Generated by Django 3.2 on 2021-12-12 18:38 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 17, 319, 33448, 12, 1065, 12, 1065, 1248, 25, 2548, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.966667
30
""" Test to measure pvc scale creation time. Total pvc count would be 50, 1 clone per PVC Total number of clones in bulk will be 50 """ import logging import pytest from ocs_ci.utility import utils from ocs_ci.ocs.perftests import PASTest from ocs_ci.framework.testlib import performance from ocs_ci.helpers import helpers, performance_lib from ocs_ci.ocs import constants, scale_lib from ocs_ci.ocs.resources import pvc, pod from ocs_ci.ocs.resources.objectconfigfile import ObjectConfFile log = logging.getLogger(__name__)
[ 37811, 198, 14402, 284, 3953, 279, 28435, 5046, 6282, 640, 13, 7472, 279, 28435, 954, 561, 307, 2026, 11, 352, 17271, 583, 46377, 198, 14957, 1271, 286, 32498, 287, 11963, 481, 307, 2026, 198, 37811, 198, 11748, 18931, 198, 11748, 12972...
3.2
165
from .database import db from .user import User from .post import Post
[ 6738, 764, 48806, 1330, 20613, 198, 198, 6738, 764, 7220, 1330, 11787, 198, 6738, 764, 7353, 1330, 2947, 198 ]
3.789474
19
import argparse from genericpath import exists import os import time import re from tqdm import tqdm import numpy as np from scipy.io import wavfile from wiener_scalart import wienerScalart TIME = time.strftime("%Y-%m-%d_%H:%M:%S", time.localtime()) CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) WORKPLACE_DIR = os.path.dirname(CURRENT_DIR) DUMP_DIR = os.path.join(WORKPLACE_DIR, os.path.join('dump', TIME)) DUMP_FEAT = 'feat_{}.scp'.format(TIME) DUMP_TEXT = 'text_{}'.format(TIME) FEAT_FORMAT = r'\s?(.+?)\s+(.+?\.wav)' intMap = {np.dtype('int8') : (0x7f, -0x80), np.dtype('int16') : (0x7fff, -0x8000), np.dtype('int32') : (0x7fffffff, -0x8000000), np.dtype('int64') : (0x7fffffffffffffff, -0x8000000000000000)} if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-f', '--feat', type=str, default=None, help='feat file path') parser.add_argument('-t', '--text', type=str, default=None, help='text file path') parser.add_argument('-dd', '--dumpDir', type=str, default=DUMP_DIR, help='the directory where holds new .wav files') parser.add_argument('-df', '--dumpFeat', type=str, default=os.path.join(DUMP_DIR, DUMP_FEAT), help='dump feat file path') parser.add_argument('-dt', '--dumpText', type=str, default=os.path.join(DUMP_DIR, DUMP_TEXT), help='dump text file path') parser.add_argument('-n', '--noiseLength', type=float, default=0.25, help='the noise time length at the beggining of the audio') parser.add_argument('-db', '--debug', action='store_true', help='print debug message') args = parser.parse_args() main(args)
[ 11748, 1822, 29572, 198, 6738, 14276, 6978, 1330, 7160, 198, 11748, 28686, 198, 11748, 640, 198, 11748, 302, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 13, 952, 1330, ...
2.488654
661
#Import libraries import random import os import noise import numpy import math import sys from chunks import Chunks as chk from PIL import Image import subprocess from scipy.misc import toimage import threading random.seed(os.urandom(6)) #Delete old chunks filelist = [ f for f in os.listdir("world/") if f.endswith(".chunk") ] #Delete previous world files for f in filelist: os.remove(os.path.join("world/", f)) #Functions #Colours dwaterCol = [54, 137, 245] waterCol = [67, 146, 245] dsandCol = [224, 214, 164] sandCol = [247, 232, 176] rockCol = [209, 209, 209] grassCol = [37, 170, 77] dgrassCol = [34, 161, 63] treeCol = [10, 122, 42] mountCol = [74, 62, 36] mountRockCol = [56, 48, 30] snowCol = [245, 254, 255] #Control Variables a = sys.argv if len(a) > 1: gridSize = int(a[1]) scale = float(a[2]) octaves = int(a[3]) persistance = float(a[4]) lacunarity = float(a[5]) thres = float(a[6]) else: gridSize = 1024 #Side length scale = 250.0 octaves = 6 persistance = 0.5 lacunarity = 2.0 thres = 0.08 #Generate base noise, Apply gradient im = Image.open("gradient/circle_grad.png") circle_grad = im.convert("L") main = numpy.zeros((gridSize,gridSize)) #Init arrays mainNoise = numpy.zeros_like(main) seed = random.randint(0,200) #Gen seed for y in range(gridSize): for x in range(gridSize): main[y][x] = noise.pnoise2(y/scale,x/scale,octaves=octaves,persistence=persistance,lacunarity=lacunarity,repeatx=gridSize,repeaty=gridSize,base=seed) #Set noise mainNoise[y][x] = (main[y][x] * mapVal(circle_grad.getpixel((round((1024/gridSize)*x),round((1024/gridSize)*y))), 0, 255, -0.05, 1)) #Apply gradient to noise if mainNoise[y][x] > 0: mainNoise[y][x] *= 20 #Amplify max_grad = numpy.max(mainNoise) mainNoise = mainNoise / max_grad #Weird even out math thing #Lay base display = numpy.zeros((gridSize//16,gridSize//16)+(16,16)+(3,)) processed = numpy.zeros((gridSize//16,gridSize//16), dtype=bool) passOver = numpy.zeros((gridSize//16,gridSize//16), dtype=bool) import time start = time.time() for cy in range(gridSize//16): for cx in range(gridSize//16): print(str(cy) + " " + str(cx)) if processed[cy][cx] == False: processed[cy][cx] = True for y in range(16): for x in range(16): m = mainNoise[y + (16*cy)][x + (16*cx)] #Set iterator to value of main array and check if meets certain thresholds to set colours if m < thres + 0.015: m = dwaterCol elif m < thres + 0.11: m = waterCol elif m < thres + 0.12: m = dsandCol passOver[cy][cx] = True elif m < thres + 0.15: m = sandCol passOver[cy][cx] = True elif m < thres + 0.28: m = grassCol passOver[cy][cx] = True elif m < thres + 0.46: m = dgrassCol passOver[cy][cx] = True elif m < thres + 0.78: m = mountCol passOver[cy][cx] = True elif m < thres + 1.0: m = snowCol passOver[cy][cx] = True display[cy][cx][y][x] = m #Second pass (Natural features) featSeed = random.randint(0,100) #Generate seed for cy in range(gridSize//16): for cx in range(gridSize//16): if passOver[cy][cx] == True: for y in range(16): for x in range(16): m = display[cy][cx][y][x] p = noise.pnoise2((y + (cy * 16))/(scale/2.5),(x + (cx * 16))/(scale/2.5),octaves=10,persistence=0.55,lacunarity=1.55,repeatx=gridSize,repeaty=gridSize,base=featSeed) #Get pond noise if all(m == grassCol) or all(m == dsandCol) or all(m == sandCol): #If light grass or beach generate pond if p > 0.17: if p < 0.25: m = sandCol elif p < 1.0: m = waterCol display[cy][cx][y][x] = m #Third pass (Structures) structScale = int(scale // 200) for cy in range(gridSize//16): for cx in range(gridSize//16): if passOver[cy][cx] == True: for y in range(16): for x in range(16): #Place rocks on beach and mountnain m = display[cy][cx][y][x] if all(m == sandCol): if percentChance(2) == True: addRock(display,cx,cy,x,y,structScale,rockCol) elif all(m == grassCol): if percentChance(5) == True: addTree(display,cx,cy,x,y,structScale) elif all(m == dgrassCol): if percentChance(20) == True: addTree(display,cx,cy,x,y,structScale) elif all(m == mountCol): if percentChance(0.01) == True: addRock(display,cx,cy,x,y,structScale,mountRockCol) #Save for cy in range(gridSize//16): for cx in range(gridSize//16): chk.writeChunk(cx,cy,display) #Display toimage(chk.readChunkArray(gridSize,display)).show()
[ 2, 20939, 12782, 198, 198, 11748, 4738, 198, 11748, 28686, 198, 11748, 7838, 198, 11748, 299, 32152, 198, 11748, 10688, 198, 11748, 25064, 198, 6738, 22716, 1330, 609, 14125, 355, 442, 74, 198, 6738, 350, 4146, 1330, 7412, 198, 11748, 8...
1.883895
2,937
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. import logging import numpy.testing as npt from reagent.core.parameters import ProblemDomain from reagent.gym.envs import Gym from reagent.gym.envs.wrappers.simple_minigrid import SimpleObsWrapper from reagent.gym.utils import create_df_from_replay_buffer from reagent.preprocessing.sparse_to_dense import PythonSparseToDenseProcessor from reagent.test.base.horizon_test_base import HorizonTestBase logger = logging.getLogger(__name__)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 15069, 357, 66, 8, 3203, 11, 3457, 13, 290, 663, 29116, 13, 1439, 2489, 10395, 13, 198, 11748, 18931, 198, 198, 11748, 299, 32152, 13, 33407, 355, 299, 457, 198, 6738, 302, ...
3.184524
168
from parser.readfile import ReadFile
[ 6738, 30751, 13, 961, 7753, 1330, 4149, 8979, 198 ]
4.111111
9
#!/usr/bin/env python # coding: utf-8 # In[1]: import requests from datetime import timezone from datetime import timedelta from datetime import datetime import hhu import os # In[2]: utc_time = datetime.utcnow().replace(tzinfo=timezone.utc) sh_tz = timezone(timedelta(hours=8),name='Asia/Shanghai') beijing_now = utc_time.astimezone(sh_tz) datestr = datetime.strftime(beijing_now,'%F') timestr = datetime.strftime(beijing_now,'%H:%M:%S') year = datestr[0:4] month = datestr[5:7] day = datestr[8:10] time = timestr hhu.hhu()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 2, 554, 58, 16, 5974, 628, 198, 11748, 7007, 198, 6738, 4818, 8079, 1330, 640, 11340, 198, 6738, 4818, 8079, 1330, 28805, 12514, 198, 6738, ...
2.399103
223
import pickle import stanza import test_stuff from datetime import datetime from dictionary import cd, dictionary, nlp_dictionary, ph_outcome, ph_key, ph_value, ph_dvalue, ph_subject import eric_nlp #does not do preprocessing ''' creates a matrix with: columns: roots rows: count how often that root occurs for a function ''' #all_roots is a dict from words to another dict from function ids to ints #roots is expected to be a dict from words to ints #attempt 1: how many nodes do they share, regardless of node depth #a tree is a list of dictionarys. every dictionary represents a word of the sentence. key-value-pairs are the attributes of that word. ''' takes a tuple as in "deprel" in dictionary.nlp_dictionary. returns list of tuples. if master_tuple was a simple tuple, the list only contains that tuple if master_tuple has lists as elements, these get split so that every tuple in the returned list has only strings as elements Example: in: (["predict", "divinate"], "obl", ["data", "person"]) out: [ ("predict", "obl", "data"), ("predict", "obl", "person"), ("divinate", "obl", "data"), ("divinate", "obl", "person") ] note: returning list has x elements with x being the product of all three lengths. (here 2*1*2 = 4) ''' ''' takes a word-object of a depparse-word and a string element from a tuple (not a list-element. use generate_sub_tuples() first) checks if dictionary.cd (by default "#") is in tuple_element. If so, it extracts which attribute (i.e. in front of "#") is wanted. then returns the corresponding attribute value of word_object and the part right of "#" in tuple_element if "#" was not in tuple_element, it returns tuple_element as it is and the default attribute of word_object also needs an eric, to invoke replacement of placeholders ''' ''' word_attribute should be from the user input, tuple_attribute one element of a tuple from the depparse templates in dictionary.nlp_dictionary it's called attribute, not element because it should only be called at the end of get_comparison_attributes() which extracts attributes from word objects (e.g. the lemma, upos or deprel, etc.) word_attribute needs to be included even though it will not have any placeholders. In the case, that "<outcome>" is in tuple_attribute, word_attribute needs to be checked if it is a different form of the possible outcomes. This gets checked via the eric.model_columns["class"]["phrasings"] dict which has all possible outcomes as keys (here "survived" and "died") and stores different forms of those as the values of that dict as list. Here ["survive", "survives"] and ["die", "dies"]. ''' replace_depparse_placeholders("", "", "") #looks for the head/mother node of word in tree and returns it (or a representing dictionary if head is root). #returns dict since root is not really represented in the word objects of depparse #takes a depparse tree t and goes through the depparse tree templates in dictionary.nlp_dictionary #returns a list of tuples (fct_id, tree template) with a tuple for every found match. #expects a list of tuples with two elements each: 1st fct_id, 2nd the tree template that matched, i.e. a list of tuples #that list should represend a ranking from most likely (lowest index) to least likey (highest index) #it then goes through all templates and sorts them into templates that contain a lemma:not and and those that do not #then creates a ranking again for both, separately #then, both lists get concatenated with the negated tuples at the lower indices. So a short but negated template will have priority over a longer, non-negated one #returns that list #t is a tree like in tree_compare(t1, t2) ''' if you thought of new sentence while analysing the output and just depparsed them over debug console and included them in the output_file, this function will help. It can read your originally used input again, then the output file, compare sentences and store all new ones, i.e. the manually analysed sentences in a new input_file. Also, it will then overwrite the output file to update the root counts ''' if __name__ == "__main__": #main() debug_depparsed_sentences_to_console() quit() lines = test_stuff.read_input_from_file("data\\wrongly_accused.txt") sentences = [x[1] for x in lines] for s in sentences: print(s) print("//////////") sp = init_stanza("en") out, root = depparse(sentences, sp) test_stuff.list_to_file(out, "output\\depparse\\wrongly_accused_out.txt") quit() #test_some_sentences() for d in nlp_dictionary: print(d["id"]) try: x = d['depparse'][0] print("\t---") except Exception as e: print("\tNOTHING") sp = init_stanza("en") input_files = [f"data\\umfrage_input_{x}_cleaned.txt" for x in range(1,5)] fct = "whatif-gl" update_depparse_output(input_files, f"output\\depparse\\{fct}.txt", fct, "data\\manually_added.txt", sp=sp)
[ 11748, 2298, 293, 198, 11748, 336, 35819, 198, 11748, 1332, 62, 41094, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 22155, 1330, 22927, 11, 22155, 11, 299, 34431, 62, 67, 14188, 11, 872, 62, 448, 2958, 11, 872, 62, 2539, 11, ...
3.157862
1,590
# coding: utf-8 import torch.nn as nn
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 11748, 28034, 13, 20471, 355, 299, 77, 628 ]
2.4375
16
# coding=utf-8 #! /usr/bin/env python3.4 """ MIT License Copyright (c) 2018 NLX-Group 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. This code reads wordnet data and index files data_file_reader(file_name): extract data from wordnet data files saved in "data/input" directory output is 1- a dictionary with key = synsetoffsets data = (synsetWrds, synsetConnections, synsetRelationTypes, connectedSynsetPos, gloss) 2- and offset_list Chakaveh.saedi@di.fc.ul.pt """ import os, sys import numpy as np from progressbar import ProgressBar, Percentage, Bar
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 18, 13, 19, 198, 198, 37811, 198, 36393, 13789, 198, 198, 15269, 357, 66, 8, 2864, 22879, 55, 12, 13247, 198, 198, 5990, 3411, 318, 29376, 7520, 11, ...
3.432018
456
"""Module for testing formats on resources entities""" from raviewer.src.core import (get_displayable, load_image, parse_image) from terminaltables import AsciiTable from raviewer.image.color_format import AVAILABLE_FORMATS import os import pkg_resources import time import pytest def test_all(formats): """Test all formats""" print("Testing all formats, It may take a while...") table_data = [["Format", "Passed", "Performance"]] start_range = 800 end_range = 810 for color_format in formats.keys(): file_path = pkg_resources.resource_filename('resources', color_format + "_1000_750") passed_results = 0 format_performance = 0 start = time.time() for width in range(start_range, end_range): try: if not os.path.exists(file_path): break img = load_image(file_path) img = parse_image(img.data_buffer, color_format, width) get_displayable(img) passed_results += 1 except: continue end = time.time() #Stats format_performance = "{:.3f}".format(round(end - start, 3)) table_data.append([ color_format, "{}/{}".format(passed_results, end_range - start_range), format_performance ]) table = AsciiTable(table_data) table.title = 'Test all formats' print(table.table)
[ 37811, 26796, 329, 4856, 17519, 319, 4133, 12066, 37811, 198, 198, 6738, 24343, 769, 263, 13, 10677, 13, 7295, 1330, 357, 1136, 62, 13812, 540, 11, 3440, 62, 9060, 11, 21136, 62, 9060, 8, 198, 6738, 5651, 2501, 2977, 1330, 1081, 979, ...
2.136111
720
from flask import request from flask import redirect from flask import session from flask import url_for from functools import wraps
[ 6738, 42903, 1330, 2581, 198, 6738, 42903, 1330, 18941, 198, 6738, 42903, 1330, 6246, 198, 6738, 42903, 1330, 19016, 62, 1640, 198, 6738, 1257, 310, 10141, 1330, 27521, 628, 198 ]
4.5
30
import math import torch from typing import Union, Optional, Tuple from dqc.utils.datastruct import ZType eps = 1e-12 ########################## safe operations ########################## ########################## occupation number gradients ########################## ########################## other tensor ops ########################## def safe_cdist(a: torch.Tensor, b: torch.Tensor, add_diag_eps: bool = False, diag_inf: bool = False): # returns the L2 pairwise distance of a and b # a: (*BA, na, ndim) # b: (*BB, nb, ndim) # returns: (*BAB, na, nb) square_mat = a.shape[-2] == b.shape[-2] dtype = a.dtype device = a.device ab = a.unsqueeze(-2) - b.unsqueeze(-3) # (*BAB, na, nb, ndim) # add the diagonal with a small eps to safeguard from nan if add_diag_eps: if not square_mat: raise ValueError("Enabling add_diag_eps for non-square result matrix is invalid") ab = ab + torch.eye(ab.shape[-2], dtype=dtype, device=device).unsqueeze(-1) * eps ab = ab.norm(dim=-1) # (*BAB, na, nb) # replace the diagonal with infinite (usually used for coulomb matrix) if diag_inf: if not square_mat: raise ValueError("Enabling diag_inf for non-square result matrix is invalid") infdiag = torch.eye(ab.shape[-1], dtype=dtype, device=device) idiag = infdiag.diagonal() idiag[:] = float("inf") ab = ab + infdiag return ab
[ 11748, 10688, 198, 11748, 28034, 198, 6738, 19720, 1330, 4479, 11, 32233, 11, 309, 29291, 198, 6738, 288, 80, 66, 13, 26791, 13, 19608, 459, 1356, 1330, 1168, 6030, 198, 198, 25386, 796, 352, 68, 12, 1065, 198, 198, 14468, 7804, 2235,...
2.528302
583
import numpy as np import gym from gym import spaces from gym.utils import seeding
[ 11748, 299, 32152, 355, 45941, 198, 11748, 11550, 198, 6738, 11550, 1330, 9029, 198, 6738, 11550, 13, 26791, 1330, 384, 8228, 198 ]
3.772727
22
from __future__ import print_function, division, absolute_import from odin import nnet as N, backend as K import tensorflow as tf
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 11, 7297, 11, 4112, 62, 11748, 198, 198, 6738, 16298, 259, 1330, 299, 3262, 355, 399, 11, 30203, 355, 509, 198, 11748, 11192, 273, 11125, 355, 48700, 628, 628, 628 ]
3.578947
38
active_account = None
[ 5275, 62, 23317, 796, 6045, 628 ]
3.833333
6
from orator import Model import pendulum
[ 6738, 393, 1352, 1330, 9104, 198, 11748, 44017, 14452, 628 ]
4.2
10
import os import sys joinp = os.path.join sys.path.insert(0, 'whitgl') sys.path.insert(0, joinp('whitgl', 'input')) import build sys.path.insert(0, 'input') import ninja_syntax build.do_game('Game', '', ['png','ogg'])
[ 11748, 28686, 198, 11748, 25064, 198, 22179, 79, 796, 28686, 13, 6978, 13, 22179, 198, 17597, 13, 6978, 13, 28463, 7, 15, 11, 705, 1929, 270, 4743, 11537, 198, 17597, 13, 6978, 13, 28463, 7, 15, 11, 4654, 79, 10786, 1929, 270, 4743,...
2.47191
89
import hashlib import struct from dataclasses import dataclass, field from typing import Dict, List, Union from factom_core.block_elements.balance_increase import BalanceIncrease from factom_core.block_elements.chain_commit import ChainCommit from factom_core.block_elements.entry_commit import EntryCommit from factom_core.utils import varint from .directory_block import DirectoryBlock ECIDTypes = Union[ChainCommit, EntryCommit, int]
[ 11748, 12234, 8019, 198, 11748, 2878, 198, 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 11, 2214, 198, 6738, 19720, 1330, 360, 713, 11, 7343, 11, 4479, 198, 198, 6738, 1109, 296, 62, 7295, 13, 9967, 62, 68, 3639, 13, 20427, 62, 2...
3.544
125
test = { 'name': 'q0', 'points': 0, 'suites': []}
[ 9288, 796, 1391, 220, 220, 705, 3672, 10354, 705, 80, 15, 3256, 198, 220, 220, 220, 705, 13033, 10354, 657, 11, 198, 220, 220, 220, 705, 2385, 2737, 10354, 17635, 92 ]
1.903226
31
#========================================================================= # inst_utils #========================================================================= # Includes helper functions to simplify creating assembly tests. from pymtl import * from tests.context import lizard #------------------------------------------------------------------------- # print_asm #------------------------------------------------------------------------- # Pretty print a generated assembly syntax #------------------------------------------------------------------------- # gen_nops #------------------------------------------------------------------------- #------------------------------------------------------------------------- # gen_word_data #------------------------------------------------------------------------- #------------------------------------------------------------------------- # gen_hword_data #------------------------------------------------------------------------- #------------------------------------------------------------------------- # gen_byte_data #------------------------------------------------------------------------- #------------------------------------------------------------------------- # gen_rr_src01_template #------------------------------------------------------------------------- # Template for register-register instructions. We first write src0 # register and then write the src1 register before executing the # instruction under test. We parameterize the number of nops after # writing both src registers and the instruction under test to enable # using this template for testing various bypass paths. We also # parameterize the register specifiers to enable using this template to # test situations where the srce registers are equal and/or equal the # destination register. #------------------------------------------------------------------------- # gen_rr_src10_template #------------------------------------------------------------------------- # Similar to the above template, except that we reverse the order in # which we write the two src registers. #------------------------------------------------------------------------- # gen_rr_dest_dep_test #------------------------------------------------------------------------- # Test the destination bypass path by varying how many nops are # inserted between the instruction under test and reading the destination # register with a csrr instruction. #------------------------------------------------------------------------- # gen_rr_src1_dep_test #------------------------------------------------------------------------- # Test the source 1 bypass paths by varying how many nops are inserted # between writing the src1 register and reading this register in the # instruction under test. #------------------------------------------------------------------------- # gen_rr_src0_dep_test #------------------------------------------------------------------------- # Test the source 0 bypass paths by varying how many nops are inserted # between writing the src0 register and reading this register in the # instruction under test. #------------------------------------------------------------------------- # gen_rr_srcs_dep_test #------------------------------------------------------------------------- # Test both source bypass paths at the same time by varying how many nops # are inserted between writing both src registers and reading both # registers in the instruction under test. #------------------------------------------------------------------------- # gen_rr_src0_eq_dest_test #------------------------------------------------------------------------- # Test situation where the src0 register specifier is the same as the # destination register specifier. #------------------------------------------------------------------------- # gen_rr_src1_eq_dest_test #------------------------------------------------------------------------- # Test situation where the src1 register specifier is the same as the # destination register specifier. #------------------------------------------------------------------------- # gen_rr_src0_eq_src1_test #------------------------------------------------------------------------- # Test situation where the src register specifiers are the same. #------------------------------------------------------------------------- # gen_rr_srcs_eq_dest_test #------------------------------------------------------------------------- # Test situation where all three register specifiers are the same. #------------------------------------------------------------------------- # gen_rr_value_test #------------------------------------------------------------------------- # Test the actual operation of a register-register instruction under # test. We assume that bypassing has already been tested. #------------------------------------------------------------------------- # gen_rimm_template #------------------------------------------------------------------------- # Template for register-immediate instructions. We first write the src # register before executing the instruction under test. We parameterize # the number of nops after writing the src register and the instruction # under test to enable using this template for testing various bypass # paths. We also parameterize the register specifiers to enable using # this template to test situations where the srce registers are equal # and/or equal the destination register. #------------------------------------------------------------------------- # gen_rimm_dest_dep_test #------------------------------------------------------------------------- # Test the destination bypass path by varying how many nops are # inserted between the instruction under test and reading the destination # register with a csrr instruction. #------------------------------------------------------------------------- # gen_rimm_src_dep_test #------------------------------------------------------------------------- # Test the source bypass paths by varying how many nops are inserted # between writing the src register and reading this register in the # instruction under test. #------------------------------------------------------------------------- # gen_rimm_src_eq_dest_test #------------------------------------------------------------------------- # Test situation where the src register specifier is the same as the # destination register specifier. #------------------------------------------------------------------------- # gen_rimm_value_test #------------------------------------------------------------------------- # Test the actual operation of a register-immediate instruction under # test. We assume that bypassing has already been tested. #------------------------------------------------------------------------- # gen_imm_template #------------------------------------------------------------------------- # Template for immediate instructions. We parameterize the number of nops # after the instruction under test to enable using this template for # testing various bypass paths. #------------------------------------------------------------------------- # gen_imm_dest_dep_test #------------------------------------------------------------------------- # Test the destination bypass path by varying how many nops are # inserted between the instruction under test and reading the destination # register with a csrr instruction. #------------------------------------------------------------------------- # gen_imm_value_test #------------------------------------------------------------------------- # Test the actual operation of an immediate instruction under test. We # assume that bypassing has already been tested. #------------------------------------------------------------------------- # gen_br2_template #------------------------------------------------------------------------- # Template for branch instructions with two sources. We test two forward # branches and one backwards branch. The way we actually do the test is # we update a register to reflect the control flow; certain bits in this # register are set at different points in the program. Then we can check # the control flow bits at the end to see if only the bits we expect are # set (i.e., the program only executed those points that we expect). Note # that test also makes sure that the instruction in the branch delay slot # is _not_ executed. # We currently need the id to create labels unique to this test. We might # eventually allow local labels (e.g., 1f, 1b) as in gas. gen_br2_template_id = 0 #------------------------------------------------------------------------- # gen_br2_src1_dep_test #------------------------------------------------------------------------- # Test the source 1 bypass paths by varying how many nops are inserted # between writing the src1 register and reading this register in the # instruction under test. #------------------------------------------------------------------------- # gen_br2_src0_dep_test #------------------------------------------------------------------------- # Test the source 0 bypass paths by varying how many nops are inserted # between writing the src0 register and reading this register in the # instruction under test. #------------------------------------------------------------------------- # gen_br2_srcs_dep_test #------------------------------------------------------------------------- # Test both source bypass paths at the same time by varying how many nops # are inserted between writing both src registers and reading both # registers in the instruction under test. #------------------------------------------------------------------------- # gen_br2_src0_eq_src1_test #------------------------------------------------------------------------- # Test situation where the src register specifiers are the same. #------------------------------------------------------------------------- # gen_br2_value_test #------------------------------------------------------------------------- # Test the correct branch resolution based on various source values. # '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' gen_jal_template_id = 0 #------------------------------------------------------------------------- # gen_ld_template #------------------------------------------------------------------------- # Template for load instructions. We first write the base register before # executing the instruction under test. We parameterize the number of # nops after writing the base register and the instruction under test to # enable using this template for testing various bypass paths. We also # parameterize the register specifiers to enable using this template to # test situations where the base register is equal to the destination # register. #------------------------------------------------------------------------- # gen_ld_dest_dep_test #------------------------------------------------------------------------- # Test the destination bypass path by varying how many nops are # inserted between the instruction under test and reading the destination # register with a csrr instruction. #------------------------------------------------------------------------- # gen_ld_base_dep_test #------------------------------------------------------------------------- # Test the base register bypass paths by varying how many nops are # inserted between writing the base register and reading this register in # the instruction under test. #------------------------------------------------------------------------- # gen_ld_base_eq_dest_test #------------------------------------------------------------------------- # Test situation where the base register specifier is the same as the # destination register specifier. #------------------------------------------------------------------------- # gen_ld_value_test #------------------------------------------------------------------------- # Test the actual operation of a register-register instruction under # test. We assume that bypassing has already been tested. # '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' #------------------------------------------------------------------------- # gen_st_template #------------------------------------------------------------------------- # Template for load instructions. We first write the base register before # executing the instruction under test. We parameterize the number of # nops after writing the base register and the instruction under test to # enable using this template for testing various bypass paths. We also # parameterize the register specifiers to enable using this template to # test situations where the base register is equal to the destination # register. # test dependency in load of same address as store
[ 2, 23926, 2559, 28, 198, 2, 916, 62, 26791, 198, 2, 23926, 2559, 28, 198, 2, 29581, 31904, 5499, 284, 30276, 4441, 10474, 5254, 13, 198, 198, 6738, 279, 4948, 28781, 1330, 1635, 198, 6738, 5254, 13, 22866, 1330, 42406, 198, 198, 2, ...
6.012087
2,151
inn = func(1) inn()
[ 198, 198, 3732, 796, 25439, 7, 16, 8, 198, 3732, 3419, 628 ]
1.916667
12
import boto3 from .. import logging logger = logging.getFormattedLogger() lambda_client = boto3.client('lambda', region_name='us-west-2')
[ 11748, 275, 2069, 18, 198, 198, 6738, 11485, 1330, 18931, 198, 198, 6404, 1362, 796, 18931, 13, 1136, 8479, 16898, 11187, 1362, 3419, 198, 50033, 62, 16366, 796, 275, 2069, 18, 13, 16366, 10786, 50033, 3256, 3814, 62, 3672, 11639, 385, ...
3
47
import unittest from transducer.functional import compose from transducer.lazy import transduce from transducer.transducers import (mapping, filtering, taking, dropping_while, distinct) if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 6738, 1007, 646, 2189, 13, 45124, 1330, 36664, 198, 6738, 1007, 646, 2189, 13, 75, 12582, 1330, 1007, 646, 344, 198, 6738, 1007, 646, 2189, 13, 7645, 41213, 1330, 357, 76, 5912, 11, 25431, 11, 2263, 11, 12...
3.309859
71
# -*- coding: utf-8 -*- # Copyright 2021 Damien Nguyen # # 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. """Wrapper script for cppcheck.""" import sys from pathlib import Path from ._utils import Command def main(argv=None): """ Run command. Args: argv (:obj:`list` of :obj:`str`): list of arguments """ if argv is None: argv = sys.argv cmd = CppcheckCmd(argv) cmd.run() if __name__ == "__main__": main()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 33448, 46107, 42379, 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, ...
3.003135
319
from django.db import models from django.conf import settings from django.core.urlresolvers import reverse_lazy from django.utils import timezone from django.forms.util import to_current_timezone from model_utils import Choices
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 7295, 13, 6371, 411, 349, 690, 1330, 9575, 62, 75, 12582, 198, 6738, 42625, 14208, 13, 26791, 1330, 640, 11340, 198, ...
3.538462
65
from django.apps import AppConfig from django.db.models.signals import post_save, post_delete from . import signals
[ 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 198, 6738, 42625, 14208, 13, 9945, 13, 27530, 13, 12683, 874, 1330, 1281, 62, 21928, 11, 1281, 62, 33678, 198, 6738, 764, 1330, 10425, 628 ]
3.545455
33
''' api tv ''' import multiprocessing import socket import time import re import signal # socketapi client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostbyname("openbarrage.douyutv.com") port = 8601 client.connect((host, port)) # danmu_re = re.compile(b'txt@=(.+?)/cid@') username_re = re.compile(b'nn@=(.+?)/txt@') def send_req_msg(msgstr): '''api''' msg = msgstr.encode('utf-8') data_length = len(msg) + 8 code = 689 # msgHead = int.to_bytes(data_length, 4, 'little') \ + int.to_bytes(data_length, 4, 'little') + \ int.to_bytes(code, 4, 'little') client.send(msgHead) sent = 0 while sent < len(msg): tn = client.send(msg[sent:]) sent = sent + tn def keeplive(): ''' 15 ''' while True: msg = 'type@=keeplive/tick@=' + str(int(time.time())) + '/\0' send_req_msg(msg) print('') time.sleep(15) def logout(): ''' ''' msg = 'type@=logout/' send_req_msg(msg) print('') def signal_handler(signal, frame): ''' ctrl+c signal.SIGINT hander ''' p1.terminate() p2.terminate() logout() print('Bye') if __name__ == '__main__': #room_id = input('ID ') # lpl room_id = 288016 # signal signal.signal(signal.SIGINT, signal_handler) # p1 = multiprocessing.Process(target=DM_start, args=(room_id,)) p2 = multiprocessing.Process(target=keeplive) p1.start() p2.start()
[ 7061, 6, 198, 40391, 198, 14981, 198, 7061, 6, 198, 198, 11748, 18540, 305, 919, 278, 198, 11748, 17802, 198, 11748, 640, 198, 11748, 302, 198, 11748, 6737, 198, 198, 2, 17802, 15042, 198, 16366, 796, 17802, 13, 44971, 7, 44971, 13, ...
2.038564
752
# -*- coding: utf-8 -*- # @Time : 2020/4/1 0:48 # @Author : Nixin # @Email : nixin@foxmail.com # @File : spider_douyin.py # @Software: PyCharm import requests, re, sys, os, time, random, socket import http.client from bs4 import BeautifulSoup if __name__ == '__main__': # download_douyin(56, "https://v.douyin.com/3wV6PQ") batch_download_douyin(80, "E:/nixin/douyin/video/20200419/1.txt") pass
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2488, 7575, 220, 220, 220, 1058, 12131, 14, 19, 14, 16, 657, 25, 2780, 198, 2, 2488, 13838, 220, 1058, 399, 844, 259, 198, 2, 2488, 15333, 220, 220, 1058, 299, ...
2.142132
197
from charms.reactive import RelationBase from charms.reactive import scopes from charms.reactive import hook from charms.reactive import when
[ 6738, 41700, 13, 260, 5275, 1330, 4718, 341, 14881, 198, 6738, 41700, 13, 260, 5275, 1330, 629, 13920, 198, 6738, 41700, 13, 260, 5275, 1330, 8011, 198, 6738, 41700, 13, 260, 5275, 1330, 618, 628 ]
4.085714
35
from __future__ import print_function import unittest import filestore
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 555, 715, 395, 198, 198, 11748, 1226, 395, 382, 198 ]
3.47619
21
# This is a little bit clunky, but is a better solution than writing passwords into import os from cryptography.fernet import Fernet # cred_dir = os.path.join(os.path.dirname(os.getcwd()), "settings") cred_dir = '/Users/cdowns/work/imac_local/CoronalHoles/mysql_credentials' key_file = os.path.join(cred_dir, "e_key.bin") # Generate a new local encryption key if needed if not os.path.exists(key_file): key = Fernet.generate_key() # print(key) with open(key_file, 'wb') as file_object: file_object.write(key) else: with open(key_file, 'rb') as file_object: for line in file_object: key = line # User inputs password interactively so it is never saved passw = input("Enter a password to encrypt and save: ") cipher_suite = Fernet(key) ciphered_text = cipher_suite.encrypt(passw.encode()) # required to be bytes creds_file = os.path.join(cred_dir, "e_cred.bin") print("Writing credential file") with open(creds_file, 'wb') as file_object: file_object.write(ciphered_text)
[ 2, 770, 318, 257, 1310, 1643, 537, 28898, 11, 475, 318, 257, 1365, 4610, 621, 3597, 21442, 656, 198, 198, 11748, 28686, 198, 6738, 45898, 13, 69, 1142, 316, 1330, 38982, 316, 198, 198, 2, 2600, 62, 15908, 796, 28686, 13, 6978, 13, ...
2.626598
391
settings = """ try: AUTHENTICATION_BACKENDS += [ "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", ] except NameError: AUTHENTICATION_BACKENDS = [ "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", ] INSTALLED_APPS += [ "django.contrib.sites", # not installed by default "allauth", "allauth.account", "allauth.socialaccount", "allauth.socialaccount.providers.google", ] SITE_ID = 1 """ urls = """ from django.urls import include urlpatterns += [path("accounts/", include("allauth.urls"))] """
[ 33692, 796, 37227, 198, 28311, 25, 198, 220, 220, 220, 37195, 3525, 2149, 6234, 62, 31098, 1677, 5258, 15853, 685, 198, 220, 220, 220, 220, 220, 220, 220, 366, 28241, 14208, 13, 3642, 822, 13, 18439, 13, 1891, 2412, 13, 17633, 7282, ...
2.464684
269
#coding=utf-8 ''' Created on 2015-10-10 @author: Devuser '''
[ 2, 66, 7656, 28, 40477, 12, 23, 198, 7061, 6, 198, 41972, 319, 1853, 12, 940, 12, 940, 198, 198, 31, 9800, 25, 6245, 7220, 198, 7061, 6, 628, 628, 198, 220, 220, 220, 220, 628, 220, 220, 220, 220, 198, 220, 220, 220, 220, 198,...
1.72
50
s = 0 problems = input().strip().split(';') for p in problems: if '-' in p: a, b = map(int, p.split('-')) s += b - a + 1 else: s += 1 print(s)
[ 82, 796, 657, 198, 198, 1676, 22143, 796, 5128, 22446, 36311, 22446, 35312, 10786, 26, 11537, 198, 1640, 279, 287, 2761, 25, 198, 220, 220, 220, 611, 705, 19355, 287, 279, 25, 198, 220, 220, 220, 220, 220, 220, 220, 257, 11, 275, ...
1.913043
92
#!/usr/bin/python from fusesoc.capi2.generator import Generator import subprocess g = IcepllGenerator() g.run() g.write()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 6738, 277, 2664, 420, 13, 11128, 72, 17, 13, 8612, 1352, 1330, 35986, 198, 11748, 850, 14681, 198, 198, 70, 796, 6663, 79, 297, 8645, 1352, 3419, 198, 70, 13, 5143, 3419, 198, 70, 13, 135...
2.673913
46
from checkcel import Checkplate from checkcel.validators import SetValidator, NoValidator from collections import OrderedDict
[ 6738, 2198, 5276, 1330, 6822, 6816, 198, 6738, 2198, 5276, 13, 12102, 2024, 1330, 5345, 47139, 1352, 11, 1400, 47139, 1352, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 628 ]
4.233333
30
# Copyright 2022 Thomas Woodruff # 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 .. import cli
[ 2, 220, 220, 220, 15069, 33160, 5658, 5326, 30622, 198, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 220, 220, 220, 345, 743, 407, 779, 428, 2393, 2845, 287, 1...
3.420765
183
# Author-kantoku # Description-! # Fusion360API Python import adsk.core import traceback try: from . import config from .apper import apper from .commands.BUNKUROCore import BUNKUROCore # Create our addin definition object my_addin = apper.FusionApp(config.app_name, config.company_name, False) my_addin.root_path = config.app_path my_addin.add_command( '', BUNKUROCore, { 'cmd_description': '!', 'cmd_id': 'bunkuro', 'workspace': 'FusionSolidEnvironment', 'toolbar_panel_id': 'UtilityPanel', 'cmd_resources': 'BUNKURO', 'command_visible': True, 'command_promoted': False, 'create_feature': False, } ) except: app = adsk.core.Application.get() ui = app.userInterface if ui: ui.messageBox('Initialization: {}'.format(traceback.format_exc()))
[ 2, 6434, 12, 74, 415, 11601, 198, 2, 12489, 12, 0, 198, 2, 21278, 15277, 17614, 11361, 198, 198, 11748, 512, 8135, 13, 7295, 198, 11748, 12854, 1891, 198, 198, 28311, 25, 198, 220, 220, 220, 422, 764, 1330, 4566, 198, 220, 220, 22...
2.165501
429
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import pandas as pd import os PROJECT_PATH = "/mnt/e/dev/test/hp_steam_data/" DATA_PATH = os.path.join(PROJECT_PATH, "data") RESULT_PATH = os.path.join(PROJECT_PATH, "result") def get_origin_data(): """ origin data """ # raw data eturb_m1_data = pd.read_csv("/mnt/e/dev/test/hp_steam_data/data/eturb_m1_1min_metrics-0817.csv", header = 0, index_col = None) eturb_m2_data = pd.read_csv("/mnt/e/dev/test/hp_steam_data/data/eturb_m2_1min_metrics-0817.csv", header = 0, index_col = None) boiler_m1_data = pd.read_csv("/mnt/e/dev/test/hp_steam_data/data/boiler_m1_1min_outlet_steam_flow.csv", header = 0, index_col = None) boiler_m3_data = pd.read_csv("/mnt/e/dev/test/hp_steam_data/data/boiler_m3_1min_outlet_steam_flow.csv", header = 0, index_col = None) steampipeline_p1_data = pd.read_csv("/mnt/e/dev/test/hp_steam_data/data/steampipeline_p1_1min_hp_steam_pressure.csv", header = 0, index_col = None) # data aggregate df = pd.DataFrame() # eturb_m1 df["eturb_m1_steam_flow_in"] = eturb_m1_data["ExtCondensTurbineOP.steam_flow_in"] df["eturb_m2_steam_flow_in"] = eturb_m2_data["ExtCondensTurbineOP.steam_flow_in"] df["boiler_m1_outlet_steam_flow"] = boiler_m1_data["CFBoilerOP.outlet_steam_flow"] df["boiler_m3_outlet_steam_flow"] = boiler_m3_data["CFBoilerOP.outlet_steam_flow"] df["steampipeline_p1_hp_steam_pressure"] = steampipeline_p1_data["SteamPipelineOP.hp_steam_pressure"] df["boiler_steam_flow"] = df["boiler_m1_outlet_steam_flow"] + df["boiler_m3_outlet_steam_flow"] df["turbine_steam_flow"] = df["eturb_m1_steam_flow_in"] + df["eturb_m2_steam_flow_in"] df = df.reset_index(drop = True) return df if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 628, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 28686, 628, 198, 31190, 23680...
2.188179
829
#!python3 """ Simulation experiment for our AAAI 2020 paper, with recipes that are vectors of ones. Comparing McAfee's double auction to our SBB auctions. Author: Dvir Gilor Since: 2020-08 """ from experiment_stock import experiment from mcafee_protocol import mcafee_trade_reduction from trade_reduction_protocol import budget_balanced_trade_reduction from ascending_auction_protocol import budget_balanced_ascending_auction import sys results_file = "stock/results/experiment_sbb_with_vectors_of_ones_stock.csv" experiment(results_file,budget_balanced_ascending_auction, "SBB Ascending Prices", recipe=4*(1,))
[ 2, 0, 29412, 18, 198, 198, 37811, 198, 8890, 1741, 6306, 329, 674, 25734, 40, 12131, 3348, 11, 351, 14296, 326, 389, 30104, 286, 3392, 13, 198, 7293, 1723, 1982, 44314, 338, 4274, 14389, 284, 674, 311, 15199, 48043, 13, 198, 198, 13...
3.285714
189
from random import randint print('=-' * 15) print('ADIVINHE EM QUE NUMERO ESTOU PENANDO') print('=-' * 15) pc = randint(0, 10) num = 11 cont = 0 while pc != num: num = int(input('Sera que voce consegue acertar o numero que pensei, entre 0, 10: ')) if num == pc: print('PARABES!!! VOCE ACERTOU') else: if num < pc: print('Mais...', end=' ') else: print('Menos...', end=' ') print('Tente novamente') print('-' * 20) cont += 1 print(f'Voce tentou {cont} vezes para acertar')
[ 6738, 4738, 1330, 43720, 600, 198, 4798, 10786, 10779, 6, 1635, 1315, 8, 198, 4798, 10786, 2885, 3824, 1268, 13909, 17228, 1195, 8924, 36871, 34812, 17160, 2606, 350, 1677, 6981, 46, 11537, 198, 4798, 10786, 10779, 6, 1635, 1315, 8, 198...
2.102273
264
""" ex20170108_model_PC.py Create Model PC (Godley & Lavoie Chapter 4). Copyright 2017 Brian Romanchuk 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 sfc_models.examples.Quick2DPlot import Quick2DPlot from sfc_models.models import * from sfc_models.sector import Market from sfc_models.sector_definitions import Household, Treasury, CentralBank, TaxFlow, FixedMarginBusiness, DepositMarket, \ MoneyMarket if __name__ == '__main__': main()
[ 37811, 198, 1069, 5539, 486, 2919, 62, 19849, 62, 5662, 13, 9078, 198, 198, 16447, 9104, 4217, 357, 13482, 1636, 1222, 21438, 78, 494, 7006, 604, 737, 628, 198, 15269, 2177, 8403, 3570, 3702, 2724, 198, 198, 26656, 15385, 739, 262, 24...
3.524345
267
import re import flask import flask.views from functools import wraps def camel_case_to_snake_case(word): """very simple mechanism for turning CamelCase words into snake_case""" return re.sub(r"(?<!^)(?=[A-Z])", "_", word).lower() def camel_case_to_slug_case(word): """very simple mechanism for turning CamelCase words into slug-case""" return re.sub(r"(?<!^)(?=[A-Z])", "-", word).lower() def extends_rule(rule): return extend_rule API = View = SimpleView
[ 11748, 302, 198, 198, 11748, 42903, 198, 11748, 42903, 13, 33571, 198, 6738, 1257, 310, 10141, 1330, 27521, 628, 198, 4299, 41021, 62, 7442, 62, 1462, 62, 16184, 539, 62, 7442, 7, 4775, 2599, 198, 220, 220, 220, 37227, 548, 2829, 9030...
2.833333
174
# ========================================================================= # Copyright 2012-present Yunify, Inc. # ------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this work except in compliance with the License. # You may obtain a copy of the License in the LICENSE file, or 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 qingcloud.iaas import constants as const from qingcloud.cli.iaas_client.actions.base import BaseAction
[ 2, 38093, 2559, 198, 2, 15069, 2321, 12, 25579, 20757, 1958, 11, 3457, 13, 198, 2, 16529, 45537, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 670, 28...
4.71
200
import datetime from datetime import timedelta from typing import Callable, Collection, TYPE_CHECKING import pytz from tsutils.formatting import normalize_server_name from tsutils.time import JP_TIMEZONE, KR_TIMEZONE, NA_TIMEZONE from padevents.enums import DungeonType, EventLength if TYPE_CHECKING: from dbcog.models.scheduled_event_model import ScheduledEventModel SUPPORTED_SERVERS = ["JP", "NA", "KR"] SERVER_TIMEZONES = { "JP": JP_TIMEZONE, "NA": NA_TIMEZONE, "KR": KR_TIMEZONE, }
[ 11748, 4818, 8079, 198, 6738, 4818, 8079, 1330, 28805, 12514, 198, 6738, 19720, 1330, 4889, 540, 11, 12251, 11, 41876, 62, 50084, 2751, 198, 198, 11748, 12972, 22877, 198, 6738, 40379, 26791, 13, 18982, 889, 1330, 3487, 1096, 62, 15388, ...
2.781421
183
# allows to import RSA lib from different dir import sys # inserts path to access RSA encryption lib # sys.path.insert(0, '../RSAEncryption') import socket import json from libs.communication import sendEncrypted, recvEncrypted, sendData, readData from libs.RSAKeys import readPrivateKey from libs.EncryptedSocket import EncryptedSocket from libs.settings import * HOST = '127.0.0.1' PORT = 4444 printDebug = True SSID = "SecureCanes" # sending data
[ 2, 3578, 284, 1330, 42319, 9195, 422, 1180, 26672, 198, 11748, 25064, 198, 198, 2, 42220, 3108, 284, 1895, 42319, 15835, 9195, 198, 2, 25064, 13, 6978, 13, 28463, 7, 15, 11, 705, 40720, 49, 4090, 27195, 13168, 11537, 198, 198, 11748, ...
3.255319
141
import taichi as ti import numpy as np from functools import partial from itertools import combinations from billiard_game_dual_ball import normalize_vector, two_ball_collides, calc_next_pos_and_velocity, \ calc_after_collision_velocity, rectify_positions_in_collision, rectify_positions_and_velocities # Constants WHITE = 0xFFFFFF RED = 0xFF0000 GREEN = 0x00FF00 BLUE = 0x0000FF # wc for world space x[0.0, ratio], y[0.0, 1.0] # sc for screen space [0.0, 1.0]^2 # Constant parameters RESOLUTION = (1230, 750) RATIO = RESOLUTION[0] / RESOLUTION[1] # x/y FPS = 60 CUE_BALL_IDX = 0 STICK_LENGTH_SC = 0.1 DRAG_COEFFICIENT = 0.03 G = 9.8 CUE_BALL_MAX_SPEED_WC = 1.0 BALL_PIXEL_RADIUS = 10 HOLE_PIXEL_RADIUS = 15 num_balls = 1 # Derived parameters ball_radius_wc = BALL_PIXEL_RADIUS / RESOLUTION[1] hole_radius_wc = HOLE_PIXEL_RADIUS / RESOLUTION[1] x_begin_wc = 0.0 x_end_wc = RATIO y_begin_wc = 0.0 y_end_wc = 1.0 if __name__ == "__main__": ti.init(ti.cpu) print("Press A to kick the cue ball") wc_to_sc_multiplier = np.array([1 / RATIO, 1]) # transform to [0,1]^ screen space sc_to_wc_multiplier = np.array([RATIO, 1]) virtual_bound_x = np.array([ball_radius_wc, x_end_wc - ball_radius_wc]) virtual_bound_y = np.array([ball_radius_wc, y_end_wc - ball_radius_wc]) dx_wc = x_end_wc / 2. dy_wc = y_end_wc / 2. hole_pos_x = np.arange(3) * dx_wc hole_pos_y = np.arange(3) * dy_wc hole_pos_x, hole_pos_y = np.meshgrid(hole_pos_x, hole_pos_y) hole_center_positions_wc = np.stack([hole_pos_x, hole_pos_y], axis=-1).reshape(-1, 2) # (3, 3, 2) -> (9, 2) hole_center_positions_wc = np.delete(hole_center_positions_wc, 4, axis=0) hole_center_positions_sc = hole_center_positions_wc * wc_to_sc_multiplier.reshape(1, 2) ball_velocities_wc = np.zeros((num_balls, 2)) ball_visible = np.ones(num_balls, dtype=bool) span_wc = np.array([virtual_bound_x[1] - virtual_bound_x[0], virtual_bound_y[1] - virtual_bound_y[0]]) offset_wc = np.array([virtual_bound_x[0], virtual_bound_y[0]]) ball_pos_wc = place_balls_wc(span_wc, offset_wc) gui = ti.GUI("billiard_game_multi_ball", RESOLUTION) gui.fps_limit = FPS delta_t = 1.0 / FPS boundary_begin_wc = np.array([ [x_begin_wc, y_begin_wc], [x_begin_wc, y_begin_wc], [x_end_wc, y_end_wc], [x_end_wc, y_end_wc] ]) boundary_end_wc = np.array([ [x_end_wc, y_begin_wc], [x_begin_wc, y_end_wc], [x_end_wc, y_begin_wc], [x_begin_wc, y_end_wc] ]) # a convenient partial function of rectify_positions_and_velocities rectify_pv = partial(rectify_positions_and_velocities, virtual_bound_x[0], virtual_bound_x[1], virtual_bound_y[0], virtual_bound_y[1]) ball_pairs = list(combinations(range(num_balls), 2)) ball_color_indices = np.ones(num_balls) ball_color_indices[CUE_BALL_IDX] = 0 ball_colors = [WHITE, RED] while gui.running: gui.clear(GREEN) hit_ball = gui.get_event(ti.GUI.PRESS) and gui.is_pressed("a") cue_ball_pos_sc = ball_pos_wc[CUE_BALL_IDX] * wc_to_sc_multiplier # the current setting is only when all balls are stationary, the mouse is available if np.allclose((ball_velocities_wc ** 2).sum(-1), 0., rtol=0.001, atol=0.001) and ball_visible[CUE_BALL_IDX]: rod_dir_sc, length = normalize_vector(gui.get_cursor_pos() - cue_ball_pos_sc) rod_line = rod_dir_sc * min(STICK_LENGTH_SC, length) gui.line(cue_ball_pos_sc, cue_ball_pos_sc + rod_line, radius=2) if hit_ball: ball_velocities_wc[CUE_BALL_IDX] = (rod_dir_sc * sc_to_wc_multiplier) \ * CUE_BALL_MAX_SPEED_WC * (min(STICK_LENGTH_SC, length) / STICK_LENGTH_SC) # modify the speed with a multiplier dependent on the distance between mouse and the cue ball # for i in range(num_balls): # for each ball, if score() returns True, set this ball invisible # # Not care now # if score(hole_center_positions_wc, ball_pos_wc[i]): # ball_visible[i] = False # ball_velocities_wc[i] = 0. # No need to care about this in verilog gui.lines(begin=boundary_begin_wc, end=boundary_end_wc, radius=2) gui.circles(ball_pos_wc[ball_visible] * wc_to_sc_multiplier.reshape(1, 2), radius=BALL_PIXEL_RADIUS, palette=ball_colors, palette_indices=ball_color_indices[ball_visible]) gui.circles(hole_center_positions_sc, radius=HOLE_PIXEL_RADIUS, color=0) gui.show() for i in range(num_balls): # unroll this loop for the two ball case if not ball_visible[i]: continue next_pos_wc, next_velocity_wc = calc_next_pos_and_velocity(ball_pos_wc[i], ball_velocities_wc[i], delta_t, DRAG_COEFFICIENT, G) next_pos_wc, next_velocity_wc = rectify_pv(next_pos_wc, next_velocity_wc) ball_pos_wc[i] = next_pos_wc ball_velocities_wc[i] = next_velocity_wc for ball_i, ball_j in ball_pairs: # only one iteration for the two ball case, since we have only one pair if not ball_visible[ball_i] or not ball_visible[ball_j]: continue ball_i_pos_wc = ball_pos_wc[ball_i] ball_j_pos_wc = ball_pos_wc[ball_j] if two_ball_collides(ball_i_pos_wc, ball_j_pos_wc, ball_radius_wc): ball_i_pos_wc, ball_j_pos_wc = rectify_positions_in_collision(ball_i_pos_wc, ball_j_pos_wc, ball_radius_wc) ball_i_v_wc = ball_velocities_wc[ball_i] ball_j_v_wc = ball_velocities_wc[ball_j] ball_i_v_wc, ball_j_v_wc = calc_after_collision_velocity(ball_i_pos_wc, ball_j_pos_wc, ball_i_v_wc, ball_j_v_wc) ball_velocities_wc[ball_i] = ball_i_v_wc ball_velocities_wc[ball_j] = ball_j_v_wc
[ 11748, 20486, 16590, 355, 46668, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 1257, 310, 10141, 1330, 13027, 198, 6738, 340, 861, 10141, 1330, 17790, 198, 198, 6738, 2855, 42425, 62, 6057, 62, 646, 282, 62, 1894, 1330, 3487, 1096, 62,...
1.885383
3,359
from bullet import Bullet, Prompt, Check, Input, YesNo from bullet import styles cli = Prompt( [ Bullet("Choose from a list: ", **styles.Example), Check("Choose from a list: ", **styles.Example), Input("Who are you? "), YesNo("Are you a student? ") ], spacing = 2 ) result = cli.launch() print(result)
[ 6738, 10492, 1330, 18003, 11, 45965, 11, 6822, 11, 23412, 11, 3363, 2949, 198, 6738, 10492, 1330, 12186, 198, 198, 44506, 796, 45965, 7, 198, 220, 220, 220, 685, 198, 220, 220, 220, 220, 220, 220, 220, 18003, 7203, 31851, 422, 257, ...
2.609023
133
def test_pck_2012_adb(style_checker): """Style check test against pck_2012.adb.""" style_checker.set_year(2006) p = style_checker.run_style_checker('repo_name', 'pck_2012.ads') style_checker.assertEqual(p.status, 0, p.image) style_checker.assertRunOutputEmpty(p) def test_pck_2012_adb_with_alt_config_forcing_gnat2012(style_checker): """Style check test against pck_2012.adb with gnat12 config option.""" style_checker.set_year(2006) p = style_checker.run_style_checker( '--config', 'gnat2012_config.yaml', 'repo_name', 'pck_2012.ads') style_checker.assertEqual(p.status, 0, p.image) style_checker.assertRunOutputEmpty(p)
[ 4299, 1332, 62, 79, 694, 62, 6999, 62, 324, 65, 7, 7635, 62, 9122, 263, 2599, 198, 220, 220, 220, 37227, 21466, 2198, 1332, 1028, 279, 694, 62, 6999, 13, 324, 65, 526, 15931, 198, 220, 220, 220, 3918, 62, 9122, 263, 13, 2617, 62...
2.3879
281
# -*- coding: utf-8 -*- import sys if __name__ == '__main__': main()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 25064, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 3419, 198 ]
2.083333
36
from timeit import default_timer import numpy as np
[ 6738, 640, 270, 1330, 4277, 62, 45016, 198, 11748, 299, 32152, 355, 45941, 628 ]
3.785714
14
import numpy as np from toolbox.exp.OutputSchema import OutputSchema from toolbox.utils.LaTeXSotre import EvaluateLaTeXStoreSchema from toolbox.utils.MetricLogStore import MetricLogStoreSchema from toolbox.utils.ModelParamStore import ModelParamStoreSchema from toolbox.utils.Visualize import VisualizeSchema
[ 11748, 299, 32152, 355, 45941, 198, 198, 6738, 2891, 3524, 13, 11201, 13, 26410, 27054, 2611, 1330, 25235, 27054, 2611, 198, 6738, 2891, 3524, 13, 26791, 13, 14772, 49568, 50, 313, 260, 1330, 26439, 4985, 14772, 49568, 22658, 27054, 2611,...
3.466667
90
import json import os from django.core.management import call_command from django.test.runner import DiscoverRunner from django.db import connections from dataloader.tests.data import data_manager
[ 11748, 33918, 198, 11748, 28686, 198, 198, 6738, 42625, 14208, 13, 7295, 13, 27604, 1330, 869, 62, 21812, 198, 6738, 42625, 14208, 13, 9288, 13, 16737, 1330, 29704, 49493, 198, 6738, 42625, 14208, 13, 9945, 1330, 8787, 198, 198, 6738, 4...
3.773585
53
#Originally created By KingMars Rain Sequence 2 {Updated} from telethon import events import asyncio from collections import deque
[ 2, 22731, 2727, 2750, 2677, 43725, 220, 10301, 45835, 362, 1391, 17354, 92, 198, 6738, 5735, 400, 261, 1330, 2995, 198, 11748, 30351, 952, 198, 6738, 17268, 1330, 390, 4188, 628 ]
4.290323
31
from preprocessing.generate_and_save_data import generate_and_save_data
[ 6738, 662, 36948, 13, 8612, 378, 62, 392, 62, 21928, 62, 7890, 1330, 7716, 62, 392, 62, 21928, 62, 7890, 201, 198 ]
3.318182
22
import matplotlib.pyplot as plt import csv import statistics import math plt.title('Population Diversity') plt.ylabel('Diversity Score') plt.xlabel('Iteration Number') random = [] randombars = [] rmin = [] rmax = [] hill = [] hillbars = [] hmin = [] hmax = [] evo = [] emin = [] emax = [] evobars = [] cross = [] crossbars = [] cmin = [] cmax = [] numRuns = 5 numIterations = 100000000 sqrtRuns = math.sqrt(numRuns) iterationDataRandom = [] iterationDataHill = [] iterationDataEvo = [] iterationDataCross = [] indicesToPlot = [10, 15, 20, 25] index = 60 while indicesToPlot[-1] < numIterations: indicesToPlot.append(index) index = int(index * 1.02) indicesToPlot[-1] = numIterations - 1 #xtiks = [] #for i in range(10): # xtiks.append(int(numIterations / 5 * i)) #plt.xticks(xtiks) for i in range(1, numRuns + 1): iterationDataRandom.append({}) iterationDataHill.append({}) iterationDataEvo.append({}) iterationDataCross.append({}) with open('rand' + str(i) + '.csv', newline='') as csvfile: reader = csv.reader(csvfile, delimiter=' ', quotechar='|') index = 0 for row in reversed(list(reader)): vals = row[0].split(',') iteration = int(vals[0]) val = float(vals[1]) while index < len(indicesToPlot) - 1 and indicesToPlot[index + 1] < iteration: index += 1 iterationDataRandom[-1][indicesToPlot[index]] = val with open('hill' + str(i) + '.csv', newline='') as csvfile: reader = csv.reader(csvfile, delimiter=' ', quotechar='|') index = 0 for row in reversed(list(reader)): vals = row[0].split(',') iteration = int(vals[0]) val = float(vals[2]) while index < len(indicesToPlot) - 1 and indicesToPlot[index] < iteration: index += 1 iterationDataHill[-1][indicesToPlot[index]] = val with open('evo' + str(i) + '.csv', newline='') as csvfile: reader = csv.reader(csvfile, delimiter=' ', quotechar='|') index = 0 for row in reversed(list(reader)): vals = row[0].split(',') iteration = int(vals[0]) * 100 val = float(vals[2]) while index < len(indicesToPlot) - 1 and indicesToPlot[index] < iteration: index += 1 iterationDataEvo[-1][indicesToPlot[index]] = val with open('ed' + str(i) + '.csv', newline='') as csvfile: reader = csv.reader(csvfile, delimiter=' ', quotechar='|') index = 0 for row in reversed(list(reader)): vals = row[0].split(',') iteration = int(vals[0]) val = float(vals[2]) while index < len(indicesToPlot) - 1 and indicesToPlot[index] < iteration: index += 1 iterationDataCross[-1][indicesToPlot[index]] = val print("Done reading data") unifiedRandom = [] unifiedHill = [] unifiedEvo = [] unifiedCross = [] index = 0 for iteration in indicesToPlot: currentRandom = [] currentHill = [] currentEvo = [] currentCross = [] unifiedRandom.append(currentRandom) unifiedHill.append(currentHill) unifiedEvo.append(currentEvo) unifiedCross.append(currentCross) for run in range(numRuns): valRandom = -1 if iteration in iterationDataRandom[run]: valRandom = iterationDataRandom[run][iteration] else: # unchanged valRandom = unifiedRandom[-2][run] currentRandom.append(valRandom) valHill = -1 if iteration in iterationDataHill[run]: valHill = iterationDataHill[run][iteration] else: # unchanged valHill = unifiedHill[-2][run] currentHill.append(valHill) valEvo = -1 if iteration in iterationDataEvo[run]: valEvo = iterationDataEvo[run][iteration] else: #unchanged valEvo = unifiedEvo[-2][run] currentEvo.append(valEvo) valCross = -1 if iteration in iterationDataCross[run]: valCross = iterationDataCross[run][iteration] else: #unchanged valCross = unifiedCross[-2][run] currentCross.append(valCross) randomAverage = statistics.mean(currentRandom) randomError = statistics.stdev(currentRandom) / sqrtRuns random.append(randomAverage) randombars.append(randomError) hillAverage = statistics.mean(currentHill) hillError = statistics.stdev(currentHill) / sqrtRuns hill.append(hillAverage) hillbars.append(hillError) evoAverage = statistics.mean(currentEvo) evoError = statistics.stdev(currentEvo) / sqrtRuns evo.append(evoAverage) evobars.append(evoError) crossAverage = statistics.mean(currentCross) crossError = statistics.stdev(currentCross) / sqrtRuns cross.append(crossAverage) crossbars.append(crossError) for i in range(len(random)): rmin.append(random[i] - randombars[i]) rmax.append(random[i] + randombars[i]) hmin.append(hill[i] - hillbars[i]) hmax.append(hill[i] + hillbars[i]) emin.append(evo[i] - evobars[i]) emax.append(evo[i] + evobars[i]) cmin.append(cross[i] - crossbars[i]) cmax.append(cross[i] + crossbars[i]) print("Done processing data") plt.xscale('log') #plt.yscale('log') #plt.plot(indicesToPlot, random, color='blue', linewidth=1, label='Random Search') plt.plot(indicesToPlot, hill, color='green', linewidth=1, label='Parallel Hill Climb') plt.plot(indicesToPlot, evo, color='red', linewidth=1, label='Weighted Selection') plt.plot(indicesToPlot, cross, color='blue', linewidth=1, label='Parental Replacement') plt.fill_between(indicesToPlot, hmin, hmax, facecolor='green', lw=0, alpha=0.5) plt.fill_between(indicesToPlot, emin, emax, facecolor='red', lw=0, alpha=0.5) plt.fill_between(indicesToPlot, cmin, cmax, facecolor='blue', lw=0, alpha=0.5) #plt.fill_between(indicesToPlot, rmin, rmax, facecolor='blue', lw=0, alpha=0.5) plt.legend(loc='best') plt.savefig('diversityp.png', dpi=500) plt.show()
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 269, 21370, 198, 11748, 7869, 198, 11748, 10688, 198, 198, 489, 83, 13, 7839, 10786, 45251, 36188, 11537, 198, 489, 83, 13, 2645, 9608, 10786, 35, 1608, 15178, 11537, ...
2.295242
2,669
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import logging from datetime import date import click from .data import DISCIPLINE_MAP from .outputs import OUTPUT_MAP if __name__ == '__main__': cli()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 11748, 18931, 198, 6738, 4818, 8079, 1330, 3128, ...
2.755556
90
import json with open('bibliography.json', 'r', encoding='utf-8') as bib_data: bib = sorted(json.load(bib_data), key=lambda d: d['ID']) with open('abstracts.json', 'r', encoding='utf-8') as tex_data: tex = sorted(json.load(tex_data), key=lambda d: d['ID']) ID1 = [b['ID'] for b in bib] ID2 = [t['ID'] for t in tex] for i in range(len(ID1)): bib[i]['reference'] = tex[i]['title'] bib[i]['abstract'] = tex[i]['abstract'] print('Done') with open('med_robo_papers.json', 'w', encoding='utf-8') as res_file: res_file.write(json.dumps(bib, indent=4, ensure_ascii=False, sort_keys=True)) res_file.close()
[ 11748, 33918, 201, 198, 201, 198, 4480, 1280, 10786, 65, 45689, 13, 17752, 3256, 705, 81, 3256, 21004, 11639, 40477, 12, 23, 11537, 355, 275, 571, 62, 7890, 25, 201, 198, 220, 220, 220, 275, 571, 796, 23243, 7, 17752, 13, 2220, 7, ...
2.182724
301
from .qton import Qcircuit, Qcodes import warnings warnings.filterwarnings("ignore") __all__ = [ # 'Simulator', 'Qcircuit', 'Qcodes' ]
[ 6738, 764, 80, 1122, 1330, 1195, 21170, 5013, 11, 1195, 40148, 198, 11748, 14601, 198, 40539, 654, 13, 24455, 40539, 654, 7203, 46430, 4943, 198, 198, 834, 439, 834, 796, 685, 198, 220, 220, 220, 1303, 705, 8890, 8927, 3256, 198, 220,...
2.491525
59
from typing import Sequence import numpy def check_area(self, loc: Sequence, radius: int, report=False): """ This method takes a location coordinate and a radius and search the delivery services around this specified area. :param loc: A tuple of integers. :param radius: An integer. :param report: A boolean that indicates whether or not print a report. return: - A sub-matrix of the pizzerias matrix which is created in terms of specified range. - A maximum in this area. - A set of cells that have maximum. """ matrix = self.area_matrix(loc, radius) x_initial, y_initial = loc y_center = self.n_of_block - y_initial x_center = x_initial - 1 low0 = y_center - radius if y_center - radius >= 0 else 0 left1 = x_center - radius if x_center - radius >= 0 else 0 maximum = self.maximum_in_matrix(matrix) max_set = self.max_locations(matrix=matrix, d0_start=low0, d1_start=left1) if report: print(f"In the given area, there are {len(max_set)} areas where {maximum} Pizzerias delivery service " f"can cover, they are: ", max_set) return matrix, maximum, max_set def check_city(self, report=False): """ This method returns the matrix, the maximum and a set of maximum tuple of cells. :param report: A boolean indicating whether or not print report. :return: - The pizzerias matrix. - A maximum in this the pizzerias matrix. - A set of cells that have maximum. """ if report: print(f"There are {len(self.max_locations())} area(s) where {self.maximum_in_matrix()} Pizzerias can cover, " f"they are: ", self.max_locations()) return self.pizzerias_matrix, self.maximum_in_matrix(), self.max_locations()
[ 6738, 19720, 1330, 45835, 198, 11748, 299, 32152, 628, 198, 220, 220, 220, 825, 2198, 62, 20337, 7, 944, 11, 1179, 25, 45835, 11, 16874, 25, 493, 11, 989, 28, 25101, 2599, 198, 220, 220, 220, 220, 220, 220, 220, 37227, 198, 220, 2...
2.446271
791
import numpy as np import matplotlib.pyplot as plt import corner mcmc = np.loadtxt("mychain1.dat") ntheta = mcmc.shape[1] fig = plt.figure(1, figsize=(15, 6)) ax = fig.add_subplot(231) ax.hist(mcmc[:, 0]/np.log(10.0), 100, normed=True, range=(-0.9, -0.1)) ax = fig.add_subplot(232) ax.hist(mcmc[:, 1]/np.log(10.0), 100, normed=True, range=(0.0, 2.0)) ax = fig.add_subplot(234) ax.hist(mcmc[:, 2], 100, normed=True, range=(1.0, 2.8)) ax = fig.add_subplot(235) ax.hist(mcmc[:, 3], 100, normed=True, range=(0.0, 1.2)) ax = fig.add_subplot(236) ax.hist(mcmc[:, 4], 100, normed=True, range=(5, 13)) mcmc = np.loadtxt("../data/mcmc.txt") ntheta = mcmc.shape[1] nb = 20000 fig = plt.figure(2, figsize=(15, 6)) ax = fig.add_subplot(231) ax.hist( (mcmc[nb:, 1]+0.5*mcmc[nb:, 2]-0.5*np.log(2.0))/np.log(10.0), 100, normed=True, range=(-0.9, -0.1)) ax = fig.add_subplot(232) ax.hist(mcmc[nb:, 2]/np.log(10), 100, normed=True, range=(0.0, 2.0)) ax = fig.add_subplot(234) ax.hist(mcmc[nb:, 5], 100, normed=True, range=(1.0, 2.8)) ax = fig.add_subplot(235) ax.hist(mcmc[nb:, 3], 100, normed=True, range=(0.0, 1.2)) ax = fig.add_subplot(236) ax.hist(mcmc[nb:, 4], 100, normed=True, range=(5, 13)) plt.show()
[ 11748, 299, 32152, 355, 45941, 220, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 220, 198, 11748, 5228, 198, 198, 76, 11215, 66, 796, 45941, 13, 2220, 14116, 7203, 1820, 7983, 16, 13, 19608, 4943, 198, 198, 429, 3202,...
1.972358
615
import numpy as np import pandas as pd import pastas as ps def test_runs_test(): """ http://www.itl.nist.gov/div898/handbook/eda/section3/eda35d.htm True Z-statistic = 2.69 Read NIST test data """ data = pd.read_csv("tests/data/nist.csv") test, _ = ps.stats.runs_test(data) assert test[0] - 2.69 < 0.02
[ 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 11748, 1613, 292, 355, 26692, 628, 628, 198, 198, 4299, 1332, 62, 48381, 62, 9288, 33529, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 2638, 1378, 2503, ...
2.235294
153
import warnings from .base import Registry __author__ = "Artur Barseghyan" __copyright__ = "2013-2021 Artur Barseghyan" __license__ = "MPL-1.1 OR GPL-2.0-only OR LGPL-2.1-or-later" __all__ = ("Registry",) warnings.warn( "The `Registry` class is moved from `tld.registry` to `tld.base`.", DeprecationWarning, )
[ 11748, 14601, 198, 6738, 764, 8692, 1330, 33432, 198, 198, 834, 9800, 834, 796, 366, 8001, 333, 2409, 325, 456, 4121, 1, 198, 834, 22163, 4766, 834, 796, 366, 6390, 12, 1238, 2481, 3683, 333, 2409, 325, 456, 4121, 1, 198, 834, 43085...
2.461538
130
# -*- coding: utf-8 -*- from valverest.database import db7 as db from sqlalchemy.ext.hybrid import hybrid_property
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 22580, 2118, 13, 48806, 1330, 20613, 22, 355, 20613, 198, 6738, 44161, 282, 26599, 13, 2302, 13, 12114, 10236, 1330, 14554, 62, 26745, 628, 628, 628 ]
2.926829
41
from instruments import VNA_handler, Fridge_handler import os import time from datetime import date, datetime today = date.today() d1 = today.strftime("_%d_%m") directory = "data"+d1 dir_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),directory) if not os.path.isdir(dir_path): try: os.mkdir(directory) except: pass VNA_lab=VNA_handler() Fridge=Fridge_handler() temps=[] freqs1=[] freqs2=[] r = Fridge.execute("C3") file_log = open(directory + "\\log.txt", "w") with open('temperatures_gap.txt', encoding='utf-8') as file: for line in file: line = line.replace('\n', '') temps.append(int(line)) with open('frequency_ranges_gap_1.txt', encoding='utf-8') as file: for line in file: line = line.replace('\n', '') splitted = [float(x) for x in line.split('\t')] freqs1.append(splitted) with open('frequency_ranges_gap_2.txt', encoding='utf-8') as file: for line in file: line = line.replace('\n', '') splitted = [float(x) for x in line.split('\t')] freqs2.append(splitted) for T in temps: try: print("Set temp: " + str(T)) print(f"{datetime.now():%H:%M:%S}\tsens_1:{Fridge.get_T(1)}\tsens_2:{Fridge.get_T(2)}\tsens_3:{Fridge.get_T(3)}\tG1: {Fridge.get_T(14)}\tG2: {Fridge.get_T(15)}") log_sensori() time.sleep(10) Fridge.wait_for_T(T) if T >= 200: freqs = freqs2 else: freqs = freqs1 for idx,f in enumerate(freqs): file_name=str(T)+'mK_range'+str(idx+1)+'.txt' print("Set freqs: " + str(f[0]) + " - "+ str(f[1])) VNA_lab.set_sweep_freq(f[0],f[1]) VNA_lab.inst.write('AVERREST;') time.sleep(40) VNA_lab.save_sweep_data(directory + '\\' + file_name, 'polar') except: pass log_sensori() Fridge.set_T(0) log_sensori() file_log.close()
[ 6738, 12834, 1330, 569, 4535, 62, 30281, 11, 1305, 3130, 62, 30281, 198, 11748, 28686, 198, 11748, 640, 198, 6738, 4818, 8079, 1330, 3128, 11, 4818, 8079, 198, 198, 40838, 796, 3128, 13, 40838, 3419, 198, 67, 16, 796, 1909, 13, 2536, ...
1.980533
976
#!/usr/bin/env python3 """ Get a json dump of all the repos belonging to a GitHub org or user. """ import json import os import sys from functools import reduce import requests url = "https://api.github.com/graphql" token = os.environ["GITHUB_TOKEN"] headers = {"Authorization": "bearer {}".format(token)} FIELDS = [ "name", "description", "sshUrl", "isArchived", "isFork", "isPrivate", "pushedAt", ] if __name__ == "__main__": who = sys.argv[1] edges = True after = None while edges: r = requests.post(url, json={"query": query(who, after)}, headers=headers) edges = json.loads(r.text)["data"]["organization"]["repositories"]["edges"] for e in edges: print(json.dumps(node(e))) after = edges[-1]["cursor"]
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 37811, 198, 3855, 257, 33918, 10285, 286, 477, 262, 1128, 418, 16686, 284, 257, 21722, 8745, 393, 2836, 13, 198, 37811, 198, 198, 11748, 33918, 198, 11748, 28686, 198, 11748, ...
2.356522
345
from conans import ConanFile, CMake, tools, RunEnvironment
[ 6738, 369, 504, 1330, 31634, 8979, 11, 327, 12050, 11, 4899, 11, 5660, 31441, 628 ]
4
15
from django import template from datetime import datetime from datetime import date from datetime import time from datetime import timedelta register = template.Library()
[ 6738, 42625, 14208, 1330, 11055, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 4818, 8079, 1330, 3128, 198, 6738, 4818, 8079, 1330, 640, 198, 6738, 4818, 8079, 1330, 28805, 12514, 198, 198, 30238, 796, 11055, 13, 23377, 3419 ]
4.384615
39
""" title : ma.py description : Marshmallow object author : Amanda Garcia-Garcia version : 0 usage : python server_api.py python_version : 3.6.1 """ from flask_marshmallow import Marshmallow ma = Marshmallow()
[ 37811, 198, 7839, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 1058, 17266, 13, 9078, 198, 11213, 220, 220, 220, 220, 1058, 9786, 42725, 2134, 198, 9800, 220, 220, 220, 220, 220, 220, 220, 220, 220, 1058, 23040, 18555, 12, 38, ...
2.351852
108
#!/usr/bin/env python ### This program simulates Fisher's geometric model with abiotic change equal to fixations during conflict simulations (from FGMconflict.py) ### ### python3 FGMabiotic.py -help for input options ### ### Written by Trey J Scott 2018 ### ### python --version ### ### Python 3.5.2 :: Anaconda 4.2.0 (x86_64) ### # Import programs import random import numpy as np from scipy.spatial import distance as dist from scipy.stats import norm import scipy.stats as stats import matplotlib.pyplot as plt import pandas as pd import argparse import scipy.special as spc from itertools import groupby ### FUNCTIONS ### # Function to generate random mutations with a specified average size # Gaussian fitness function # Calculates probability of fixation for new mutations # Functon that simulates adaptation to a moving optimum with Fisher's geometric model # Runs simulations multiple times ### SET ARGUMENTS ap = argparse.ArgumentParser() ap.add_argument('-x', '--samples', help = 'number of resamples', type = int) ap.add_argument('-p', '--population_size1', help = 'population size for one population', type = int) ap.add_argument('-pp', '--population_size2', help = 'population size for second population', type = int) ap.add_argument('-m', '--mutations', help = 'mutation distribution for mutation vectors') ap.add_argument('-q', '--Q', help = 'changes Q parameter in fitness function', type = float) ap.add_argument('-z', '--attempts', help = 'number of generations per walk', type = int) ap.add_argument('-c', '--init_fit', help = 'changes the distance optimal values by a factor of the input value', type = float) ap.add_argument('-r', '--rate', help = 'mutation rate for population 1', type = int) ap.add_argument('-b', '--burn_in', help = 'define burn in period for equilibrium', type = int) ap.add_argument('-a', '--ave_mut', help = 'average mutation norm', type = float) ap.add_argument('-d', '--selection', help = 'Adjust strength of selection', type = float) ap.add_argument('-mut', '--changes', help = 'mutation file for moving optimum', type = str) args = ap.parse_args() # get arguments if args.samples: samples = args.samples else: samples = 500 # Define initial position and optima position1 = np.zeros(1) position = position1 position2 = position1 if args.init_fit: r = 1-args.init_fit else: r = 1-0.2 # Set average norm size for mutations if args.ave_mut: average_mutation = args.ave_mut else: average_mutation = 0.1 # Get population sizes # Population 1 if args.population_size1: N_1 = 10**(args.population_size1) else: N_1 = 'infinite' # Population 2 if args.population_size2: N_2 = 10**(args.population_size2) else: N_2 = 'infinite' # Get distributions # Mutation distribution (default is uniform) if args.mutations: distribution = args.mutations else: distribution = 'normal' # Number of mutations if args.attempts: m = args.attempts else: m = 50000 # Get mutation rate if args.rate: rate = args.rate else: rate = 1 # Calculate normalization factor (used in mutation function) sd_1d = average_mutation*((np.pi)**(1/2))/(2**(1/2)) uni = 2*average_mutation expo = average_mutation if args.burn_in: burn_in = args.burn_in else: burn_in = 0 if args.Q: Q = args.Q q_string = 'Q_' + str(Q) + '_' else: Q = 2 q_string = '' if args.selection: d1 = args.selection else: d1 = 0.5 if args.changes: shake_file = args.changes[:-7] + 'mut.csv' # Open output file output = open('abiotic_data.csv', 'w') output.write('Iteration,Simulation,z,s,Mutation Size,Fitness,Population,Status\n') ### Run simulations run_simulations(position, samples)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 21017, 770, 1430, 985, 15968, 14388, 338, 38445, 2746, 351, 450, 16357, 1487, 4961, 284, 4259, 602, 1141, 5358, 27785, 357, 6738, 376, 15548, 10414, 13758, 13, 9078, 8, 44386, 198, ...
3.031145
1,188
import spidev import RPi.GPIO as GPIO import time import yaml with open("config.yml", 'r') as f: cfg = yaml.load(f, Loader=yaml.FullLoader) # Pin definition RST_PIN = cfg['pinout']['RST_PIN'] DC_PIN = cfg['pinout']['DC_PIN'] CS_PIN = cfg['pinout']['CS_PIN'] BUSY_PIN = cfg['pinout']['BUSY_PIN'] # SPI device, bus = 0, device = 0 SPI = spidev.SpiDev(0, 0)
[ 11748, 599, 485, 85, 198, 11748, 25812, 72, 13, 16960, 9399, 355, 50143, 198, 11748, 640, 198, 11748, 331, 43695, 628, 198, 4480, 1280, 7203, 11250, 13, 88, 4029, 1600, 705, 81, 11537, 355, 277, 25, 198, 220, 220, 220, 30218, 70, 79...
2.186747
166
from datetime import date from unicodedata import name from urllib import request import requests from bs4 import BeautifulSoup as bs import pandas as pd import datetime import os import zipfile import glob CoinName= input('Enter the coin name: ').upper() duration= input('Enter the duration of data you want(1m,1h,2h): ').lower() start_date= input ('Enter the date (dd-mm-yyyy): ') end_date= input('Enter the end date (dd-mm-yyyy): ') coin= requests.get('https://data.binance.vision/?prefix=data/spot/daily/klines/') ucoin= bs(coin.content , 'html.parser') start = datetime.datetime.strptime(start_date, "%d-%m-%Y") end = datetime.datetime.strptime(end_date, "%d-%m-%Y") date_generated = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days)] date_list=[] for date in date_generated: x=date.strftime("%Y-%m-%d") date_list.append(x) file_name_list= [] cols=['opening time', 'opening price','highest price','lowest price','closing price','volume','closing time','turnover','number of transactions','active buy volume','NA','NAN'] for item in date_list: try: file_name=(f'{CoinName}-{duration}-{item}.zip') download_mainurl= (f'https://data.binance.vision/data/spot/daily/klines/{CoinName}/{duration}/{CoinName}-{duration}-{item}.zip') download= requests.get(download_mainurl, allow_redirects= True) print(f'Scrapping data of {item} ') with open(file_name, 'wb') as f: f.write(download.content) with zipfile.ZipFile(file_name, 'r') as zip_ref: zip_ref.extractall('C:/Users/rocka/Desktop/Practice python/Binance data scrapper/data') file_name_list.append(file_name+'.csv') os.remove(file_name) except: print('skipped') continue master_df= pd.DataFrame() for file in os.listdir('C:/Users/rocka/Desktop/Practice python/Binance data scrapper/data'): if file.endswith('.csv'): master_df= master_df.append(pd.read_csv('C:/Users/rocka/Desktop/Practice python/Binance data scrapper/data/'+file, names= cols)) master_df.to_csv(f'{CoinName}-{duration}-master file.csv', index=False) for file in os.listdir('C:/Users/rocka/Desktop/Practice python/Binance data scrapper/data'): if file.endswith('.csv'): os.remove('C:/Users/rocka/Desktop/Practice python/Binance data scrapper/data/'+file) print('Data Scrapped sucessfully!!!')
[ 6738, 4818, 8079, 1330, 3128, 201, 198, 6738, 28000, 9043, 1045, 1330, 1438, 201, 198, 6738, 2956, 297, 571, 1330, 2581, 201, 198, 11748, 7007, 201, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 355, 275, 82, 201, 198, 11748, 19798,...
2.422964
1,019
from flask import Flask, jsonify, request, session,redirect, url_for import bcrypt from flask_sqlalchemy import SQLAlchemy from sqlalchemy.sql import func from sqlalchemy.exc import IntegrityError import os from sqlalchemy.orm import load_only from flask_bcrypt import Bcrypt import urllib.parse from itertools import groupby from operator import attrgetter import json from flask_cors import CORS, cross_origin from flask_session import Session import redis from werkzeug.utils import secure_filename from datetime import datetime, timedelta, timezone from models import db, tweet_database, User, LoginForm, Project, Submission, CompareSubmission from dotenv import load_dotenv from flask_login import LoginManager, login_required, login_user, current_user, logout_user from sqlalchemy.orm import sessionmaker import pandas as pd import requests from sqlalchemy.types import String, DateTime import io load_dotenv() app = Flask(__name__,static_folder="../build", static_url_path='/')# app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///HarveyTwitter.db" app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True app.config["SECRET_KEY"] = "6236413AA53537DE57D1F6931653B" app.config['SQLALCHEMY_ECHO'] = True app.config['SESSION_TYPE'] = "filesystem" # causes bugs right here this needs to be in redis soon need to download reddis and do some reddis cli stuff app.config['SESSION_USE_SIGNER'] = True #app.config['SESSION_COOKIE_NAME'] #app.config['SESSION_COOKIE_DOMAIN] #app.config['SESSIO N_COOKies] #app.config['SESSION_COOKIE_SECURE'] = True # add this to make the cookies invisible or something bcrypt = Bcrypt(app) # this is encyrpt the app CORS(app, supports_credentials=True) server_session = Session(app) db.__init__(app) with app.app_context(): db.create_all() login_manager = LoginManager() login_manager.init_app(app) with app.app_context(): # before intialization of the app, commands under here are ran first # Replace with the commented when running the command gunicorn3 -w 3 GeoAnnotator.api:app optionsData = jsonify(json.load(open('../../createProjectOptions.json'))) # 'GeoAnnotator/api/createProjectOptions.json' configurationsData = json.load(open('../../configuration_data.json')) # 'GeoAnnotator/api/configuration_data.json' if __name__ == '__main__': app.run(host='0.0.0.0')
[ 6738, 42903, 1330, 46947, 11, 33918, 1958, 11, 2581, 11, 6246, 11, 445, 1060, 11, 19016, 62, 1640, 198, 11748, 275, 29609, 220, 198, 6738, 42903, 62, 25410, 282, 26599, 1330, 16363, 2348, 26599, 198, 6738, 44161, 282, 26599, 13, 25410, ...
3.069737
760
from django import forms from .pqrsf import pqrsf
[ 6738, 42625, 14208, 1330, 5107, 198, 6738, 764, 79, 80, 3808, 69, 1330, 279, 80, 3808, 69, 198 ]
2.777778
18
__doc__ = ''' This file is generated by the `prisma-client-py-tortoise-orm (0.2.2)`, Please do not modify directly. repository: https://github.com/mao-shonen/prisma-client-py-tortoise-orm ''' import typing from enum import Enum from tortoise import fields from tortoise.models import Model from prisma import base as base __all__ = ['Role', 'User', 'Post', 'Group']
[ 834, 15390, 834, 796, 705, 7061, 198, 1212, 2393, 318, 7560, 416, 262, 4600, 1050, 38017, 12, 16366, 12, 9078, 12, 83, 419, 25678, 12, 579, 357, 15, 13, 17, 13, 17, 8, 47671, 198, 5492, 466, 407, 13096, 3264, 13, 198, 198, 260, ...
2.967742
124
from os.path import join, realpath from os import listdir, environ import shlex import subprocess import pickle import json import pickle as pkl import time import numpy as np from copy import copy MODEL_PATH = ("/root/Projects/models/intel/person-detection-retail-0013/FP32" "/person-detection-retail-0013.xml") DATASET_PATH = "/root/Projects/train/" ALPHA = 0.1 ALPHA_HW = 0.01 RES_PATH = ("/root/Projects/gst-video-analytics-0.7.0/samples/" "people_on_stairs/classify_overspeeding/res.json") SVM_PATH = '/root/Projects/models/overspeed_classify/SVM_Classifier_without_interval.sav' CLASSIFY_PIPELINE_TEMPLATE = """gst-launch-1.0 filesrc \ location={} \ ! decodebin ! videoconvert ! video/x-raw,format=BGRx ! gvadetect \ model={} ! queue \ ! gvaspeedometer alpha={} alpha-hw={} interval=0.03333333 \ ! gvapython module={} class=OverspeedClassifier arg=[\\"{}\\"] \ ! fakesink sync=false""" if __name__ == "__main__": svclassifier = pickle.load(open(SVM_PATH, 'rb')) for file_name in listdir(DATASET_PATH): if file_name.endswith(".mp4"): video_path = join(DATASET_PATH, file_name) pipeline_str = CLASSIFY_PIPELINE_TEMPLATE.format( video_path, MODEL_PATH, ALPHA, ALPHA_HW, realpath(__file__), join(DATASET_PATH, file_name.replace('.mp4', '.json')) ) print(pipeline_str) proc = subprocess.run( shlex.split(pipeline_str), env=environ.copy()) if proc.returncode != 0: print("Error while running pipeline") exit(-1)
[ 6738, 28686, 13, 6978, 1330, 4654, 11, 1103, 6978, 198, 6738, 28686, 1330, 1351, 15908, 11, 551, 2268, 198, 11748, 427, 2588, 198, 11748, 850, 14681, 198, 11748, 2298, 293, 198, 11748, 33918, 198, 11748, 2298, 293, 355, 279, 41582, 198,...
2.043632
848
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2018-11-06 08:34 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 1157, 13, 17, 319, 2864, 12, 1157, 12, 3312, 8487, 25, 2682, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, ...
2.73913
69
import requests import json from urllib3.exceptions import HTTPError
[ 11748, 7007, 198, 11748, 33918, 198, 198, 6738, 2956, 297, 571, 18, 13, 1069, 11755, 1330, 14626, 12331, 628 ]
3.736842
19
from validators.validation_configurator import ValidationConfigurator from pipeline.models import InputFile
[ 6738, 4938, 2024, 13, 12102, 341, 62, 11250, 333, 1352, 1330, 3254, 24765, 16934, 333, 1352, 198, 6738, 11523, 13, 27530, 1330, 23412, 8979, 628 ]
4.36
25
from ..utils import Object
[ 198, 198, 6738, 11485, 26791, 1330, 9515, 628 ]
3.75
8
""" Exceptions for Read Group headers """
[ 37811, 198, 3109, 11755, 329, 4149, 4912, 24697, 198, 37811, 198 ]
3.818182
11
""" Tests for calculations. """ from __future__ import print_function from __future__ import absolute_import import os import numpy as np def test_process(logger_code): """ Test running a calculation. Also checks its outputs. """ from aiida.plugins import DataFactory, CalculationFactory from aiida.engine import run from aiida.common.extendeddicts import AttributeDict from aiida_logger.tests import TEST_DIR # pylint: disable=wrong-import-position # Prepare input parameters parameters = AttributeDict() parameters.comment_string = '#' parameters.labels = True # Define input files to use SinglefileData = DataFactory('singlefile') datafile = SinglefileData( file=os.path.join(TEST_DIR, 'input_files', 'datafile')) # Set up calculation inputs = { 'code': logger_code, 'parameters': DataFactory('dict')(dict=parameters), 'datafiles': { 'datafile': datafile }, 'metadata': { 'options': { 'resources': { 'num_machines': 1, 'num_mpiprocs_per_machine': 1 }, 'parser_name': 'logger', 'withmpi': False, 'output_filename': 'logger.out' }, 'description': 'Test job submission with the aiida_logger plugin' }, } result = run(CalculationFactory('logger'), **inputs) assert 'data' in result assert 'metadata' in result data = result['data'] metadata = result['metadata'] metadata = metadata.get_dict() assert 'labels' in metadata assert 'comments' in metadata assert metadata['labels'] == ['time', 'param1', 'param2', 'param3'] assert metadata['comments'][0] == '# This is an example file' test_array = np.array([[1.0e+00, 3.0e+00, 4.0e+00, 5.0e+00], [2.0e+00, 4.0e+00, 5.7e+00, -1.0e-01], [3.0e+00, 1.0e-03, 1.0e+03, 8.0e-01]]) np.testing.assert_allclose(data.get_array('content'), test_array)
[ 37811, 220, 198, 51, 3558, 329, 16765, 13, 198, 198, 37811, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 11748, 28686, 198, 11748, 299, 32152, 355, 45941, 628, 198, ...
2.236674
938
#!/usr/bin/env python3 # -*- coding:utf-8 -*- """Requests test package initialisation."""
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 198, 37811, 16844, 3558, 1332, 5301, 4238, 5612, 526, 15931 ]
2.727273
33
import json import logging import os from typing import List, Dict import click import numpy as np import tensorflow as tf from sklearn.metrics import cohen_kappa_score, precision_recall_fscore_support, accuracy_score from tqdm import tqdm from discopy.components.component import Component from discopy.components.connective.base import get_connective_candidates from discopy.evaluate.conll import evaluate_docs, print_results from discopy.utils import init_logger from discopy_data.data.doc import Document from discopy_data.data.loaders.conll import load_bert_conll_dataset from discopy_data.data.relation import Relation logger = logging.getLogger('discopy') if __name__ == "__main__": main()
[ 11748, 33918, 198, 11748, 18931, 198, 11748, 28686, 198, 6738, 19720, 1330, 7343, 11, 360, 713, 198, 198, 11748, 3904, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 1341, 35720, 13, 4164, 10466,...
3.281106
217
from django.db import models
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 628 ]
3.75
8
from enum import Enum
[ 6738, 33829, 1330, 2039, 388, 628, 628 ]
3.571429
7
from flask import Flask, render_template, request, url_for, redirect from forms import * from model import generate_recommendations, get_desc import os app = Flask(__name__) SECRET_KEY = os.urandom(32) app.config['SECRET_KEY'] = SECRET_KEY if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
[ 6738, 42903, 1330, 46947, 11, 8543, 62, 28243, 11, 2581, 11, 19016, 62, 1640, 11, 18941, 198, 6738, 5107, 1330, 1635, 198, 6738, 2746, 1330, 7716, 62, 47335, 437, 602, 11, 651, 62, 20147, 198, 11748, 28686, 198, 198, 1324, 796, 46947,...
2.809091
110
import matplotlib import matplotlib.pyplot as plt import numpy as np labels = ['AP on bin (0,10)', 'AP on bin (10,100)'] baseline = [0.0, 13.3] fc2_ncm = [6.0, 18.9] fc2 = [8.6, 22.0] fc3_rand = [9.1, 18.8] fc3_ft = [13.2, 23.1] x = np.arange(len(labels)) # the label locations width = 0.15 # the width of the bars matplotlib.rcParams.update({'font.size': 16}) # plt.rc('ytick', labelsize=10) fig, ax = plt.subplots() # rects1 = ax.bar(x - width, baseline, width, label='baseline') # rects2 = ax.bar(x - width/2, fc2_ncm, width, label='2fc_ncm') # rects3 = ax.bar(x , baseline, fc2, label='baseline') # rects4 = ax.bar(x + width/2, fc3_rand, width, label='2fc_ncm') # rects5 = ax.bar(x + width, fc3_ft, width, label='baseline') # Set position of bar on X axis r1 = np.arange(len(labels)) r2 = [x + width for x in r1] r3 = [x + width for x in r2] r4 = [x + width for x in r3] r5 = [x + width for x in r4] # Make the plot rects1 = ax.bar(r1, baseline, color='#7f6d5f', width=width, edgecolor='white', label='baseline') rects2 = ax.bar(r2, fc2_ncm, color='#557f2d', width=width, edgecolor='white', label='2fc_ncm') rects3 = ax.bar(r3, fc2, width=width, edgecolor='white', label='2fc_rand') rects4 = ax.bar(r4, fc3_rand, width=width, edgecolor='white', label='3fc_rand') rects5 = ax.bar(r5, fc3_ft, width=width, edgecolor='white', label='3fc_ft') ax.set_ylim([0,25]) ax.set_xticks([0.3, 1.3]) ax.set_xticklabels(labels) ax.legend() def autolabel(rects): """Attach a text label above each bar in *rects*, displaying its height.""" for rect in rects: height = rect.get_height() ax.annotate('{}'.format(height), xy=(rect.get_x() + rect.get_width() / 2, height), xytext=(0, 3), # 3 points vertical offset textcoords="offset points", ha='center', va='bottom') autolabel(rects1) autolabel(rects2) autolabel(rects3) autolabel(rects4) autolabel(rects5) fig.tight_layout() plt.savefig('head_design_choices.eps', format='eps', dpi=1000) plt.show()
[ 11748, 2603, 29487, 8019, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 628, 198, 23912, 1424, 796, 37250, 2969, 319, 9874, 357, 15, 11, 940, 8, 3256, 705, 2969, 319, 9874, 357, 940,...
2.169831
948
from datetime import datetime from itertools import count from tkinter import * import tkinter.ttk as ttk from functools import partial from tkcalendar import DateEntry from case import COD, CONTRIES, Case, INCIDENT, ORGANIZATION, POLICESTATION, STATES from db import referred_other_agency from preview import CasePreview if __name__ == '__main__': root = Tk() entry = CaseEntry(root) entry.pack() root.mainloop()
[ 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 340, 861, 10141, 1330, 954, 198, 6738, 256, 74, 3849, 1330, 1635, 198, 11748, 256, 74, 3849, 13, 926, 74, 355, 256, 30488, 198, 198, 6738, 1257, 310, 10141, 1330, 13027, 198, 6738, 256, ...
3.085106
141