text stringlengths 3.07k 22.1k |
|---|
# Various 2D filters that can be applied to data.
from .filters1d import blockavg1d
import numpy as np
from astropy.modeling.models import Gaussian2D
from scipy.signal import gaussian, fftconvolve
############################################################################
# Master function that assigns operations base... |
"""Class and methods that represent a Bluetooth Adapter."""
# D-Bus imports
import dbus
import dbus.mainloop.glib
# python-bluezero imports
from bluezero import constants
from bluezero import dbus_tools
from bluezero import async_tools
from bluezero import device
from bluezero import tools
logger = tools.create_mod... |
# -*- coding: utf-8 -*-
# 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
#... |
import gym
import numpy as np
import os
import time
import pandas
from sklearn.preprocessing import StandardScaler
from sklearn.kernel_approximation import RBFSampler
from sklearn.pipeline import FeatureUnion
from tqdm import tqdm
import matplotlib.pyplot as plt
from sklearn.model_selection import ParameterGrid
import ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Manipulates the vehicle table
"""
from psycopg2 import connect
import common
constraints = {
'type': ['UNKNOWN', 'CAR', 'MOTORCYCLE', 'BUS', 'CARGO', 'AGRICULTURAL', 'OTHER'],
'make': ['UNKNOWN'],
'model': ['UNKNOWN'],
'fuel_type': ['UNKNOWN', 'DIESEL', ... |
#!/bin/python3
import os, sys
import numpy as np
from scipy.stats import rankdata
from sinatra_pro.mesh import *
def reconstruct_by_sorted_threshold(meshfile, directions, rates, n_filtration = 25, n_direction_per_cone = 1, ball_radius = 1.0, by_rank = False, verbose = False):
"""
Reconstruction algorithms
... |
from os.path import join
from typing import Optional, Union
import discord
from discord.ext import commands
from ...lib import (
Embed,
ErrorEmbed,
check_if_warning_system_setup,
get_roles,
get_user,
return_ban_channel,
return_warning_channel,
)
class Moderation(commands.Cog):
def __... |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import time
import numpy as np
import tensorflow as tf
from tqdm import tqdm
from keras.preprocessing.sequence import pad_sequences
# In[2]:
with open("test.conll.txt") as fopen:
corpus = fopen.read().split("\n")
with open("dev.conll.txt") as fopen:
corpus... |
# Copyright 2019 Katteli Inc.
# TestFlows.com Open-Source Software Testing Framework (http://testflows.com)
#
# 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/lice... |
from __future__ import print_function
import os
import struct
class RemusRom(object):
def __init__(self, sum_off, chk_sum, size, base_addr, name, short_name):
self.sum_off = sum_off
self.chk_sum = chk_sum
self.size = size
self.base_addr = base_addr
self.name = name
self.short_name = short_n... |
from torch.nn.functional import softmax, relu, selu, leaky_relu, elu, max_pool1d
import torch.nn.init as init
import time
import torch
import torch.nn as nn
import torch.optim as optim
import inspect
import random
import math
#import spacy
cudaid = int(0)
DEVICE = torch.device("cuda:%d" % (cudaid) if torch.cuda.is_avai... |
""" This code was adapted from: https://github.com/jeffreyhuang1/two-stream-action-recognition/blob/master/network.py
"""
import torch.nn as nn
import math
import numpy as np
import torch.utils.model_zoo as model_zoo
import torch
from torch.autograd import Variable
import torch.nn as nn
import math
import torch.utils... |
# -*- coding: utf-8 -*-
"""Copyright 2015 <NAME>.
FilterPy library.
http://github.com/rlabbe/filterpy
Documentation at:
https://filterpy.readthedocs.org
Supporting book at:
https://github.com/rlabbe/Kalman-and-Bayesian-Filters-in-Python
This is licensed under an MIT license. See the readme.MD file
for more informa... |
import os
import multiprocessing as mp
from typing import Text, Type, List, Set, Dict, Tuple
from copy import deepcopy
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor
from appyratus.enum import EnumValueStr
from ravel.util.misc_functions import remove_keys, import_object
from ravel.co... |
from RIRData import *
from torch import nn, optim
from torch.nn import functional as F
import torchaudio
import torchaudio.functional as audioF
from torchsummary import summary
import librosa
import librosa.display
from torch.utils.tensorboard.writer import SummaryWriter
from models.my_vae import MyVAE
from t... |
import os
import sys
import random
import math
import re
import time
import numpy as np
import tensorflow as tf
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import skimage
import glob
from mrcnn import utils
from mrcnn import visualize
from mrcnn.visualize import display_images... |
import numpy as np
import tensorflow as tf
from models.layers import CustomDense, GraphConvolution, InnerProductDecoder, get_layer_uid
from utils.preprocess import normalize_graph_gcn, sparse_to_tuple
flags = tf.compat.v1.flags
FLAGS = flags.FLAGS
class GraphAE(object):
"""Base GraphAE class. Defines basic API ... |
from polharmonic import util as myutil
from sympy import *
from sympy.physics.wigner import gaunt, wigner_3j, clebsch_gordan
kd = KroneckerDelta
import numpy as np
# Illumination
def hill(polarizer=True):
At = Symbol('At')
Bt = Symbol('Bt')
n0 = [1, 0, 0, -At/sqrt(5), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]... |
"""
Flappy Bird, but with a square instead
"""
import os
import sys
import random
import pygame as pg
SCREEN_SIZE = (640, 360)
TRANSPARENT = (0, 0, 0, 0)
TRIGGER = pg.K_SPACE
GRAVITY = -1
TERMINAL_VELOCITY = -10
class Box(object):
"""
This class defines the main player box.
"""
SIZE = (50, 50)
COLOR = pg.Color... |
#!/usr/bin/env python
from subprocess import Popen, PIPE
import tempfile
import os.path
import os
import json
import pysubs2
import argparse
import fnmatch
from scipy.io.wavfile import read
#import matplotlib.pyplot as plt
import numpy
from scipy.optimize import fmin
from scipy import signal, fftpack
temp = []
def... |
# coding: utf-8
from __future__ import unicode_literals
from .compat import get_bytes, quote, text
from .constants import MAX_RETRY, UPLOAD_CHUNK_SIZE
from .endpoint import APIEndpoint
from .exceptions import HTTPError, UploadError
from .models import Batch, Blob
from .utils import SwapAttr
try:
from typing impor... |
'''
Created on Sep 1, 2014
@author: theo
'''
import os,json
import numpy as np
import pandas as pd
from django.shortcuts import render, render_to_response, get_object_or_404
from django.template.loader import render_to_string
import settings
from forms import ScenarioForm
from models import Matrix
def home(request)... |
'''
Created on 27 Sep 2017
@author: orazio.angelini
'''
import numpy as np
from py_vollib.black_scholes import black_scholes
from sklearn.covariance import GraphLassoCV, GraphLasso
from modelinter.models.constants import Const, Paths
from modelinter.models.utils import lf, Pkl
tradingyear = 252
annualize = np.sqrt(t... |
import numpy as np
import scipy.misc
import h5py
import os
from px2graph.data.genome.driver import local as vg
data_dir = os.path.dirname(__file__)
class_labels, relationships = [], []
with open(data_dir + '/sorted_objects.txt', 'r') as f:
for line in f: class_labels += [line[:-1]]
with open(data_dir + '/sorted_p... |
# coding: utf-8
""" Class for reading data from SCF simulations """
from __future__ import division, print_function
__author__ = "adrn <<EMAIL>>"
# Standard library
import os
import glob
# Third-party
import astropy.units as u
from astropy import log as logger
from astropy.constants import G
from astropy.table imp... |
import logging
from time import gmtime, strftime
from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten, MaxPool2D, Dropout
from keras.optimizers import SGD
from keras.models import model_from_json
from keras.callbacks import ModelCheckpoint, EarlyStopping, TensorBoard, CSVLogger, Learning... |
"""
R help system.
"""
import sys, os
from collections import namedtuple
import sqlite3
import rpy2.rinterface as rinterface
from rpy2.rinterface import StrSexpVector
from rpy2.robjects.packages_utils import get_packagepath, _libpaths, _packages
from collections import OrderedDict
if sys.version_info[0] == 2:
... |
"""=============================================================
c:/1work/fsdviz/fsdviz/tests/common/test_PointPolygonCollection.py
Created: 20 Apr 2021 17:32:56
DESCRIPTION:
The PointPolygonCollection class provides a data container for
polygons associated with each point in a list of points. It is
us... |
import os
import random
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import StandardScaler
import inspect
current_path = os.path.realpath(inspect.getfile(inspect.currentframe()))
print(current_path... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import os
import sys
from bs4 import BeautifulSoup
import subprocess
from ricecooker.utils import downloader, html_writer
from ricecooker.chefs import SushiChef
from ricecooker.classes import nodes, files, questions, licenses
from ricecooker.config import LOGGER ... |
from waitress import serve
from flask import Flask, render_template, request, url_for, make_response
from time import strftime
import time
import datetime
import regex
import nltk
from nltk.stem.wordnet import WordNetLemmatizer
from nltk import FreqDist
from nltk import word_tokenize
from nltk.corpus import stopwords, ... |
#!/usr/local/bin/python
# -*- coding:utf-8 -*-
"""
@author: valor
@file: adb.py
@time: 2018/11/2 11:02
"""
import time
import os
import re
from plat import adb_path
from enum import Enum
import xml.etree.cElementTree as xmlParser
class By(Enum):
text = 'text'
content = 'content-desc'
naf = 'NAF'
... |
import time
def cross(A, B):
# concat of chars in string A and chars in string B
return [a + b for a in A for b in B]
digits = '123456789'
rows = 'ABCDEFGHI'
cols = digits
cells = cross(rows, cols) # 81 cells A1..9, B1..9, C1..9, ...
# unit = a row, a column, a box; list of all units
unit_list = ([cross(r... |
from asyncio import AbstractEventLoop
from asyncio import get_event_loop
from random import choice as choose
from re import search
from typing import Union
from urllib.parse import quote, urlencode
from aiohttp import ClientSession
from .classes import Image, RankCard, CrewMateColors
from .errors import BadRequest, H... |
# Copyright (c) 2015-2019 Data King Ltd
# See LICENSE file for license details
from django.core.exceptions import ValidationError
from django.db import models
from mptt.models import MPTTModel, TreeForeignKey
import collections
import datetime
import functools
import operator
import time
from . import display
clas... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
import numpy as np
from numba import jit, prange
from scipy.fftpack import fft2, next_fast_len
from dautil.util import zero_padding
from tail.numba_wrap import fftfreq
from tail.util import fill_nan, norm_fft, normalize_row
@jit(nopython=True, nogil=True, parallel=True)
def _bin_psd2(pixel_size, l_max, mask):
''... |
import pygame
import random
pygame.init()
sw = 640
sh = 480
half_sh = sh // 2
screen = pygame.display.set_mode((sw, sh))
icon = pygame.image.load('imgs/truck.png')
pygame.display.set_icon(icon)
pygame.display.set_caption("Truck V/S Car")
text_font_20 = pygame.font.Font("fonts/SF-Pro-Text-Regular.otf",... |
import requests
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
import os
import datetime
from datetime import date
import time
import random
import string
def crawling(date, product_id, type_, product_name, proxy=None):
start_time = time.time()
headers = {
'authority': 'www.appannie.com',
... |
import abc
import hashlib
import six
from django.http import HttpResponse
from rest_framework import generics, mixins, status
from rest_framework.parsers import FileUploadParser, MultiPartParser
from rest_framework.renderers import BrowsableAPIRenderer, JSONRenderer
from rest_framework.response import Response
from r... |
# Copyright 2021 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
from collections import namedtuple
from django import forms
from .models import FormHourly, FormDaily2, FormMonthly, FormSynoptic2Ra1
ValueFlag = namedtuple('ValueFlag', 'value flag')
class HourlyForm(forms.ModelForm):
class Meta:
model = FormHourly
labels = {
'id': '',
... |
"""
State machine for EAP-MD5 authentication flow
"""
import hashlib
import logging
import struct
import time
from flowsieve import eap_events, events
from flowsieve.packet import eap, eapol
from flowsieve.user_store import UserStore
from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.cont... |
import csv
from functools import partial
from torchtext.data import *
from transformers import BertTokenizer
import dill
import os
import timeit
from random import sample
from tqdm import tqdm
def load_split_datasets(path, fields):
with open(os.path.join(path, 'train.dill'), 'rb') as f:
train_examples = d... |
import asyncio
import numpy as np # type: ignore
import string
from datetime import datetime, timedelta
from collections import deque
from random import choice, random, randint
from typing import AsyncIterator, Deque, Iterator, List, Set
from ..exchange import Exchange
from ...core import Instrument, OrderBook, Order,... |
import numpy as np
import torch
import torch.nn as nn
def add_conv(in_ch, out_ch, ksize, stride):
"""
Add a conv2d / batchnorm / leaky ReLU block.
Args:
in_ch (int): number of input channels of the convolution layer.
out_ch (int): number of output channels of the convolution layer.
... |
#!/usr/bin/env python
################################################################################
# MIT License
# Copyright 2017-2020 <NAME>
################################################################################
# Python 2.7 and 3
from __future__ import print_function
# Load modules
import argparse... |
from functools import partial
import numpy as np
import torch
import torch.nn as nn
from models.modules import BinarisedWnConv2d, WnConv2d, softplus, WnConvTranpose2d, \
BinarisedWnLayer, Sign, Pass
# potential improvements
# - move resnet layers to same location as in bit-swap
# - make "scale" for latent layer... |
import torch
import torch.nn as nn
import torchvision.models as models
import torch.nn.functional as nn_F
import numpy as np
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, b... |
import os
import trimesh
import numpy as np
import pandas as pd
from enum import Enum
from matplotlib import cm
from urdfpy import URDF, JointLimit
from tools.utils import io
# from tools.visualization import Viewer
# override attributes to make effort, velocity optional
JointLimit._ATTRIBS = {
'effort': (float, ... |
'''Train CIFAR10 with PyTorch.'''
from __future__ import print_function
import argparse
import os
from datetime import datetime
import torch
import torch.backends.cudnn as cudnn
from torch.optim.lr_scheduler import CosineAnnealingLR
import torchvision.datasets as datasets
import torchvision.transforms as transforms
... |
import os.path
import pytest
import win32com.client
import win32com.client.selecttlb
import pythoncom
import nitsm.codemoduleapi
_standalone_tsm_context_tlb = win32com.client.selecttlb.FindTlbsWithDescription(
"NI TestStand Semiconductor Module Standalone Semiconductor Module Context"
)[0]
class PublishedData:
... |
from django.shortcuts import render
import requests
import base64
import json
import urllib.request
import wikipediaapi
import math
import re
import lyricsgenius
import time
import random
from login.models import Song, Album, Author, Profile, Fav
# Identifiants pour se connecter à 'API de Spotify
clientId = "5a3ae217e... |
from confduino import version, mculist
from easyprocess import Proc
from path import Path
from pyavrutils.avrsize import AvrSize
from pyavrutils.util import tmpdir, separate_sources, tmpfile, rename, \
CompileError
import logging
import os
log = logging.getLogger(__name__)
class ArduinoCompileError(CompileError)... |
import json
import sys
from enum import Enum
from functools import wraps
from logging import Logger
import requests
assert sys.version_info >= (3, 8), "Необходим Python 3.8+"
log = Logger("yandex-tool")
TITLES = {
'classwork': 'Классная работа',
'homework': 'Домашняя работа',
'additional': 'Дополнительны... |
"""A FUSE filesystem wrapper for the reMarkable."""
import os
import sys
from errno import *
from posix import O_WRONLY, O_RDWR
import stat
from fuse import FUSE, FuseOSError, Operations
from remarkable_fs.documents import Collection, Document, NewDocument
from io import BytesIO
import traceback
class FileHandles(obj... |
# -*- coding: utf-8 -*-
from django.contrib.auth.models import User, Group
from django.db.models import Q
from django.conf import settings
from googletrans import Translator
import datetime
from fms import tasks
from restapi.utils import AahoTranslator
def get_sms_template(instance, dest_lang, city_joiner, vehicle, r... |
from decimal import Decimal
from django.contrib.sessions.models import Session
from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
# Product Model
class Product(models.Model):
# Detail informations
name = models.CharField(verbose_name=_("Nom")... |
#!/usr/bin/env python3
import sys
import argparse
from datetime import datetime, timedelta, timezone
import json
import pandas as pd
from dateutil.parser import parse
DAY = timedelta(days=1)
WEEK = 7 * DAY
def day_int(bitmap):
return int(bitmap, 2)
SUNDAY = day_int('0000001')
WEEK_BITMAP = day_int('1' * 7)
def... |
from collections import defaultdict
from multiprocessing import Manager as IPCManager
from glycopeptidepy.structure.glycan import GlycanCompositionProxy
from glycan_profiling.task import TaskBase
from .scoring.signature_ion_scoring import SignatureIonScorer
from ..chromatogram_mapping import ChromatogramMSMSMapper
... |
import operator
from collections import OrderedDict, defaultdict
import numpy as np
import logging
from rl_agents.agents.common.factory import safe_deepcopy_env
from rl_agents.agents.dynamic_programming.value_iteration import ValueIterationAgent
from rl_agents.agents.tree_search.graph_based import GraphBasedPlannerAge... |
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import plotly.plotly as py
from plotly.graph_objs import *
from scipy.stats import rayleigh
from flask import Flask
import numpy as np
import pandas as pd
import os
import sqlite3
import... |
"""
Based on Haarnoja's TensorFlow SQL implementation
https://github.com/haarnoja/softqlearning
"""
import numpy as np
import torch
import torch.optim as optim
# from torch.autograd import Variable
from collections import OrderedDict
import robolearn.torch.utils.pytorch_util as ptu
from robolearn.algorithms.rl_alg... |
import time
import gevent
from gevent import sleep
from gevent import spawn, GreenletExit
from gevent.queue import Queue
from hashlib import sha256
from binascii import hexlify
from ..lib import Component, loop
from ..utils import time_format
from ..stratum_server import StratumClient
class Reporter(Component):
... |
import numpy as np
import tensorflow as tf
import matplotlib
matplotlib.use('TkAgg')
from matplotlib import pyplot as plt
from mpl_toolkits import mplot3d
from tensorflow.python import debug as tf_debug
# Returns uniformly generated numpy array with generate [ x | t | random] where x and t are shuffled
# Shape of the ... |
from propellant import Propellant, Propellant_Mix, Pressurant
from nist_reader import propellant_data
from numpy import pi
class Material(object):
def __init__(self,name,yield_strength,density):
self.name = name
self.yield_strength = yield_strength
self.density = density
class Vehicle(obje... |
#!/usr/bin/env python
# coding: utf-8
# # Asset Replacement Model
#
# **<NAME>, PhD**
#
# This demo is based on the original Matlab demo accompanying the <a href="https://mitpress.mit.edu/books/applied-computational-economics-and-finance">Computational Economics and Finance</a> 2001 textbook by <NAME> and <NAME>.
#... |
# The piwheels project
# Copyright (c) 2017 <NAME> <https://github.com/bennuttall>
# Copyright (c) 2017 <NAME> <<EMAIL>>
#
# 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 ... |
from dataclasses import dataclass
import weakref
from copy import deepcopy
from enum import Enum
from typing import Any, AsyncGenerator, Generic, TypeVar, cast
from aiohttp import ClientSession, ClientResponse
from aiohttp.client_exceptions import ContentTypeError
from .asyncy import end_loop_workaround #type: igno... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2013 Team-XBMC
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later versio... |
"""Test CLEVR dataset."""
from pathlib import Path
from unittest.mock import patch
import pytest
from pytorch_ssd.data.datasets.clevr import CLEVR
@pytest.fixture
def sample_scene_and_annotation():
"""Return sample scene dict with processed annotation."""
scene = {
"image_index": 0,
"objects... |
#!/usr/bin/env python
import cv2
import matplotlib.pyplot as plt
import numpy as np
EDGE_KERNELS = {
'rectangle': cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)),
'ellipse': cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)),
'cross': cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 5))
}
def display... |
import matplotlib.pyplot as plt
plt.rcParams['pdf.fonttype'] = 42
plt.rcParams['ps.fonttype'] = 42
plt.rcParams["font.family"] = "Arial"
import numpy as np
def circle_graph(market_share_dpos1, market_share_dpos2, market_share_dpos3,
market_share_mdpos_75_1, market_share_mdpos_75_2, market_share_mdpos... |
#!/usr/bin/env python3
import configparser
import argparse
import os
import sys
import subprocess
import git
from xdg.BaseDirectory import (xdg_data_home, xdg_config_home, xdg_cache_home)
# global constants
VERSION='1.1.0'
def parse_config (conf_file, conf):
if not os.path.exists (conf_file):
print (f'No... |
"""
Query-by-committee strategies.
"""
# Author: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
from copy import deepcopy
import numpy as np
from sklearn.utils.validation import check_array, _is_arraylike
from ..base import SingleAnnotPoolBasedQueryStrategy, SkactivemlClassifier
from ..utils import simple_batch, fit_if... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class MyGroupNorm(nn.Module):
def __init__(self, num_groups, num_channels):
super(MyGroupNorm, self).__init__()
self.num_channels = num_channels - num_channels % num_groups
self.num_groups = num_groups
se... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from ..registry import HEADS
from mmdet.models import builder
from mmdet.ops.roi_align_rotated import roi_align_rotated_cuda
import mmcv
import cv2
import mmcv
import numpy as np
import pycocotools.mask as mask_util
import torch
impor... |
# -*- coding: utf-8 -*-
import copy
import json
import random
from enum import Enum, unique
@unique
class LayerType(Enum):
attention = 0
self_attention = 1
rnn = 2
input = 3
output = 4
class Layer(object):
def __init__(self, type, input=None, output=None, size=None):
self.input = inpu... |
'''
Module : Main
Description : The main entry point for the program.
Copyright : (c) <NAME>, 2018
License : MIT
Maintainer : <EMAIL>
Portability : POSIX
Simple case-control analysis of CNVs by family.
Compare:
positive cases, negative cases, positive controls, negative controls
Using chi-squared t... |
import json
import operator
import functools
from datetime import timedelta
import firebase_admin
from firebase_admin import credentials, auth
from django.contrib.auth.models import User
from django.conf import settings
from django.db.models import Q
from django.shortcuts import render
from django.utils import timezone... |
import os
import pathlib
from urllib.error import HTTPError
from warnings import warn
import geopandas as gpd
import pandas as pd
def get_census_gdb(years=None, geom_level="blockgroup", output_dir="."):
"""Fetch file geodatabases of ACS demographic profile data from the Census bureau server.
Parameters
... |
from __future__ import absolute_import, print_function
import json
import numpy as np
import tensorflow as tf
from gym import spaces
from rltools import log, util
from rltools.algos.policyopt import TRPO, SamplingPolicyOptimizer, ConcurrentPolicyOptimizer
from rltools.baselines.linear import LinearFeatureBaseline
fr... |
# <NAME>
# Oct 14, 2019
# 66 test cases
# designed for elevation.py 2019 fall semester
import unittest
import elevation as e # require elevation.py file
class A2CheckerV2(unittest.TestCase):
def setUp(self):
self.m_1 = [[1]]
self.m_2 = [[2, 3],
[5, 1]]
self.m_3 = [[11... |
import itertools
from collections import OrderedDict
import os
import logging
from six.moves import configparser
from snmpagent_unity import cipher, enums, utils
from snmpagent_unity import exceptions as snmp_ex
LOG = logging.getLogger(__file__)
V2, V3 = enums.UserVersion.V2, enums.UserVersion.V3
def to_console_st... |
import os
os.environ["CUDA_VISIBLE_DEVICES"]="0"
import socket
import sys
import tensorflow as tf
import numpy as np
from data_loaders.zhangfeats_loader import zhangfeats_loader
from arch.layer_factory import layer_factory
flags = tf.flags
FLAGS = flags.FLAGS
flags.DEFINE_integer("feats_height", 28, "")
flags.DEF... |
"""
Implementation of an R-Max agent [Brafman and Tennenholtz 2003]
Use Value Iteration to compute the R-Max upper-bound following [Strehl et al 2009].
"""
import random
import numpy as np
from collections import defaultdict
from myrl.agents.agent import Agent
def compute_n_model_samples_high_confidence(epsilon, de... |
import numpy as np
import bqplot
from ..compatibility import ScatterGL, ImageGL
from glue.core.data import Subset
from glue.viewers.scatter.state import ScatterLayerState
from glue.core.exceptions import IncompatibleAttribute
from glue.viewers.common.layer_artist import LayerArtist
from ...link import dlink, on_chang... |
'''
Test routines for class LatLon3 in package LatLon3
Designed for use with pytest
Created on Sep 2, 2014
@author: gdelraye
'''
from builtins import str
import pyproj
from numpy import (exp, angle, deg2rad, rad2deg)
from numpy.testing import (assert_almost_equal, assert_equal)
from LatLon3.LatLon import (LatLon, ... |
import logging
from plan2scene.common.residence import Room, House
from plan2scene.config_manager import ConfigManager
from plan2scene.evaluation.matchers import AbstractMatcher
from plan2scene.utils.io import fraction_str
import numpy as np
class EvalResult:
"""
Accumulates evaluation results.
"""
... |
import numpy as np
import pandas as pd
import random
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense, Dropout, ActivityRegularization
from keras.wrappers.scikit_learn import KerasRegressor, KerasClassifier
from sklearn.model_selection import cross_val_predict
from skle... |
# -*- coding: utf-8 -*-
u"""Hellweg dump parser.
:copyright: Copyright (c) 2017 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
import ctypes
import math
_LIVE_PARTICLE = 0
_LOSS_VALUES = ['live', 'rad... |
# monkey patching solidpython to be more pythonic
import solid
from solid.utils import *
import os
import math
from typing import Union, List, Tuple, Callable
__version__ = "0.1.0"
def subseteq(x, y):
return (xset := set(x)) in y and list(xset) == list(x)
def ff_translate(self, x, y, z=0):
return solid.trans... |
import sys
import json
import h5py
import numpy as np
import warnings
from timeit import default_timer as timer
import torch
import torch.nn as nn
# from torch.autograd import Variable
import torch.nn.functional as F
import options
import misc.utilities as utils
from torch.utils.data import DataLoader
from sklearn.m... |
import pytest
@pytest.fixture
def config_v4_devices(api, utils):
"""Configure bgpv4 devices"""
config = api.config()
tx, rx = config.ports.port(
name="tx", location=utils.settings.ports[0]
).port(name="rx", location=utils.settings.ports[1])
tx_device, rx_device = config.devices.device(na... |
import os
import time
import math
import numpy as np
import random
import json
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd import Variable
from utils import to_gpu, Corpus, batchify, train_ngram_lm, get_ppl, create_exp_dir
from models import Seq2Se... |
"""
Copyright 2019 Inmanta
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 ... |
import csv
import random
import numpy as np
import matplotlib.pyplot as plt
import scipy.spatial
import math
def load_csv(filename):
'''
load data.
https://stackoverflow.com/questions/4315506/load-csv-into-2d-matrix-with-numpy-for-plotting
https://machinelearningmastery.com/index-slice-reshape-numpy-arrays-mac... |
from __future__ import annotations
from collections import defaultdict
from pathlib import Path
from typing import Union, Dict, Optional, List, Set, Sequence
from domain_classes.schema import Factory, get_dto
from domain_classes.dto import DTO
from restful import request_object as req
import zipfile
import io
from e... |
import numba.cuda as cuda
import numpy as np
import math
@cuda.jit
def mat_morph_mul_max_plus_impl(a, b, c, stmp, w, q, h):
row, col = cuda.grid(2)
tmp = stmp
if row < h and col < w:
for i in range(q):
val = a[row, i] + b[i, col]
tmp = max(tmp, val)
c[row, col] = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.