text stringlengths 6.04k 39.5k |
|---|
import json
import os
import re
import graphviz
import pytest
from featuretools.feature_base import (
AggregationFeature,
DirectFeature,
FeatureOutputSlice,
GroupByTransformFeature,
IdentityFeature,
TransformFeature,
graph_feature
)
from featuretools.primitives import Count, CumMax, Mode,... |
from GameEngine.BoardGame.Board import BoardItem, BoardItemInput, Board, BoardInput
from GameEngine.GameUtility.Dice import Dice
from GameEngine.CardUtility.CardCollection import Deck, DeckInput, Card, CardInput
from Utility.Logger import Logger, LogLevel
from enum import Enum
MAX_TURN_IN_PRISON = 3
MONEY_FROM_GO = 20... |
import argparse
import datetime
import logging
import os
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sn
import webcolors
from PIL import Image
from keras.callbacks import ModelCheckpoint, TensorBoard
from keras.losses import binary_crossentropy
from keras.utils import plot_... |
from array import array
from asyncio import TimeoutError
from enum import Enum
from importlib import import_module
from logging import getLogger
from os import urandom
from aiohttp import ClientError, ClientHttpProxyError, ClientProxyConnectionError, ClientResponseError, ServerTimeoutError
from cyrandom import choose_... |
import numpy as np
import krikos.nn.utils as utils
class Layer(object):
def __init__(self):
super(Layer, self).__init__()
self.params = {}
self.cache = {}
self.grads = {}
def forward(self, input):
raise NotImplementedError
def backward(self, dout):
raise N... |
import os
import logging
logger = logging.getLogger(__name__)
columns = {0: 'ner', 1:'pos', 2:'dep', 3:'head'}
pos_map = {'X':0, 'ADJ':1, 'ADP':2, 'ADV':3, 'AUX':4, 'CONJ':5, 'CCONJ':6, 'DET':7, 'INTJ':8, 'NOUN':9, 'NUM':10, 'PART':11, 'PRON':12, 'PROPN':13, 'PUNCT':14, 'SCONJ':15, 'SYM':16, 'VERB':17}
dep_m... |
#!/usr/bin/env python
import sys;
import os;
import argparse;
import shutil;
import stat;
import subprocess;
import xml.etree.ElementTree as ET
import time;
from contextlib import closing
from sys import platform as _platform
if _platform != "win32":
import signal;
try:
from urllib.request import urlopen
except ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import tensorflow as tf
import json
import unicodedata
import re
import os
import io
import sys
import time
import math
import argparse
from RedBlackTree.rbtree import RedBlackNode
from RedBlackTree.rbtree import RedBlackTree
from StackDecoder.stack_d... |
import sympy as sp
import numpy as np
from typing import Any, Dict, Iterator, List, Optional, Tuple, TYPE_CHECKING, Union
from pyomo.environ import (
ConcreteModel, Constraint, Set, Var, Param,
)
from sympy import Matrix as Mat
from . import utils, visual
from .system import System3D
from .links import Link3D
if T... |
from deeptam_tracker.models.helpers import *
import deeptam_tracker.utils.message as mg
import tensorflow as tf
import string
import numpy as np
PRINT_PREFIX = '[MODELS][BLOCKS]: '
def create_flow_inputs_and_gt(
key_image,
current_image,
intrinsics,
depth,
rotation,
tr... |
import pandas as pd
import os
import numpy as np
import argparse
import json
import sys
import shutil
import argparse
import numpy as np
import glob
from lxml import etree
def write_voc_file(fname, labels, coords, img_width, img_height):
"""
Writes label into VOC (XML) format.
Args:
fname - full ... |
from enum import Enum
from typing import List, Literal, Optional
from pydantic import BaseModel
from .bytes_to_base64url import bytes_to_base64url
from .cose import COSEAlgorithmIdentifier
from .json_loads_base64url_to_bytes import json_loads_base64url_to_bytes
from .snake_case_to_camel_case import snake_case_to_came... |
# -*- coding: utf-8 -*-
'''
-------------------------------------------------------------------------------------------------
This code accompanies the paper titled "Human injury-based safety decision of automated vehicles"
Author: <NAME>, ***,
Corresponding author: <NAME> (<EMAIL>)
------------------------------------... |
import torch.utils.data as data
from PIL import Image
import cv2
import os
import os.path
import torch
import numpy as np
import torchvision.transforms as transforms
import argparse
import time
import random
from lib.transformations import quaternion_from_euler, euler_matrix, random_quaternion, quaternion_matrix
import... |
import numpy as np
import pandas as pd
import holidays
from sklearn.preprocessing import MinMaxScaler, OneHotEncoder
import tensorflow as tf
import joblib
import os
def data_preprocessing(df, hour=1, timesteps=12, debug=False):
"""
Input:
+ raw df contains all data
columns: ['PM25', 'AQI... |
"""
This source includs two types of classes or functions.
1. Evaluation methods:
This source includs some evaluation metrics, such as r-square, CI, mse ...
or even confidence intervals and ECE, which are uncertainty measures.
2. Some plotting functions.
"""
from lifelines.utils import concordance_index
... |
import enum
import pickle
from dataclasses import dataclass, replace
from typing import Callable, List
import haiku as hk
import jax
import jax.numpy as jnp
import numpy as np
import optax
from einops import rearrange
from jax.example_libraries.optimizers import l2_norm
from jax.random import PRNGKey
from jax.tree_uti... |
#!/usr/bin/python3
#A Python script to set the theme for GTK+ 2 and GTK+ 3 applications in minimal environments
#By <NAME>
from tkinter import *
from tkinter import messagebox
import os
def findThemes(themeType) :
homeDir = os.path.expanduser('~')
a = os.listdir("/usr/share/themes")
for x in a : a[a.index... |
import logging
import math
import torch
import torch.nn as nn
from torch.nn import functional as F
from modules.commons.common_layers import ConvNorm, Embedding
from modules.commons.common_layers import SinusoidalPositionalEmbedding, Linear, EncSALayer, DecSALayer, BatchNorm1dTBC
from utils.hparams import hparams
DE... |
'''
Copyright (c) 2018 <NAME>, Rutgers University
http://www.cs.rutgers.edu/~hxp1/
This code is free to use for academic/research purpose.
'''
import numpy as np
import cntk as C
import sys
import argparse
from LayerUtils import conv_bn_lrelu, bi_recurrence, flatten
from SysUtils import get_current_time_string, is_W... |
import os
import re
from pprint import pprint
from tqdm import tqdm
import json
from copy import deepcopy
import numpy as np
import Levenshtein
import difflib
from PIL import Image
from transformers import BertTokenizer
from public.data_provider.doc2dial import load_doc, load_dialogue, ocr_correction
from config_file... |
import json
import hashlib
import base64
import time
import binascii
import pyrx
from sys import exc_info
from os import path
from decimal import Decimal, getcontext
from bitcoin.signmessage import BitcoinMessage, VerifyMessage
from bitcoin.wallet import P2PKHBitcoinAddress
from coincurve.utils import verify_signature... |
"""
Nasbench adaptation for NAO.
"""
import logging
from operator import itemgetter
import networkx as nx
import torch
import torch.nn as nn
import numpy as np
import IPython
from torch.distributions import Categorical
from nasws.cnn.search_space.nasbench101.model_search import NasBenchCellSearch
from nasws.cnn.sear... |
import csv
import json
import os
import shutil
import uuid
from functools import partial
from io import StringIO
import pandas as pd
from pandas import DataFrame
import pyproj
import requests
import shapely.geometry as shapely_geom
import shapely.wkt as shapely_wkt
import app.helper
from app import ce... |
#!/usr/bin/env python
#----------------------------------------------------------------------------
# Name: ListCtrl.py
# Purpose: Testing lots of stuff, controls, window types, etc.
#
# Author: <NAME> & <NAME>
#
# Created:
# Copyright: (c) 1998-2017 by Total Control Software
# Licence: wxWi... |
#!/usr/bin/env python
from __future__ import print_function
import sys
import os
import jinja2
import argparse
import json
from ssg import yaml, checks
from ssg.shims import input_func
from ssg.utils import read_file_list
import ssg
import ssg.products
import ssg.rules
import ssg.rule_yaml
SSG_ROOT = os.path.abspa... |
from __future__ import print_function
import os
import sys
import wx
import numpy as np
import matplotlib
matplotlib.interactive(False)
#Use the WxAgg back end. The Wx one takes too long to render
matplotlib.use('WXAgg')
from sas.sasgui.guiframe.local_perspectives.plotting.SimplePlot import PlotFrame
#import matplotli... |
# -*- coding: utf-8 -*-
"""
shepherd_herd
~~~~~
click-based command line utility for controlling a group of shepherd nodes
remotely through ssh. Provides commands for starting/stopping harvest and
emulation, retrieving recordings to the local machine and flashing firmware
images to target sensor nodes.
:copyright: (c... |
import time, os, csv, random
import cma
import numpy as np
import pandas as pd
from scipy.linalg import cholesky
from numpy.linalg import LinAlgError
from numpy.random import standard_normal
from sklearn.decomposition import PCA
from copy import deepcopy
import matplotlib.pyplot as plt
from nevergrad.functions import... |
import pickle
import pylab
import select
import socket
import sys
import threading
import time
import uuid
from queue import Queue
import matplotlib
import pygame
import pygame_gui
import pygame_menu
from matplotlib.backends import backend_agg
from matplotlib.ticker import FuncFormatter
pygame.init()
matplotlib.use(... |
# pyt_utilities.py (python3)
# utilities for CNN training with pytorch; data preparation, training, evaluation
# added saving checkpoint
# FEB 2020 / 21
# sources:
# https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html#load-data
# https://pytorch.org/tutorials/beginner/finetuning_torchvision_models_t... |
###########################################################################
# Created by: NTU EEE
# Email: <EMAIL>
# Copyright (c) 2019
###########################################################################
from __future__ import division
import os
import numpy as np
import torch
import torch.nn as nn
from torch.n... |
import numpy as np
import pyDOE2
import sample_generator as sg
from copy import deepcopy
import os
import glob
import pickle
import sys
import emcee
from linna.nn import *
from scipy.special import erf
from scipy.stats import chi2
import io
import gc
import torch
from torch.utils.data import Dataset, DataLoader
from to... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 UnitedStack Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.or... |
import functools
print = functools.partial(print, flush=True)
import torch
import torch.autograd as autograd
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.nn.parameter import Parameter
import numpy as np
import datetime
import time, mat... |
from addict import Dict
from .style_values import Align, Position
from .style_values import Axis
from typing import NamedTuple, Any
from aenum import Enum, auto
from versa_engine.common.plot_utils import pick_colors_from_anchors
#Chart.defaults.datasets.line.showLine = false;
colorSchemes = {"default": ["#7f3b08", "#... |
from __future__ import division, print_function
import sys
import os
import os.path
import re
import importlib
import pkg_resources
import time
import csv
import numpy as np
from . import Srinivas2017 as default_translation_scheme
from .designer import run_designer, get_parameters_from_crn_file, score_fixed
if sys... |
import networkx as nx
import matplotlib.pyplot as plt
class Population:
def __init__(self, name, n, e, w):
"""
:param name:
:param n: # of neurons (estimated from density and cortical area from Markov)
:param e: # of extrinsic inputs per neuron (typical values by cortical layer)
... |
# %% [markdown]
# ##
import warnings
def noop(*args, **kargs):
pass
warnings.warn = noop
import os
import time
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy
import seaborn as sns
from joblib import Parallel, delayed
from scipy.ndimage import gaussi... |
import cv2
import numpy as np
import keras
import keras.backend as K
import statsmodels.api as sm
import cv2
import numpy as np
import matplotlib.pyplot as plt
import cv2
import skimage.color
import skimage.feature
"""
Functions:
[TEST] get_color_measure(image, mask=None, type=None, verbose=True)
[TEST] get_texture_m... |
r"""Automatically adds syntactic metrics to TPR-DB tables by using the astred library by <NAME>. Metrics are added both on the segment level (.sg tablles) and on the token level (.st and .tt).
WARNING: by default, the files are changed in-place. If you want to write the output to different files, use the -d option.
I... |
"""
This module provides ways of systematically combining operations, sets of
operations, etc., and executing such sequences of operations.
"""
import copy
from collections import Iterable
import functools
import itertools
import operator
import threading
import traceback
from six import string_types
from combtest.ac... |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 3 18:12:36 2020
@author: Akash1313
"""
#Question 1
###############################################################################
print("---------------------------Question1----------------------------------------")
import numpy as np
import pandas as pd
import scipy a... |
# -*- coding: utf-8 -*-
"""Provides :class:`Screen`, which lets you write text to specific coordinates
in the dos command shell, with colors.
"""
# pylint:disable=R0201,R0902
# R0201: method could be a function
# R0902: too many instance attributes
from __future__ import print_function
import sys
import os
import s... |
import csv
import json
import pickle
from difflib import SequenceMatcher as SeqMat
import django_rq
import pandas as pd
import tablib
from django import db
from django.conf import settings
from django.core.management import call_command
from django.http import HttpResponse, JsonResponse
from django.shortcuts import re... |
from copy import deepcopy
import requests
import os
import bs4
from openpyxl import load_workbook
import pandas as pd
from ..helpers.db_funcs import get_ep_id_by_number, get_season_id_by_number_type
from ..helpers.extract_helpers import search_for_new_seasons
import glob
import re
import numpy as np
DOCS_URL_TEMPLAT... |
import tkinter
import tkinter.filedialog
from tkinter import messagebox as tkMessageBox
import os
import pandas as pd
import numpy as np
import tkinter.ttk as ttk
import datetime
from configparser import ConfigParser
from src.fedwatcher import Fedwatcher
import re
import datetime
import webbrowser
from PIL import Image... |
import os
import shutil
import importlib
import inspect
from glob import glob
import re
import json
from scrapy.http import Request
from scrapy.utils.python import to_unicode
from scrapy.utils.reqser import request_from_dict, _get_method
from scrapy.exceptions import _InvalidOutput, UsageError
def get_cb_settings(te... |
# Copyright 2022 Garena Online Private Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... |
from os import environ
environ['PYGAME_HIDE_SUPPORT_PROMPT'] = '1'
import pygame, pygame.sndarray
import numpy
import scipy.signal
import re
from note import Note
from note import basic_notes
sample_rate = 44100
sampling = 4096 # or 16384
S = 2**(1/12) # Semi-tone frequency multiplier
T = S ** 2 # Full-tone freque... |
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
#!/usr/bin/env python
import numpy as np
from numpy import *
import os
# ROS
import rospy
import tf_conversions as tf
def normalize(v):
norm = np.linalg.norm(v)
if norm < 0.00001:
return v
return v / norm
class Quaternion:
@staticmethod
def normalize(v):
return normalize(v)
@staticm... |
"""
本文件包含所有字符串算法
"""
# 给定两个字符串形式的非负整数num1 和num2,计算它们的和。
#
#
#
# 提示:
#
# num1 和num2的长度都小于 5100
# num1 和num2 都只包含数字 0-9
# num1 和num2 都不包含任何前导零
# 你不能使用任何內建 BigInteger 库,也不能直接将输入的字符串转换为整数形式
import networkx as nx
def Reverse(s:str) -> str:
"""
字符串逆
:param s:
:return:
"""
num = len(s)
ans = ""
... |
#!/usr/bin/env python3
import configparser
from opcua import Client
from opcua import ua
import paho.mqtt.client as mqtt
import json
import logging
import sys
import time
from pysnmp.hlapi import *
import shelve
## TODO: Add Sphinx
## TODO: Add secure login methods
# TEST TRAVIS
# Handler class for OPC/UA events
class... |
#!/usr/bin/env python3
import array
import numpy as np
import os
import sys
import time
import tensorrt as trt
import pycuda.driver as cuda
import pycuda.autoinit
import pycuda.tools
import mlperf_loadgen as lg
## LoadGen test properties:
#
LOADGEN_SCENARIO = os.getenv('CK_LOADGEN_SCENARIO', 'SingleStream')... |
# -*- coding: utf-8 -*-
"""
Author
------
<NAME>
Email
-----
<EMAIL>
Created on
----------
- Fri Nov 25 12:53:24 2016
Modifications
-------------
- re-organized on Tue May 23 21:00:00 2017
Aims
----
- utils for apertures
"""
import numpy as np
from .background import apbackground
from .extract import (get_apert... |
#!/usr/bin/env python
import argparse
import logging
import os
import sys
from typing import Dict
from PyQt5.QtCore import QTimer, QMutex, QMutexLocker
from PyQt5.QtGui import QIcon, QFont, QFontDatabase
from PyQt5.QtWidgets import QSystemTrayIcon, QMenu, QAction, QApplication, QWidget, QLabel, QTextEdit, QPushButton,... |
#!/usr/bin/env python
# BAREOS - Backup Archiving REcovery Open Sourced
#
# Copyright (C) 2018-2020 Bareos GmbH & Co. KG
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of version three of the GNU Affero General Public
# License as published by the Free Software F... |
import random
import numpy as np
from chessbot_utils import fast_predict, create_piece_decoder, flatten_board
from math import inf
import chess
import chess.engine
# import cProfile
# import pstats
class Player:
def __init__(
self, team: int, encoder: dict, score_encoder: dict, boosted_rewards: bool... |
#!/usr/bin/env python
from functools import wraps
import cookielib
import HTMLParser
import json
import os
import sys
import re
import urllib
import urllib2
import urlparse
import uuid
def cached(wrapped):
@wraps(wrapped)
def wrapper():
if not hasattr(wrapped, 'cache'):
wrapped.cache = wra... |
from datetime import datetime, timedelta, time
from django.core import serializers
from django.db import models
from django.utils import timezone
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from www.contrib import NamedMode... |
"""
This module converts to/from a nested structure (e.g. list of lists of lists of ... of values) and a (nest pattern, flat list) tuple
The nest pattern is a string consisting solely of square brackets and digits.
A number represents the number of consecutive values at the current level of the nested structure.
An op... |
import pickle
import cv2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
# ! GLOBALS
# Define conversions in x and y from pixels space to meters
ym_per_pix = 20/720 # meters per pixel in y dimension
xm_per_pix = 3.7/780 # meters per pixel in x dimension
def calibrate_camera():
... |
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
from __future__ import print_function
import sys, shlex, operator
import re
import string
tk_http, tk_ftp, tk_telnet, tk_mailto,tk_divider, tk_question,tk_at, tk_doubledot, tk_dot, tk_plus, tk_space, tk_string, tk_letter, tk_number, tk_EOI, tk_epsilon,tk_dollar = range(17)
nd_start,nd_ftp,nd_telnet,nd_mailto,nd_httpa... |
"""
"Energetics of the Southern Ocean Mode" paper submitted to JGR: Oceans
this script creates the maps
it needs the 'nc/LEC_SOM_paper_maps_A_D.nc' that is created with the 'creating_netCDF.ipynb'
"""
import os
import sys
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import se... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import scipy.odr
import itertools
def computeModelDetails(frame):
""" Takes a dataframe and computes columns related to the dynamical frb model """
tauwerror_expr = lambda r: 1e3*r['time_res']*np.sqrt(r['max_sigma']**6*r['min_sigma_error']**2*np... |
#!/usr/bin/env python
# coding: utf-8
import sys
import argparse
from datetime import datetime
import math
import pandas as pd
from numpy.random import default_rng
import simpy
from pathlib import Path
class BorderCrossing(object):
def __init__(self, env, num_officers, num_officers2,
mean_i... |
# -*- coding: utf-8 -*-
"""
ENERPI - CLI methods & argument parser
"""
import datetime as dt
import os
import re
import sys
from enerpi import PRETTY_NAME, DESCRIPTION, __version__
from enerpi.base import (IMG_TILES_BASEPATH, DATA_PATH, CONFIG, SENSORS, CONFIG_FILENAME, SENSORS_CONFIG_JSON_FILENAME,
... |
# -*- coding: utf-8 -*-
import torch
import os
import sys
sys.path.append('../lightning-transformers')
import argparse
import json
import re
from torch.utils.data import DataLoader
from transformers import AutoTokenizer, AutoModelForSequenceClassification, T5TokenizerFast, T5ForConditionalGeneration
from typing import ... |
#! /usr/bin/env python
# encoding: utf-8
"""
# test_hickle.py
Unit tests for hickle module.
"""
# %% IMPORTS
# Built-in imports
from collections import OrderedDict as odict
import os
import re
from pprint import pprint
# Package imports
import pytest
import pickle
import h5py
import numpy as np
from py.path impor... |
import tempfile
import pytest
import magma as m
from magma.testing import check_files_equal
from magma import (IO, In, Out, Flip, Clock, Reset, reset, Enable, enable,
AsyncReset, Circuit, Bit, bit, wire, compile)
from magma.digital import DigitalMeta
from magma.compile_exception import UnconnectedPor... |
#!/bin/python3
# author: <NAME>
from collections import defaultdict
import matplotlib.axes
import matplotlib.figure
from cihpc.cfg.config import global_configuration
from cihpc.common.utils.datautils import flatten
from cihpc.core.db import CIHPCMongo
import pandas as pd
import numpy as np
from scipy import stats
fro... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import telegram
from telegram.error import Unauthorized, TelegramError
import random
THRESHOLD_PLAYERS = 10
with open("api_key.txt", 'r') as f:
TOKEN = f.read().rstrip()
bot = telegram.Bot(token=TOKEN)
class Player:
def __init__(self, id, h... |
"""
Cross Site Request Forgery Middleware.
This module provides a middleware that implements protection
against request forgeries from other sites.
"""
import logging
import string
from collections import defaultdict
from urllib.parse import urlparse
from django.conf import settings
from django.core.exceptions import... |
# -*- coding: UTF-8 -*-
#
# This file is part of khmer, https://github.com/dib-lab/khmer/, and is
# Copyright (C) 2010-2015, Michigan State University.
# Copyright (C) 2015-2016, The Regents of the University of California.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permi... |
# -*- coding: utf-8 -*-
""" DisCoPy rewriting methods. """
from discopy import cat, messages
def interchange(self, i, j, left=False):
"""
Returns a new diagram with boxes i and j interchanged.
Gets called recursively whenever :code:`i < j + 1 or j < i - 1`.
Parameters
----------
i : int
... |
# pins_to_c.py 17.8.2020/pekka
# Converts hardware IO specification(s) written in JSON to C source and header files.
import json
import os
import sys
pin_types = {
"inputs" : "PIN_INPUT",
"outputs" : "PIN_OUTPUT",
"analog_inputs" : "PIN_ANALOG_INPUT",
"analog_outputs" : "PIN_ANALOG_OUTPUT",
"pwm" :... |
import find_mxnet
import argparse,logging,os
import mxnet as mx
from symbol_resnet import resnet
import socket
import getpass
def multi_factor_scheduler(begin_epoch, epoch_size, step=[60, 75, 90], factor=0.1):
step_ = [epoch_size * (x-begin_epoch) for x in step if x-begin_epoch > 0]
return mx.lr_sched... |
from datetime import datetime
from io import StringIO
import numpy
import pandas
import pytest
from hts.hierarchy import HierarchyTree
from hts.utilities.load_data import load_hierarchical_sine_data, load_mobility_data
@pytest.fixture
def events():
s = """ts,start_latitude,start_longitude,city
2019-12-06 12... |
"""Train CIFAR10 with PyTorch."""
import csv
import glob
import numpy as np
import torch.backends.cudnn as cudnn
import os
import argparse
from torch.optim import Adam, AdamW, Adamax, SGD
from torch.utils.tensorboard import SummaryWriter
from kd.util_kd import make_criterion
from models import *
from utils.dataUtil imp... |
# CXI reader code borrowed from <NAME>'s pySTXM
import os, h5py
import datetime
import numpy as np
import scipy as sc
from skimage.restoration import unwrap_phase
from errno import ENOENT
class cxi(object):
def __init__(self, cxiFile = None, loaddiff = True):
self.beamline = 'COSMIC'
self.facili... |
"""
A structure walker for ctypes derived structures, including (and especially) Bitfields.
All the tools here work by mapping a Node onto the underlying object. Node objects
are grouped into two subclasses: UnboundNode, which points to classes, and
BoundNode, which points to instances. BoundNodes have an additional... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This is an example of working with very large data. There are about
700,000 unduplicated donors in this database of Illinois political
campaign contributions.
With such a large set of input data, we cannot store all the comparisons
we need to make in memory. Instead, we ... |
import copy
from typing import Optional, List
import torch
import torch.nn.functional as F
from torch import nn, Tensor
import argparse
import numpy as np
from torchsummary import summary
class Transformer(nn.Module):
def __init__(self, d_model=512, nhead=8, num_encoder_layers=6,
num_decoder_la... |
# -*- coding: utf-8 -*-
# Copyright 2020 <NAME>, Modified by Trinhlq (@l4zyf9x)
# MIT License (https://opensource.org/licenses/MIT)
"""Train FastSpeech."""
import argparse
import logging
import os
import sys
import numpy as np
import tensorflow as tf
import yaml
import tensorflow_tts
from tqdm import tqdm
from ... |
from pprint import pformat
import numpy as np
import tensorflow as tf
from tqdm import trange, tqdm
from env_settting import *
from script.data_handler.Base.BaseDataset import BaseDataset
from script.model.sklearn_like_model.Mixin import paramsMixIn, loss_packMixIn, slice_np_arr
from script.model.sklearn_lik... |
from lt_parser import *
# torch.zeros(input.size(), dtype=input.dtype, layout=input.layout, device=input.device).
# torch.ones(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)
my_list = [
'torch.is_tensor(obj)',
'torch.numel(input)',
'torch.tensor(data, device=None, requires_grad=False, ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 1 12:07:43 2020
@author: Annika
"""
import numpy as np
from numpy import pi
import math
#Constants:
T0 = 273.15 # K
p0 = 101325 # Pa
M_air =(0.21*0.031998+0.79*0.0280134) # kg/mol, molar mass of dry air
R = 8.3144598 # J/(mol K) gas constant
Ra = R/M_air #J/(kgK), ... |
#This code is written by @sracaniere from DeepMind
#https://github.com/sracaniere
import numpy as np
import math
STANDARD_MAP = np.array([
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, ... |
import os
import sys
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from datetime import datetime
import joblib
import argparse
from deep_gmm import DeepGMM
import itertools
import inspect
from utils import generate_random_pw_linear
def deep_iv_fit(z... |
#!/usr/bin/env python
'''
Compile the Software Carpentry web site.
'''
import sys
import os
import re
import yaml
import glob
import jinja2
import datetime
import time
from collections import defaultdict
from optparse import OptionParser
from os.path import join
from PyRSS2Gen import RSS2, RSSItem
try: # Python 3
... |
from tkinter import Tk,Toplevel,Listbox,Entry,Frame,Label,StringVar,Button,StringVar,filedialog,Scrollbar,Frame,END,CENTER,W,BOTTOM,TOP,BOTH,Toplevel,X,Menu
from tkinter import colorchooser
from tkinter.ttk import Treeview
import h5py
import matplotlib
from matplotlib.colors import Colormap
matplotlib.use("TkAgg")
from... |
"""
lipydomics/stats.py
<NAME>
2019/02/03
description:
A set of functions for performing statistical analyses on the lipidomics data. Generally, these functions
should produce one or more columns to associate with the data, as well as a label describing the analysis
performed (... |
from __future__ import print_function, absolute_import
import ujson
import sys
import datetime as dt
from decimal import Decimal
class NestingLevelTooHigh(Exception):
pass
class DictionaryAdapter(object):
def getfields(self, dict):
return dict.keys()
def getval(self, dict, field):
if f... |
import caffe
from caffe import layers as L, params as P, to_proto
def conv_bn_relu(n, name, top_prev, ks, nout, stride=1, pad=0, loop=1):
for idx in range(loop):
n[str(name)+"_"+str(idx)] = L.Convolution(top_prev, #name = name,
convolution_param=dict(
... |
#!/usr/bin/python
import abc
from utilities import json_pp
from flask_excel import make_response_from_array
import logging
from jsonobject import JsonObject, StringProperty, FloatProperty, \
IntegerProperty, ListProperty, ObjectProperty, DictProperty
module_logger = logging.getLogger("dashboardService.elastic_requ... |
# -*- encoding: utf-8 -*-
# flake8: noqa
"""reinit
Revision ID: 1
Revises:
Create Date: 2020-01-01 22:59:10.872705
"""
from alembic import op
import sqlalchemy as sa
import lazyblacksmith
# revision identifiers, used by Alembic.
revision = '1'
down_revision = None
branch_labels = None
depends_on = None
def upgrade... |
import logging
import os
import netCDF4 as nc
import numpy as np
import pandas as pd
import pytz
import utm
from smrf.envphys import phys
from smrf.envphys.radiation import get_hrrr_cloud
try:
from weather_forecast_retrieval import hrrr
except:
pass
class grid():
"""
Class for loading and storing ... |
import time
import json
import torch
import torch.nn.functional as F
import torch.nn as nn
from apex import amp
from config import configs
from build_data import AmazonQA
from CHIME import CHIME_Model
from utils import get_batch, random_seed
from transformers import AutoModel, AutoConfig, AdamW, get_linear_schedule_wit... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.