content
stringlengths
5
1.05M
#!/usr/bin/python3 # -*- coding: utf-8 -*- import logging import os import platform import sqlite3 import subprocess import sys import time from PyQt5.QtCore import Qt from PyQt5.QtGui import QFont, QIcon from PyQt5.QtWidgets import * sf_name = "commander" dbname = './yunqi.db' # 存储预设的数据库名字 presetTableName = 'comman...
from django.db import models # Create your models here. from .toolGroup import * from .tool import * from .timeSlot import *
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Feb 3 16:53:55 2021 @author: lenakilian """ import pandas as pd import numpy as np import matplotlib.pyplot as plt import copy as cp data_dir = r'/Users/lenakilian/Documents/Ausbildung/UoLeeds/PhD/Analysis/data/' first_year = 2007 last_year = 2016 ...
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # (C) British Crown Copyright 2017-2020 Met Office. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions a...
# -*- coding: utf-8; -*- """Axially moving solid, Eulerian view, small-displacement regime (on top of axial motion).""" import numpy as np import matplotlib.pyplot as plt from unpythonic import ETAEstimator, timer, Popper from fenics import (FunctionSpace, VectorFunctionSpace, TensorFunctionSpace, ...
from __future__ import unicode_literals import os import time import json import logging import requests from nose.tools import assert_equals, assert_true, assert_is_not_none, assert_is_none, assert_false RETRIES=100 TIMEOUT=3 def wait_for_automation_server(): logger.info('waiting for automation server') co...
__author__ = "Riccardo De Zen <riccardodezen98@gmail.com>" import unittest import numpy.testing from parameterized import parameterized from algorithms_for_engineering.matrix import Matrix, matrix_sum, matrix_product_naive, matrix_fractal_product class TestMatrix(unittest.TestCase): @parameterized.expand([[Mat...
from __future__ import annotations from enum import Enum, unique import logging import typing from dataclasses import dataclass from iaqualink.typing import DeviceData from iaqualink.const import ( AQUALINK_TEMP_CELSIUS_LOW, AQUALINK_TEMP_CELSIUS_HIGH, AQUALINK_TEMP_FAHRENHEIT_LOW, AQUALINK_TEMP_FAHR...
import pickle print("lstm word2vec 150") with open('lstm_word2vec_epoch_5_150d_f1s.p', 'rb') as f21: # The protocol version used is detected automatically, so we do not # have to specify it. data = pickle.load(f21) print("f1") print(data) with open('lstm_word2vec_epoch_5_150d_nbatch.p', 'rb') as f...
import os import pysynth as ps import uuid mapping = { 1: 'a0', 2: 'a#0', 3: 'b0', 4: 'c1', 5: 'c#1', 6: 'd1', 7: 'd#1', 8: 'e1', 9: 'f1', 10: 'f#1', 11: 'g1', 12: 'g#1', 13: 'a1', 14: 'a#1', 15: 'b1', 16: 'c2', 17: 'c#2', 18: 'd2', 19: 'd#2'...
import os import sys import json import argparse import os import subprocess import io import time from mpi4py import MPI comm = MPI.COMM_WORLD my_rank = comm.Get_rank() comm_sz = comm.Get_size() parser = argparse.ArgumentParser() parser.add_argument('-i', '-interval', '--interval', default='5') ...
import unittest import pandas as pd import numpy as np from pyrate.rate import ratingbase from pyrate.rate import leastsquares from pyrate.rate import mle from pyrate.rate import gom class ToyLeagueHyper(unittest.TestCase): def setUp(self): # Data from Massey (1997) Example 4.2. Home/away values have ...
""" The main configuration for the latex generator. """ class LatexConfigError(Exception): pass class LatexConfiguration: def __init__(self): self.document_class = None self.class_options = None def check_configuration(self): if not self.document_class: raise LatexConf...
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
def hilbert(): pass
""" HTML color names. For more details, see https://developer.mozilla.org/ru/docs/Web/CSS/color_value. """ COLOR_NAMES_TO_HEX = { """ A map of HTML color names to their hex values. """ "black": "#000000ff", "silver": "#c0c0c0ff", "gray": "#808080ff", "white": "#ffffffff", "maroon": "#...
# # Copyright (c) 2017 Luis F. Simoes (github: @lfsimoes) # # Licensed under the MIT License. See the LICENSE file for details. from math import sqrt, exp from functools import wraps, partial #, total_ordering import numpy as np import PyKEP as pk from scipy.optimize import minimize_scalar from .constants import ...
# アプリケーション上で使うラベル from collections import OrderedDict # TODO フロントエンドを実装する時はいらなくなるかもしれない # 順番をちゃんと決めたいので敢えてOrderdDictで実装 THROWS = OrderedDict() THROWS['R'] = '右' THROWS['L'] = '左' PITCH_TYPES = OrderedDict() # まっすぐ系→次に早い系→遅い系の順番で PITCH_TYPES['FF'] = '4シーム' PITCH_TYPES['FT'] = '2シーム' PITCH_TYPES['SI'] = 'シンカー' PITCH_T...
from news_scrapper import scrape print "Test Case #1" print scrape.SentimentNews('AAPL') print "Test Case #2" print scrape.SentimentNews('GOOG') print "Test Case #3" print scrape.SentimentNews('T')
from django.db import models # Create your models here. class File(models.Model): file_name = models.CharField(max_length=500) upload = models.FileField(upload_to='uploads/')
#Imports import random #Constants MAGIC_SHUFFLE_NUMBER = 7 END_GAME = 21 DEALER_NUMER = 17 ACE_DIFF = 10 #Game deck, used to shuffle and keep track of cards class Deck(object): # 4 Suits suits = ["Hearts", "Diamonds", "Clubs", "Spades"] # 13 different values, last 3 are face cards worth 10 values = ra...
from glob import glob import os, shutil val_dir="./val" train_dir="./train" val_folders=glob(os.path.join(val_dir,"*")) train_folders=glob(os.path.join(train_dir,"*")) for val_folder,train_folder in zip(val_folders,train_folders): imgs=glob(os.path.join(val_folder,"*")) for img in imgs: try: ...
# Generated by Django 2.1.2 on 2018-11-28 20:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('velhot', '0011_auto_20181128_0303'), ] operations = [ migrations.AlterField( model_name='chat', name='created', ...
import pytest from unittest.mock import Mock from eth_utils import ( decode_hex, ) from web3.contract import ( CONCISE_NORMALIZERS, ConciseContract, ConciseMethod, ) @pytest.fixture() def EMPTY_ADDR(): return '0x' + '00' * 20 @pytest.fixture() def zero_address_contract(web3, WithConstructorAdd...
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- from ._do...
from numpy import random x = random.choice([3, 5, 7, 9], p=[0.1, 0.3, 0.6, 0.0], size=(100)) print(x)
import os from enum import Enum from functools import partial from pathlib import Path from strictdoc.backend.dsl.models.document import Document from strictdoc.cli.cli_arg_parser import ExportCommandConfig from strictdoc.core.document_meta import DocumentMeta from strictdoc.core.document_tree import DocumentTree from...
class ModelPath(object, IDisposable): """ A path to a file stored on a disk or on a server. """ def Compare(self, otherPath): """ Compare(self: ModelPath,otherPath: ModelPath) -> int Compares this ModelPath with another otherPath: The path to compare against. Return...
#!/usr/bin/env python #coding=utf-8 import os, sys sys.path.append(os.path.abspath(os.path.dirname(__file__))) # from flask.ext.script import Manager, Server from flask_script import Manager, Server # from OctBlog import create_app # app = create_app(os.getenv('config') or 'default') from miniblog import app mana...
from .token import Token from .user import User
#!/usr/bin/env python import os import numpy as np from pyems.utilities import print_table from pyems.port import RectWaveguidePort from pyems.simulation import Simulation from pyems.field_dump import FieldDump from pyems.structure import standard_waveguides from pyems.coordinate import Coordinate3, Box3, Axis from py...
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.converter import TextConverter from pdfminer.layout import LAParams from pdfminer.pdfpage import PDFPage from cStringIO import StringIO import re import pprint import json from collections import deque def _convert_pdf_to_txt(path): ...
# -*- coding: UTF-8 -*- from django.shortcuts import render # Create your views here. from django.shortcuts import render # Create your views here. from django.http import HttpResponse, HttpResponseRedirect from django.template import loader, Context from django.shortcuts import render_to_response from django.views....
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : qichun tang # @Contact : tqichun@gmail.com # from skopt.learning.forest import RandomForestRegressor, ExtraTreesRegressor # from skopt.learning.gbrt import GradientBoostingQuantileRegressor from copy import deepcopy import numpy as np from frozendict import...
import argparse import tensorflow as tf import utils import data_reader import network_maker import network_helper INPUT_SIZE = 2 FC_FILTERS = (50, 100, 500, 50) TCONV_DIMS = (50, 150, 300) TCONV_FILTERS = (16, 8, 4) X_RANGE = [0, 1] Y_RANGE = [i for i in range(2, 1003)] CROSS_VAL = 5 VAL_FOLD = 0 BATCH_SIZE = 20 SHU...
import json from player_manager.models import Player from guild_manager.models import Guild from game_map.utils import notify_dynamic_map_structure_change from websocket_controller import WebsocketRoutes from websocket_controller.message_utils import error_message, SUCCESS_MESSAGE from city_game_backend import CONSTANT...
import pandas as pd import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sns import statsmodels.formula.api as statsform from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error from sklearn.metrics import mean_absolute_error i...
import math import torch from torch import tensor, zeros import torch.nn.init as init from torch.autograd import Variable import torch.nn.functional as F from torch.autograd import Function sqrt_of_2 = math.sqrt(2) eps = 1e-5 def my_mean(x): size = x.size() size_tensor = torch.Tensor([s for s in size]) e...
import copy import numpy as np from random import randint from CommonUtils.StaticStorage import StaticStorage class DE_: def __init__(self, params, calculate_objectives, evolutionary_operators, visualiser, greedy_heuristic): ''' Differential Evolution Algorithm (DE) ''' self.param...
"""Build forest graph from edges Assuming forest is represented as a list of edges as list of child-parent pairs: >>> l = ["A1 B", "C1 D", "A2 B", "C2 D", "A3 B"] build a forest (list of trees) as a dictionary: >>> { >>> "B": { "A1": {}, "A2": {}, "A3": {} }, >>> "D": { "C1": {}, "C2": {} } >>> } """ from ...
#!/usr/bin/env python3 #simulates monty hal problem from random import shuffle, choice tests = 10000 results_switched = [0] * tests results_stayed = [0] * tests def runtest(isSwitch, result): for i in range(tests): # Generate random prize sequence all_doors_contents = ['Prize', 'Goat', 'Goat'] ...
def f(n): if n==0: return 1 else: for i in range(n): f(n-1)
# Date: September 2017 # Author: Kutay B. Sezginel """ Initialize Lammps simulation using lammps_interface """ import os import glob from lammps_interface.lammps_main import LammpsSimulation from lammps_interface.structure_data import from_CIF from . import read_lines, write_lines from thermof.sample import lammps_inpu...
from apispec import APISpec from apispec.ext.marshmallow import MarshmallowPlugin from flask_apispec.extension import FlaskApiSpec from app import BaseUrl class ApiDocs: """Class for Flask-Apispec Autodocs""" def __init__(self, app, version): """Constructor""" self.app = app self.titl...
# -*- coding: utf-8 -*- import json from scrapy import FormRequest from scrapy_ddiy.utils.common import get_str_md5 from scrapy_ddiy.utils.spiders.ddiy_base import DdiyBaseSpider """ ALAPI:QPS限制为3 , 每天限制请求100次 """ class AlapiDogSpider(DdiyBaseSpider): description = 'ALAPI-舔狗日记' name = 'alapi_dog' start_u...
#!/usr/bin/env python import json from kafka import KafkaProducer from flask import Flask, request, session app = Flask(__name__) producer = KafkaProducer(bootstrap_servers='kafka:29092') def log_to_kafka(topic, event): event.update(request.headers) producer.send(topic, json.dumps(event).encode()) @app.rout...
""" Author: Salva Rühling Cachay """ import argparse import time import wandb from climart.models.GNs.constants import GLOBALS from climart.models.interface import is_gnn, is_cnn, is_graph_net from climart.utils.utils import set_gpu, get_name def get_argparser(jupyter_mode=False): parser = argparse.ArgumentPar...
#!usr/bin/env python # # Copyright 2018 houjingyong@gmail.com # # MIT Lisence from __future__ import absolute_import from __future__ import print_function class KWS_Label(): def __init__(self, meta_file): self.label_dict = dict() with open(meta_file) as fid: self.metadata = [line.str...
# (c) 2021 Okawo # This code is licensed under MIT license (see LICENSE for details) """Python entry point.""" from . import main main.main()
import subprocess import time from asynchronousfilereader import AsynchronousFileReader __version__ = '0.0.1' class ProcessManager(object): def __init__(self): self._command = None self._process = None self._stdout = None self._stderr = None def start_process(self, command):...
import pandas as pd import numpy as np from sklearn.metrics.pairwise import linear_kernel from sklearn.feature_extraction.text import TfidfVectorizer df = pd.read_csv("book_data.csv") df = df.dropna() df2 = df['genres'].str.split('|', expand=True) df2.head(10) df['genres'] = df2[0] df.drop_duplicates('book_title', i...
"""Module containing helper functions.""" import ConfigParser # import io from itertools import islice def get_data_dict(data): """Method: Cleanup data and convert it in the dict format.""" data_s = data.to_json() # string data_d = json.loads(data_s) # dict return data_d def take(n, iterable): "...
""" Area and amplitude spectrum for photon recorded in different pile-up fraction and dpe fraction. Lanqing Yuan, Jan 10 2022 """ import numpy as np import straxen import pandas as pd import sys from tqdm import tqdm ######################## # Amplitude acceptance # ######################## def get_avg_spe_amp(top...
import matplotlib.pyplot as plt import numpy as np import matplotlib as mlt from matplotlib.patches import Polygon, Wedge, Rectangle, FancyBboxPatch, BoxStyle y_lim = 260000000 chr1_size = 249250621 fig = plt.figure(num=None, figsize=(5,6)) # plt.ylim([-10000000, y_lim]) plt.xlim([0, 5]) # plt.axes.get_xaxis().set...
import sys import os extensions = [ "sphinx.ext.autodoc", # Support automatic documentation "sphinx.ext.coverage", # Automatically check if functions are documented "sphinx.ext.mathjax", # Allow support for algebra "sphinx.ext.viewcode", # Include the source code in documentation "numpydoc", #...
import os from pathlib import Path import sys from arcgis import GeoAccessor from arcgis.geometry import Geometry import arcpy import pandas as pd import pytest # facilitate local resource imports project_dir_str = Path(os.path.abspath(os.path.join(os.path.dirname(__file__), '../'))) src_dir_str = project_dir_str sys...
# -*- coding: utf-8 -*- # generate a CSV file of meta data to be imported into MySQL import os import csv import numpy as np import h5py from PIL import Image dset = 'emoji' base = '/Users/yliu0/data/{}/'.format(dset) img_base = base + 'images/' h5 = base + '{}.h5'.format(dset) out = base + 'color.csv' img_rows, im...
from typing import Optional import numpy as np import torch import torch.nn.functional as F from .tensor import coerce_numpy @coerce_numpy def compute_precisions( predictions: torch.Tensor, targets: torch.Tensor, src_lengths: Optional[torch.Tensor] = None, minsep: int = 6, maxsep: Optional[int] = ...
# Random forest classifier to predict names only from MachineLearning.RandomForestAll import RandomForestAll class RandomForestNames(RandomForestAll): def __init__(self): super().__init__() # Selects only the names from the dataframe to train the model on def __selectData(self): name = ['...
import datetime from database.database_schemas import Schemas from sqlalchemy import Column, Integer, String, DateTime from database.base import Base class DescriptorSets(Base): """Maps to descriptor_sets table in qsar databases.""" __tablename__ = 'descriptor_sets' __table_args__ = {'schema': Schemas....
from sys import stdin import logging def main(): last_id = None last_county = None for line in stdin: line = line.strip() id, county, state = line.split(':') if id != last_id or county != last_county: print(f"{id}:{state}") last_id = id las...
# -*- coding: utf-8 -*- """ 16. 3Sum Closest 给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数, 使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。 例如,给定数组 nums = [-1,2,1,-4], 和 target = 1. 与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2). 解题思路: 和15题解法差不多,只是这里只需要三个数的和,而且不用处理重复情况的逻辑, 就是多加一个变量,用于判断是否最接近target,这个变量初始值一定要大,以免 在判断时把一些满...
import pygame class Ship(): def __init__(self, scree, ai_setting): super().__init__() self.scree = scree self.ai_settings = ai_setting # 加载飞船外形以及外接矩形 self.image = pygame.image.load('外星人游戏/img/ship.bmp') self.rect = self.image.get_rect() self.scree_rect = scr...
from config import app from config.clv_base import SlaveHandler __all__ = ["slave"] slave = SlaveHandler(app)
from category import Category cats = { "legs": Category("False Legs"), "bats": Category("Baseball Bats"), "fruit": Category("Fruit"), "special": Category("Bobs Special Place") }
import os import platform import pytest from mist.action_run import execute_from_text CHECK_FILE = "bool_func_if.mist" @pytest.mark.asyncio async def test_check_if_bool_functions(examples_path): with open(os.path.join(examples_path, CHECK_FILE), "r") as f: content = f.read() output = await execute_f...
from collections import namedtuple DateRangeFacet = namedtuple('DateRangeFacet', ('slug', 'label', 'date_range')) def get_field_facets(facet_counts, facet_name, key=None): def key_method(facet): return key(facet[0]) facets = facet_counts.get('fields', {}).get(facet_name, []) facets = [(item, c...
import anndata import napari import numpy as np from morphometrics._gui._qt.annotation_widgets import QtClusterAnnotatorWidget from morphometrics.data import cylinders_and_spheres from morphometrics.explore.cluster import cluster_features from morphometrics.explore.dimensionality_reduction import pca, umap from morpho...
import os import signal import threading from subprocess import check_output, Popen from http.server import HTTPServer, BaseHTTPRequestHandler from urllib.parse import urlparse, parse_qs from unittest import TestCase import pytest from brotab.tests.utils import wait_net_service from brotab.mediator.brotab_mediator im...
#!/usr/bin/env python from time import sleep import os import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) R9 = 10000 #in ohms (see schematic) R10 = 6800 #in ohms VoltageThreshold = 4.8 #TODO: determine it empirically n = 1024 #Resolution MCP3001 #numeros de pins SPICLK = 6 SPIMISO = 5 #DOUT SPIC...
#!/usr/bin/env python2 # RunReadingComprehension.py # Created 12/11/14 by DJ based on PlaySoundsWithQuestions.py. # Updated 11/9/15 by DJ - cleanup import os, random from psychopy import visual, event, core, sound #declare parameters questionDur_sec = 8 # time between questions randomize_questions = True #nTrials = ...
from .base_trainer import E2ETrainer from .base_trainer import ImageFirstE2ETrainer
#!/usr/bin/env python import sys import rospy import math3d import moveit_commander import geometry_msgs.msg from std_msgs.msg import Float64 from dynamixel_controllers.srv import TorqueEnable from cute_unit_app.srv import GetObject class PickPlace: def __init__(self): self.__arm_group = moveit_comman...
import json import random import tornado.ioloop import tornado.web import tornado.websocket class MainHandler(tornado.web.RequestHandler): def get(self): self.write('Foo') class SyncSocket(tornado.websocket.WebSocketHandler): clients = set() states = dict() def check_origin(self, origin): ...
# coding: utf-8 import festune.index import festune.playlist from pelican import signals as pelican_signals import pelican.generators class SpotifyPlaylistGenerator(pelican.generators.Generator): playlists = None tracks = None def init(self): self.playlists = festune.index.FestonPlaylistsIndex()...
import math print("Kinjal Raykarmakar\nSec: CSE2H\tRoll: 29\n") N = int(input("Enter the kilometers per day(N): ")) M = int(input("Enter the total route length(M): ")) print("The car will take {} days".format(math.ceil(M/N)))
import sys from tp00 import Tp00 import tpUtils from constant import * import json import time class Tp28: """ #28 Ambient light sensor """ def __init__(self, slot, host=None): """ コンストラクタ """ self.slot = slot self.comm = I2C self.host = host ...
# Copyright 1999-2020 Alibaba Group Holding Ltd. # # 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 a...
#!/usr/bin/python # -*- mode: python -*- # -*- coding: utf-8 -*- # vi: set ft=python : import unittest from unittest import mock from unittest.mock import MagicMock import mimesis from deploy2ecscli.aws.client.config import Config from deploy2ecscli.aws.client.ecs.resources import Service from deploy2ecscli.aws.clie...
import pygame import math import time as t import random from entities.level import Level, Point, Tile, empty_next_tile_horiz, empty_next_tile_vert from entities.shot import Shot from entities.tank import Tank POSSIBLE_WAYS = [0, 1, 2, 3] def find_random_path(angle): angle //= 90 random.shuffle(POSSIBLE_WAY...
from telethon import TelegramClient,events UravxBuCwNMpYWTzKhPE=True UravxBuCwNMpYWTzKhPH=None UravxBuCwNMpYWTzKhPO=False UravxBuCwNMpYWTzKhPI=print UravxBuCwNMpYWTzKhPg=len UravxBuCwNMpYWTzKhRc=bytes UravxBuCwNMpYWTzKhRP=enumerate UravxBuCwNMpYWTzKhRA=exit UravxBuCwNMpYWTzKhRm=range UravxBuCwNMpYWTzKhRt=type UravxBuCw...
import sys import os import string import json class RTemplate(string.Template): delimiter = '@' def input(fname): species = [] fpath = os.path.abspath(fname) with open(fpath, 'r') as f: for line in f.readlines(): individuals = filter(lambda x: x != '', string.split(line.strip(), ' ')) sp...
import requests from lxml import etree import time import dateutil.parser import rsstastic class AtomReader() : def __init__(self,config) : self.url = config def get_items(self) : namespace = "{http://www.w3.org/2005/Atom}" response = requests.get(self.url) tree = etree.fromstri...
#import distorm from pyasm import * from distorm3 import * _REGS = ["RAX", "RCX", "RDX", "RBX", "RSP", "RBP", "RSI", "RDI", "R8", "R9", "R10", "R11", "R12", "R13", "R14", "R15", "EAX", "ECX", "EDX", "EBX", "ESP", "EBP", "ESI", "EDI", "R8D", "R9D", "R10D", "R11D", "R12D", "R13D", "R14D", "R15D", "AX", "CX", "DX...
LABELPATH = 'C:\\Data\\bn_bd\\line_index.tsv' SAVEPATH = 'C:\\Data\\bn_bd\\synth\\' import os import pandas as pd from gtts import gTTS df = pd.read_csv(LABELPATH,delimiter='\t', header = None) NSAMPLES = df.shape[0] for index, row in df.iterrows(): try: fileID = row[0] text = row[1] pri...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 22 12:03 2021 @author: MCR File containing all diagnostic plotting functions for the empirical trace construction and centroiding. """ import matplotlib.pyplot as plt import numpy as np import corner def _plot_centroid(clear, centroid_dict): ...
import pathlib import shutil import tempfile def appendzip(dest: pathlib.Path, file_to_include: pathlib.Path, arcname: str): if file_to_include.exists() is False: raise Exception("file to include does not exist") if dest.exists() is False: raise Exception("destination zip does not exist") ...
#!/usr/local/bin/python # -*- coding: utf-8 -*- # Author: illuz <iilluzen[at]gmail.com> # File: AC_simulation_n.py # Create Date: 2015-08-04 18:33:10 # Usage: AC_simulation_n.py # Descripton: class Solution: # @param {string} s # @param {string} t # @return {boolean} def isAnagram(...
import pandas as pd import numpy as np from sentence_transformers import SentenceTransformer from gensim.utils import tokenize from gensim.models import FastText from gensim.models.phrases import Phrases, Phraser from gensim.parsing.preprocessing import remove_stopwords, strip_punctuation, strip_non_alphanum from skle...
#!/usr/bin/env python # Copyright 2016 Ufora Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
####################################################################### ### Config.py: Configuration file for Save Tweets ### ### Copyright: Elena Daehnhardt ### ### Contact me at: edaehn@gmail.com ### ################################...
import os class DiscoverDQMFiles: def recursive_file_gen(self, mydir): for root, dirs, files in os.walk(mydir): for file in files: yield os.path.join(root, file) def filesList(self, sourceDir, type = ""): fullList = list(self.recursive_file_gen(sourceDir)) ...
# -*- coding:utf-8 -*- # @Time : 2021/11/26 22:26 # @Author : Sakura # @QQEmail : 1018655370@qq.com # @Google : jiangjiefeng0@gmail.com from rest_framework.serializers import ModelSerializer from rest_framework import serializers from . import models class ScoreSerializer(ModelSerializer): coursera_id = serialize...
import logging import os import random import subprocess import string import sys class CertGen: def __init__(self, config, SECURITY_DIR): self.logger = logging.getLogger("wms.cert-gen") try: data = subprocess.Popen([ "openssl", "version" ...
def solve(): data = input().split() rows = int(data[0]) cols = int(data[1]) horse_x = int(data[2]) horse_y = int(data[3]) horse_reached = horse_reach(horse_x, horse_y) board = [[0 for i in range(cols+1)] for j in range(rows+1)] board[0][0] = 1 for i in range(rows+1): for j...
import struct from typing import Union, Any from pygoridge.constants import PayloadType from pygoridge.exceptions import ServiceException, TransportException from pygoridge.json import json_dumps, json_loads from pygoridge.relay import Relay class RPC: def __init__(self, relay: Relay, ...
import hmac import hashlib from typing import Dict, Any class CryptoComAuth(): """ Auth class required by crypto.com API Learn more at https://exchange-docs.crypto.com/#digital-signature """ def __init__(self, api_key: str, secret_key: str): self.api_key = api_key self.secret_key =...
from pathlib import Path import cv2 from imutils import paths import sys,shutil import numpy as np from tqdm import tqdm import hashlib import time ## _md=hashlib.md5() ## def img_hash(img): img=cv2.resize(img,(10,10)) hash_=hash(str(img)) return hash_ def img_md5(img): _md.updat...
from autograd import numpy as np from autograd import grad, jacobian import numpy.matlib as nm from svgd import SVGD import sys #from mpltools import style #from mpltools import layout #style.use('ggplot') import matplotlib.pyplot as plt #-(1.0/(2*observation_variance))*(theta_i - time_series[t])**2 + np.log(1...
from .TemporalEngine import TemporalEngine