text stringlengths 3.07k 22.1k |
|---|
import numpy as np
import copy
from sklearn.linear_model import LogisticRegression, SGDClassifier
class ClassifierChain() :
'''
Classifier Chain
----------------
TODO: much of this can be shared with Regressor Chains, and thus
probably we should use some kind of base class to inhe... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
pcgs_prices.py
Script to programmatically scrape all coin prices from www.pcgs.com/prices
Author: <NAME>, 2020
github: ryanamannion
twitter: @ryanamannion
"""
import json
import time
import pickle
import argparse
from tqdm import tqdm
from datetime import datetime
fr... |
"""The 'bat-country' package is an easy to use, highly extendible, lightweight
Python module for inceptionism and deep dreaming with Convolutional Neural
Networks and Caffe."""
from __future__ import division, print_function
import logging
import os
import tempfile
import time
from google.protobuf import text_format... |
import torch
import torch.nn as nn
from torch.nn import functional as F
from nets.resnet import ResNetBackbone
from config import cfg
from nets.sem_gcn import SemGCN
from utils.gcn_utils import adj_mx_from_skeleton
class HeadNet(nn.Module):
def __init__(self, joint_num):
self.inplanes = 2048
self... |
import pickle
from typing import Tuple, List, Iterable, Any
import logging
from PyQt5 import QtWidgets, QtCore
from .samples_ui import Ui_WizardPage
from ......core2.instrument.instrument import Instrument
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class Model(QtCore.QAbstractItemModel):
... |
import unittest
import shutil
import time
import os
import json
import shelve
import glob
import random
import sys
if sys.version_info.minor == 3:
from contextlib import closing
shelve_open = lambda file, flag="c", protocol=None, writeback=False: closing(shelve.open(file, flag))
else:
shelve_open = shelve.... |
'''Define unit tests for calib_prep with pytest.
Authors
-------
- <NAME>
Use
---
Ensure you have pytest installed. Then, simply run pytest in any
parent directory of jwst_reffiles/tests/:
>>> pytest
'''
from collections import OrderedDict
import copy
import os
from astropy.io import ascii
from jwst.... |
#!/usr/bin/python3
#
# Copyright 2018 Codeplay Software Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use these files 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... |
# pylint: disable=too-many-locals
import pathlib
import yaml
import collections
from aiida.orm import StructureData, Dict
ang_2_bohr = 1.889725989
def get_kinds_section(kinds_dict, protocol='gapw_std'):
""" Write the &KIND sections in gw calculations given the structure and the settings_dict"""
bset = 'gapw... |
# MIT License
# Copyright (c) 2017 Rebecca ".bx" Shapiro
# 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,... |
'''ResNet in PyTorch.
For Pre-activation ResNet, see 'preact_resnet.py'.
Reference:
[1] <NAME>, <NAME>, <NAME>, <NAME>
Deep Residual Learning for Image Recognition. arXiv:1512.03385
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import ipdb
class Bas... |
import sys
sys.setrecursionlimit(10000)
# python3 compatibility
try:
foo = long
except:
long = int
# The prime modulus of the field
field_modulus = 21888242871839275222246405745257275088696311157297823662689037894645226208583
# See, it's prime!
assert pow(2, field_modulus, field_modulus) == 2
# The modulus o... |
#
# Copyright (c) 2017 Ensoft Ltd, 2008-2010 <NAME>, <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, modi... |
import os
import sys
import time
import typing
from dataclasses import dataclass
from torch.utils.tensorboard import SummaryWriter
from codebase.torchutils.log import get_logger
import matplotlib
import numpy as np
import torch
from matplotlib import pyplot as plt
from codebase.third_party.spos_ofa.ofa.nas.accuracy_pre... |
import os
import sys
import json
import argparse
import logging
from pathlib import Path
from urllib.parse import urljoin
import requests
from bs4 import BeautifulSoup
from pathvalidate import sanitize_filename
from pathvalidate import sanitize_filepath
from tqdm import tqdm
def configurate_argparse(get_pages_count,... |
import numpy as np
import h5py
import xfields as xf
import xpart as xp
import xtrack as xt
import xobjects as xo
def get_electroncloud_fieldmap_from_h5(
filename, tau_max=None, buffer=None, ecloud_name="e-cloud"):
assert buffer is not None
ff = h5py.File(filename, "r")
nx = len(ff["grid/xg"][()]... |
#!/usr/bin/env python3
#
# https://github.com/mseitzer/pytorch-fid
#
"""Calculates the Frechet Inception Distance (FID) to evalulate GANs
The FID metric calculates the distance between two distributions of images.
Typically, we have summary statistics (mean & covariance matrix) of one
of these distributions, while t... |
# coding=utf-8
# Copyright 2018 The TensorFlow 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 requ... |
import torch as torch
import torch.nn as nn
import numpy as np
import time
import argparse
def shape_to_matrix(feature_num, env_list, label_num, max_data, data_len, data, device='cuda'):
env_num = len(env_list)
matrix = torch.zeros([env_num, label_num, max_data,
feature_num], ... |
import logging
from flask import g
from flask_wtf import Form
from functools import partial
from wtforms import (BooleanField, StringField,
TextAreaField, IntegerField, FloatField, DateField, DateTimeField)
from wtforms.ext.sqlalchemy.fields import QuerySelectMultipleField, QuerySelectField
from... |
"""Functions to produce a H-mesh from stage design."""
import numpy as np
from . import design, geometry
# import matplotlib.pyplot as plt
# Configure numbers of points
nxb = 97 # Blade chord
nr = 81 # Span
nr_casc = 4 # Radial points in cascade mode
nrt = 65 # Pitch
rate = 0.5 # Axial chords required to fully re... |
import traceback
from flask import Flask, redirect, request, render_template, session , url_for, jsonify
from flask_socketio import SocketIO, emit
from flask_compress import Compress
import os
from utils import *
ResponseThread = None
app = Flask(__name__)
app.app_context().push()
websocket = SocketIO(app)
ap... |
"""Script wrapper for initializing survey planning and scheduling.
This is normally run once, at the start of the survey, and saves its results
to a FITS file surveyinit.fits. With the default parameters, the running time
is about 25 minutes.
This script will calculate the ephemerides and expected weather (dome open... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 20 17:38:57 2017
The ethanol production section for the baseline lipid cane biorefinery is defined here as System objects. The systems include all streams and units starting from sugar concentration to denaturing the ethanol product.
@author: yoel
... |
import numpy as np
import torch
eps = 1e-8
class metric_manager(object):
def __init__(self, task, save_dir, model, save_best_only=True):
if(
'ASC' not in task and
'SED' not in task and
'TAG' not in task
): raise ValueError('task unrecognized, got:{}'.format(ta... |
import turtle as tu
tu2 = tu.Turtle()
# _Settings_____
height = 720
width = 1280
speed = 0
thickness = 4
squareThickness = 6
# _Math_____
lines = height / 6 * 4
distance = height / 8
# ____________________
tu.setup(width, height)
tu.pensize(thickness)
tu.speed(speed)
# __Basic Coordinates___
x = 0 + distance
y =... |
"""Reference implementation of Falcon: https://falcon-sign.info/."""
from common import q
from numpy import set_printoptions
from math import sqrt
from fft import fft, ifft, sub, neg, add_fft, mul_fft
from ntt import add_zq, mul_zq, div_zq
from ffsampling import gram, ffldl_fft, ffsampling_fft
from ntrugen import ntru... |
"""Metrics file specific to njit / CPU implementations."""
import os
from math import sqrt
import numpy as np
from . import cpu_helper as hp
from numba import njit
inline = os.environ.get("INLINE", "never")
fastmath = bool(os.environ.get("FASTMATH", "1"))
cols = os.environ.get("COLUMNS")
# USE_64 = bool(os.environ.g... |
"""
# =============================================================================
Copyright Government of Canada 2019
Written by: <NAME>, Public Health Agency of Canada,
National Microbiology Laboratory
Funded by the National Micriobiology Laboratory and the Genome Canada / Alberta
Innovates Bio Solutions p... |
"""Report routes."""
import bottle
from ..database.reports import latest_reports, latest_report, insert_new_report
from ..database.datamodels import latest_datamodel
from ..util import iso_timestamp, report_date_time, uuid
from .measurement import latest_measurement, insert_new_measurement
@bottle.post("/report/<re... |
import os
import torch
import numpy as np
from PIL import Image
from copy import deepcopy
from tqdm import tqdm
from torch.nn.functional import softmax
import utils
class TwoModelsMSE ():
def __init__(self, orig_model, weight_decay):
self.orig_model = deepcopy(orig_model)
for p in self.orig_model... |
#!/usr/bin/env python
import os,sys
from array import array
import numpy as np
import json
from scipy.spatial import distance
sys.path.append("/Users/avoorhis/programming/vamps-node.js/public/scripts/visualization_scripts/")
import distance2 as TEST_SCRIPT
"""
Run this way: py.test -v distance_test.py
"""
class Te... |
#coding=utf8
# 一些数据预处理
import numpy as np
import pandas as pd
from sklearn.ensemble import IsolationForest
import os
import sys
import pickle
import argparse
import configparser
class Outliers:
'''
异常点检测类,包含读取、预处理、异常点检测等功能
'''
# 输入输出文件
# 读入:本地的 csv 文件(已经计算过新的特征,只需要做一些数据填充),做异常点检测
# 输出:检测结果(只包含时... |
from __future__ import annotations
import os
from pathlib import Path
from typing import MutableMapping, Optional, Union, Mapping, cast, Dict, List
import numpy as np
import torch
from loguru import logger
from transformers import AdamW, BertConfig, BertModel
from codenets.codesearchnet.data import DatasetParams
fro... |
import numpy as np
import random
from pprint import pprint
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import gc
import math
# n = int(input())
def main():
n = 7
hidden_layer = 2
_graph = np.ones((n, n))
graph = np.tril(_graph, k=-1) # intilize edge
_adjacent = np.ones... |
# coding=utf-8
# Copyright (c) Microsoft. All rights reserved.
# Code is adpated from https://github.com/google-research/bert
import collections
import json
import os
from collections import namedtuple
from typing import Union
MaskedLmInstance = namedtuple("MaskedLmInstance", ["index", "label"])
def truncate_seq_pai... |
import base64
import lycanthropy.sql.interface
import lycanthropy.sql.agent
import lycanthropy.sql.server
import lycanthropy.auth.client
import lycanthropy.crypto
import datetime
import requests
import hashlib
import urllib3
import json
import time
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
... |
#
# (c)2005 LIRIS - University Claude Bernard Lyon 1
# http://liris.cnrs.fr/
#
# Author: <NAME>
# http://champin.net/
#
# This software is distributed under the terms of the GNU LGPL v2.1.
# See LICENSE.txt for more details.
#
from cross.ns import OWL, XSD
from cross.datasource.utils import *
from rdfli... |
"""
Numdifftools.nd_statsmodels
======================
This module provides an easy to use interface to derivatives calculated with
statsmodels.numdiff.
"""
from __future__ import division, print_function
from functools import partial
from statsmodels.tools.numdiff import ( # approx_fprime,
approx_fprime_cs,
... |
#!/usr/bin/env python
"""Tests for `damitalia` package."""
import pytest
from damitalia import damitalia, params
@pytest.fixture
def extremity_id():
extremity = int(params.BOARD_BREADTH * (params.BOARD_BREADTH / 2) - 1)
return extremity
@pytest.fixture
def first_row1_id():
first_row1 = int(params.BOARD_... |
import numpy as np
import matplotlib.pyplot as plt
import cv2
def reals(array):
return np.invert(np.isnan(array))
def extremes(left, right):
mask_l, mask_r = reals(left), reals(right)
min_x, max_x = np.amin(left[mask_l]), np.amax(right[mask_r])
min_z, max_z = np.argmin(left[mask_l]), np.argm... |
'''
@author Waldinsamkeit
@email <EMAIL>
@create date 2020-10-10 10:41:30
@desc
: Generate DataSet and DataLoader for Classifier
'''
from pathlib import Path
import random
from typing import Dict, List, Optional, Set, Tuple, Any
from copy import copy
import numpy as np
from utils import set_padding
import pickle... |
from pyegl._pyegl import ffi, lib
EGL_ALPHA_SIZE = 0x3021
EGL_BAD_ACCESS = 0x3002
EGL_BAD_ALLOC = 0x3003
EGL_BAD_ATTRIBUTE = 0x3004
EGL_BAD_CONFIG = 0x3005
EGL_BAD_CONTEXT = 0x3006
EGL_BAD_CURRENT_SURFACE = 0x3007
EGL_BAD_DISPLAY = 0x3008
EGL_BAD_MATCH = 0x3009
EGL_BAD_NATIVE_PIXMAP = 0x300A
EGL_BAD_NATIVE_WINDOW = 0... |
#!/usr/bin/env python3
from slickrpc import Proxy
import time
import sys
import datetime
import os
import json
import re
import platform
import calendar
def selectRangeInt(low,high, msg):
while True:
try:
number = int(input(msg))
except ValueError:
print("integer only, try ... |
import os
from algorithms.RNN import RNN
from algorithms.LSTM import LSTM
from algorithms.GRU import GRU
from algorithms.Transformer import Transformer
from algorithms.RTransformer import RT
from HDF5Dataset import HDF5Dataset
import plotting
import torch
from torch.utils import data
from sklearn.preprocessing import M... |
import pytest
from fastapi import BackgroundTasks
from typing import List, Tuple, Any
from PIL import Image
import numpy as np
import os
from src.constants import PLATFORM_ENUM
from tests.utils import floats_almost_equal, nested_floats_almost_equal, get_image_data
from src.app.ml.base_predictor import BaseData, BaseDa... |
import os
from .base import StorageBackend
from muninn.schema import Mapping, Text, Boolean
import muninn.util as util
from muninn.exceptions import Error
import muninn.config as config
from muninn.util import product_size
class _FSConfig(Mapping):
_alias = "fs"
root = Text()
use_symlinks = Boolean(opt... |
import numpy as np
class ODEStates:
def __init__(self, t) -> None:
self.t = t
n_points = len(self.t)
# start filling up from 0th index
self.index = 0
# state values
self.S = np.zeros(n_points)
self.ERR = np.zeros(n_points)
self.ERS = np.zeros(n_... |
""" Command line interface for Verisure MyPages """
from __future__ import print_function
import argparse
import json
import verisure
COMMAND_OVERVIEW = 'overview'
COMMAND_SET = 'set'
COMMAND_CLIMATE = 'climate'
COMMAND_EVENTLOG = 'eventlog'
COMMAND_INSTALLATIONS = 'installations'
COMMAND_CAPTURE = 'capture'
COMMAND_... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cv2
from scipy import misc
import tensorflow as tf
import numpy as np
import sys
import os
import copy
import argparse
import facenet
import align.detect_face
import random
from os.path import join as p... |
import pathlib
from typing import List, Tuple, Union, Optional
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import attr
from attr.validators import instance_of, optional
import tifffile
from calcium_bflow_analysis.dff_analysis_and_plotting.dff_analysis ... |
import logging
import os
import re
import uuid
from io import BytesIO
from mimetypes import guess_extension
from os.path import splitext
from PIL import Image
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.core.validators import RegexValidator
from django.db import models
from django.db.mo... |
"""
Author: <NAME>
Date created: Mon 27 Apr 18:11:03 IST 2020
Description:
Main jetson/pc python file for controlling gimbal via the tracked object.
License :
------------------------------------------------------------
"THE BEERWARE LICENSE" (Revision 42):
Param Deshpande wrote this code. As long as you reta... |
import os
import re
import datetime as dt
import nltk
from googletrans import Translator
import json
import math
'''
ForceSem.py takes a Whatsapp chat history in German and/or English and converts it into a JSON file containing nodes and
links (or edges), which may be used to create a force-directed graph layout. In ... |
import ptypes
from ptypes import *
from . import portable
from .headers import *
import logging
class Signature(portable.IMAGE_FILE_HEADER):
_fields_ = [
(Machine, 'Machine'),
(uint16, 'NumberOfSections'),
]
def isImportSignature(self):
return all((self['Machine'].li.int() == sel... |
# Copyright (c) 2020, <NAME>, Honda Research Institute Europe GmbH, and
# Technical University of Darmstadt.
# 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 mus... |
import pyglet
import cv2
import numpy as np
import os
from copy import deepcopy
def show_stuff(win, frame, width, height, total_reward, fps, car, car_already_drown, steps, style_state, command=None, show_help=False, discrete=False, classf_name=None, save=False, helper=None, gcam_target=None, comms=None):
win.swit... |
#!/usr/bin/python3
"""
perfPredictor implements the performance prediction model as described in the reference below:
<NAME>, <NAME>,
"A quantitative roofline model for GPU kernel performance estimation using
micro-benchmarks and hardware metric profiling",
Journal of Parallel and Distributed Computing, Volume 107, S... |
##
# BSD 3-clause licence
#
# Copyright (c) 2015, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# lis... |
#!/usr/bin/env python3
# Copyright 2021 Secureworks
#
# 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... |
#!/usr/bin/env python3
"""Get all of the functional annotations from PATRIC genomes, link to 16S records."""
import os
import re
import io
import uuid
import boto3
import argparse
import pandas as pd
import sciluigi as sl
from urllib.request import urlopen
from Bio.SeqIO.FastaIO import SimpleFastaParser
def read_tsv... |
import math
import pandas as pd
import numpy as np
import prepare_data as p_d
from matplotlib import pyplot as plt
from sklearn.cluster import AgglomerativeClustering
import scipy.cluster.hierarchy as sch
def eucl_dist(x,y):
# x [x1,x2]; y [y1, y2]
[x1, x2] = x
[y1, y2] = y
# print(x, " ", y)
resul... |
# -*- coding: utf-8 -*-
# File: config.py
# Copyright 2021 Dr. <NAME>. 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... |
"""Rendering utilities."""
import enum
import math
import os
from typing import Any, Callable, Dict, Iterable, Optional, Text
from absl import logging
import gin
import numpy as np
# These matrices will change by any call to render() and should be saved
# immediately to the local object.
last_used_view_matrix = None... |
import math
import os
import random
from abc import abstractmethod
import numpy as np
from PIL import Image, ImageDraw, ImageFilter, ImageEnhance
from lib.detection import FaceMetadata
from typing import List
class IllegalStateException(Exception):
pass
class ImageProcessingContext(object):
def __init__(se... |
"""
Some commonly-used functions of matrix.
"""
import numpy as np
from numpy import linalg as LA
import scipy.sparse as sps
from scipy.sparse import csr_matrix,csc_matrix
from itertools import product
def get_random_hermitian_matrix(n):
'''
Generate random hermitian matrix(n, n)
'''
x = np.random.rand... |
"""
(c) 2011, 2012 Georgia Tech Research Corporation
This source code is released under the New BSD license. Please see
http://wiki.quantsoftware.org/index.php?title=QSTK_License
for license details.
This package includes code for representing and learning HMM's.
Most of the code in this package was derived from the... |
import datetime
from pathlib import Path
from typing import Optional, Union, List
from typing_extensions import Protocol
from rich import print
from rich.markdown import Markdown
from rich.table import Table
from github_secrets.config import SecretsConfig, Secret
from github_secrets import git
from github_secrets imp... |
import time
import copy
import torch
import matplotlib
import torchvision
import random
import numpy as np
import torch.nn as nn
import sklearn.metrics as skm
from tqdm import tqdm
from pathlib import Path
from torchvision import models
from to... |
"""Objects and reading/writing routines for PRT files."""
import collections
import struct
import bitmap
import palette
Rect = collections.namedtuple('Rect', ['left', 'top', 'right', 'bottom'])
Point = collections.namedtuple('Point', ['x', 'y'])
class PRTLoadError(Exception):
pass
class PRTFile(object):
de... |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest, time, ... |
from typing import Dict, List, Tuple
import numpy as np
import torch
from neuralhydrology.training.regularization import BaseRegularization
from neuralhydrology.utils.config import Config
ONE_OVER_2PI_SQUARED = 1.0 / np.sqrt(2.0 * np.pi)
class BaseLoss(torch.nn.Module):
"""Base loss class.
All losses exte... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import itertools
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn.metrics import roc_curve, roc_auc_score
import matplotlib as mpl
f... |
import numpy as np
import torch
import pandas as pd
import pytest
from sklearn.exceptions import NotFittedError
from pytorch_widedeep.preprocessing import TabPreprocessor
from pytorch_widedeep.utils.deeptabular_utils import (
LabelEncoder,
find_bin,
get_kernel_window,
)
from pytorch_widedeep.preprocessing.... |
import json
from django.db.models import Count, Avg, Max, Min, Sum, F, Q
from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from .models import *
# Create your views here.
def hallo_welt(request):
return JsonResponse({"res": "hallo-welt"})
# 获得所有
def get_all_title():
re... |
#!/usr/bin/python
# REV3
from __future__ import print_function
from sys import stdout
import socket
import time
import sys
import os
# CHECK FOR CORRECT NUMBER OF ARGUMENTS =================================================
if len(sys.argv) != 3:
print('[TEST_FOR_OVERFLOW_LOCATION]')
print('[Usage]: python cspe... |
#! /usr/bin/env python3
from pathlib import Path
from collections import defaultdict
from collections import OrderedDict
from functools import lru_cache
import yaml
from yaml import Loader
import json
import re
from lxml import etree
from lxml.builder import E
import click
# File configuration & ASI file version
BA... |
import numpy as np
from numba import guvectorize
from ..blocks.het_block import het
from .. import interpolate
def hh_init(b_grid, a_grid, z_grid, eis):
Va = (0.6 + 1.1 * b_grid[:, np.newaxis] + a_grid) ** (-1 / eis) * np.ones((z_grid.shape[0], 1, 1))
Vb = (0.5 + b_grid[:, np.newaxis] + 1.2 * a_grid) ** (-1 ... |
####
# TO DO: TURN INTO SCRIPT
###
import os
import glob
import cv2
import datetime
import numpy as np
import matplotlib.pyplot as plt
import zipfile
import shutil
import fnmatch
import sys
import math
### FUNCTIONS ###
def time_between_frames(timestamps_csv):
time_diffs = []
for t in range(len(timestamps_cs... |
import logging
import os
import time
import numpy as np
import matplotlib.pyplot as pt
from keysight_fpga.sd1.fpga_utils import \
print_fpga_info, config_fpga_debug_log, print_fpga_log, get_fpga_image_path, fpga_list_registers
from keysight_fpga.sd1.sd1_utils import check_error
from keysight_fpga.sd1.dig_iq impor... |
from homeassistant import config_entries
from homeassistant import data_entry_flow
from bluepy.btle import Scanner, DefaultDelegate
from subprocess import check_output
import traceback
import random
import string
from re import search
import voluptuous as vol
from homeassistant.core import callback
from .lib import Red... |
import sys
if sys.version_info >= (3, 8):
from typing import List, Optional, Literal, Dict
else:
from typing import List, Optional, Dict
from typing_extensions import Literal
import logging
from pydantic import BaseModel
from aiortc import RTCIceCandidate
import sdp_transform
from .media_section import Med... |
from typing import Type
import pytest
from ..core import type_params_issubclass, merge_params
from .. import Proxytype, GenericProxytype, is_generic, validate_typespec
from ... import Struct, List, Tuple, Int, Float, Str
# NOTE: we test with non-Proxytype classes for this first test to be a little more hermetic,
# si... |
"""
This module contains functions related to Lagrange Coefficients and universal variables
The source comes from the book Orbital Mechanics for Engineering Students
"""
# Standard library imports
from typing import Any,Dict,List,Tuple,Sequence
#https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html
from functool... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
from pathlib import Path
from typing import Iterable, Optional
from compiler_gym.datasets import Benchmark, BenchmarkSource, Da... |
import torch
from torchviz import make_dot
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
from torchsummary import summary
from Model.torch_utils import Conv2dStaticSamePadding, MaxPool2dStaticSamePadding
def _upsample_like(src, tar):
src = F.interpolate(src, size=tar.shape[2:], mode='b... |
import collections
import os
import queue
import random
import subprocess
import sys
import threading
import time
from make_order import getFeedstockOrder, getFeedstockName, getFeedstockDependencies
from pathlib import Path
SRC_DIR = Path(__file__).parent.absolute()
versions_to_build = {
"numpy": ("1.18.1", "1.1... |
#!/usr/bin/python3
import sys, argparse, operator, re, typing, itertools
DEBUG=0
MODE_POSITION=0
MODE_PARAMETER=1
ARG1=0
ARG2=1
ARG3=2
OP_ADD=1
OP_MUL=2
OP_INPUT=3
OP_OUTPUT=4
OP_JNZ=5
OP_JZ=6
OP_SLT=7
OP_SEQ=8
OP_HALT=99
def jump_opcode(opc):
return opc in [OP_JZ, OP_JNZ ]
class Intcode:
class Opcode:
... |
# -*- coding: utf-8 -*-
import uuid
from enum import Enum
from sqlalchemy import desc
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.sql import and_, func
from common.database import db
from common.languages import _local_
from common.log.journal import system_logger
from common.models.auth import Us... |
"""
This is turning into the API submodule for
"""
from typing import Callable, Iterable, Dict, Tuple, FrozenSet, Set, NamedTuple
import operator
from boozetools.support import foundation
from . import frontend, runtime, domain, semantics
__ALL__ = ['Universe', 'AlreadyRegistered']
class AlreadyRegistered(Exception):... |
import numpy as np
from PIL import Image
import torch
import torch.nn as nn
from torchvision import transforms
from torch.utils.data import Dataset, DataLoader
import cv2
import random
def channel_norm(img):
# img: ndarray
mean = np.mean(img)
std = np.std(img)
eps = 0.0000001
pixels = (img - mean)... |
from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from .firebase import create_user, teacher_login, uploadimage
from .models import _new_course, _new_user, get_token, ge... |
#!/usr/bin/env python
import numpy
import re
mstohtk = 10000
sectoms = 1000
frameshift = 5
class ContextInfo:
def __init__(self, fileID, frameStart, frameEnd, context, btlnkFeats=None):
self.fid = numpy.array([int(fileID)])
self.sframe = numpy.array([int(frameStart)])
self.eframe = numpy... |
"""
This module contains all core classes required for drawing diagrams.
Available Classes:
- Graph
- Cluster
- Group
- Node
- Edge
- Flow
Available Functions:
- get_graph
- set_graph
- get_cluster
- set_cluster
- get_state
- set_state
- wrap_text
- get_node_obj
- get_cluster_obj
Details for each can be found in the... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 11 14:22:08 2021
@author: jaimewalter
"""
## Visualize a cube that rotates in 3D, and its 2D orthographic projections. Made with linear transformations.
import numpy as np
import math
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3... |
#!/usr/bin/env python
# coding: utf-8
"""
Classifiers implemented:
* Decision tree: See http://en.wikipedia.org/wiki/Decision_tree_learning
* Naive Bayes: See http://en.wikipedia.org/wiki/Naive_Bayes_classifier
* K-Nearest Neighbor: See http://en.wikipedia.org/wiki/K-nearest_neighbor
"""
import numpy
f... |
import networkx
import numpy
import MinimumBoundingRectangle
import time
def create_greateast_weakyl_connected_component(file_name):
G = networkx.DiGraph()
graph_file = open(
"./data/raw/{}_social".format(file_name), "r")
counter = 0
for edge in graph_file:
edge = edge.replace("\n", ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import io
import json
import math
import os
import numpy as np
from PIL import Image
from PIL import ImageFile
import tensorflow.compat.v2 as tf
from absl import logging
from absl import app
from absl import... |
from django.core.management.base import BaseCommand, CommandError
import socket
import imaplib
import sys
import email
from django.conf import settings
from main.models import Email, EmailOversizeNotified, Leg
import pprint
from django.core.mail import send_mail
# This file is part of https://github.com/cpina/science-... |
#noinspection
import numpy as np
import riskslim.loss_functions.fast_log_loss as fast
import riskslim.loss_functions.log_loss as normal
import riskslim.loss_functions.log_loss_weighted as weighted
import riskslim.loss_functions.lookup_log_loss as lookup
from riskslim.setup_functions import _setup_training_weights
np.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.