text
stringlengths
3.07k
22.1k
import random import numpy as np from PyQt5.QtWidgets import QMainWindow, QApplication from OpenGL import GL, GLU, GLUT import logging from ui.mainwindow import Ui_MainWindow def random_rgb(): """ Get random bright enough color """ color = [random.random() for _ in range(4)] if sum(color[:3]...
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : Main_Train.py @Description : @Time : 2020/11/23 14:50:36 @Author : <NAME> @Email : <EMAIL> @Version : 1.0 ''' import matplotlib as mpl # mpl.use('Agg') import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim imp...
import pkgutil, inspect, sys,os, importlib,json,enum,warnings,nbformat,re from IPython.core.display import display, Markdown from nbconvert.preprocessors import ExecutePreprocessor from pathlib import Path __all__ = ['create_module_page', 'generate_all', 'update_module_page', 'update_all'] def get_empty_notebook(): ...
import pandas as pd import sys class Installation: def __init__(self, _id, name, installation_power, azimuth, elevation, latitude, longitude, altitude, pv_cell_temp_noct, temp_coeff_of_current, temp_coeff_of_voltage, nominal_cell_power, short_circuit_current, open_circuit_voltag...
# -*- coding: utf-8 -*- """Console script to generate goals for real_robots""" import click import numpy as np from real_robots.envs import Goal import gym import math basePosition = None def pairwise_distances(a): b = a.reshape(a.shape[0], 1, a.shape[1]) return np.sqrt(np.einsum('ijk, ijk->ij', a-b, a-b))...
#!/usr/bin/env python # coding: utf-8 # # Ocean Optics Data Prep import os import io import sys import re import glob import math import numpy as np import pandas as pd from bric_analysis_libraries import standard_functions as std # # Data Prep def sample_from_file_name( file ): name_search = '^(.*?)' # u...
import time # from urllib import request import requests import json from bs4 import BeautifulSoup from getMaterial import * def GetResponse(url): headers = { "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8," "application/signed...
"""Command line / script utilities.""" # Copyright © 2019 <NAME> # # 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,...
import random import re from functools import lru_cache from pathlib import Path from typing import Tuple, List, Dict, Union, Iterator import numpy as np import torch from nltk.tokenize import PunktSentenceTokenizer, WordPunctTokenizer from torch import LongTensor, FloatTensor from torch.utils.data import Sampler, Dat...
from __future__ import print_function import qt import shutil import sys import os import time import progressbar from constants import * def copy_script(data, once): if once: shutil.copy2('%s'%sys.argv[0],'%s/%s'%(data.get_filepath()[:-(len(data.get_filename())+1)],os.path.basename(sys.argv[0...
''' Module containing data relating to DLPOLY field files ''' from collections import defaultdict from abc import ABC from dlpoly.species import Species from dlpoly.utility import read_line, peek class Interaction(ABC): ''' Abstract base class for managing atomic interactions ''' def __init__(self): ...
''' Created on Apr 5, 2012 @author: Dan ''' from Common.Shapes import * def xstr(s): return '' if s is None else str(s) class DevicePart(object): def __init__(self, device, symbolsDict, gates, converter): self.device = device self.name = str(device.fullName) + "_" + str( self.dev...
import os import queue import re from datetime import datetime from tkinter import Frame, StringVar, IntVar, DoubleVar, ttk, filedialog from tkinter import LEFT, RIGHT, BOTTOM, CENTER, X from admitad_feed_filter import AliexpressFeedFilter from style.fonts import LARGE_FONT NOW = datetime.now() CURRENT_DATE = NOW.str...
from __future__ import print_function import io import six import numpy import dynet as dy from enum import Enum from xml.sax.saxutils import escape, unescape from lxml import etree from scipy.stats import poisson import xnmt.linear as linear import xnmt.expression_sequence as expression_sequence from xnmt.events i...
"""A package to accelerate REST API development""" import getopt import logging import os import sys import time from dataclasses import Field, fields from functools import wraps from typing import Optional, Type from flask import jsonify, make_response from flask.wrappers import Response from nova_api import baseapi...
from datetime import datetime import pandas as pd import numpy as np from statistics import mean from fate_manager.db.db_models import ApplySiteInfo from fate_manager.entity.types import FateJobStatus, FateJobType, FateJobEndStatus from fate_manager.operation.db_operator import SingleOperation from fate_manager.oper...
import math import random import numpy as np import matplotlib.pyplot as plt import headers.constants as constants from headers.cmac import CMAC def generate_dataset(function, input_space_size=constants.plot_input_space_size, minimum_input_value=0, maximum_input_value=360, dataset_split_factor=0...
""" ШАШЕЧКИ """ class Checkers_figure(object): def __init__(self, Table, pos_y, pos_x, color): self.table = Table self.y = pos_y self.x = pos_x self.color = color self.symbol = '' def move(self, pos_y, pos_x, pos_y_cut, pos_x_cut): self.table.matrix[self.y][se...
import os import time import sys sys.path.append(os.getcwd()) import torch import src.train.atomic_train as train import src.models.models as models import src.data.data as data import utils.utils as utils import src.train.utils as train_utils import src.data.config as cfg from src.data.utils import TextEncoder from...
""" Insert a module description """ import math from operator import attrgetter from cab.abm.agent import CabAgent import cab.util.rng as cab_rng __author__ = '<NAME>' __version__ = '1.0' class Team: def __init__(self, number, color, walk, seed): self.number = number self.color = color ...
from flask import Flask, json, jsonify, request, render_template import subprocess import sys import os import warnings from datetime import datetime import time from math import pi from threading import Thread if 'RELDIR' in os.environ: sys.path.append('%s/lib/python' % os.environ['RELDIR']) else: warnings.wa...
''' Setup some utilities, very much related to our project of displaying figures in Jupyter. ''' __author__ = '<NAME>' __license__ = 'MIT License' __version__ = '1.0' # Sys import import sys, os, re # Python programming from itertools import cycle import time import datetime from enum import Enum, IntFlag from co...
#!/usr/bin/env python import random import operator import collections import uuid import math import heapq from .simulator import Simulator from .reward import Reward from .. import constants '''Globals''' STOP = constants.Action.Stop UP = constants.Action.Up DOWN = constants.Action.Down LEFT = constants.Action.Le...
# full assembly of the sub-parts to form the complete net # sub-parts of the U-Net model import torch import torch.nn as nn import torch.nn.functional as F class UNet(nn.Module): def __init__(self, n_channels, n_classes): super(UNet, self).__init__() self.down1 = down(n_channels, 32) sel...
#!/usr/bin/python3 # -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function from logging import error __metaclass__ = type ''' Cisco ACIスイッチのiShell上のコマンドshow lldp neighborsの出力結果を分析してデータを返却します。 コマンド出力結果はset_factsされていることを前提とします。 ''' __author__ = 'takamitsu-iida' __version__ = '0.1' __dat...
import json import argparse import os from os import path import codecs import matplotlib.pyplot as plt from matplotlib.pyplot import figure, savefig import numpy as np def list_codalab_bundles(root_dir): return [dir for dir in os.listdir(root_dir) \ if dir.endswith('-predict') and path.isdir(os.path....
# Implementing Different Layers # --------------------------------------- # # We will illustrate how to use different types # of layers in TensorFlow # # The layers of interest are: # (1) Convolutional Layer卷积层 # (2) Activation Layer激活层 # (3) Max-Pool Layer池化层 # (4) Fully Connected Layer 全连接层 # # We will generate t...
from http import HTTPStatus import os from urllib import parse import socket import mimetypes import subprocess import io class Request(object): """ A simple class to encapsulate reading and parsing a raw HTTP request string. It takes a client socket connection and stores the http command, resource path r...
# -*- coding: utf-8 -*- """ Created on Thu Feb 8 11:48:11 2018 @author: abaena """ #****************************************************************************** #Add logmapper-agent directory to python path for module execution #****************************************************************************** if __na...
# -*- coding: utf-8 -*- from django.utils.translation import ugettext_lazy as _ class CalcBase(object): _interval_borders = (0,2,8,10) @staticmethod def get_boundaries(value, lst, max_pts=10): ''' determines the position of the value in the provided list and returns the matching...
#!/usr/bin/env python from emanesh import manifest import os.path import re import textwrap class EmaneManifest2Model(object): class EmaneModel(object): class EmaneModelParameter(object): intfloat_regex = re.compile(r'^([0-9]+)\.(0*)$') indent = ' ' * 16 def __init_...
from __future__ import absolute_import, division, print_function import os import pickle import random import time import unittest import warnings from tempfile import mkstemp import numpy as np import tensorflow as tf from odin.ml import fast_pca from odin.utils import catch_warnings_ignore, md5_checksum from sisua...
#coding: utf-8 from django import http from m3_ext.ui.containers.containers import ExtToolBar, ExtStaticToolBarItem, ExtTextToolBarItem, ExtRadioGroup from m3_ext.ui.containers.forms import ExtFieldSet, ExtTitlePanel from m3_ext.ui.containers.grids import ExtGrid, ExtGridRowSelModel, ExtGridGroupingView, ExtGridColumn...
# Copyright (c) 2018-2019 ISciences, LLC. # All rights reserved. # # WSIM is 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 app...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys sys.path.append('./') import codecs import collections import torch import pickle import utils import torch.nn as nn class Loader(): def __init__(self, target_dir): self.target_dir = target_dir self.word2idx = collections.defaultdict(int)...
import logging import shlex import sys from argparse import ArgumentParser from pathlib import Path from typing import List from ..core import filesystem from . import common logger = logging.getLogger(__name__) class IntegrationOptions(common.Base): ATTR_ARGS = "args" def __init__(self, name: str = "", a...
''' 游戏机制 ''' import os, sys print(os.getcwd()) import pygame from pygame.locals import * import sprites import controllers from gameobjects import Vec2d import random from constants import * from asserts import PIPE_LIST, BACKGROUND_LIST, STARTMESSAGE, GAMEOVERMESSAGE from asserts import SOUND_HIT, SOUND_DIE # from i...
import torch import numpy as np import matplotlib.pyplot as plt import altair as alt from src.data import open_data, assign_apparent_sources from uwnet.thermo import * def open_data_with_lts_and_path(): ds = open_data('training').sel(time=slice(120,140)) p = open_data('pressure') # make necessary computa...
import random from ceefax import config import os from ceefax.page import Page import signal import curses from ceefax.error import error_list from ceefax.error.exceptions import ConfigError, PageError, TimeUp import traceback try: from imp import reload except: pass def alarm(signum, frame): raise TimeU...
""" Generating figures for the upcoming letter """ import numpy as np import matplotlib.pylab as plt import astropy.units as u from matplotlib.patches import Circle from matplotlib.colors import ListedColormap from skimage import morphology from astropy.io import fits import aplpy from spectra_xy_list import xlist, yl...
import torch import glob import os import sys sys.path.append(os.getcwd()) import shutil import warnings warnings.filterwarnings("ignore") from torch_geometric.io import read_txt_array from torch_geometric.data.data import Data import torch_geometric.transforms as T from torch_geometric.nn import knn_interpolate im...
#!/usr/bin/env python3 # __file__: /home/ubuntu/parallel_locust.py # profiling-go.sh calling: # python3 parallel_locust.py $PROFILEE $LOCUST_CLIENT=4 $LOCUST_RUMTIME=300 $LOGFOLDER $STREAM_INDEX='=' import sys import locust.main as locust_main from multiprocessing import Process, Pool, TimeoutError import random impo...
import platform import pytest from netaddr import iprange_to_cidrs, IPNetwork, IPAddress, INET_PTON, AddrFormatError from netaddr.strategy.ipv6 import int_to_str @pytest.mark.skipif('sys.platform != "darwin"') def test_ip_behaviour_osx(): assert iprange_to_cidrs('::1', '::255.255.255.254') == [ IPNetwor...
import sys import argparse from logging import exception import git from lxml import etree as et from misc.xml_lib import Line_to_Xml_Element, fetch_descendants_by_attrib from misc import ghx_object_lib as ghxl class Branch: def __init__(self, repo, branch_name): # try: self.branch = None ...
# -*- coding: utf-8 -*- import asyncio import discord import typing from discord.ext import commands from core.context import StrapContext from core.voice import * class MissingPerms(commands.MissingPermissions): def __init__(self, missing_perms, *args): self.missing_perms = missing_perms missin...
import pyqtgraph as pg import pandas as pd import numpy as np import sys,time,os from pyqtgraph.exporters import ImageExporter, SVGExporter from PyQt4 import QtGui, QtCore from PyQt4.Qt import QImage, QPainter, QBuffer, QIODevice, QByteArray, SIGNAL from IPython.core.display import SVG from IPython.html import widgets ...
#!/usr/bin/env python3 import os import logging import jiwer import editdistance from espnet.asr.asr_utils import get_model_conf from espnet.asr.asr_utils import torch_load from espnet.asr.pytorch_backend.asr_init import load_trained_model import espnet.nets.pytorch_backend.lm.default as lm_pytorch import lattice imp...
#!/usr/bin/env python # -*- coding: utf-8 -*- import cv2 import math import pyrealsense2 as rs import numpy as np from pyquaternion import Quaternion import time import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import os import moderngl from objloader import Obj from pyrr import Matrix44 from P...
#!/usr/bin/python # -*- coding: utf-8 -*- import json from collections import defaultdict from .HttpUtil import httpGet, httpPost from ..exchange import Exchange class Gate(Exchange): def __init__(self, apikey, secretkey): self.api = GateAPI(apikey, secretkey) self.markets = self.get_all_trading...
import os import random import numpy as np import matplotlib.pyplot as plt import torch import torch.utils.data from torchvision import transforms from torchvision.utils import make_grid from PIL import Image import warnings def pil_loader(path): # open path as file to avoid ResourceWarning (https://github.com/py...
import matplotlib matplotlib.use('Agg') import flask from flask import Flask, request, render_template, session from sklearn.externals import joblib import numpy as np from scipy import misc from flask import send_from_directory from skimage.io import imread from skimage.filters import threshold_otsu from skimage impo...
# -*- coding: utf-8 -*- # Copyright The IETF Trust 2017, All Rights Reserved from __future__ import print_function, unicode_literals, division import re from collections import namedtuple try: from pyterminalsize import get_terminal_size except ImportError: get_terminal_size = None try: import debug ...
import logging import os import pickle from typing import List, Union import numpy as np import tensorflow as tf from tensorflow.python import keras from tensorflow.python.keras import layers from filelock.filelock import FileLock from zergbot.ml.agents import BaseMLAgent logger = logging.getLogger(__name__) SAVE_D...
import fileinput import math import random import sys from typing import Tuple, List import matplotlib import matplotlib.pyplot as plt import numpy as np from hmm import HMM from hmm_utils import Vector, Matrix2d eps = sys.float_info.epsilon matplotlib.rcParams["font.family"] = 'JetBrains Mono' def close(t1, t2, t...
import json import os import h5py import numpy as np import res.global_data as global_data import datetime # import res.world_data as world_data def load_config(configpath): """ Load the configuration file :param configpath: Path to configuration .json file :return: dict with the configuration """...
import seaborn as sns import numpy as np import matplotlib import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from mpl_toolkits.axes_grid1 import make_axes_locatable from analysis_functions import calculate_angle_from_history, calculate_winning_pattern_from_distances from analysis_functions import...
#!/usr/bin/env python """ createPhasingN50Plot.py 18 May 2011 dent earl dearl(a) soe ucsc edu used in the assemblathon report project to create the phasing N50 stats plots. """ ############################## # Copyright (C) 2009-2011 by # <NAME> (<EMAIL>, <EMAIL>) # <NAME> (<EMAIL>, <EMAIL>) # <NAME> (<EMAIL>) # .....
import numpy as np import pandas as pd from os import listdir from os.path import join from os.path import basename, splitext from Bio import SeqIO from Bio.SeqUtils import seq1 from Bio.PDB import PDBParser from deepab.util.pdb import protein_pairwise_geometry_matrix from deepab.util.util import _aa_dict, letter_to_n...
from genericpath import exists import sys from HRGAT.data import * from HRGAT.model import * from HRGAT.gats import * from warnings import filterwarnings import dill from HRGAT.data import Graph filterwarnings("ignore") import dill as pickle import argparse import os parser = argparse.ArgumentParser(descr...
""" A general finite automaton representation """ from typing import Set, List, Any import networkx as nx from networkx.drawing.nx_pydot import write_dot from .epsilon import Epsilon from .state import State from .symbol import Symbol class FiniteAutomaton(object): """ Represents a general finite automaton ...
# Copyright (c) 2012, <NAME> <<EMAIL>> # Copyright (c) 2009 - 2010, <NAME> <<EMAIL>> # Copyright (c) 2009 <NAME> <<EMAIL>> # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice a...
import collections import z3 from .. import consts, config from ..encoder import encoder # TODO: Remove dependency on encoder from ..utils import logger from ..utils import utils from . import model_utils ############################################################################### # Single-Structure/Sort Model ##...
import numpy as np import sys import datetime import copy class SensorExpiredError(Exception): pass # %% Definitions class Sensor(object): """Base CGM Sensor Class""" def __init__(self): return def get_bg(self, true_bg): raise NotImplementedError def get_bg_trace(self, true...
import six from collections import defaultdict import itertools import json import re import os import struct import numpy as np from tqdm import tqdm from .lib import red, toiter from .storage import Storage SEGIDRE = re.compile(r'/(\d+):0.*?$') def filename_to_segid(filename): matches = SEGIDRE.search(filename...
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of curveball. # https://github.com/yoavram/curveball # Licensed under the MIT license: # http://www.opensource.org/licenses/MIT-license # Copyright (c) 2015, <NAME> <<EMAIL>> from __future__ import division from builtins import range from un...
import os import re import dotenv from prettytable import PrettyTable from project_alignment_optimizer.program.constants import * dotenv_file = dotenv.find_dotenv('config.env') dotenv.load_dotenv(dotenv_file) def getVariableIntEnv(key): return int(os.environ[key]) def getVariableFloatEnv(key): return float(o...
from abc import ABC, abstractmethod from collections.abc import Iterable from pydoc import locate import pickle import io import base64 import pandas as pd import numpy as np from raymon.globals import Buildable, Serializable, DataException from raymon.globals import ExtractorException class Extractor(Serializable,...
# -*- coding: utf-8 and gbk -*- """ Created on Sat Oct 16 08:44:53 2021 @author: <NAME> """ # from __future__ import division from tensorflow.keras.models import Sequential # from nltk.book import * import pandas as pd import numpy as np np.set_printoptions(threshold=np.inf) # 将numpy数组显示完全 import matplotlib.mlab as ...
import math import sys import stibble import heapq import time from PIL import Image def readFromFile(): text_file = open("test.txt", "r") lines = text_file.read().split('\n') text_file.close() pointList = [] for each in lines: if each != "": point = each.split(',') xval = int(point[0][1:]) yval = int...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import re import pandas as pd from collections import namedtuple import hashlib from fastai.text import progress_bar from .elastic import Fragment, setup_default_connection from .json import * from .table import reference_re, remove_text_styles, r...
# -*- coding: utf-8 -*- """ Created on Sat Apr 7 13:47:02 2018 @author: Pramod """ import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data from tensorflow.python.framework import ops mnist = input_data.read_data_sets("MNIST_data/",one_hot=True) def spiky(x): ...
# Copyright (c) 2020, DjaoDjin inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and t...
import argparse import glob import os import shutil import time import shelve import sys from pathlib import Path from tkinter import Tk, filedialog from zipfile import ZipFile from PIL import Image from tqdm import tqdm from unrar import rarfile my_parser = argparse.ArgumentParser( description='F...
from jericho import * from jericho.template_action_generator import TemplateActionGenerator from tqdm import tqdm import json import pickle import uuid from os.path import join as pjoin from jericho import util as utl from jericho import defines def load_attributes(): global attributes global readable glo...
# -*- encoding: utf-8 -*- # # The MIT License (MIT) # # Copyright (c) 2016-2018 <NAME> <<EMAIL>> # # 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 limit...
from datetime import datetime from typing import Any, Callable, List, Optional, Union import xarray from xarray import DataArray, Dataset from xclim.core import calendar from icclim.icclim_exceptions import InvalidIcclimArgumentError from icclim.models.cf_calendar import CfCalendar from icclim.models.frequency import...
# manually-verify-links.py # # This script opens candidate URLs for municipalities websites in the # web browser and asks the user to check whether or not they seem to be the # official city hall or city council portals. # # Este script abre no navegador as URLs candidatas a sites dos municípios e # pede ao utilizador...
from text_processing import TextProcessor from helpers import * from multiprocessing import Pool, cpu_count, freeze_support data_path = '../' feature_path = '../' commit_column = 'commit' cwe_column = 'cwe' index_col = 'index_col' total_len = [] def divide_work(f, args): return f(*args) tp = None token = None t...
#import jsonl file import srsly from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException import os import signal im...
import cv2 import numpy as np from numpy import linalg import timeit from common_lab_utils import HomographyEstimate, homogeneous, hnormalized, \ retain_best, extract_matching_points, randomly_select_points, \ colours, draw_keypoint_detections, draw_keypoint_matches, draw_estimation_details def run_mosaic_so...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 7 21:29:28 2019 @author: prasad """ import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import metrics from sklearn import preprocessing def get_data(column_names): train_df = pd.read_csv('./data/20_percent...
# YOLOv5 by Ultralytics, GPL-3.0 license # https://github.com/ultralytics/yolov5/tree/v6.0 import math import torch import torch.nn as nn import torch.nn.functional as tnf from mycv.models.yolov5.common import Conv, C3, SPPF class Backbone(nn.Module): ''' https://github.com/ultralytics/yolov5/tree/v6.0 '...
import torch import numpy as np from models.encoder import BertEncoder from models.utils import get_bert_tokenizer from data_reader.utils import _naive_tokenize import pickle import os, re import config def get_service_repn(model, tokenizer, service): PAD = 0 n_service = len(service) item_ids = [[]]*n_serv...
# -*- coding: utf-8 -*- # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # This program is free software; you can redistribute it and/or modify # it under the terms of the MIT License. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the...
# Copyright 2021 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
import os import sys import json import random import requests lib_path = '/workspaces/private_vyperlogix_lib3' if (not any([f == lib_path for f in sys.path])): sys.path.insert(0, lib_path) domain = '172.16.31.10' uuid = '4a1bf01e-0693-48c5-a52b-fc275205c1d8' def test_get1(): items = ['status', 'has_plugins'...
#!/usr/bin/python # Copyright Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
# -*- coding: utf-8 -*- import unittest from webob import multidict class BaseDictTests(object): def setUp(self): self._list = [('a', u'\xe9'), ('a', 'e'), ('a', 'f'), ('b', 1)] self.data = multidict.MultiDict(self._list) self.d = self._get_instance() def _get_instance(self, **kwargs)...
#!/usr/bin/env python # Copyright (c) 2021 Computer Vision Center (CVC) at the Universitat Autonoma de # Barcelona (UAB). # # This work is licensed under the terms of the MIT license. # For a copy, see <https://opensource.org/licenses/MIT>. """ boto3 ec2 wrappers. """ import datetime import functools import logging i...
#!/usr/bin/python # Classification (U) """Program: argparser_init.py Description: Unit testing of ArgParser.__init__ in gen_class.py. Usage: test/unit/gen_class/argparser_init.py Arguments: """ # Libraries and Global Variables # Standard import sys import os if sys.version_info < (2, 7): ...
import requests from bs4 import BeautifulSoup import re import logging import sys from .bot import login def generate_template(name, kwargs=None): if kwargs is None: kwargs = {} buff = [r"{{", name] for key, value in kwargs.items(): buff.append("\n") buff.append(f"| {key} = {value}...
import os from copy import deepcopy import detectron2 from detectron2.utils.logger import setup_logger from tqdm import tqdm # from utils import mid_point, get_frames, FRAMES_FOLDER, compute_perspective_transform, \ # compute_perspective_unit_distances, return_people_ids, compute_point_perspective_transformation, c...
from trajopt.spacetime.objective import ObjectiveTerm import trajopt.utilities.adInterface as AD import numpy as N import math class StateValue(ObjectiveTerm): def __init__(self, baseVal=None): """ objective function that minimizes the difference between the state vector and a provided bas...
#!/usr/bin/python3 ## # \brief Implements regression trees using greedy, # best first splits. ## from __future__ import division import numpy as np from numba import jit from dtree.node import BiNode, maskDataJit class RegTree(BiNode): """! @brief Regression tree """ def __init__(self, x, y, yhat=None...
from . import directions from . import datums from . import ellipsoids # the final CRS object which is instantiated with all of the below and parameters # remember to use +no_defs when outputting to proj4 # ... class CRS: def __init__(self, toplevel): """ The main CRS class that defines a coor...
""" Views """ import decimal from crispy_forms.helper import FormHelper from crispy_forms.layout import Div, Field, Layout, Submit from django import forms from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.db import IntegrityError from dj...
import inspect import datetime import logging import re import json import random from datetime import timedelta from typing import List, Optional, Dict, TypeVar, Union, Callable, Generic, Type import requests from publicsuffixlist import PublicSuffixList logger = logging.getLogger(__name__) T = TypeVar('T') S = Type...
# -*- coding: utf-8 -*- import lfads import chainer.functions as F import chainer.links as L import math import numpy as np from chainer import Chain, ChainList from chainer.functions import gaussian_kl_divergence from chainer.functions import gaussian_nll from chainer.functions.math import exponential from chainer imp...
"""The surepetcare integration.""" from __future__ import annotations from datetime import timedelta import logging from random import choice from typing import Any import async_timeout from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_PASSWORD, CONF_TOKEN, CONF_USERNAME from h...
""" detector Copyright (c) 2020 <NAME> Licensed under the MIT License (see LICENSE for details) Written by <NAME> """ import os import sys import json # import datetime # not really useful so remove soon pls import numpy as np import skimage.draw import imgaug # should augment this improt as well haha # from PIL impor...