text
stringlengths
3.07k
12.6k
import torch import copy import pickle from torch.utils.data import Dataset from torch.autograd import Variable from tqdm import tqdm import numpy as np use_cuda = torch.cuda.is_available() def custom_collate_fn(batch): print(batch) # input is a list of dialogturn objects bt_siz = len(batch) # sequen...
import os import re import time import numpy as np from argparse import ArgumentParser from skimage.io import imread from shapely.affinity import affine_transform from sldc.locator import mask_to_objects_2d from cytomine.cytomine import _cytomine_parameter_name_synonyms, Cytomine from cytomine.models import Projec...
import numpy as np import matplotlib.pyplot as plt def wave(n,nprime,x,w): return (2/w)*np.sin(nprime*np.pi/w*x)*x*np.sin(n*np.pi/w*x) def simpson_rule(initial,final,N,n,nprime,w): initial=initial final=final N=N+1 h=(final-initial)/(N-1) x=np.linspace(initial,final,N) y=[] for i in ra...
# Copyright 2021 QuantumBlack Visual Analytics Limited # # 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 # # THE SOFTWARE IS PROVIDED ...
from contextlib import suppress from warnings import warn import numpy as np import pandas as pd import statsmodels.api as sm from scipy.stats import iqr from ..mapping.evaluation import after_stat from ..doctools import document from ..exceptions import PlotnineError, PlotnineWarning from .stat import stat # NOTE:...
import os import sys import json from random import randint from bst.pygasus.core import ext from bst.pygasus.wsgi.interfaces import IRequest from bst.pygasus.wsgi.events import IApplicationStartupEvent from bst.pygasus.wsgi.interfaces import IApplicationSettings from bst.pygasus.demo import model from bst.pygasus.d...
from tracker.net import SiamRPNvot from tracker.run_SiamRPN import SiamRPN_init, SiamRPN_track import glob import time import numpy as np import cv2 import torch from models import DeepMask from collections import namedtuple from utils.load_helper import load_pretrain import matplotlib.pyplot as plt # visualization ...
""" dynamic python files """ import os import logging import signal import time from datetime import datetime import functools import types import tornado.web import tornado.ioloop import tornado.gen import tornado.options import tornado.httpserver from concurrent.futures import ProcessPoolExecutor from dynamic_impor...
import json import re import unittest import warnings import responses import base warnings.simplefilter('ignore') commit_data = """ { "ref": "refs/heads/master", "after": "a96dbcb0e566ba8330b2b24ce0f31ed53a29e0ff", "before": "4a666d1d66e5db362742acee3c6fed4ca0b77a97", "created": false, "deleted": false, ...
# Monsters Castle Socket Server # Python 2.7.14 import socket, select, os, time, json, struct, hashlib import game, msg, scene CONNECTION_LIST = [] # Read sockets CONNECTION_USERS = {} # Socket-Username (if not logined, username is None) CONNECTION_MSGQUEUE = {} # Socket-MsgQueue [[len, str], tail] USERS_CON...
# coding=utf-8 # Copyright 2022 The Fiddle-Config Authors. # # 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...
from scipy.optimize import curve_fit from scipy import signal import numpy as np from numpy import fft, linspace from math import pi import csv import matplotlib.pyplot as plt T_WIDTH_MIN = 1e-6 T_WIDTH_MAX = 2e-4 def lorentz(x, a, w, y0, xc): ''' 洛伦兹函数 ''' return y0 + (2*a/pi)*w/(4*(x-xc)**2+w**2) ...
from rest_framework.views import APIView from rest_framework import status from rest_framework.response import Response from utils.celery_tasks.sms.tasks import send_sms_code import re import requests import json from random import randint from django_redis import get_redis_connection from .serializers import UserModel...
#Functions for learning policy by ARS # Importing the libraries import datetime import numpy as np import gym from gym import wrappers import pybullet_envs import os # Hyper Parameters class Hp(): def __init__(self): self.nb_steps = 1000 self.episode_length = 1000 self.learning_rate = 0.0...
import pandas as pd import numpy as np test_df = pd.DataFrame(pd.read_csv("test.csv")) train_df = pd.DataFrame(pd.read_csv("train.csv")) train_df.drop(train_df.columns[train_df.columns.str.contains('unnamed',case = False)],axis = 1, inplace = True) test_df.drop(test_df.columns[test_df.columns.str.contains('unnamed',c...
#!/usr/bin/env python3 """ IM epsilon value calculation script. Generates a file ot be passed to plot_items.py Takes IM and Rrup files and uses them to calculate how far above or below the empirical median each simulated value is. To see help message: python spatial_im_rrup_epsilon_plot.py -h Sample command: python s...
import sqlite3 import functools import json import os from pathlib import Path from typing import Tuple, Union import time import tornado import tornado.websocket as websocketT from jupyter_server.base.handlers import APIHandler from jupyter_server.utils import url_path_join from packaging.version import parse wss = ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2020-2022 F4PGA Authors # # 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 # # Unl...
import argparse import logging import os import pathlib import sys import time import sqlalchemy.orm from sqlalchemy.orm import Load import ispyb from ispyb.sqlalchemy import BLSession, DataCollection, GridInfo, Proposal def _tty_line_length(): if not sys.stdout.isatty(): return False return os.get_...
# main imports import numpy as np import pandas as pd import sys, os, argparse # image processing from PIL import Image from ipfml import utils from ipfml.processing import transform, segmentation import matplotlib.pyplot as plt # model imports import joblib # modules and config imports sys.path.insert(0, '') # tri...
import numpy as np from math import floor import SimulationParameters as params import turtle import gc class IntersectionSimulator: def __init__(self): self.intersection = Intersection() self.intersection.generateArrivalDetectionTimes() self.queue = [] self.vehicleTurt...
from collections import namedtuple import logging import warnings import uproot import numpy as np import awkward as ak import awkward._io # workaround for https://github.com/scikit-hep/awkward-1.0/issues/968 from .definitions import mc_header from .tools import cached_property, to_num, unfold_indices from .rootio im...
''' Here I want to check the mapping the core supperimpotion of de novo protein 7jrq by <NAME>. ''' import os import sys import numpy as np import prody as pr sys.path.append(r'/mnt/e/GitHub_Design/Metalprot/scripts_other/porphyrin/') import porphyrin_library from metalprot import ligand_database ligands = ['HEM', 'H...
# SPDX-FileCopyrightText: 2017 <NAME>, written for Adafruit Industries # SPDX-FileCopyrightText: Copyright (c) 2020 <NAME> for Adafruit Industries # # SPDX-License-Identifier: MIT """ `adafruit_bh1750` ================================================================================ CircuitPython library for use with t...
"""Helper functions for time series tests """ import random import numpy as np # type: ignore import pandas as pd from pandas.core.indexes import period # type: ignore from pycaret.internal.pycaret_experiment import TimeSeriesExperiment from pycaret.datasets import get_data from pycaret.containers.models.time_serie...
import json import os from typing import Any, Dict, Optional import requests from dateutil import parser from dateutil.relativedelta import relativedelta from django.contrib.postgres.fields import JSONField from django.utils.timezone import now from rest_framework import request, serializers, viewsets from rest_framew...
# coding=utf-8 # Copyright 2018 Google LLC & <NAME>. # # 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 o...
import asyncio import csv import pandas as pd from os.path import ( join, dirname, ) from typing import ( List, Tuple, ) import hummingbot from hummingbot.client.hummingbot_application import MARKET_CLASSES from hummingbot.core.utils.async_utils import safe_ensure_future from hummingbot.core.utils.trad...
import torch.utils.data as data import random from PIL import Image import numpy as np from utils import python_pfm as pfm import torchvision.transforms as transforms import operator def rgbLoader(path): return Image.open(path).convert('RGB') def pfmLoader(path): return pfm.readPFM(path)[0] def grayLoader...
from link import Link from arm import Arm import numpy as np from maddux.environment import Environment def simple_human_arm(seg1_len, seg2_len, q0, base=None): """Creates a simple human-like robotic arm with 7 links and 2 segments with the desired lengths and starting joint configuration :param seg1_len: The le...
import datetime import random import subprocess import sys from OpenSSL import crypto from bottle import template from six import string_types from eu.softfire.tub.utils.utils import get_config, get_logger KEY_LENGTH_CHOICES = { 'none': ('', ''), '512': ('512', '512'), '1024': ('1024', '1024'), '2048...
from CommonServerPython import * import copy from itertools import chain import traceback def find_start_task(tasks: Dict): for task in tasks.values(): if task.get('type') == 'start': return task return DemistoException('No start task was configured') def traverse_tasks(tasks: Dict[str, ...
import hydra import util import os import random import argparse import numpy as np import logging import wandb from model.deeplab import deeplabv3_resnet50, deeplabv3plus_resnet50 from torch.utils import data from util import transform from util import StreamSegMetrics from dataset import ScanNet import torch import...
import os import sys import time import queue import threading import traceback from enum import Enum from queue import Queue from threading import Lock, Thread import numpy import src.libav_functions as libav_functions # for testing import random # an enum for now in case we expand commands in the future class Co...
""" RDB metadata. This file is part of the telex project. See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information. Created on Jul 31, 2014. """ from sqlalchemy import Column from sqlalchemy import DateTime from sqlalchemy import ForeignKey from sqlalchemy import Integer from sqlalchemy import Meta...
from collections import defaultdict from time import sleep from typing import Any, Callable, Dict, Generic, TypeVar, Union from bluepy.btle import UUID from .constants import UUIDs from .messages import * PeerListenerFunc = Callable[[UUID, bytes], Any] class Peer: def disconnect(self): raise NotImplemen...
import numpy as np class ODESolver(object): """ Superclass for numerical methods solving scalar and vector ODEs du/dt = f(u, t) Attributes: t: array of time values u: array of solution values (at time points t) k: step number of the most recently computed solution f: callable object...
import unittest import random from ..collections import TypedList, TypedDict, DictSet, OrderedSet, SplitList from ...Meta.bencode import bencode, bdecode from ...Meta.Info import MetaInfo class APITest(object): """API test mixin - Requires that all attributes of `baseclass` be present in `thisclass`""" b...
import numpy as np import matplotlib.pyplot as plt import soundfile as sf from scipy.signal import spectrogram from scipy.stats import pearsonr import warnings warnings.filterwarnings("ignore") def draw_spectogram(filename): s, fs = sf.read(filename) s.min(), s.max() t = np.arange(s.size) / fs f, t, sgr = spectro...
import os from Bio.PDB import PDBParser from Bio.PDB.PDBIO import PDBIO from Bio.PDB.mmtf import MMTFParser, MMTFIO from utils.structure import AA_DICT def get_files(data_dir, ext='.pdb'): """ Return a list of files with the desired extension from the specified directory. Parameters ---------- ...
import os import logging import datetime import sys # logging info dateTimeInfo = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") logger1 = logging.getLogger('1') logger1.addHandler(logging.FileHandler("logs/aids_export_no_xml_file_" + dateTimeInfo + ".log")) logger1.setLevel(logging.INFO) logger2 = logging.get...
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module defines a logging class based on the built-in logging module. The module is heavily based on the astropy logging system. """ from __future__ import print_function import os import sys import logging from logging import FileHandler from lo...
#!/bin/env python # # Stupid python-isms to make code slightly more portable # from __future__ import print_function # # Import modules # import datetime import optparse import os import socket import sys import time import xdd from xdd.profileparameters import ProfileParameters # # Time in seconds to wait between p...
#!/usr/bin/env python """ This script runs a telegram bot that checks the kimsufi servers availability for users that ask for it. I took inspiration from ncrocfer's code (https://github.com/ncrocfer/kimsufi-availability) to use and parse OVH's API. Author : <NAME> """ import requests from telegram.ext import Update...
import pandas as pd from english_words import english_words_lower_alpha_set from wordfreq import zipf_frequency as wf def get_all_wordle_words(): with open("all_wordle_words.txt", "r") as infile: return [line.strip() for line in infile.readlines()] # words_to_choose_from = list(english_words_lowe...
"""Script for provisioning build server. TODO: add command line params for what langs (all or just one); useful for build server To get all: ``$ python scripts/download_all_models.py`` For selected languages only: ``$ python scripts/download_all_models.py --languages=grc,lat`` """ import argparse import time from ty...
import re from lib.metadata.metadata import Metadata from lib.metadata.regex.regexanimeextension import RegexAnimeExtension from lib.metadata.regex.regexcommonextension import RegexCommonExtension from lib.metadata.regex.regexfilmextension import RegexFilmExtension from lib.metadata.regex.regexshowextension import Reg...
# !/usr/bin/env python # -*- coding:utf-8 -*- """ Test the projection module """ import unittest import numpy as np import pandas as pd from numpy.polynomial import legendre from pyrotor.projection import trajectory_to_coef from pyrotor.projection import trajectories_to_coefs from pyrotor.projection import compute_we...
from django.db import transaction from django.forms import ChoiceField, Form, ModelChoiceField, ModelForm from .fields import CheckpointsChoiceField from .models import ( Activity, ActivityPerformance, ActivityType, Checkpoint, Gear, Place, Route, ) class RouteForm(ModelForm): """ ...
import numpy as np from scipy.stats import random_correlation, norm, expon from scipy.linalg import svdvals import warnings warnings.filterwarnings("error") from collections import defaultdict def get_mae(x_imp, x_true, x_obs=None): """ gets Mean Absolute Error (MAE) between x_imp and x_true """ x_imp...
# ------------------------------------------------------------------------------ # Hippocampus segmentation task for the HarP dataset # (http://www.hippocampal-protocol.net/SOPs/index.php) # ------------------------------------------------------------------------------ import os import re import SimpleITK as sitk imp...
#! /usr/bin/env python3 """ Copyright 2021 <NAME>. 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 wri...
# coding: utf-8 # # This code is part of lattpy. # # Copyright (c) 2021, <NAME> # # This code is licensed under the MIT License. The copyright notice in the # LICENSE file in the root directory and this permission notice shall # be included in all copies or substantial portions of the Software. """Contains plotting to...
# -*- coding: utf-8 -*- #========================================== #Ce code est un ransomware qui a été développé # dans le cadre de l'enseignement CYB_5101A - # Sécurité CLoud. #Le code ne fonctionne actuellement que dans # le dossier /tmp/test #========================================== from path import Path fro...
import sys from optparse import OptionParser import random import torch import torch.nn.parallel import torch.utils.data import torchvision.utils as vutils import numpy as np import matplotlib.pyplot as plt from loaders import dataset_loader from trainers import transfer_trainer import constants parser = OptionParser(...
from itertools import chain import re # op_0 : X -> p(T) # op_1 : p(T) -> p(T) # ind : p(T) -> {0,1}^F class FeatureTemplate: """Base feature template class""" def __init__(self): self.label = None self.xpaths = set(['//node']) self.subsets = None # subtrees / p(T) def apply(self, root): """ ...
import ast from peval.tags import get_inline_tag from peval.core.reify import NONE_NODE, FALSE_NODE, TRUE_NODE from peval.core.expression import try_peval_expression from peval.core.function import Function from peval.core.mangler import mangle from peval.core.gensym import GenSym from peval.tools import ast_walker, r...
import argparse import os import sys # Arguments parser = argparse.ArgumentParser(description="generate a docker-compose.yml for ipfsearch.") parser.add_argument("-g", "--go-version", default="latest", help="the version to use for go-ipfs (ipfs/go-ipfs:GO_VERSION), default: latest") parser.add_argu...
import tensorflow as tf from tensorflow.keras import layers from tensorflow.keras.layers import TextVectorization import string import re import numpy as np batch_size = 32 raw_train_ds = tf.keras.preprocessing.text_dataset_from_directory( "aclImdb/train", batch_size=batch_size, validation_split=0.2, s...
import random import numpy as np import torch import torch.nn as nn import re import json import sys from nltk.translate.bleu_score import corpus_bleu, SmoothingFunction import nltk def initialize_weights(m): ''' Initialize the weights of a model m: model ''' if hasattr(m, 'weight') and m.w...
import sublime from collections import namedtuple from .. import utils from .delimited_scopes import DELIMITED_SCOPE_LIST Block = namedtuple( "Block", "block_type, indent_pt, start_to_char, char_to_end, end_to_char" ) BLOCK_START_SELECTOR = "punctuation.section.block.begin.cfml" BLOCK_END_SELECTOR = "punctuation.s...
import sys import os import json from tqdm import tqdm def dict_compare(d1, d2): d1_keys = set(d1.keys()) d2_keys = set(d2.keys()) shared_keys = d1_keys.intersection(d2_keys) added = d1_keys - d2_keys removed = d2_keys - d1_keys modified = {o : (d1[o], d2[o]) for o in shared_keys if d1[o] != d2...
import logging import scipy.interpolate as interpolate import numpy as np radius_earth = 6371.0 # km radius_orbit = 7148.0 sat_alt = radius_orbit - radius_earth factor = radius_orbit / radius_earth def create_grid(): x_size = 512 return (np.arange(x_size, dtype=np.float64) - (float(x_size - 1)) / 2) / radi...
"""Define a procedure for filling missing values.""" # Copyright (c) 2012-2016 <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 r...
#!/usr/bin/env python # # Copyright 2019 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """\ Helper script for compiling and running the Wasm C/C++ API examples. Usage: tools/run-wasm-api-tests.py outdir tempdir [filter...
# --- # jupyter: # jupytext: # notebook_metadata_filter: all,-language_info,-toc,-latex_envs # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.6.1-dev # kernelspec: # display_name: Python 3 # language: python # na...
""" some networks edit by hichens """ import torch import torch.nn as nn import torch.nn.functional as F from collections import namedtuple from torchvision.models import vgg16 class TransformerNet(nn.Module): def __init__(self): super(TransformerNet, self).__init__() ## More flexiable s...
""" js2esi.token.adict At its core, an ``adict`` is just an automatic-attribute version of dict(), i.e. all items are automatically converted to attributes. However, ``adict`` also adds the ability to inherit attributes from other adicts or objects. TODO: is this *REALLY* the right thing to do??? (ie. is there no stan...
import calendar from flask import redirect, flash, url_for, Markup from .forms import TestForm from flask_appbuilder._compat import as_unicode from flask_appbuilder import ModelView, GroupByChartView, aggregate_count, action, expose, BaseView, has_access from flask_appbuilder.views import SimpleFormView, MultipleView f...
import os import dgl import tqdm import torch import os.path import numpy as np import scipy.sparse as sp from dgl import DGLGraph from dgl.data import citegrh from itertools import compress from torchvision.datasets import VisionDataset from .continuumLS import ContinuumLS from .continuumOGB import ContinuumOGB def...
#!/usr/bin/env python # # Copyright (c) <NAME> and the University of Texas MD Anderson Cancer Center # Distributed under the terms of the 3-clause BSD License. import os import sys from setuptools import find_packages, setup from setuptools.command.bdist_egg import bdist_egg _py_ver = sys.version_info if _py_ver.maj...
from django import forms from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.decorators import permission_required from django.contrib.auth.mixins import LoginRequiredMixin from django.db.models import Q from django.shortcuts import redirect from django...
"""Pipeline functionality shared amongst multiple analysis types. """ import os import collections from contextlib import closing import subprocess import pysam from bcbio import broad from bcbio.pipeline import config_utils from bcbio.utils import file_exists, safe_makedir, save_diskspace from bcbio.distributed.tran...
#!/usr/bin/env python3 # Author: <NAME> import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from dgl.nn.pytorch import KNNGraph, EdgeConv from torch.utils.data import DataLoader from tqdm import tqdm import os import open3d as o3d from model.Descriptor.descriptor_dataset import * f...
from cProfile import label from ECGController import ECGController import streamlit as st from Controllers.ECGModel import ECG import wfdb # import pandas as pd import Controllers.Constants as cons import Controllers.Common as common import os from pathlib import Path import shutil import numpy as np import matplotlib....
import random from datetime import datetime, timedelta from django.contrib import auth from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.core.paginator import Paginator from django.db.models import Q from django.http import HttpResponse from django.shortc...
import matplotlib.pyplot as plt import matplotlib.image as mpimg import seaborn as sns import numpy as np colors = np.loadtxt("/home/connor/Dev/semseg/data/ade20k/ade20k_colors.txt") names = np.loadtxt("/home/connor/Dev/semseg/data/ade20k/ade20k_names.txt", dtype='str', usecols=0, delimiter="\n") def get_sample(inde...
#!/usr/bin/env python import os, glob, datetime,sys,getopt from GeoData.GeoData import GeoData import matplotlib.pyplot as plt import numpy as np from GeoData.utilityfuncs import readIonofiles, readAllskyFITS,readSRI_h5 from PlottingClass import str2posix from matplotlib.dates import YearLocator, MonthLocator, DateForm...
"""Various misc. utilities.""" import os import sys import shutil import json from pathlib import Path from typing import List, Callable import requests import colorama from ipify import get_ip from ipify.exceptions import ConnectionError, ServiceError from .conditions import is_exception from .exceptions import Expe...
import codecs, os import xml.etree.ElementTree as ET def read_xml(): # read in the xml files from both versions and return tree objects # Note, the question's URIs prefixes must be identical in both files. # This is reads in rdmo >v0.11 data model xml_example = codecs.open(os.path.abspath("rdmo...
from malaya.supervised import tag from malaya.path import PATH_ENTITIES, S3_PATH_ENTITIES from malaya.text.entity import ENTITY_REGEX from herpetologist import check_type label = { 'PAD': 0, 'X': 1, 'OTHER': 2, 'law': 3, 'location': 4, 'organization': 5, 'person': 6, 'quantity': 7, ...
# !/usr/bin/env python # coding=utf-8 """ Graphs for lecture 4, plot solution to an ODE """ from __future__ import print_function import sys import numpy as np from scipy.integrate import odeint from scipy.optimize import fsolve from common import make_fig, GOOD_RET __author__ = 'hbmayes' # noinspection PyUnusedL...
import json from django.conf import settings from django.http import HttpResponse from django.shortcuts import render from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt from django.views.generic.base import View from rest_framework import status from home.forms ...
import PySimpleGUI as sg import serial from serial.tools import list_ports import sys import binascii import time #以下自作関数群 sys.path.append('./') import crc_checker devices = None buff = None ser = None file_name = None read_file = None def uart_connect(combo): #UART接続 global ser connect_state = True try...
''' Script file for HPC for running a 1D fragnet. ''' import sys sys.path.append('../../dnn/') sys.path.append('../dnn/') import os import numpy as np # Custom Built libraries from model.nets.fragilityaux import CNNFragility from model.nets.ieegcnn import iEEGCNN from model.train import traincnn from model.train.fra...
import random def game_over_decision(game_sticks): if game_sticks <= 0: return True else: return False def continue_game(): #User continues to play after a game continue_game = '' continue_bool = False while True: continue_game = input("Play again? [Y/n]: ").lower() ...
import matplotlib.pyplot as plt import tensorflow as tf import tensorflow.keras.datasets as datasets plt.rcParams['font.size'] = 16 plt.rcParams['font.family'] = ['STKaiti'] plt.rcParams['axes.unicode_minus'] = False def load_data(): # 加载 MNIST 数据集 (x, y), (x_val, y_val) = datasets.mnist.load_data() # 数...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import math from typing import Optional, List, Tuple import torch import torch.nn as nn import torch.nn.functional as F from blueprint.ml.util import deal_with_remote_file from blueprint import Context from . import farl def _make_fpns(vis...
from django import forms from django.conf import settings from django.contrib.auth import password_validation from django.contrib.auth.models import User from hacker.models import Hacker, HackathonApplication, AcademicData, Organizational, CV, RSVP from phonenumber_field.widgets import PhoneNumberInternationalFallbac...
import dataclasses import numpy from typing import List from .base import abs, wrap_mpi_pi, PI, EPS from .transforms3d import isrot, ishom @dataclasses.dataclass class InverseRotSolution(): is_ok: bool msg: str is_singular: bool num_solutions: int axes: List[numpy.ndarray] angles: List[float] ...
#!/usr/bin/env python # coding: utf-8 # Author: <NAME> """ Dataset """ import os import pickle import random import numpy as np from scipy.spatial import distance import networkx as nx import torch from torch.utils.data import Dataset from torch.distributions.multivariate_normal import MultivariateNormal import dgl f...
""" Overall these views are awful. - Add back option between steps - Make use of GeneriViews - ViewClass - between each step, post to self, validate data and use next to go to next step """ from django.shortcuts import render, redirect from collections import defaultdict, namedtuple from .forms import SetupForm, scor...
"""Utilities to generate and store tracks. Uses the Union-Find algorithm, with image ID and keypoint index for that image as the unique keys. A track is defined as a 2d measurement of a single 3d landmark seen in multiple different images. References: 1. <NAME>, <NAME>. Unordered Feature Tracking Made Fast and Easy, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from collections import OrderedDict import re from textwrap import dedent as dd import glfw from glfw import gl class Shader(object): '''Wrapper for opengl boilerplate code''' def __init__(self, source): assert glfw.core.init(), 'Error: GLFW could not b...
from django.contrib.auth.base_user import AbstractBaseUser from django.core.validators import RegexValidator, MaxValueValidator from django.db import models from django.contrib.auth.models import UserManager, PermissionsMixin from django.core.mail import send_mail from django.db.models import Max, F from django.utils i...
""" The MIT License (MIT) Copyright (c) 2013 <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, modify, merge, publi...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import cv2 import numpy as np from keras.models import model_from_json, Sequential import multiprocessing ## import oscar ########################### sys.path.insert(0, './oscar/neural_net/*') from net_model import NetModel from drive_data import DriveData from...
from random import getrandbits, uniform import numpy as np import dataset_iterator.helpers as dih import numpy as np from scipy.ndimage.filters import gaussian_filter from ..model.utils import ensure_multiplicity def get_normalization_center_scale_ranges(histogram, bins, center_centile_extent, scale_centile_range, ver...
# -*- coding: utf-8 -*- """ Python Collection Of Functions. Package with collection of small useful functions. Decorators functions """ import functools import logging import time LOG = logging.getLogger(__name__) def num_calls(_func=None, *, loglevel="DEBUG", print_info=False): """ Count the number of ...
from _helpers import validate_family, validate_op class Action(): pass class AcceptAction(Action): def get(self): return {"accept": None} class DropAction(Action): def get(self): return {"drop": None} class JumpAction(Action): _target = None def __init__(self, target) -> None:...