text stringlengths 3.07k 22.1k |
|---|
import numpy as np
import tensorflow as tf
import pathlib
import json
from datetime import datetime
from mip.get_nn import get_nn
import time
from multiprocessing import Pool
import os
from helper.misc import infer_and_accuracy, clear_print, printProgressBar
from helper.misc import extract_params, get_weighted_mean_bou... |
"""
This module will be given a student, an assignment, and then:
- Download the instructor code. git pull if it already exists .
- Download the student code (git pull if it already exists. )
- Do any copying/editing to student code dir and make new copy of code
-- look in instructorrepo/grades/config for list of... |
#%% Change working directory from the workspace root to the ipynb file location. Turn this addition off with the DataScience.changeDirOnImportExport setting
from matplotlib.figure import Figure
import os
try:
os.chdir(os.path.join(os.getcwd(), 'viewer'))
print(os.getcwd())
except:
pass
#%%
import sys
impor... |
import os
import matplotlib as mpl
import matplotlib.patches as patches
import numpy as np
from matplotlib import pyplot
from autumn.projects.covid_19.mixing_optimisation.constants import (
DURATION_PHASES_2_AND_3,
OPTI_REGIONS,
PHASE_2_DURATION,
PHASE_2_START_TIME,
)
from autumn.projects.covid_19.mix... |
# -*- coding: utf-8 -*-
"""
forms used for charts
"""
import logging
import datetime
import pytz
from django import forms
from django.utils import timezone
from trello_reporter.charting.models import Sprint
logger = logging.getLogger(__name__)
TICK_CHOICES = (
("h", "Hour(s)"),
("d", "Day(s)"),
("m",... |
'''
Created on Jan 8, 2012
Large refactor to notebook Bokeh plotting 5 Jan, 2015
@author: <EMAIL>
A simple interactive tool plotting pulse sequences for visual inspection
Copyright 2012,2013,2014,2015 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in complia... |
# -*- coding: utf-8 -*-
"""
code-similarity.smoss
~~~~~~~~~~~~~~~~~~~~~
the implement base on mosspy: https://github.com/soachishti/moss.py
"""
import os
import glob
import enum
import time
import pandas as pd
import socket
from collections import OrderedDict
from bs4 import BeautifulSoup
from jinja2 impo... |
from datetime import datetime
from pdb import set_trace as bp
import asyncio
import pytz
import aiofiles
from uuid import uuid4 as gen_uuid
import pandas as pd
from shapely.geometry import Point
import asyncpg
POSTGRESQL_LOC = 'ST_AsGeoJson(loc)'
def encode_loc_type(value_type):
if value_type == 'loc':
r... |
import collections
import codecs
import os
import tensorflow as tf
from bert import tokenization
from text_model import TextConfig
import numpy as np
class InputExample(object):
def __init__(self, guid, text_a, text_b=None, label=None):
"""
构造bert模型样本的类
Args:
guid... |
import os
import random
import subprocess
import questTranslation
#import adventuresawait
import math
import time
import questPlanning
header = "(define (problem agent)\n(:domain vincentland)\n(:objects "
""" Deprecated
predicates = ["(location ?l)",
"(item ?i)",
"(info ?info)",
"(character ?c... |
import argparse
import torch.optim as optim
import matplotlib.pyplot as plt
from source.utils.log import *
from source.inputters.lstm_dataset import LSTMDataset
from source.models.NeuPL import *
from source.inputters.corpus import *
from source.utils.misc import str2bool
from source.utils.draw import *
def model_con... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import datetime
import json
import os.path
import re
import signal
import subprocess
import time
from collections import Counter
from collections import namedtuple
from functools import reduce
from operator import at... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from numpy import arccos
from numpy import array
from numpy import mean
from numpy import sin
from numpy import sqrt
from numpy import zeros
from numba import jit
from scipy.sparse import find
from compas.nu... |
from random import randint
from qm.QuantumMachinesManager import QuantumMachinesManager
from qm.qua import *
from qm import SimulationConfig, LoopbackInterface
import numpy as np
import matplotlib.pyplot as plt
from configuration import config, gauss, gauss_der
from scipy import optimize
# Open communication with the... |
import pyglet
from gym import spaces
from gym.utils import seeding
from dm_env import specs
import gym
import numpy as np
import sys
from dm_control import suite, viewer
from dm_control.viewer import util, runtime
from dm_control.rl.control import flatten_observation
from dm_env import _environment as environment
from... |
# flake8: noqa
"""Usage: from repo root, run `python3 -m unittest tests.core -v`
This test module makes sure that the `commands` packages is not imported
"""
import json
import os
import sys
import tempfile
import unittest
from collections import OrderedDict, defaultdict
from unittest.mock import MagicMock
sublime = ... |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
# 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 l... |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import pdb
import numpy as np
from onconet.models.pools.factory import get_pool
from onconet.models.factory import RegisterModel
from onconet.models.cumulative_probability_layer import Cumulative_Probability_Layer
EMBEDDING_DIM = 96
MAX_TI... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import requests
import sys
import json as JSON
import logging as log
import logging.config
sys.path.append('.')
from sms_api.exceptions import GeneralAltiriaException
from sms_api.exceptions import AltiriaGwException
from sms_api.exceptions import ConnectionException
from sms... |
# This file is part of the scanning-squid package.
#
# Copyright (c) 2018 <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... |
from scipy import optimize
import numpy as np
import itertools
import math
import scipy.stats as stats
import logging
import matplotlib.pyplot as plt
import matplotlib as mpl
plt.style.use('seaborn-whitegrid')
mpl.style.use('seaborn')
prop_cycle = plt.rcParams["axes.prop_cycle"]
colors = prop_cycle.by_key()["color"]
im... |
##https://yixiaoyang.github.io/articles/2016-12/opencv-contours
import cv2
import os
import math
import numpy as np
CWD_PATH = os.getcwd()
IMAGE_NAME = 'test_images/001461.jpeg'
PATH_TO_IMAGE = os.path.join(CWD_PATH,IMAGE_NAME)
OUTPUT_PATH = os.path.join(CWD_PATH, 'output')
class Config:
def __init__(self):
... |
# -*- coding: utf-8 -*-
"""Public models."""
import datetime as dt
from school.user.models import User
from school.database import Column, Model, SurrogatePK, db, reference_col, relationship
class School(SurrogatePK, Model):
"""学校列表
表名称:schools
parameters参数:
name:学校名称
active:是否激活 指是否可以添加下级操作
state:是否可使用,暂定,无... |
# Copyright 2021 Collate
# 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, software... |
#!/pxrpythonsubst
#
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
... |
# coding: utf-8
import dataclasses
import typing
import serpyco
from sqlalchemy.orm.exc import NoResultFound
from guilang.description import Description
from guilang.description import Part
from guilang.description import Type
from rolling.action.base import WithCharacterAction
from rolling.action.base import get_wit... |
# -*- Mode: Python; tab-width: 4 -*-
import string
"""
A collection of producers.
Each producer implements a particular feature: They can be combined
in various ways to get interesting and useful behaviors.
For example, you can feed dynamically-produced output into the compressing
producer, then wrap this with the ... |
#!/usr/bin/env python3
import argparse
import csv
import json
import logging
import multiprocessing
import os
import os.path
import sys
from datetime import datetime
from typing import List, Dict, Any
import boto3
from cloudsplaining.command.scan_policy_file import scan_policy
from mypy_boto3_iam import Client as IAMC... |
from typing import List
import numpy as np
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
import pandas as pd
from modules.CD_parameters import *
from modules.utilities import *
# check if the output directory exists
check_dir("".join((project_dir, '/figures/foo.eps')))
def flatten_list(list... |
import hashlib
from datetime import datetime
from operator import itemgetter
from base64 import b64encode, b64decode
import numpy
import requests
from requests.exceptions import HTTPError
from elasticsearch import Elasticsearch
from elasticsearch.exceptions import ConflictError, NotFoundError
from furl import furl
fro... |
import torch
import timm
import numpy as np
from einops import repeat, rearrange
from einops.layers.torch import Rearrange
from timm.models.layers import trunc_normal_
from timm.models.vision_transformer import Block
def random_indexes(size : int):
forward_indexes = np.arange(size)
np.random.shuffle(forward_... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
#!/usr/bin/env python3
"""
This script generates a creation schema from the GHGA Metadata Schema.
The creation schema is then used to generate artifacts that can be used
within the GHGA Microservices like the Metadata Repository Service and
the Metadata Transpiler Service.
"""
import copy
import typer... |
import os
import pickle
import argparse
import numpy as np
from collections import Counter
from utils import load_data, mat2array
from sklearn.metrics import cohen_kappa_score as kappa
import keras.backend as K
from keras.backend import clear_session
from keras.models import Sequential, Model
from keras.optimizers imp... |
from matplotlib.text import Text
from operon_analyzer.genes import Feature, Operon
from operon_analyzer.rules import RuleSet, FilterSet
from operon_analyzer.visualize import calculate_adjusted_operon_bounds, \
create_operon_figure, \
build_imag... |
"""
This module contains the discord cog for managing channels
"""
import asyncio
from typing import Optional
from uuid import uuid4, UUID
import discord
from discord.ext import commands
from models import Guild, ChannelCategory, VoiceChannel, ChannelOwner
class ChannelCog(commands.Cog, name='Channel Commands'):
... |
import os
import sys
import json
import bpy
import itertools
from mathutils import *
from bpy_extras.io_utils import axis_conversion
def mesh_triangulate(mesh):
import bmesh
bm = bmesh.new()
bm.from_mesh(mesh)
bmesh.ops.triangulate(bm, faces=bm.faces)
bm.to_mesh(mesh)
bm.free()
blender_matrix ... |
from formais.finite_automata import *
from formais.regular_expressions import *
from collections import defaultdict
import copy
def GR_to_AFND(GR):
AFND = NDFiniteAutomata()
AFND.states = GR.non_terminals.union('F')
AFND.alphabet = GR.terminals
AFND.initial = GR.initial_state
if '&' in GR.rules[... |
#!/usr/bin/python3
from argparse import ArgumentParser
import datetime # date and time manipulations
from matplotlib import pyplot
import numpy as np
import re # regular expression operations
import requests # HTTP requests
from termcolor import colored # colored terminal output
def get_cookie_crumb(url='https://... |
# -*- coding: utf-8 -*-
#
# computeFunctions and -Routines for parallel calculation
# of single trial measures needed for the averaged
# measures like cross spectral densities
#
# Builtin/3rd party package imports
import numpy as np
from scipy.signal import fftconvolve, detrend
from inspect import signature
# backend... |
import re
import csv
from collections import Counter
from math import log2
##### This contains shared functions or definitions that are used across multiple scripts
# The ambiguity letters for nucleotides
ambiguityLetters = {
frozenset(("A")): "A",
frozenset(("C")): "C",
frozenset(("G")): "G",
frozens... |
from __future__ import division, print_function
import __builtin__
import sys
#========================================
# IMPORTS
#========================================
# Standard library imports
import itertools
import sys
import os
import warnings
import textwrap
# Hotspotter Frontend Imports
import hotspotter.dra... |
from functools import reduce
from librosa.core.spectrum import stft
from config import *
import os
import librosa
import librosa.display
from pydub import AudioSegment
import numpy as np
import soundfile as sf
import streamlit as st
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanva... |
from collections import defaultdict
from typing import Dict, List
import defusedxml.ElementTree as ET
import numpy as np
from trip_kinematics.Utility import Rotation
from trip_kinematics.Transformation import Transformation
def from_urdf(filename: str) -> List[Transformation]:
"""Converts a robot speci... |
import socket
import struct
import math
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
"""
Requires PyGame and PyOpenGL
For the window to run there must be UDP data coming out aka you must be in a rally
Window doesn't close on exit unless you click it then re-en... |
import convert
from numpy import int16
from numpy import array
from sys import argv
opcodes = {
"ADD" : "3",
"SUBT" : "4",
"ADDI" : "B",
"CLEAR" : "A",
"LOAD" : "1",
"STORE" : "2",
"INPUT" : "5",
"OUTPUT": "6",
"JUMP" : "9",
"SKIPCOND" : "8",
"JNS" : "0",
"JUMPI" : "C",
"STOREI": "D",
"LOADI" : "E",
"... |
#!/usr/bin/env python3
from olctools.accessoryFunctions.accessoryFunctions import make_path, SetupLogging
from argparse import ArgumentParser
from click import progressbar
from threading import Thread
from subprocess import call
from queue import Queue
from ftplib import FTP
from time import sleep
import logging
import... |
# MIT License
#
# Copyright (c) 2018 <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... |
#!/usr/bin/env python3
# Validate extension metadata
# This script expects a copy of the envoy source to be located at /source
# Alternatively, you can specify a path to the source dir with `ENVOY_SRCDIR`
import ast
import os
import pathlib
import re
import subprocess
import sys
from importlib.util import spec_from_... |
#### Import all the supporting classes
import os
import sys
from utils import *
from encoder import GRUEncoder
from cn_variants import LAN, GCN, GAT
class OKGIT(nn.Module):
def __init__(self, args, embed_matrix, rel2words):
super(OKGIT, self).__init__()
self.args = args
self.conve = CaRE(a... |
#!/usr/bin/python
import os, sys
import time
import numpy as np
np.set_printoptions(threshold=np.nan, linewidth =np.nan)
from walking_generator.visualization_traj import PlotterTraj
from walking_generator.combinedqp_traj import NMPCGeneratorTraj
from walking_generator.interpolation_traj import Interpolation
from math... |
import datetime
import random
import time
from functools import partial
import numpy as np
import paddle
import paddle.nn as nn
import utils
from paddle.metric import Accuracy
from paddle.optimizer import AdamW
from paddlenlp.data import Dict, Pad, Stack
from paddlenlp.datasets import load_dataset
from paddlenlp.trans... |
"""
Creates clusters from processed data for any number of dimensions using k-means.
Requirement: Data in a pandas dataframe, files in a numpy array.
arranged as follows:
[str(filename),feature1,feature2,...,featureN]
"""
import random
import numpy as np
import sys
np.set_printoptions(threshold=sys.maxsize)
from mul... |
import datetime
import pytz
from dateutil.parser import parse
from django.db.models.query import Q
from threepio import logger
from core.models import EventTable
from core.models.allocation_source import AllocationSource
from core.models.instance import Instance
def create_report(report_start_date, report_end_date,... |
""" Main training methods for SPIT"""
from __future__ import (print_function, absolute_import, division, unicode_literals)
import tensorflow as tf
import numpy as np
import datetime
import os, sys, time
import pdb
# Use PrettyTensor to simplify Neural Network construction.
import prettytensor as pt
# Some globals
#... |
""" test chemkin_io.calculator.mechanism
"""
from __future__ import unicode_literals
from builtins import open
import os
import numpy
import chemkin_io
def _read_file(file_name):
with open(file_name, encoding='utf8', errors='ignore') as file_obj:
file_str = file_obj.read()
return file_str
# Set pat... |
# 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 itertools
import os
import random
import numpy as np
import torch
from fairseq.data import (
BaseWrapperDataset,
ColorizeData... |
import os.path as osp
from dbinspector.startup import REFSEQ, UNIPROT
from dbinspector.map import read_refseq_data, read_uniprot_data, get_refseq_entry, get_uniprot_entry, \
retrieve_by_refseq_id, retrieve_by_uniprot_id, retrieve_by_symbol, find_entries
from dbinspector.parse import parse_all
MSG = "This test mig... |
import copy
from collections import Mapping
import six
import deepmatcher as dm
import torch
import torch.nn as nn
from .modules import RNN, GatingMechanism, SelfAttention, PairAttention, GlobalAttention, Fusion
from ..data import MatchingDataset, MatchingIterator
from ..runner import Runner
from ..utils import Bunc... |
import os
import csv
import json
import random
basePath = '/media/young/MyPassport/跨越险阻'
categoryDic = {"H":1, "V":2, "B":3}
def get_csv_dic():
dataFolders = [x for x in os.listdir(basePath) if x.split('.')[-1] != 'zip']
all_data = {}
for folder in dataFolders:
gtPath = basePath + '/' + folder + '/... |
#coding:utf-8
#
# PROGRAM/MODULE: firebird-base
# FILE: firebird/base/protobuf.py
# DESCRIPTION: Registry for Google Protocol Buffer messages and enums
# CREATED: 27.12.2019
#
# The contents of this file are subject to the MIT License
#
# Permission is hereby granted, free of charge, to any person o... |
import multiprocessing
import os
import shutil
from functools import partial
from multiprocessing.pool import ThreadPool
import pytest
import esmvalcore
from esmvalcore._config import DIAGNOSTICS
from esmvalcore._task import (
BaseTask,
DiagnosticError,
DiagnosticTask,
TaskSet,
_py2ncl,
)
class ... |
import os
import sys
import platform
import argparse
import colorama
from pytube import Playlist
try:
import version
import error
import font
from ytam import Downloader
from discogs import Discogs
except ModuleNotFoundError:
import ytam.version as version
import ytam.error as error
im... |
from dateutil.parser import parse as dateutil_parse
from hdmf.build import ObjectMapper
from .. import register_map
from ..file import NWBFile, Subject
from ..core import ScratchData
@register_map(NWBFile)
class NWBFileMap(ObjectMapper):
def __init__(self, spec):
super(NWBFileMap, self).__init__(spec)
... |
import numpy as np
import gym
import pdb
from classifier_network import LinearNetwork, ReducedLinearNetwork
import torch
import torch.nn as nn
import torch.nn.functional as F
from scipy.stats import triang
#import serial
import matplotlib.pyplot as plt
import time
# take in data, make a change to th state ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
# Copyright (c) 2019. <NAME>, <NAME>, <NAME>, #
# <NAME>. All rights reserved. #
# Copyrights licensed under the CC BY 4.0 License. ... |
from torch import nn
import torchvision
import torch
class BrainResNetV1(nn.Module):
def __init__(self, hparams):
super().__init__()
self.model = torchvision.models.resnet18(pretrained=True)
in_features = self.model.fc.in_features
self.indv_layers = nn.ModuleList([
nn.Se... |
import csv
import torch
import torch.nn.functional as F
import xlsxwriter
from colour import Color
from torch.nn.modules.loss import _Loss
from torchtext.data import Iterator
from tqdm import tqdm
from task_A.frameworks.base_framework import Base_Framework
from utils.utils import totext
def frobenius_norm(mat):
... |
import numpy as np
import scipy.io as sio
import torch.utils.data
from torch.utils.data import DataLoader
import pdb
class NeuralData(torch.utils.data.Dataset):
def __init__(self, data, data2, num_trials_per_class=91):
self.data = data
self.data2 = data2
self.num_trials_per_class = num_tri... |
import torch
import torch.nn as nn
from models.MultiHeadAttention import MultiHeadAttentionLayer
from models.PositionalEncoding import PositionalEncodingLayer
from models.PositionwiseFeedforward import PositionwiseFeedforwardLayer
from models.MultiHeadAttention import MultiHeadAttentionLayerRPE
class EncoderLayer(nn... |
import math
import copy
import torch
import torch.nn as nn
from ..utils import ConvNdTorch, NormNdTorch, PoolingNdTorch
from ..basic_networks import BaseClassificationTorchNetwork
class BottleneckTorch(nn.Module):
expansion = 4
start_filts = 64
"""
RexNeXt bottleneck type C
(https://github.com/fac... |
# -*- coding: utf-8 -*-
"""Defining functions and classes for arrhythmia detection through ECG signals.
The contents of this module define functions and classes for analyzing,
visualizing, and making predictions based on data from the
MIT-BIH Arrhythmia Database.
Explore this repository at:
https://github.com/cha... |
# -*- coding: utf-8 -*-
from gluon import current
from s3 import *
from s3layouts import *
try:
from .layouts import *
except ImportError:
pass
import s3menus as default
# =============================================================================
class S3MainMenu(default.S3MainMenu):
""" Custom Applica... |
#Handle Front and middle of application: CLI and processing
from errors import *
from dbhandler import *
from datetime import datetime
import time
import copy
#Responses which indicate yes for "y/n" prompts
AFFIRMATIVE = ["y","yes","yeah","yah","yep","yup","ye","ya",""]
def show_welcome():
#Show welcome message
p... |
from collections import deque, namedtuple
from datetime import datetime
import json
import copy
class Configuration:
"""A class representing a configuration of the Emergent Web Server."""
#component list
#relation list
def __eq__(self, obj):
if(type(obj) == Configuration):
... |
#!/usr/bin/python3
import numpy as np
import random as rd
from math import *
import matplotlib.pyplot as plt
########################################
####### Méthode des rectangles #########
########################################
tests = False
### Exercice 1-a ###
def Irg(f, a, b, n):
ints = np.linspace(a, b, n... |
#-*- coding: utf-8 -*-
import numpy as np
from matplotlib import pyplot as plt
import time
import sys
import cv2
import rospy
from geometry_msgs.msg import Twist, Vector3, Pose
from nav_msgs.msg import Odometry
from sensor_msgs.msg import Image, CompressedImage
from cv_bridge import CvBridge, CvBridgeError
bridge = C... |
import unittest
import subprocess
import requests
import time
import pytest
import psycopg2
import os
import json
import jwt
import re
from urllib3.exceptions import NewConnectionError
from copy import deepcopy
from datetime import datetime
from psycopg2.extras import RealDictCursor
from quizmous_api import Quiz, Ques... |
import hashlib
import itertools
import re
import time
import traceback
from abc import ABC, abstractmethod
from collections import Counter, defaultdict
import nltk
from ftfy import fix_text
from nltk.tokenize.moses import MosesTokenizer
from pymongo import MongoClient
from article_extractors import ArticleExtractorFa... |
import coreapi
from rest_framework import status, viewsets
from rest_framework.generics import GenericAPIView, get_object_or_404
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.schemas import AutoSchema
from environments.models import Environment, Identi... |
import re
import os
import gzip
import pickle
from utils import CONFIG, get_dict_path, load_datasets
NAR_REG = re.compile("\d+-.*")
RANDOM_SEED = 1917
VECT_PATH = CONFIG['vect_words_path']
DATASET_PATH = CONFIG['dataset_path']
REZ_PATHS = CONFIG['publish_dictionary_paths']
DICT_WORDS_PATH = CONFIG['dict_words_path']
... |
'''
Created on 2021-07-21
@author: wf
'''
import datetime
from typing import Callable
from lodstorage.entity import EntityManager
from lodstorage.jsonable import JSONAble
from wikibot.wikiuser import WikiUser
from wikibot.wikiclient import WikiClient
from wikibot.wikipush import WikiPush
from wikifile.wikiFileManager ... |
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from videoanalyst.model.common_opr.common_block import conv_bn_relu
from videoanalyst.model.module_base import ModuleBase
from videoanalyst.model.task_head.taskhead_base import TRACK_HEADS
class ConvModule(nn.Module):
... |
import tensorflow as tf
from copy import deepcopy
import numpy as np
import time
import json
import tqdm
from base import *
from lm import loss
from lm import stop
class Config(wb.Config):
def __init__(self, data_or_vocab_size=1000, hidden_size=200, hidden_layers=2):
if isinstance(data_or_v... |
import zipfile
from unittest import TestCase
import frappe
from frappe.utils import cstr, now_datetime, today
from six import BytesIO
from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice
from germany_compliance.utils.datev.datev_constants import (
AccountNames,
DebtorsCreditors... |
# Copyright 2017 Google Inc. and Skytruth 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 or agr... |
import os
import sys
import json
import random
import argparse
import numpy as np
from tqdm import tqdm
import pytrec_eval
def add_default_args(parser):
parser.add_argument('--result_fold_0', type=str, required=True,
help="The path to be combine sub results.")
parser.add_argument('--re... |
"""
Python bindings to Linux uinput system.
Usage:
>>> import uinput
>>> events = (
... uinput.BTN_JOYSTICK,
... uinput.ABS_X + (0, 255, 0, 0),
... uinput.ABS_Y + (0, 255, 0, 0),
... )
>>> with uinput.Device(events) as device:
... device.emit(uinput.ABS_X, 5, syn=False)
... device.emit(uinput.AB... |
"""Helper functions to call command line tools from python
@todo:
- Make it flexible so that a dict(a=42) can be given and
'a=42' or '-a 42' or '--a 42' is generated depending on an option!
- Make it a class, so that options like dryrun or options formattting
don't have to be handed around all the time!!!"""
import s... |
import os
import torch
import argparse
import numpy as np
from tqdm import tqdm
from torch.utils import data
import torchvision.transforms as transform
from torch.nn.parallel.scatter_gather import gather
import encoding.utils as utils
from encoding.nn import SegmentationLosses, BatchNorm2d
from encoding.parallel impor... |
""" The Thycotic Secret Server SDK API facilitates access to the Secret Server
REST API using *OAuth2 Bearer Token* authentication.
Example::
# connect to Secret Server
secret_server = SecretServer(base_url, username, password)
# or, for Secret Server Cloud
secret_server = SecretServerCloud(tenant, us... |
from __future__ import print_function, division
import os
import serial
import time
import platform
import atexit
import exceptions
import operator
DEBUG = False
class WriteFrequencyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
cla... |
# Copyright (c) 2018-2022 <NAME>, Durham University, UK
# SPDX-License-Identifier: MIT
#
# Copyright (C) 2020-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
"""Torch models defining encoder, decoder, Generator and Discriminator.
Code adapted from https://github.com/samet-akcay/ganomaly.
"""
import m... |
import os
import requests
import shutil
import zipfile
import glob
import tifffile
import numpy as np
from bs4 import BeautifulSoup
from b3get.utils import filter_files, tmp_location
from b3get.datasets import dataset, ds_006, ds_008, ds_024, ds_027
import pytest
# manual tests for exploration
def test_006_images_m... |
import discord
from discord.ext import commands
import time
import calendar
import traceback
from cogs.database import Session
class auto_mod():
def __init__(self, bot):
self.bot = bot
async def on_member_join(self, member):
db = Session().db
cursor = db.cursor()
cursor.execute... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 28 12:09:36 2020
@author: chris
"""
# std lib
import attr
import numpy as np
# broadcast loop controls
DIMEQ = 0 # EQ dimensions
DIMLP1 = 1 # loop over side 1
DIMLP2 = 2 # loop over side 2
DIMPAD1 = -1 # pad on side 1
DIMPAD2 = -... |
"""Collect all time series results in standardised format."""
from pathlib import Path
from dataclasses import dataclass
import numpy as np
import pandas as pd
import xarray as xr
import pycountry
MODEL_NAME = "euro-calliope"
TOTAL_COVERED_REGION = "Total covered region"
GERMANY = "DEU"
ALL_COUNTRIES = ['ALB', 'AUT'... |
from functools import wraps
from collections.abc import Mapping, Sequence
from collections import OrderedDict
import warnings
import numpy as np
from . import Proxy
from ._producer import Producer
from ._mutable import Mutable, Mutant, Mutables
from ._applier import Applier
from ._configurator import Configurator
fro... |
"""Fit the averaged delta sigma profiles.
"""
from catalog import *
import numpy as np
import cluster_toolkit as ct
import scipy.optimize as op
import matplotlib.pyplot as plt
def get_model(M, args):
Redges = args['Redges']
Rlam = args['Rlam']
h = args['h']
Om = args['Om']
z = args['z']
r = arg... |
import os
import argparse
import time
import numpy as np
import torch
from tqdm import tqdm
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import roc_auc_score
from datasets.mvtec import MVTecDataset
from models.resnet_backbone import modified_resnet18
from utils.util import time_string, conve... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.