text stringlengths 3.07k 22.1k |
|---|
#!/usr/bin/env python
#
# Copyright 2014 <NAME>
#
# 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 ... |
"""Tests task scheduling and execution"""
import os
import sys
import asyncio
import threading
from pulsar.api import send, create_future
from pulsar.apps import rpc
from pq import api
CODE_TEST = '''\
import time
def task_function(N = 10, lag = 0.1):
time.sleep(lag)
return N*N
'''
PATH = os.path.dirname(_... |
import numpy as np, scipy.stats
import gym, torch, sysadmin
import wandb, argparse, itertools, os, glob, json
from vec_env.subproc_vec_env import SubprocVecEnv
from net import Net
from tqdm import tqdm
from config import config
# --------------------------------------------------------------------------------------... |
import xmltodict
import re
from collections import OrderedDict
bible = "!failed"
def set_bible(file_name):
global bible
try:
with open(file_name) as fd:
bible = xmltodict.parse(fd.read())
bible = bible['osis']['osisText']['div']
except KeyError:
raise Exception('Your xml OSIS bible is not correctly forma... |
import time
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import savefig
from sklearn import preprocessing
from sklearn.model_selection import KFold
from sklearn.naive_bayes import MultinomialNB
from sklearn import svm
from sklearn.ensemble import RandomForestCl... |
#!/usr/bin/env python
#
# <NAME>
#
from random import random, randint, uniform
import sys
from multiprocessing import Process, Value, Lock
import fileinput
import os
import time
import datetime
import numpy.random as nrand
from numpy import sort, append
from scipy.stats import binom
class DistributionType:
OTHER,... |
# Copyright 2016 The Johns Hopkins University Applied Physics Laboratory
#
# 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 ... |
# -*- coding: utf-8 -*-
import pandas as pd
import xlrd
def build_school_dict(report, district_name):
"""Builds school dictionary given the sheet and district name
:param report: xlrd sheet object
:param district_name: string (Northwest, North Central, Western, Northeast, Southwest, Sandhils, Southeast, Piedmont ... |
# -*- coding: utf-8 -*-
import unittest
class TestList(unittest.TestCase):
def test_indexed(self):
arr = [1, 2, 3]
self.assertEqual(3, arr[2])
self.assertEqual(2, arr[-2])
self.assertEqual(1, [1, 4, 5][0])
def test_slicing(self):
arr = [1, 2, 3, 4, 5]
self.asse... |
#parser.py
#<NAME> 2016
import scanner as sc
import sys
import pickle
#try parsing test file
#required datastructures
symbtab = [] #symbol table this is very ineficient MUST CHANGE
lhs = ''
next_address=0 #memory address pointer
ip =0 #instruction pointer for now it's going to hold the index of ... |
print(f'Loading {__file__}')
from ophyd import ( Component as Cpt, ADComponent, Device, PseudoPositioner,
EpicsSignal, EpicsSignalRO, EpicsMotor,
ROIPlugin, ImagePlugin, TransformPlugin,
SingleTrigger, PilatusDetector,
OverlayPlugin, FileP... |
# Jax implementation of a Linear Dynamical System
# Author: <NAME> (@gerdm), <NAME>(@karalleyna), <NAME> (@murphyk)
from jax import config
config.update("jax_default_matmul_precision", "float32")
import chex
import jax.numpy as jnp
from jax.random import multivariate_normal, split
from jax.scipy.linalg import solve
... |
from Scripts import graphiti
from Scripts import nx
import re
import fnmatch
import json
import random
def vec2_to_str(v):
return str(v[0]) + " " + str(v[1])
def vec3_to_str(v):
return str(v[0]) + " " + str(v[1]) + " " + str(v[2])
def vec4_to_str(v):
return str(v[0]) + " " + str(v[1]) + " " + str(v[2]) + ... |
import pandas as pd
import numpy as np
from abc import ABCMeta, abstractmethod
from concurrent.futures import ProcessPoolExecutor
from multiprocessing import cpu_count
from typing import Callable, Type, Dict
from rlbook.testbeds import Testbed
import warnings
from collections import namedtuple
import logging
from itert... |
import copy
import json
import logging
import math
import os
from typing import Any
from typing import Dict
from typing import List
from typing import Optional
from typing import cast
from allennlp.common import Params
from allennlp.common.checks import ConfigurationError
from allennlp.common.util import prepare_envir... |
import collections
import torch
import torch.nn.functional as F
from torch import nn
from torch.nn.utils import spectral_norm
import matplotlib.pyplot as plt
import numpy as np
# Code Description:
# U can choose nn.Softmax()[also change threshold from 0 to number greater then 0]
# or torch.norm to using different 0&... |
from __future__ import annotations
import enum
from typing import Iterable, List, Optional, Tuple, Union
from .dicerolls import roll_dice, DiceResult
from .items import (Armor, ArmorType, SimpleWeapon, MartialWeapon,
Weapon, WeaponType)
class HitType(enum.Enum):
FULL = enum.auto()
SHIELD_... |
# -*- coding: utf-8 -*-
#
# main.py
#
from machine import Pin, Signal, SPI, reset, ADC
from utime import sleep, ticks_ms
from max7219 import Matrix8x8
from network import WLAN, STA_IF
import symbols
import urequests as requests
import gc
# #############################################################################
#... |
#!/opt/conda/bin/python
import argparse
import glob
import json
from collections import Counter
import os
from bs4 import BeautifulSoup
import requests
from datetime import datetime
def extract_metadata():
try:
os.makedirs('/EDR/search_engine/records')
except:
pass
path=sorted(glob.glob('/data/col... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import os.path
import sys
import re
import subprocess
import shutil
import json
# TODO
# parallel tests
# clean up / refactor
# *.act in CMAKE_BINARY_DIR
# boost tests
# choose tests by regex
# simplelinecheck: check every line without: check-line/modify-line a... |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... |
'''
Backpropagation and training a neural network by a TensorFlow custom estimator
-How are the network parameters in the optimisation initialised: with random values?
ex3_nn.py shows you how to initialise them any way you like.
-Can I add regularisation?
I haven't found out yet how to include the network weights in ... |
import json
from django.db import models
from django.core import serializers
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from .fields import GravityField, ColorField
from .managers import IngredientManager
__all__ = (
'BaseStockModel',
'BaseMalt', 'Base... |
# -*- coding: utf-8 -*-
# Copyright (C) 2012, <NAME>
#
# Visvis is distributed under the terms of the (new) BSD License.
# The full license can be found in 'license.txt'.
""" Module motion
Defines the class to create animated data.
"""
import visvis as vv
from visvis import Wobject, Timer
class MotionMixin(object... |
from __future__ import absolute_import
from .limits import INT32_MIN, INT32_MAX, UINT32_MAX, INT64_MIN, INT64_MAX, UINT64_MAX
_number_types = [int]
try:
_number_types.append(float)
except NameError:
pass
try:
_number_types.append(long)
except NameError:
pass
_number_types = tuple(_number_types)
clas... |
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-#
"""
Garbage Collection of all Functions used or will be used in this Programm (this is my Code)"
!!! The update.py isn't made by myself (I just improved it lol) !!!
I know my english is awesome :)
"""
from subprocess import Popen, PIPE
import os
import sys
import funct... |
import numpy as np
from relations import Relations
def pretty_print_eval_map(result_map):
s,_ = pretty_print_eval_map_rec(result_map, '')
return s
def pretty_print_eval_map_rec(result_map, spaces):
assert type(result_map) is dict
if type(list(result_map.values())[0]) is str or type(list(result_map.val... |
from google.appengine.ext import db
import datetime
import markdown
from libs import PyRSS2Gen
import logging
import md5
import layer_cache
from google.appengine.api import memcache
class BaseModel(db.Model):
pass
class Tag(BaseModel):
tag = db.StringProperty()
class NewsItem(BaseModel):#Which in ... |
import math
# I plan on fixing the bad variable
# names later - this is the result of my whiteboard math!
# At Q=0 is the nose, and at Q=Lp is the end of the tail.
# Q is used as the location on the plane, on the axis from front to back.
Qw = None # wing location
Qvc = None # tail location
Qcl = None # center of... |
import matplotlib.pyplot as plt
import numpy as np
import cv2
from features import single_img_features, get_hog_features, bin_spatial, color_hist
# Functions reproduced from Search and Classify lesson
# Define a function that takes an image,
# start and stop positions in both x and y,
# window size (x and y dimensio... |
import argparse
import collections
import numpy as np
import torch
import torch.optim as optim
from torchvision import transforms
from retinanet import model
from retinanet.dataloader import CocoDataset, FLIRDataset, CSVDataset, collater, \
Resizer, AspectRatioBasedSampler, Augmenter, \... |
#!/usr/env python
#
# binary_search_tree.py - implementation of a binary search tree of Integers
class Node:
"""This class represents a single
Node of a binary search tree."""
def __init__( self, value ):
"""Constructor, initializes the attributes."""
self.value = value
self.bfs... |
# Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com)
from __future__ import annotations
import ast
import sys
from ast import (
AST,
ClassDef,
FunctionDef,
AsyncFunctionDef,
NodeVisitor,
ImportFrom,
Module,
Name,
)
from types import CodeType
from typing import Op... |
import logging
from collections import Counter
from typing import List
import networkx as nx
from synse.base import BaseGraph
from synse.sbn import SBN_EDGE_TYPE, SBN_NODE_TYPE, SBNGraph
from synse.ud import UD_EDGE_TYPE, UD_NODE_TYPE, UDGraph
from synse.ud_spec import UDSpecBasic
logger = logging.getLogger(__name__... |
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.3.0
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # データの確認
# ## 事前設定
# defa... |
import numpy as np
import vtk
import pyvista as pv
from ..common import readBinaryArray, Profile, vCutter
from ..numtools import makeRotationTensor
import warnings
def binaryVelbar(velbar_path) -> np.ndarray:
"""Get velbar array from binary file.
Wrapping around vpt.readBinaryArray. Assumes that the number of... |
import os
import json
import wget
import xlrd
def download_allgemeine_Schulen():
allgemeine_Schulen = 'allgemeine_Schulen.xlsx'
url_allgemeine_Schulen = 'https://statistik.hessen.de/sites/statistik.hessen.de/files/Verz-6_19.xlsx'
wget.download(url_allgemeine_Schulen, allgemeine_Schulen)
workbook ... |
"""
This is the core connection manager.
"""
import time
from socket import socket, AF_INET, SOCK_STREAM
try:
import thread
except ImportError:
import _thread as thread
def colorize(text, color):
"""
Adds color (code @color) to text @text, which can then be embedded in a
message.
"""
# \x... |
import os
import re
from cStringIO import StringIO
from unittest import TestCase
import nose
import numpy as np
from numpy.testing.decorators import slow
from pandas.io.html import read_html, import_module
from pandas import DataFrame, MultiIndex
from pandas.util.testing import assert_frame_equal, network
def _ski... |
import numpy as np
import matplotlib.pyplot as pl
import h5py
import platform
import os
from ipdb import set_trace as stop
from astropy.io import fits
import scipy.io as io
import time
import matplotlib.animation as manimation
os.environ["KERAS_BACKEND"] = "tensorflow"
if (platform.node() != 'vena'):
os.environ["... |
import datetime
import math
from decimal import ROUND_HALF_UP, Decimal
from django.core.cache import cache
from django.db import models
from django.db.models import Count, Max, Min, Q, Sum
from django.utils import timezone
from .crawler import QuotesIEX
def find_quote_day(date, days_ago=0, type='earlier'):
"""
... |
#!/bin/false
# Copyright (c) 2022 <NAME>. 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 above copyright notice, this list of conditions and th... |
import math
import bdgmath as m
class ClipVolume:
def clipPolyLines(self, polyLines):
newPolyLines = []
for p in polyLines:
newPolyLines += self.clipPolyLine(p)
return newPolyLines
def clipPolyLine(self, polyLine):
# for each segment, generate a list of intersec... |
#!/usr/bin/env python3
import ctypes
import json
import math
import threading
import time
import hid
import keyboard
_default_config = {
'general': {
'blinking_times': 3,
'blinking_speed': .1,
},
'controller': {
'vendor_id': 0x054c,
'product_id': 0x1000,
'1': 'playe... |
import torch
import torch.nn as nn
from torch.autograd import grad
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import pickle
import copy
class TwoChannel(nn.Module):
def __init__(self, a_center=None, b_center=None,
bc=('dirichlet', 0),
dtype=torch.float32... |
'''
implement training process for Light CNN
@author: <NAME>
@date: 2017.07.04
'''
from __future__ import print_function
import argparse
import os
import shutil
import time
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils... |
import ast
from collections import ChainMap
from numbers import Number
from operator import add, sub, mul, truediv, floordiv, mod
import attr
__all__ = ('AST', 'Module', 'Assign', 'If', 'Const', 'Slot', 'BoolOp', 'BinOp', 'Compare', 'Call', 'Label')
class AST:
pass
@attr.s
class Module(AST):
body = attr.i... |
"""
MIT License
Copyright (c) 2020 - µYert
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distr... |
import numpy as np
import openmdao.api as om
from ccblade.utils import get_rows_cols
class SimpleInflow(om.ExplicitComponent):
def initialize(self):
self.options.declare('num_nodes', types=int)
self.options.declare('num_radial', types=int)
self.options.declare('dynamic_coloring', types=bo... |
import sys, pygame
import gamestate as gs
import random
pygame.init()
size = width, height = 800, 500
speed = [1, 1]
black = 0, 0, 0
screen = pygame.display.set_mode(size)
wolf = pygame.image.load("wolf.png")
wolfrect = wolf.get_rect()
sheep = pygame.image.load("sheep.png")
sheeprect = sheep.get_rect()
ticks = py... |
import os
import tempfile
import unittest
import time
import numpy as np
import tensorflow as tf
import tf_encrypted as tfe
from tf_encrypted.operations.secure_random import secure_random
from tf_encrypted.protocol.aby3 import ABY3
from tf_encrypted.protocol.aby3 import ARITHMETIC
from tf_encrypted.protocol.aby3 impor... |
"""
Cubic symmetric graphs with more than 102 vertices. The lettering for graphs of the
same order follows Conder's list (https://www.math.auckland.ac.nz/~conder/symmcubic2048list.txt),
which sorts by arc-transitivity, not Foster's list.
"""
from mpmath import *
from shibuya.generators import cu, star_radius
from shibu... |
"""
Super biblioteca pro tmp117 com a raspberry.
developed by italogsfernandes.github.io
"""
import smbus
Temp_Result_Register = 0x00 # 8000h Temperature result register
Configuration_Register = 0x01 # 0220h Configuration register
THigh_Limit_Register = 0x02 # 6000h Temperature high limit register
TLow_Limit_Regis... |
# this is to cater for Python 2, is it really needed?
try:
from inspect import getfullargspec
except ImportError:
from inspect import getargspec as getfullargspec
try:
from PIL import Image, ImageTk
PIL_AVAILABLE = True
except ImportError:
PIL_AVAILABLE = False
from tkinter import PhotoImage, Tcl... |
import numpy as np
import pandas as pd
from scipy import stats
import seaborn as sns
import matplotlib.pyplot as plt
import scipy.stats
from pandas_profiling import ProfileReport
from utils import tools as t
class Preprocess:
"""Exploratory Data Analysis of the input dataframe.
Parameters
----------
... |
import imgaug.augmenters as iaa
import numpy as np
import cv2
import random
from os import listdir
from os.path import isfile, join
truncate_fg=True,
change_back_ground_prob=0.5
color_aug_prob=0.8
image_augmentations_lm=(
iaa.Sequential([
iaa.Sometimes(0.4, iaa.CoarseDropout( p=0.1, size_perc... |
#!/usr/bin/env python
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense, Embedding, Dot, Flatten, Concatenate, Dropout, Lambda, Subtract
from tensorflow.keras.initializers import Initializer, RandomNormal, Zeros, Ones
from tensorflow.keras.constraints import Constraint, UnitNo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 15 19:29:10 2019
@author: skoebric
"""
import pandas as pd
keep_columns = {'control_reg':'first',
'control_reg_id':'first',
'state':'first',
'state_id':'first',
'departamento':'first'... |
import time
def generate_mock_c(file_name, include_path, fun_data):
mock_c = top_comment_generate(file_name)
mock_c += includes_generate(file_name, include_path)
for fun in fun_data:
mock_c += struct_params_generate(file_name, fun[0], fun[1])
mock_c += struct_internal_generate(file_name, ... |
#!/usr/bin/env python3
# Common Imports
import rospy
import roslib
from harmoni_common_lib.constants import State
from harmoni_common_lib.service_server import HarmoniServiceServer
from harmoni_common_lib.service_manager import HarmoniServiceManager
import harmoni_common_lib.helper_functions as hf
# Specific Imports... |
import time
import numpy as np
import matplotlib.pyplot as plt
from simple_pid import PID
from scipy.interpolate import interp1d
class Pid_location(object):
def __init__(self, exp_val, kp, ki, kd):
self.KP = kp
self.KI = ki
self.KD = kd
self.exp_val = exp_val
self.now_val =... |
from tkinter import ROUND
import pandas as pd
import discord
from discord.ext import commands
from discord_slash import SlashCommand, SlashContext
from discord_slash.utils.manage_commands import create_choice, create_option
from typing import Optional
import os
import numpy as np
import re
THRESHOLD_SCORE = 20
WHITELI... |
"""
Collection of data validators.
Many of these validators are heavily inspired by those from marshmallow.
https://marshmallow.readthedocs.io/en/stable/marshmallow.validate.html
"""
from __future__ import annotations
import inspect
import warnings
from abc import ABCMeta, abstractmethod
from collections.abc import C... |
import torch
import numpy as np
import cv2
import os
from ...utils import CS, normalize_image, meani_list
class CSPointDataset(torch.utils.data.Dataset):
def __init__(self, image_root, data_list, segment_root, target_size,
rand_crop=False, rand_mirror=False, rand_scale=None, return_src=False,
... |
# Copyright 2017 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 ... |
import numpy as np
from tqdm import tqdm
import torch
from torch.nn import *
import torch.optim as optim
from torch.optim.lr_scheduler import LambdaLR
from torch.utils.data.dataloader import DataLoader
# this code is adapted from the minGPT code written by <NAME>
# https://github.com/karpathy/minGPT
class GPT(Modu... |
import tensorflow as tf
import math
from hmc import hmc
from tensorflow.python.platform import flags
from torch.utils.data import DataLoader
from models import DspritesNet, ResNet32, ResNet32Large, ResNet32Wider, MnistNet
from data import Cifar10, Mnist, DSprites
from scipy.misc import logsumexp
from scipy.misc import ... |
import discord
from discord.ext import commands
from datetime import datetime
import json
import tracemalloc
tracemalloc.start()
base_color=0x3498db
su_color=0x2ecc71
err_color=0xe74c3c
null_color=discord.Color.from_rgb(47,49,56)
class root(commands.Cog):
def __init__(self, Bot):
self.Bot = Bot
... |
from playTypes import noplay, puntplay, kickoffplay, fieldgoalplay, beginplay
from playTypes import patplay, tbdplay, safetyplay, fumbleplay, touchdownplay
from playTypes import timeoutplay, endplay, sackplay, rushingplay, passingplay
# create logger
import logging
module_logger = logging.getLogger('log.{0}'.format(__... |
import usb.core
import usb.util
import numpy
import logging
from .classes import AbstractPush2Section
from .exceptions import Push2USBDeviceConfigurationError, Push2USBDeviceNotFound
from .constants import ABLETON_VENDOR_ID, PUSH2_PRODUCT_ID, USB_TRANSFER_TIMEOUT, DISPLAY_FRAME_HEADER, \
DISPLAY_BUFFER_SIZE, DISPLA... |
"""
the string "eyaxx" in hex is 101 121 97 120 120, which translates to
eyiyaxxx iyayayaxxxx uyaxx iyayayaxxx iyayayaxxx
Rules:
This language "eyaxx" basically only cares about powers of 2.
2 ay (just y if it's leading a word)
4 ey
5 ex
8 iy
16 oy
32 uy
Now, if a number n is of the form n = 2^k * m, where m is ... |
# Modified based on the HRNet repo.
import logging
import os
import time
import numpy as np
import sys
import numpy as np
import numpy.ma as ma
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.distributed as dist
from torch.nn import functional as F
from utils.utils import AverageMeter
from uti... |
"""Modified from Pytorch Image Models (https://github.com/rwightman/pytorch-image-models/)"""
import argparse
from datetime import datetime
import logging
import os
import sys
import time
import torch
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as NativeDDP
import torch.utils... |
import json
import networkx as nx
import matplotlib.pyplot as plt
import scipy as sp
import numpy as np
import collections
from copy import deepcopy
def get_type_dict(kb_path):
"""
Specifically, we augment the vocabulary with some special words, one for each of the KB entity types
For each type, the corr... |
#Ref: <NAME>
"""
Gaussian
Bilateral, Total variation filter, Wavelet denoising filter
Shift invariant wavelet
Anisotropic diffusion
NLM - Skimage
NLM - opencv
BM3D Block-matching and 3D filtering
Markov random field
The 3 top denoising algorithms for MRI denoising are
NLM, Bilateral, block-match and 3D filtering (B... |
"""
``otf.pack.bin``: msgpack based binary format
=============================================
Encode values in a binary format.
The binary format used is an extension of `MessagePack <https://msgpack.org/>`_
"""
from __future__ import annotations
import pickle
import typing
if typing.TYPE_CHECKING: # pragma: no... |
#!/usr/bin/env python
import logging
from ..comm import Capability
from ..link import GlobalBroadcast
from ..apdu import WhoIsRequest, IAmRequest, IHaveRequest, SimpleAckPDU
from ..errors import ExecutionError, InconsistentParameters, \
MissingRequiredParameter, ParameterOutOfRange
from ..task import call_later
_... |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from pandora.impl.pytorch import utils
class RNNEncoder(nn.Module):
"""RNN Character level encoder of the focus token"""
def __init__(self, num_layers, input_size, hidden_size, dropout=0.0,
... |
import unittest
import os
import unfurl.manifest
from unfurl.yamlmanifest import YamlManifest
from unfurl.localenv import LocalEnv
from unfurl.job import Runner, JobOptions
from unfurl.support import Status, _getbaseDir, RefContext
from unfurl.configurator import Configurator
from unfurl.util import sensitive_str, API_... |
import warnings
from pathlib import Path
import numpy as np
import torch
import ool.data.utils
import ool.env
from ool.data.mmnist import FlatMnist
from ool.data.multi import ModDataset, FilteredDataset, WrappedCLEVRTEX
from ool.data.pascal import PascalVOC
from ool.data.transforms import Resize, MaxObjectsFilter, Ch... |
# -*- coding: utf-8 -*-
from sanic import Sanic, response
import aiohttp
import asyncio
from aioconsole import ainput
from json import loads
import yaml
import logging
import os
from websockets.exceptions import ConnectionClosed
from urllib.parse import urlparse
import socket
import aiosqlite
import math
from async... |
"""
A module for calculating dry spell events from time series of
precipitation and near-surface air temperature.
"""
from __future__ import print_function, division
import numpy as np
import netCDF4 as nc
from cftime import utime
from . import (FMDI, _PR_MAX, _TAS_MIN, _DURATION_MIN, _DURATION_ANTE,
... |
import os
import pandas as pd
import numpy as np
import tensorflow as tf
import tensorflow.keras as tfk
import gc
import pickle
from conf import cat_feats, REFINED_PATH, useless_cols, MODELS_PATH
tfkl = tfk.layers
K = tfk.backend
np.random.seed(42)
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
## e... |
from django import template
from django.db.models import Q
from django.utils.html import format_html
from spectator.core import app_settings
from ..models import Publication, Reading
from .. import utils
register = template.Library()
@register.simple_tag
def annual_reading_counts(kind="all"):
"""
Returns a... |
import pandas as pd
from pandas_datareader import data as pd_data
import numpy as np
import matplotlib.pyplot as plt
p = print
google = pd.read_csv('data/goog.csv', index_col='Date', parse_dates=True)
def data_intro():
p(pd.__version__)
p(google)
start = pd.Timestamp('2010-1-1')
end = pd.Timestamp... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
from tensorflow.keras.layers import Input, Flatten, concatenate
from tensorflow.keras.models import Model, Sequential
from tensorflow.keras.layers import BatchNormalization
from tensorflow.keras.layers import LeakyReLU
from tensorflow.keras.layers import Conv3D, MaxPool... |
#!/usr/bin/env python
# Templating for Arm Robot
import em
import rospkg
import os
import math
import yaml
import copy
def init_joint():
joint = {
'name' : '',
'type' : '',
'parent' : '',
'child' : '',
'limit' : 0,
'ox' : 0,
'oy' ... |
#!/usr/bin/env python
# coding: utf8
"""
Renderer for the keyboard and the text box used to display
the current text.
"""
import os.path as osp
import pygame # pylint: disable=import-error
from . import vkeys
def fit_font(font_name, max_height):
"""Set the size of the font to fit the given height.
This f... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import LinearSegmentedColormap
import capsule_distance
capsule = capsule_distance.Capsule(0.18, -0.5, 0.45)
k_robot = 0.25
k_pedestrian = 0.5
dt = 0.05
def integrate_reference_motion(xy_zero, gain_k, xy_ref, dt):
# ... |
""" Extra questions for Lab 08 """
from lab08 import *
# OOP
class Keyboard:
"""A Keyboard takes in an arbitrary amount of buttons, and has a
dictionary of positions as keys, and values as Buttons.
>>> b1 = Button(0, "H")
>>> b2 = Button(1, "I")
>>> k = Keyboard(b1, b2)
>>> k.buttons[0].key
... |
# INTs, FLOATs --------------------------------------------------------------
my_int = 89
my_float = 9.8
# methods
float(57)
int(390.8)
abs() # absolute value of a number from null
my_int // my_float # floor division, returns a quotient
my_int % my_float # modulo division, returns a remainder
# finding the quotient ... |
# Copyright (c) 2018, The Regents of the University of California
# 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
# notice, thi... |
#!/usr/bin/env python3
# Copyright 2021 Xiaomi Corporation (Author: <NAME>)
# Apache 2.0
import argparse
import logging
import os
from pathlib import Path
from typing import Union
import k2
import torch
from snowfall.common import average_checkpoint, store_transcripts
from snowfall.common import get_texts
from snow... |
# -*- coding: utf-8 -*-
'''
.. _module_mc_salt:
mc_salt / salt related helpers
================================
'''
# Import salt libs
import mc_states.api
import random
import copy
import os
import logging
import sys
from mc_states.grains import makina_grains
from mc_states.version import VERSION
from distutils.ve... |
"""
avg_group:
name: name of the group (str)
configs: list of train/test pairs
sid_list_train: list of train SIDs for this config (list of str)
sid_list_test: list of test SIDs for this config (list of str)
cv_group:
name: name of the group (str)
n_train: number of SIDs to use for trai... |
#<Buscador medicamentos OpenFDA>
#Copyright (C) <2017> <<NAME>>
#
#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
#any later version.
#
#This program is distri... |
import sys, inspect, torch
from contextlib import contextmanager
def overfit(trainer, data, batch_size, epochs=1, metric='loss', **kwargs):
r"""Runs training on small samples of the dataset in order to overfit.
If you can't overfit a small sample, you can't model the data well.
This debugger tries to ove... |
from enum import *
import constid
import bels
class NextpnrPipType(Enum):
TILE_ROUTING = 0
SITE_ENTRANCE = 1
SITE_EXIT = 2
SITE_INTERNAL = 3
LUT_PERMUTATION = 4
LUT_ROUTETHRU = 5
class NextpnrBelPin:
def __init__(self, bel, port):
self.bel = bel
self.port = constid.make(port)
class NextpnrWire:
def __ini... |
# -*- coding: utf-8 -*-
"""
This package contains object classes and functions to access the Ionic Liquids Database - ILThermo (v2.0)
from NIST (Standard Reference Database #147) within Python.
Concept
-------
The :func:`pyilt2.query` function uses the *requests* module to carry out the query on the NIST server.
The ... |
from sklearn.metrics import classification_report, f1_score, cohen_kappa_score, accuracy_score
from sklearn.preprocessing import LabelEncoder, StandardScaler, MinMaxScaler
from sklearn.model_selection import train_test_split
import os
import time
import random
import numpy as np
import pandas as pd
import matplotlib a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.