text stringlengths 3.07k 22.1k |
|---|
from pathlib import Path
import pandas as pd
class YearData:
"""
Base Year Data
All annual files are mapped to a class which describes the name of the data
file, the year (as an integer), and a count of expected births for that year.
These attributes are used to assist in processing of raw files... |
# 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 torch
import torch.nn as nn
import numpy as np
import sys
import os
sys.path.append(os.path.join(os.getcwd(), "lib")) # HACK add the ... |
import os
import numpy as np
# Tiles are 10x10 squares
TILE_LENGTH = 10
# 2d array representing the seamonster
SEA_MONSTER = np.array([
[" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "#", " "],
["#", " ", " ", " ", " ", "#", "#", " ", " ", " ", " ", "#", "#", " ", " ",... |
"""
Module that provides various audio augmentors.
Each augmentor class should provide a function called 'augment' with the following signature:
augment(x)
where x is a numpy ndarray (len(x.shape) should be equal to 1), and should return an ndarray
with the same shape that contains the augmented version of x.
"""
... |
import json
import os
import re
from abc import ABC, abstractmethod
from datetime import timedelta, datetime
import humanfriendly
from typing import (
Any,
Iterator,
Iterable,
Optional,
Union,
List,
Dict,
Sequence,
cast,
Collection,
)
import sh
from jinja2 import Environment, D... |
# coding: utf-8
# In[8]:
import sys
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
from torch.autograd import Variable
from torchvision import models, transforms
import time
import os
from torch.utils.data import Dataset
from torch.utils import model_zoo
from ... |
##############################################################################
# CODE OF MARIA #
##############################################################################
import gym
import numpy as np
import sys
import os
import time
import pandas
import... |
import logging
import sys
import time
import cv2
import numpy as np
import pprint
import numpy as np
from tf_pose import common
from tf_pose.estimator import TfPoseEstimator
from tf_pose.networks import get_graph_path
# get humans class
# model setted mobilenet_thin (later should check which model is the best and use... |
from tkinter import *
from tkinter.filedialog import askdirectory
from tkinter.messagebox import showerror
import tkinter.ttk as ttk
import os, csv
import time, datetime, calendar
LARGE_FONT = ("Verdana", 12)
NORM_FONT = ("Verdana", 10)
SMALL_FONT = ("Verdana", 9)
def path_shorten(path):
path = path.split('/')
... |
# !usr/bin/env python
# -*- coding: utf-8 -*-
#
# Licensed under a 3-clause BSD license.
#
# @Author: <NAME>
# @Date: 2017-11-29 10:28:58
# @Last modified by: <NAME>
# @Last Modified time: 2018-07-27 17:22:02
from __future__ import print_function, division, absolute_import
import pytest
from tree import config
fro... |
import dill
import pandas as pd
import numpy as np
from sklearn import metrics
import re
from scipy.sparse import issparse
from scipy.spatial.distance import pdist
from nltk import ngrams
import spacy
nlp = spacy.load('en_core_web_lg') # may need to consider the large vectors model if the vectors perform well
stopwor... |
import ast
import collections
import contextlib
import functools
import inspect
import io
import logging
import sys
import traceback
import types
from typing import Any, Optional, Union
log = logging.getLogger(__name__)
# A type alias to annotate the tuples returned from `sys.exc_info()`
ExcInfo = tuple[type[Exceptio... |
from bs4 import BeautifulSoup
import requests
import ExcelWriter
class Search_enum:
SSD = "SSD"
Motherboard = "Základová deska"
Procesor = "Procesor"
class SSD:
def __init__(self, capacity = 0, speed_read = 0, speed_write = 0):
self.Capacity = capacity
self.Speed_read = speed_read
... |
# ======================================================================
# Copyright TOTAL / CERFACS / LIRMM (03/2020)
# Contributor: <NAME> (<<EMAIL>>
# <<EMAIL>>)
# <NAME> (<<EMAIL>>)
# This software is governed by the CeCILL-B license under French law and
# abiding by the rul... |
'''
Definitions of geometrical objects.
'''
import numpy as np
from mesh.operate import transform
def ellipsoid_create(name, position=(0, 0, 0),
lengths=(1, 1, 1),
axe1=(1, 0, 0),
axe2=(0, 1, 0),
velocity=(0, 0, 0),
... |
#!/usr/bin/env python
# coding: utf-8
"""Parsers for Hebrew texts."""
__all__ = ["chabad_org", "tanach_us", "mechon_mamre_org"]
# native
from dataclasses import dataclass
from functools import partial
from inspect import cleandoc
from multiprocessing import Process, RLock, Queue
from pathlib import Path
from typing i... |
#
#
# Extra stats -> sparse/dense/loaded
# _4xx: lines regarding PROCESSING TIME AND TOURSIZE
# _5xx: boxplot regarding _4xxx
# _6xx: zoom in _5xx
#
#
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
fileIn="_stats_summary.txt"
SPARSE=20
DENSE=... |
import pytest
import magma as m
import magma.testing
import fault as f
def test_basic():
class _Top(m.Circuit):
io = m.IO(I=m.In(m.Bit), O=m.Out(m.Bit)) + m.ClockIO()
with m.compile_guard("COND", defn_name="COND_compile_guard"):
out = m.Register(m.Bit)()(io.I)
io.O @= io.I
... |
# coding=utf-8
"""
Small command module to merge existing datasets or extend them with additional data
"""
import os as os
import pandas as pd
import multiprocessing as mp
from string import ascii_uppercase as asciiup
from crplib.auxiliary.hdf_ops import get_default_group, get_chrom_list,\
load_data_group, check... |
import sys
import limix
from limix.core.covar import LowRankCov
from limix.core.covar import FixedCov
from limix.core.covar import FreeFormCov
from limix.core.covar import CategoricalLR
from limix.core.mean import MeanBase
from limix.core.gp import GP
import scipy as sp
import scipy.stats as st
from limix.mtSet.core.i... |
import asyncio
from collections import defaultdict, abc
from copy import deepcopy
from typing import Callable, Any, Union
from aiosaber.utility.typings import Predicate, POS_INF, NEG_INF, Getter, Putter
from aiosaber.utility.utils import extend_method, class_to_method, async_getter
from .channel import ConstantChannel... |
from math import sqrt, floor, ceil
from datetime import datetime
from asyncio import TimeoutError
from discord import Message, Color
from discord.errors import Forbidden
from discord.ext.commands import (
Cog,
Context,
command,
group,
cooldown,
BucketType,
)
from nagatoro.converters import Mem... |
"""Unit tests for the ZMQServer and ZMQClient drivers."""
import time
from schema import SchemaError
import zmq
import pytest
from testplan.testing.multitest.driver.zmq import ZMQServer, ZMQClient
from testplan.common.utils.context import context
from testplan.common.utils.timing import TimeoutException
from testpla... |
import os
import sys
import re
import json
import pandas as pd
import collections
import pytz
from datetime import datetime, timedelta
try:
from jaws import tilt_angle, fsds_adjust
except ImportError:
import tilt_angle, fsds_adjust
#############################################################################... |
import pytest
import falcon
from falcon import ASGI_SUPPORTED, constants, testing
from _util import create_app, disable_asgi_non_coroutine_wrapping # NOQA
def capture_error(req, resp, ex, params):
resp.status = falcon.HTTP_723
resp.body = 'error: %s' % str(ex)
async def capture_error_async(*args):
ca... |
import tkinter as tk, sys
from tkinter import ttk
from urllib import error
from validators import url
from threading import Thread
from os import rename, path
from re import sub
from pytube import exceptions, YouTube
from spotipy import Spotify
from spotipy.exceptions import SpotifyException
from spotipy.oauth2 import ... |
#!/usr/bin/env python3
"""Functional Python Programming
Chapter 16, Example Set 3
"""
# pylint: disable=wrong-import-position
from functools import lru_cache, reduce
import operator
from fractions import Fraction
import warnings
@lru_cache(128)
def fact(k: int) -> int:
"""Simple factorial of a Fraction or an int... |
import copy
import random
class Civilization:
def __init__(self, name: str, aliases: [str] = []):
self.name = name
self.aliases = aliases
def __lt__(self, civ):
if(isinstance(civ, Civilization)):
return self.name.lower() < civ.name.lower()
elif(isinstance(civ, str)... |
import pandas as pd
from matplotlib import pyplot as plt
import numpy as np
def get_house_prices_and_rooms():
# getting the data
interesting_columns = ['house_price', 'number_of_rooms']
houses_df = pd.read_csv('data/HousingData.csv')[interesting_columns]
# getting data without outliers
number_o... |
import time
import pandas as pd
import tushare as ts
from src.calNetValue.utils import print_info, get_api, tushare_token, player_dict, stock_dict, figs_dict, index_dict
import pyecharts.options as opts
from pyecharts.charts import Line
def all_net_value(player_pool, start_date, end_date, adj="qfq"):
# 计算所有参与者的净值... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 26 16:23:01 2021
@author: mlampert
"""
from flap_nstx.analysis import calculate_tde_velocity, calculate_sde_velocity, calculate_sde_velocity_distribution
#Core modules
import os
import copy
import h5py
import pickle
from matplotlib.backends.backe... |
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import multivariate_normal as mvn
#from scipy.linalg import toeplitz
from scipy.linalg import solve_banded
from scipy import sparse
from mpl_toolkits.mplot3d import Axes3D
'''
Metropolis-Hastings iterations
'''
def metropolis_hastings(model):
nite... |
# SPDX-FileCopyrightText: 2020 <NAME> <<EMAIL>>
#
# SPDX-License-Identifier: Apache-2.0
import ast
import logging
import os
from typing import Type, Optional, Generator, List
from codeprep.bpepkg.bpe_config import BpeConfig
from codeprep.config import DEFAULT_PARSED_DATASETS_DIR, DEFAULT_PREP_DATASETS_DIR, USER_BPE_D... |
"""
Helper functions
"""
import logging
import math
import os
import subprocess
import sys
import time
from collections import Counter
from contextlib import contextmanager
from warnings import warn
import numpy as np
from .exceptions import ArimWarning, NotAnArray, InvalidDimension, InvalidShape
def get_name(meta... |
"""
Pure Virtual Python (purepy) is a toolkit for helping with virtual classes so we can handle
a more complex ABCMeta scenario and alert us to problems before possible deep runtime code
is executed.
Example:
from purepy import PureVirtualMeta, pure_virtual
class Interface(metaclass=PureVirtualMeta):
... |
# Copyright 2020 <NAME>
# SPDX-License-Identifier: Apache-2.0
import typing
from unittest import mock
import cv2
import numpy
from bloom import game_map
from bloom.editor import map_objects
from panda3d import core
from .. import map_data
from ..editor import map_objects, undo_stack
from ..editor.map_objects.drawing... |
import os
import numpy as np
import matplotlib.pyplot as plt
#import SLIP for whitening and PIL for resizing
import SLIP
# copied from https://raw.githubusercontent.com/bicv/LogGabor/master/default_param.py
pe = {
# Image
# 'N_image' : None, #use all images in the folder
'N_image' : 100, #use 100 images in ... |
from django.db import models as m
# Create your models here.
# Revenue
class Client(m.Model):
class Meta:
verbose_name = "Client"
verbose_name_plural = "Clients"
def __str__(self):
return "{}: {} (ID: {})".format(self.__class__.__name__, self.name, self.id)
id = m.AutoField(verbose_name="Client I... |
"""
Binary Search Tree Traversal
"""
from enum import Enum
class DFSTraversalTypes(Enum):
PREORDER = 1
INORDER = 2
POSTORDER = 3
class Node():
def __init__ (self, val):
self.value = val
self.parent = None # type: Node
self.left = None # type: Node
self.right = None... |
from Bio import SeqIO
from Bio.SeqUtils import GC
from mob_suite.blast import BlastRunner
from mob_suite.blast import BlastReader
import os
from subprocess import Popen, PIPE
import shutil,sys
def check_dependencies(logging):
external_programs = ['blastn', 'makeblastdb', 'tblastn', 'circlator']
missing = 0
... |
#
# This source code is licensed under the Apache 2 license found in the
# LICENSE file in the root directory of this source tree.
#
import json
import cPickle as pickle
import numpy as np
import h5py
import random
import pandas as pd
from nltk.tokenize import TweetTokenizer
word_tokenize = TweetTokenizer().tokenize
... |
# Original source: https://github.com/TLKline/AutoTKV_MouseMRI
# Libraries
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D, add
from tensorflow.keras.layers import Dropout, BatchNormalization
from fmri.models.unsupervised.keras.metrics import dice_... |
from bs4 import BeautifulSoup
# from urllib2 import urlopen #python 2
from urllib.request import urlopen #python 3
import time
import datetime
import re
import urllib
import sys
total_number_of_images = 3227131
def make_query(query, site="safebooru.org", images_per_page=10, page_id=0):
tags = query.split(" ")
... |
from elementary_step_om.external_calculation.gaussian_calculations import GaussianCalculator
import unittest
from rdkit import Chem
import numpy as np
from elementary_step_om.chem import (
MoleculeException,
BaseMolecule,
Molecule,
MappedMolecule,
Fragment,
Conformer,
Reaction
)
from ele... |
#
# Copyright 2022 DMetaSoul
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
import discord
import random
import utils
from discord.ext import commands
from unsplash import Unsplash, Photo, UnsplashException
from typing import Optional, List
from aiohttp import ClientError
utm_params = '?utm_source=discord_bot_doggie_bot&utm_medium=referral'
async def get_pic(url: str, ctx: utils.CustomCont... |
# Copyright 2015 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
#! /usr/bin/env python
# coding=utf-8
#================================================================
# Copyright (C) 2019 * Ltd. All rights reserved.
#
# Editor : VIM
# File name : train.py
# Author : YunYang1994
# Created date: 2019-10-17 15:00:25
# Description :
#
#=========================... |
#!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed... |
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler,MinMaxScaler
from sklearn.model_selection import train_test_split
import random
import math
import os
import time
from utils.VLSW import pad_all_cases
# from VLSW import pad_all_cases
# set the random seeds for reproducability
SEE... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 19-5-15 下午5:49
# @Author : Hubery
# @File : crawler.py
# @Software: PyCharm
import os
import django
from concurrent.futures import ThreadPoolExecutor
from lxml import etree
from queue import Queue
from utils.helper import get_text
from utils.validator import... |
# -*- coding: utf-8 -*-
# Copyright Noronha Development Team
#
# 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 applica... |
# coding: utf-8
import sys
import xlsxwriter
from reports import headers
import models
def jcatalog():
# Cria a pasta Excel e adiciona uma planilha
workbook = xlsxwriter.Workbook('output/journals_catalog.xlsx')
worksheet = workbook.add_worksheet('SciELO Journals Catalog')
format_date = workbook.add_... |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Subset
import numpy as np
import ignite.metrics as metrics
#import ignite.contrib.metrics.average_precision as average_precision
def average_precision_compute_fn(y_preds, y_targets):
try:
from sklear... |
"""
TODO: What does this do? It looks like calculating some metrics, running everything etc,
and writing/saving logs.
This needs to be split up
"""
import os
import time
import config
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
sns.set(style="darkgrid")
class... |
#!/usr/bin/env python3
import argparse
import datetime
import http.server
import json
import logging
import os
import platform
import socketserver
import threading
import time
import yaml
import subprocess
import sys
import schedule
from pytimeparse import parse as parse_time
import sensorproxy.sensors.illumination
... |
import numpy as np
import math
import cmath
def transform_point(point, matrix):
return matrix @ np.hstack([point,1]).T
def subdet(m):
return m[0,0] * m[0,1] - m[0,1] * m[1,0]
def angle(point):
return (180 / math.pi) * math.atan2(point[1], point[0])
def pointwise_equal(a,b, epsilon):
if a.__class__... |
from .chart import Chart
from .lib.utils import adjust_lightness
from .lib.formatter import Formatter
import numpy as np
class RangePlot(Chart):
""" Plot categorical data with two data points, for example change over time.
Mimics Datawrapper's dito in form and functionality
"""
def __init__(self, *... |
# Copyright (C) 2016 <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
# ========================================... |
# -*- coding: Utf-8 -*
# Author: <EMAIL>
import random
import sys
################################################################################
# MODEL #
################################################################################
### Cons... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2011-2018, <NAME>
# Copyright (c) 2011-2018, B2CK
# 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 a... |
import torch
import random
import librosa
import numpy as np
import nlpaug.flow as naf
import nlpaug.augmenter.audio as naa
import nlpaug.augmenter.spectrogram as nas
from torchvision.transforms import Normalize
from torch.utils.data import Dataset
from torchaudio.datasets import LIBRISPEECH
BAD_LIBRISPEECH_INDICES =... |
# Copyright 2021 NVIDIA Corporation
#
# 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 wr... |
#!/usr/bin/env python3
import math
import helper
class SnailMath:
def __init__(self, line: str) -> None:
self.internal: list[str] = self.take_apart(line)
def take_apart(self, line: str) -> list[str]:
result: list[str] = []
#
i = 0
while i < len(line):
c =... |
# coding=utf-8
# Copyright 2021 The Google Research 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 applicab... |
import os
import tensorflow as tf
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
class OCRDataLoader:
"""
OCR Data Loader, return tf.data.Dataset.
"""
def __init__(self, annotation_paths, parse_funcs, image_width, table_path,
batch_size=64, shuffle=False, repeat=1):
#最原始获取的path... |
#####################
#####==IMPORTS==#####
#####################
import os
import numpy as np
from psychopy import core, visual, event, data, logging
from numpy.random import shuffle
def instImport(path):
"""
instImport is a function for importing instruction text to be used in the experiment and does the r... |
import os
from glob import glob
import torch
import torch.backends.cudnn as cudnn
from torch.utils.tensorboard import SummaryWriter
import numpy as np
from arguments import get_config
from dataloader import get_dataloader
from model.resnet import ResNet
from model.wide_resnet import get_wide_resnet
from model.pyramid... |
#!/usr/bin/env python3
''' Helper tool to generate hybrid grids containing uniform and stretched
segments.
Example
=======
Generate a grid with 3 uniform segments of fixed cell size joined by
stretched grid segments. In each stretched grid segment, cell size varies
from the cell size of one uniform segment to the ot... |
import argparse
import numpy as np
import math
import os
import time
from six.moves import cPickle # six.moves is used to self-adjust the change of python 2 and python 3
import yaml
import itertools
from multiprocessing.dummy import Pool as ThreadPool
import torch
import torch.optim as optim
from torch.optim.lr_sched... |
import numpy
import matplotlib.pyplot as plt
import h5py
# constants
xs = [1, 0, -1, 0]
ys = [0, 1, 0, -1]
J = 1 # Coupling strength
k = 1 # k Boltzman
# global variables
# Initialize grid with random 1s and 0s
def initialize_grid(N):
grid = numpy.random.random_integers(0, 1, (N, N)) # Initialize gr... |
import dataset
import tensorflow as tf
import sys
sys.path.append('../../MyLibrary/')
import siannodel.ml.tf_estimator as myestimator
import siannodel.ml.tf_extend as mytf
from easydict import EasyDict
import siannodel.mytime as mytime
import os
#构建模型
class Net(myestimator.BaseNet):
def __init__(self, config):
... |
__author__ = '<NAME> <<EMAIL>>'
__date__ = '19 February 2016'
__copyright__ = 'Copyright (c) 2016 Seven Bridges Genomics'
import abc
from string import Template
from .expression import *
class Statement(metaclass=abc.ABCMeta):
SERIALIZATION_RAW = 'raw'
SERIALIZATION_PRETTY = 'pretty'
@abc.abstractmetho... |
# Copyright 2017 Rice University
#
# 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 writin... |
import threading
import queue
import numpy as np
from util import text_processing
import ipdb
batch_mix_control = 1
class BatchLoaderVqa:
def __init__(self, imdb, data_params):
self.imdb = imdb
self.data_params = data_params
self.vocab_dict = text_processing.VocabDict(
data_par... |
import numpy as np
import torch
import torch.nn as nn
class Discriminator2DFactory(nn.Module):
def __init__(self, time_length, freq_length=80, kernel=3, c_in=1, hidden_size=128,
norm_type='bn', reduction='sum'):
super(Discriminator2DFactory, self).__init__()
padding = kernel // 2
... |
# -*- coding: utf-8 -*-
import os
from kivy.app import App
from kivy.lang import Builder
from kivy import Logger
from kivy.metrics import dp
from kivy.properties import ObjectProperty, NumericProperty, StringProperty, ListProperty, OptionProperty, \
BooleanProperty
from kivy.uix.boxlayout ... |
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Name: BlackScholes
# Purpose:
#
# Author: kklekota
#
# Created: 22/05/2014
# Copyright: (c) kklekota 2014
# Licence: <your licence>
#----------------------------------------------------------... |
import math
INFINITY = float('inf')
NAN = float('nan')
def sqrt_nothrow(x):
return math.sqrt(x) if x >= 0 else NAN
def cg(opfunc, x, config, state=None):
"""
This cg implementation is a rewrite of minimize.m written by <NAME>. It is supposed to produce exactly same results (give
or take numerical ... |
import cx_Oracle
import pandas as pd
import numpy as np
from tabulate import tabulate
# Database connection. Note I am hiding my actual database password information
connection = cx_Oracle.connect('connection goes here')
cursor = connection.cursor()
# Admin login credentials
adminUsername = "jbalda"
admi... |
#!/usr/bin/python3 -u
import pwd
import grp
import datetime
import time
import json
import sys
import os
import struct
from ctypes import (CDLL, get_errno)
from ctypes.util import find_library
import signal
import atexit
from socket import (
socket,
SOCK_CLOEXEC,
AF_BLUETOOTH,
SOCK_RAW,
BTPROTO_HCI... |
import numpy as np
import pytest
from ..utils import ArrayDeque, ExperienceCache, softmax
from ..errors import ArrayDequeOverflowError
def test_softmax():
rnd = np.random.RandomState(7)
w = rnd.randn(3, 5)
x = softmax(w, axis=1)
y = softmax(w + 100., axis=1)
z = softmax(w * 100., axis=1)
# ch... |
import argparse
import logging
import os
import sys
import torch
import wandb
import numpy as np
import torch.nn.functional as F
import torch.nn as nn
from datetime import datetime
from model_zoo.BBSNet.models.BBSNet_model import BBSNet
from model_zoo.BBSNet.models.BBSNet_model_effnet import BBSNet as BBSNet_effnet
f... |
import numpy as np
import os
import time
import json
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
from tensorflow.keras.preprocessing.image import array_to_img, img_to_array, load_img
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
from pysam import AlignmentFile
from pybedtools import BedTool, Interval
from progress.bar import... |
"""
Script to process tweets into featurized format
"""
import argparse
import logging
import time
import os
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
from sklearn.feature_extraction.text import TfidfVectorizer
import re
import pandas as pd
import texthero as hero
import glob
import tqdm
i... |
from CHECLabPy.core.reducer import WaveformReducer, column
import numpy as np
from numba import njit, prange, float64, float32, int64
@njit([
(float64[:, :], int64, int64),
(float32[:, :], int64, int64),
])
def obtain_pulse_timing(waveforms, window_start, window_end):
n_pixels, n_samples = waveforms.shape... |
# -*- coding: utf-8 -*-
# Copyright © 2021 Wacom 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
#
# Unle... |
'''
MDL Display App
Displays status and data from databear.
- Must test on MDL
'''
from PIL import Image, ImageDraw, ImageFont
from datetime import datetime
from math import ceil
from enum import Enum
import importlib.resources as pkg_resource
import struct
import fcntl #Unix utility
import selectors
imp... |
import os
import glob
import torch
import random
import matplotlib.pyplot as plt
import numpy as np
from trainer import parse_args
from tqdm import tqdm
from torch.utils.data import Dataset, DataLoader
from inference import parse_args as parse_inference_args
from trainer import parse_args as parse_train_args
from mode... |
import os
import sys
import scipy
import logging
import numpy
import tempfile
import shutil
import numpy
import subprocess
import random
from scipy.io import savemat, loadmat
from PIL import Image
from aletheialib import utils
from aletheialib.octave_interface import _embed
import multiprocessing
from multiprocessin... |
import chainladder as cl
import pandas as pd
import numpy as np
import copy
tri = cl.load_dataset('clrd')
qtr = cl.load_dataset('quarterly')
# Test Triangle slicing
def test_slice_by_boolean():
assert tri[tri['LOB'] == 'ppauto'].loc['Wolverine Mut Ins Co']['CumPaidLoss'] == \
tri.loc['... |
import click
from pathlib import Path
import os
import subprocess
import json
import time
import lib
import datetime
import logging
import asyncio
class MissingEnvironmentVariable(Exception):
def __init__(self, variable):
self.variable = variable
def os_environ(env_var):
if env_var in os.environ:
... |
import os
import cv2
import numpy as np
import tensorflow as tf
from config import config
from logger import Logger
#from models import Simple, NASNET, Inception, GAP, YOLO
from models import Inception
from utils import annotator, change_channel, gray_normalizer
from information import Information
def load_model(ses... |
# -*- encoding: utf-8 -*-
'''
@Time : 2021-10-26
@Author : EvilRecluse
@Contact : https://github.com/RecluseXU
@Desc : china.cn 公司联系方式字体加密处理
'''
# here put the import lib
from typing import Dict, List
from fontTools.ttLib import TTFont
from fontTools.cffLib import CharStrings
from fontTools.misc.textToo... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
import h5py as h5
class FieldType:
def __init__(self, Prandtl_number=1.0, Rayleigh_number=1000.0, wave_number=1.0):
self.Pr = Prandtl_number
self.Ra = Rayleigh_number
self.a = wave_number
... |
class Tool(object):
"""A tool is typically an object that can be used to perform a
specific task on the solver's pre_step/post_step or post_stage callbacks.
This can be used for a variety of things. For example, one could save a
plot, print debug statistics or perform remeshing etc.
To create a n... |
from itertools import product
import numpy as np
import pytest
from estimagic.optimization.trust_region_sampling import _create_upscaled_lhs_sample
from estimagic.optimization.trust_region_sampling import _extend_upscaled_lhs_sample
from estimagic.optimization.trust_region_sampling import _get_empty_bin_info
from esti... |
import abc
import datetime as dt
from django.db.models import IntegerField, Case, When, Value
from django.db.models.functions import Cast, Substr, Concat
from django.utils import timezone
from dear_petition.petition import constants, utils
from dear_petition.petition.export.annotate import Checkbox
class PetitionFo... |
import os
import subprocess
import matplotlib.pylab as plt
import numpy as np
import pandas as pd
import seaborn as sns
from scipy import stats
def load_data(fpath=''):
if len(fpath) == 0:
fpaths = ['data/BF_CTU.csv', 'data/BF_V.csv', 'data/BF_OU.csv']
else:
fpaths = fpath
honest_data = ... |
'''
Created 2012
@author: GieseS
Little plotting script which is called in the analysis of different mappings to an artificial reference genome.
It produces the following plots:
1) ROC Curve
2) Overview histograms for FP / TP.
'''
import matplotlib
matplotlib.use('Agg')
import numpy as np... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.