text stringlengths 3.07k 22.1k |
|---|
#!/usr/bin/env python3
"""Coronavirus projections"""
import os.path as op
import re
import sys
import datetime
from collections import namedtuple
import matplotlib.pyplot as plt
import numpy as np
import requests
import pandas as pd
VERBOSE = False
LAST_N = 5
NUMBER_FILE = op.join(op.dirname(op.realpath(__file__)), ... |
# BSD 3-Clause License
# Copyright (c) 2021, ShashankKumarSaxena | ShashankNetSolutions
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the... |
from collections import OrderedDict
import torch
import torch.nn as nn
from src.models.layers import MultitaskClassifiers, BN_AC_CONV3D
from src.utils.initializer import xavier
class MF_UNIT_SF(nn.Module):
def __init__(self, num_in, num_mid, num_out, g=1, stride=(1, 1, 1), first_block=False, temporal_kernel=1):
... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import rospy
import cv2
from sensor_msgs.msg import Image
import sys
import numpy as np
from rospy.numpy_msg import numpy_msg
from std_msgs.msg import Int32MultiArray
import argparse
import logging
import os
import torch
import torch.nn.functional as F
from PIL import Im... |
# ------------------------------------------------------------------------------
# Cluster the attention map of inverted images for unsupervised segmentation.
# ------------------------------------------------------------------------------
import h5py
import numpy as np
import os
import params
import scipy
import scip... |
import os
print(os.listdir("../content"))
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import scipy.sparse as scs # sparse matrix construction
import scipy.linalg as scl # linear algebra algorithms
import scipy.optimize as sco # for minimization use
import... |
from abc import ABC
from glob import glob
from inspect import Parameter, signature
from pathlib import Path
from typing import Any, Dict, List, NamedTuple, Optional, Tuple, Type, cast
from ..helpers import (
import_module_and_get_attr,
import_module_and_get_attrs,
is_abstract,
is_primitive,
re_find... |
"""klass.py (I know it's spelt wrong, OK)?
base class for all character classes in SMNW. handles
image generation, spawning, and default movement, and attacking.
"""
import random
from . import new_terrain
from .block import Block
from .character_image import CharacterImage
from .smr_error import SMRError
BEIGE = (23... |
import copy
import tdapi
import tdapi.obj
from tdapi.cmdb import TDConfigurationItem
class TDProductTypeQuerySet(tdapi.obj.TDQuerySet):
pass
class TDProductTypeManager(tdapi.obj.TDObjectManager):
pass
class TDProductType(tdapi.obj.TDObject):
pass
tdapi.obj.relate_cls_to_manager(TDProductType, TDProd... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
import torch.nn.functional as F
from torch import nn
from maskrcnn.structures.bounding_box import BoxList
from maskrcnn.structures.boxlist_ops import boxlist_nms
from maskrcnn.structures.boxlist_ops import cat_boxlist
from maskrcnn.mo... |
from PIL import Image, ImageDraw, ImageFont
from collections import Counter
from math import ceil
def load_font(fontpath, fontsize):
if fontpath == "Kanji":
fonts = [
"NotoSansJP-Regular.otf",
"yumin.ttf",
"meiryo.ttc",
"YuGothM.ttc",
"msgothic.t... |
import os
import numpy as np
import pandas as pd
import pickle
from tqdm import tqdm
import argparse
from sklearn.utils import shuffle
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import CountVectorizer
#from nltk.stem import PorterStemmer
from pathlib import Path
##############... |
#!/usr/bin/env python
# coding: utf-8
import sys
import os
import time
import json
import numpy as np
import pandas as pd
import dill
import random
from os.path import join, dirname, abspath, pardir, basename
from sklearn.pipeline import FeatureUnion, Pipeline
from sklearn.ensemble import RandomForestClassifier
from... |
"""This module contains all the implementation for the 'scraper'
function in the 'ark' library, with both JSON parsing and Gamepress
implementation implemented."""
import argparse
import sys
from halo import Halo # extremely important
from bs4 import BeautifulSoup
from operatorclasses.operator import Operator
from... |
from acqdp.tensor_network import TensorNetwork
import numpy as np
from acqdp.circuit import CNOTGate, CZGate, Circuit, HGate, Measurement, PlusState, State, Trace, ZeroMeas, ZeroState
from demo.QEC.noise_model import add_idle_noise, add_noisy_surface_code
params = {
'T_1_inv': 1 / 30000.0,
'T_phi_inv'... |
import logging
import dbus
import dbus.exceptions
import dbus.mainloop.glib
import dbus.service
from ble import (
Advertisement,
Characteristic,
Service,
Application,
find_adapter,
Descriptor,
Agent,
)
import struct
import requests
import array
from enum import Enum
import sys
MainLoop ... |
import argparse
import os
import re
import shutil
import sys
import subprocess
from colorama import init as colorama_init
colorama_init()
from colorama import Fore, Style
def findRootDir():
absPath = os.path.abspath(__file__)
while absPath:
absPath = os.path.dirname(absPath)
if os.path.exists(... |
import pandas as pd
import pysam
import glob
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import re
import subprocess as sp
import random
import progressbar as pgb
import time
import numpy as np
from multiprocessing import cpu_count, Process, Manager
from sklearn.cluster import DBSCAN
def run(dir_name, logger, ... |
import numpy as np
import tensorflow as tf
import gensim
import json
#model = gensim.models.KeyedVectors.load_word2vec_format('../../GoogleNews-vectors-negative300.bin', binary=True)
model =dict()
with open('../data/labs_2', 'r') as f:
labels_org = f.read()
with open('../data/sentences_2', 'r') as f:
sent... |
"""
Lispify converts Python objects into Lisp-like encoded strings that are
readable by START.
Use the 'lispify' function to encode a Python object.
To create a new way of interpreting data subclass the LispType class.
Prefix your class with an underscore (_) if it is an intermediate representation
so that the lispif... |
# -*- test-case-name: xmantissa.test.test_stats -*-
# Copyright 2008 Divmod, Inc. See LICENSE file for details
"""
Statistics collection and recording facility.
This is a system for sending locally recorded stats data to remote observers
for further processing or storage.
Example::
twisted.python.log.msg(interfac... |
import json
class Uporabnik:
def __init__(self, uporabnisko_ime, geslo, ime_in_priimek, planer): #geslo je tu že zašifrirano
self.uporabnisko_ime = uporabnisko_ime
self.geslo = geslo
self.ime_in_priimek = ime_in_priimek
self.planer = planer
def preveri_geslo(self, geslo):
... |
# The contents of this file are subject to the BitTorrent Open Source License
# Version 1.1 (the License). You may not copy or use this file, in either
# source code or executable form, except in compliance with the License. You
# may obtain a copy of the License at http://www.bittorrent.com/license/.
#
# Software di... |
from __future__ import print_function
import os
import numpy as np
import viscid
from viscid import logger
from viscid.readers import vfile
try:
import h5py
HAS_H5PY = True
except ImportError:
HAS_H5PY = False
logger.warn("h5py library not found, no hdf5 support.")
class H5pyDataWrapper(vfile.Data... |
from befh.ws_api_socket import WebSocketApiClient
from befh.market_data import L2Depth, Trade
from befh.exchanges.gateway import ExchangeGateway
from befh.instrument import Instrument
from befh.util import Logger
from befh.clients.sql_template import SqlClientTemplate
import time
import threading
import json
from funct... |
from __future__ import print_function
import keras
from keras.models import Model
from keras.layers import Dense, Dropout, Flatten, Input
from keras.layers import Conv1D, Conv2D, MaxPooling1D, MaxPooling2D, BatchNormalization, Activation, SeparableConv1D
from keras.callbacks import ModelCheckpoint
from keras import bac... |
#!/usr/bin/env python
import os
import dill as pickle
import sys
import emcee
import matplotlib
import matplotlib.pyplot as plt
from astropy.table import Table
from emcee.mpi_pool import MPIPool
import src.globals as glo
import pandas as pd
import numpy as np
import corner
from src.objects import SpecCandidate, Tar... |
# Module that groups the greedy search strategies that can be incorporated as a hybrid strategy in
# the algorithms.
#
# Author: <NAME>
# Email: <EMAIL>
#
import numpy as np
import joblib
import networkx as nx
from .base import MetaHeuristic
from ..optim import ObjectiveFunction
from ..c_ntools import getValidPaths
c... |
import re
import copy
from nonebot.message import handle_event
from nonebot.plugin import on_message, on_command
from nonebot.adapters.cqhttp import (Event, GroupMessageEvent, GROUP_ADMIN, GROUP_OWNER, Bot,
Message, MessageEvent, unescape)
from nonebot.typing import T_State
from .ut... |
from falcon_kit import kup, falcon, DWA
from falcon_kit.fc_asm_graph import AsmGraph
import networkx as nx
import sys
RCMAP = dict(list(zip("ACGTacgtNn-", "TGCAtgcaNn-")))
def rc(seq):
return "".join([RCMAP[c] for c in seq[::-1]])
def get_aln_data(t_seq, q_seq):
aln_data = []
K = 8
seq0 = t_seq
... |
#!/usr/bin/env python
# coding: utf-8
# # Invertible Convolution and WaveNet Custom Layers
# ## Boilerplate
# Start with standard imports as well as adding the scripts directory to the system path to allow custom imports.
# In[1]:
import tensorflow as tf
from tensorflow.keras import layers
import tensorflow_addon... |
"""
Copyright 2010-2011 <NAME> <<EMAIL>>
Copyright 2008-2009 <NAME>
This file is part of PyCAM.
PyCAM 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 late... |
import torch
import numpy as np
def blaugment9to15(x, bl, blr, num_bone=15):
'''
this function convert 9 blr to 15 blr, and apply to bl
bl: b x joints-1 x 1
blr: b x 9 x 1
out: pose3d b x joints x 3
'''
blr9to15 = torch.Tensor([
[1, 0, 0, 0, 0, 0, 0, 0, 0], # 1
... |
from django.conf import settings
from django.db import models
from django.http import FileResponse
from modelcluster.fields import ParentalKey
from wagtail.core import hooks
from wagtail.core.models import Orderable, Page
from wagtail.core.fields import RichTextField, StreamField
from wagtail.admin.edit_handlers impo... |
from utils import *
from torch.autograd import Variable
import matplotlib.pyplot as plt
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data
from part_a.neural_network import train, load_data
from part_a.item_response import irt
from part_a.knn import knn_impute_by_u... |
#! /usr/bin/env python3
"""
Copyright (c) 2020, ETH Zurich, Computer Engineering Group
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright n... |
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
# -*- coding: utf-8 -*-
'''ICMPv4'''
from datetime import datetime, date
import net
import ipv4
import udp
import tcp
import raw
from common import *
import logging
log = logging.getLogger(__name__)
# global IP setting
return_data_bytes = 64
# statistics
class _stat:
rx_count = 0
rx_dropped = 0
tx_coun... |
# Copyright (c) 2021 AccelByte Inc. All Rights Reserved.
# This is licensed software from AccelByte Inc, for limitations
# and restrictions contact your company contract manager.
#
# Code generated. DO NOT EDIT!
# template file: justice_py_sdk_codegen/__main__.py
# pylint: disable=duplicate-code
# pylint: disable=li... |
from panda3d.core import NodePath
# For copying and changing a nodes render states:
class RenderState:
__slots__=(
'name',
'panda_node',
'set_depth_write',
'get_depth_write',
'set_depth_offset',
'get_depth_offset'
)
def __init__(self, EZnode, name):
... |
# <<BEGIN-copyright>>
# Copyright 2021, Lawrence Livermore National Security, LLC.
# See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
# <<END-copyright>>
"""Routines for writing an ENDF file"""
from pqu import PQU as PQUModule
from xData import XYs as XYsModule
from xData impo... |
"""Implement the .train function."""
import torch
import numpy as np
from torch.autograd import Variable
import torch.nn as nn
from collections import defaultdict
from .scheduler import GradualWarmupScheduler
from .. import consts
from ..consts import BENCHMARK, NON_BLOCKING
torch.backends.cudnn.benchmark = BENCHMA... |
from argparse import ArgumentParser
from typing import Any, Dict, List, Tuple, Type
import os
from copy import deepcopy
import torch
from pytorch_lightning import LightningModule, Trainer, seed_everything
import pytorch_lightning as pl
import pl_bolts
from torch import Tensor, nn
from torch.nn import functional as F
i... |
import numpy as np
from collections import OrderedDict
from munkres import Munkres, make_cost_matrix
from sklearn.metrics.cluster import contingency_matrix
from sklearn.preprocessing import LabelEncoder
def entropy(labels):
"""Calculates the entropy for a labeling."""
if len(labels) == 0:
return 1.0
... |
import copy
import datetime
import json
import logging
from functools import wraps
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
import backoff
import dateutil
import dateutil.tz
import requests
from requests.structures import CaseInsensitiveDict
from annofabapi.models import Task, Task... |
import nltk
import re
import random
import csv
from google.cloud import storage
# Parameters on robustness of training data
SHUFFLE, DELETE, DUPLICATE = 0.2, 0.2, 0.2
# Training/testing ratio
PERCENT_TRAINING = 0.8
# Mapping of file attribute titles to libpostal fields
HEADER = {'LAT': '',
'LON': '',
... |
import torch
from torch import nn
import torch.nn.functional as F
import pytorch_lightning as pl
from sklearn.metrics import r2_score
class LinearBlock(nn.Module):
def __init__(self, *args, **kwargs):
super().__init__()
self.block = self.generate_layers(*args, **kwargs)
self.out_sz = kwarg... |
#!/usr/bin/env python3
import argparse
import os, sys
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
sys.path.append(os.path.realpath("."))
from src.YachtMod import Yacht, Keel, Rudder
from src.SailMod import Main, Jib, Kite
from src.VPPMod import VPP, KNOTS_TO_MPS
tws = np.array([... |
"""
training code
"""
from __future__ import absolute_import
from __future__ import division
import argparse
import logging
import os
import torch
from config import cfg, assert_and_infer_cfg
from utils.misc import AverageMeter, prep_experiment, evaluate_eval, fast_hist
import datasets
import loss
import network
impor... |
from django.db import models
from django.utils import timezone
class Project(models.Model):
"""
A model to store the project - this can be related to several different Analyses
"""
name = models.CharField(max_length=250, unique=True)
description = models.CharField(max_length=500)
def __str__(... |
#!/usr/bin/env python3
# vim: autoindent tabstop=4 shiftwidth=4 expandtab softtabstop=4 filetype=python
# -*- coding: utf-8 -*-
# BSD LICENSE
#
# Copyright (c) 2016, <NAME> All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the follow... |
# -*-coding:utf8-*-
"""
author:zhiyuan
date:20190317
train wd model
"""
from __future__ import division
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
def get_feature_column():
"""
age,workclass,education,education-num,marital-status,occupation,relationship,race,sex,capital-gain,ca... |
import csv
import logging
from datetime import datetime
from decimal import Decimal
import oas
import old.server.oas.tools
from oas.rpc.engine import remote
from oas.rpc.engine import remote_custom
_LOG = logging.getLogger('oas.rpc')
#
# remote procedures below
#
@remote
def get_currencies():
locator = oas.get... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Analysis of fire seasons.
For the purpose of these analyses, burned area at each location is relative to the
maximum burned are observed at that location. This allows the use of a single unitless
threshold throughout.
The start & end months of the fire seasons and the... |
import sys
import json
import click
import json
from prettytable import PrettyTable
from calm.dsl.api import get_api_client, get_resource_api
from calm.dsl.constants import PROVIDER_ACCOUNT_TYPE_MAP
from calm.dsl.log import get_logging_handle
from .utils import highlight_text
LOG = get_logging_handle(__name__)
def ... |
import json
import re
import sqlite3
from sqlite3 import Error
from sys import platform
from collections import OrderedDict
import Tkinter,tkFileDialog
import tkMessageBox
import os
import glob
import sys
#============================================================================
# opens the json file from GEE to be... |
# -*- coding: utf-8 -*-
"""
Copyright (c) 2020, University of Southampton
All rights reserved.
Licensed under the BSD 3-Clause License.
See LICENSE.md file in the project root for full license information.
"""
from pathlib import Path
import joblib
import numpy as np
import psutil
from matplotlib import pyplot as plt... |
import argparse
import os
import sys
import json
import zipfile
import boto3
class ProjectInfo:
def __init__(self, project_name, zip_info, lambda_info):
self.ProjectName = project_name
self.ZipInfo = zip_info
self.LambdaInfo = lambda_info
class ZipInfo:
def __init__... |
project_name = '06b-anime-dcgan'
import opendatasets as od
# dataset_url = 'https://www.kaggle.com/tunguz/1-million-fake-faces-3'
# od.download(dataset_url)
# dataset_url = 'https://www.kaggle.com/tunguz/1-million-fake-faces-4'
# od.download(dataset_url)
#dataset_url = 'https://www.kaggle.com/tunguz/1-million-fake-f... |
"""Utilities to parse/write various files
* metadata table from Uniprot
* fasta files
* JSON file of TOPCONS predictions
* SignalP output file
Author: <NAME> (<EMAIL>)
August 2018
All code contained herein is licensed under an
[MIT License](https://opensource.org/licenses/MIT)
"""
import os.path
imp... |
import logging
import math
import six
from opcodes import *
from z3 import *
from z3.z3util import *
from vargenerator import *
from utils import *
import global_params
log = logging.getLogger(__name__)
# THIS IS TO DEFINE A SKELETON FOR ANALYSIS
# FOR NEW TYPE OF ANALYSIS: add necessary details to the skeleton funct... |
import logging
from typing import List
import numpy as np
import pandas as pd
from scipy.interpolate import CubicSpline
import scipy.interpolate
from .db_connect import db_connect
logger = logging.getLogger(__name__)
def calculate_k_isq(source: np.array, cells: np.array, dref: float
) -> np.arr... |
import math
import sys
import os
from multiprocessing import Pool
from pathlib import Path
from esper.prelude import par_for
from query.models import Video
import captions.util as caption_util
from captions import Documents, Lexicon, CaptionIndex, MetadataIndex
INDEX_DIR = '/app/data/index'
DOCUMENTS_PATH = os.path... |
# -*- coding: utf-8 -*-
# pylint: disable-msg=
"""
Created on Thu Dec 19 18:02:37 2013
This module contains the model definition for the automata-based abstraction
patterns. Since abstraction patterns are defined by regular grammars, the
internal representation is based on finite automatas.
@author: <NAME>
"""
from ... |
import keras
from keras import optimizers
#from keras.utils import multi_gpu_model
import scipy as sp
import scipy.misc, scipy.ndimage.interpolation
from medpy import metric
import numpy as np
import os
from keras import losses
import tensorflow as tf
from keras.models import Model
from keras.layers import I... |
"""Helper to score pipelines."""
from __future__ import annotations
import warnings
from traceback import format_exc
from typing import Any, Callable, Dict, Generic, List, Optional, Sequence, Tuple, Type, TypeVar, Union, cast, overload
import numpy as np
from typing_extensions import Protocol
from tpcp._dataset impo... |
from netmiko import ConnectHandler
class Asa:
def __init__(self, mgmt, pub, pubNet, pri, priNet):
self.mgmt = mgmt
self.pub = pub
self.pubNet = pubNet
self.pri = pri
self.priNet = priNet
asa_dict = {}
#Gather user input and create ASA objects for configuration.... |
import numpy as np
import logging
import pickle
import copy
import gzip
from itertools import chain
from matplotlib import pyplot as plt
from ticket.core import TicketToRide
from ticket.strategy import Strategy
from ticket.game import Game
from ticket import utils
class Population(TicketToRide):
def __init__(sel... |
from osgeo import gdal, osr, gdal_array
import numpy as np
from scipy import mgrid
import matplotlib.pyplot as plt
class MyRaster():
"""
The MyRaster object has the raster properties and some functions attached to it.
"""
def __init__(self, raster_file):
"""
The init... |
from eos3dmpl.nbody import *
from eos3dmpl.eos_core import *
import datetime
import os
# Surpress any warnings
import warnings
warnings.filterwarnings("ignore")
os.system('cls')
def option1():
eos1 = Eos()
eos1.view_init()
eos1.orbit(a=26554,e=0.72,tp=4000,i=63.4,om=0,w=-90,unit_i='km',unit_o='km',body=... |
import os
import sys
import argparse
import binascii
try:
import re
except ImportError:
import ure as re
import socket
try:
import socketserver
except ImportError:
try:
import SocketServer as socketserver
except ImportError:
import upy.socketserver as socketserver
import errno
import rpcBind, rpcRequest
from ... |
#
# Copyright (c) 2022 Airbyte, Inc., all rights reserved.
#
import base64
from abc import ABC
from typing import Any, Iterable, List, Mapping, MutableMapping, Optional, Tuple
import pendulum
import requests
from airbyte_cdk.sources import AbstractSource
from airbyte_cdk.sources.streams import Stream
from airbyte_cdk... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2015-2018 by ExopyHqcLegacy Authors, see AUTHORS for more details.
#
# Distributed under the terms of the BSD license.
#
# The full license is in the file LICENCE, distributed with this software.
# ------... |
"""Project logging configuration.
Project-scope constants may reside here, but more importantly, some setup here
will provide a logging infrastructure for all of the project's modules.
Individual modules and classes may provide separate configuration on a more
local level, but this will at least provide a foundation.
... |
# Copyright 2008-2013 Nokia Siemens Networks Oyj
#
# 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... |
# Copyright 2020 Twitter, Inc.
# SPDX-License-Identifier: Apache-2.0
import argparse
from tqdm import tqdm
import torch
import torch.nn.functional as F
from torch_sparse import SparseTensor
from torch_geometric.utils import to_undirected, dropout_adj
from ogb.nodeproppred import PygNodePropPredDataset
import numpy ... |
import argparse
import math
import numpy as np
import os
import sys
import torch
import provider
import torch.nn as nn
import models.model_cls
import torch.optim as optim
from torch.optim import lr_scheduler
import datetime
import matplotlib.pyplot as plt
begin_time = datetime.datetime.now()
BASE_DIR = os.path.dirname... |
#: vim set encoding=utf-8 :
##
# Paper
# Develop apps for Pythonista using HTML, CSS and JavaScript
#
# author 0x77
# version 0.4
##
# Imports
import os
import sys
import json
import traceback
import webbrowser
from types import ModuleType
from bottle import run, route, get, post, static_file, request
__all__ ... |
import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
from datetime import datetime
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
import sys
import pickle
def loss(a,b):
x = np.abs(a-b)
y = math.pi*2-np.abs(a-b)
z = np.greater... |
import os
import numpy as np
import pandas as pd
from rulevetting.projects.tbi_pecarn import dataset
# from sklearn.impute import KNNImputer
from sklearn.linear_model import LogisticRegression
from sklearn.feature_selection import SelectFromModel
from sklearn.exceptions import ConvergenceWarning
from warnings import s... |
import re
from collections import OrderedDict
from random import shuffle
from os import mkdir
from shutil import copyfile
import pathlib
import os
import random
import argparse
random.seed(483745342)
labels_dict = {}
disaster_type_names = {
0: 'flooding-0',
1: 'flooding-1',
2: 'flooding-2',
3: 'flood... |
from collections import defaultdict
import jmespath
from .invocation_tools import _extract_invocations, _name_of
class VaqueroException(Exception):
pass
def _make_pairs_table(d, sort_ks=True, depth=""):
rows = [depth + "<table>"]
ks = d.keys() if not sort_ks else sorted(d.keys())
for k in ks:
... |
# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals
from scrapy.downloadermiddlewares.retry import RetryMiddleware
# from scrapy.downloadermiddlewares.retry import get_retry_request
from http import H... |
"""
Routines provided by <NAME>. Important function to use for model is liquidus (at bottom of file).
Description
------------------------------
The following code contains routines to compute the Equation of States (EoS)
for l-Fe-S and l-Fe-Si based on Terasaki 2019 (10.1029/2019JE005936).
"""
import numpy as np... |
import torch
from torch.autograd import Variable
import torch.nn as nn
import math
import torch.nn.functional as F
from .core import *
import copy
def acoustic_builder(aco_type, opts):
if aco_type == 'rnn':
model = acoustic_rnn(num_inputs=opts.num_inputs,
emb_size=opts.emb_si... |
#!/usr/bin/env python
""" See the file "LICENSE" for the full license governing this code.
Copyright 2011-2021 <NAME>
"""
#adjust pylint for pytest oddities:
#pylint: disable=missing-docstring
#pylint: disable=unused-argument
#pylint: disable=attribute-defined-outside-init
#pylint: disable=protected-access
#pylint:... |
import matplotlib.pyplot as plt
from matplotlib import colors
import pandas as pd
import numpy as np
from scipy.stats import spearmanr, gaussian_kde
import sys
def make_diff_avg_plot(x_vals, y_vals, title, xlab, ylab, figname):
"""Find the Spearman R correlation value and create scatter plot of beta
values.... |
# Copyright 2018 <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.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license" file accompanying this fil... |
from __future__ import print_function, division
from builtins import range
import numpy as np
"""
This file defines layer types that are commonly used for recurrent neural
networks.
"""
def rnn_step_forward(x, prev_h, Wx, Wh, b):
"""
Run the forward pass for a single timestep of a vanilla RNN that uses a ta... |
# main imports
import sys, os, argparse
import numpy as np
import pandas as pd
import random
# image processing imports
from PIL import Image
from ipfml import utils
# modules imports
sys.path.insert(0, '') # trick to enable import of main folder module
import custom_config as cfg
from modules.utils import data as ... |
import logging
import argparse
import asyncio
import signal
from typing import (Dict, Generator, Callable, Iterable, Coroutine, # noqa: F401
Any, Optional, Union, TypeVar)
from enum import IntEnum
from katpoint import Timestamp, Catalogue, Target, Antenna
from kattelmod.clock import Clock, WarpE... |
import numpy as np
import os
import pickle
import sys
import torch
from PIL import Image
from torch.utils.data import Dataset
from utils import makedir_exist_ok
from .utils import download_url, check_integrity, make_branch_classes_to_labels
class CIFAR10(Dataset):
data_name = 'CIFAR10'
base_folder = 'cifar-10-... |
import os as os
import cPickle as cPickle
import matplotlib.pyplot as plt
import numpy as np
from py_dp.dispersion.binning import get_cdf_from_bins
def get_histogram(plume, bins):
n, bins = np.histogram(plume, bins=bins, density=True)
return n
def plot_side_byside_plumes(ax, x_vals, plume_list, label_list, s... |
# coding: utf-8
# Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
from __future__ import print_function
import click
import datetime
import functools
import getpass
import json
import pytz
import six
import sys
import uuid
from .formatting import render_config_errors
from cryptography.haz... |
# Copyright International Business Machines Corp, 2020
#
# 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 ... |
# -*- coding:utf-8 -*-
import operator
import warnings
from collections import namedtuple
from warnings import warn
import numpy as np
__copyright__ = 'Copyright 2017'
__author__ = u'Bsc. <NAME>'
Stats = namedtuple('Stats', [
# Rate curves
'thrs', # Thresholds
'fmr', # False match rates
'fnmr'... |
from secret import BOT_TOKEN
from discord.ext import commands
from aiohttp import ClientSession
from util.checks import is_owner
from datetime import datetime
from math import ceil
from db.models import objects, Configuration
from secret import MIXPANEL_TOKEN, DISCORD_BOTS_TOKEN
from collections import Counter
import b... |
import contextlib
import glob
import json
import os
import pprint
import sys
import threading
from multiprocessing.connection import Client, Listener
from typing import Any, Callable, Dict, List, MutableMapping, Optional, TextIO
__loggers_stop = False
@contextlib.contextmanager
def lock_access(lock: threading.Lock... |
########### import 模型用到的 package ###########
import numpy as np
from keras.utils import np_utils
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer
from keras.layers import Dense, Activation, Dropout
from keras.models import Sequential
from keras.la... |
import requests
import psycopg2
import psycopg2.extras
import uuid
from lxml import etree
import route
# Get the current "agencyList" from the nextbus API. Upsert to the
# postgres database.
def update_agencies(conn):
# Hit the agencyList endpoint.
agency_xml = requests.get(
route.BASE_URL + 'agencyL... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.