text stringlengths 3.07k 22.1k |
|---|
# Copyright 2021 The Distla 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 ... |
'''This module contains classes used by pool core to interact with the rest of the pool.
Default implementation do almost nothing, you probably want to override these classes
and customize references to interface instances in your launcher.
(see launcher_demo.tac for an example).
'''
import time
from twisted.... |
##
# .driver.dbapi20 - DB-API 2.0 Implementation
##
"""
DB-API 2.0 conforming interface using postgresql.driver.
"""
threadsafety = 1
paramstyle = 'pyformat'
apilevel = '2.0'
from operator import itemgetter
from functools import partial
import datetime
import time
import re
from .. import clientparameters as pg_param... |
''' Mesh analysis '''
import numpy as np
from scipy import sparse
FLOAT64_EPS = np.finfo(np.float64).eps
FLOAT_TYPES = np.sctypes['float']
white = 0
red = 1
black = 2
green = 3
def sym_hemisphere(vertices,
hemisphere='z',
equator_thresh=None,
dist_thresh=None... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Commonly used utility functions."""
# mainly backports from future numpy here
from __future__ import absolute_import, division, print_function
import numpy as np
import nibabel as nib
def thresholding_abs(A, thr, smaller=True, copy=True):
"""thresholding of the adjac... |
"""
Procedures for running a privacy evaluation on a generative model
"""
from sklearn.metrics import roc_curve, auc
from os import path
from numpy import concatenate, mean, ndarray
from pandas import DataFrame
from pandas.api.types import is_numeric_dtype
from multiprocessing import Pool
from synthetic_data.privacy_... |
'''
Parse input args, parse task file
'''
import argparse,json,logging,sys
import db
'''Variables whose values will be set by the following init() or init_by_cmd_line_args() function.'''
action = None #what action to do
task = None #task infomation
group_int_list = [] #group integer list of task
''' Fun... |
import numpy as np
import tensorflow as tf
def set_seed(x):
"""
Set seed for both NumPy and TensorFlow.
"""
np.random.seed(x)
tf.set_random_seed(x)
def check_is_tf_vector(x):
if isinstance(x, tf.Tensor):
dimensions = x.get_shape()
if(len(dimensions) == 0):
raise Typ... |
################################################################################
import sys, types, os
from xml.etree.ElementTree import Comment, ProcessingInstruction, QName
from xml.etree.ElementTree import _encode, _escape_cdata, _escape_attrib
from xml.etree.ElementTree import ElementTree, Element, _ElementInterf... |
from pyramid.httpexceptions import (
HTTPBadRequest,
HTTPFound,
)
from pyramid.security import (
remember,
forget,
)
from deform import Form, ValidationFailure, Button
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm.exc import NoResultFound
from .models import SASession, BaseUser
from .for... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2010-2012 <NAME>
from os import urandom
import datetime
from django.db.models import *
from django.utils.translation import ugettext_lazy as _
from django.urls import reverse
from django.core.validators import validate_comma_separated_integer_list
ACCOMMNIGHTS_CHOICES = (
(... |
# Copyright Amazon.com, Inc. or its affiliates. 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
#
# Unl... |
"""
.. module:: sparse_rep
.. moduleauthor:: <NAME>
.. moduleauthor:: <NAME>
The original SparsePZ code to be found at https://github.com/mgckind/SparsePz
This module reorganizes it for usage by DESC within qp, and is python3 compliant.
"""
__author__ = '<NAME>'
import numpy as np
from scipy.special import voigt_prof... |
# coding=utf-8
"""
Compute TaskEmb for classification/ regression/ question-answering tasks (Vu et al., 2020).
Adapted from https://github.com/tuvuumass/task-transferability.
"""
import argparse
import logging
import os
from dataclasses import dataclass
import numpy as np
import torch
from torch.distributions.normal ... |
# Copyright 2021 The TF-Coder Authors.
#
# 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 sys
import os
import logging
import datetime
import datetime
import json
import traceback
import copy
import random
import string
import gzip
import asyncio
from pathlib import Path
from collections.abc import Iterable
import discord
from tqdm import tqdm
__version__ = "0.3.3"
PBAR_UPDATE_INTERVAL = 100
PBAR_... |
#!/usr/bin/env python
# coding: utf-8
# # Aging Setup Data Prep
# ### Imports
import os
import io
import sys
import re
import glob
import math
import logging
import numpy as np
import pandas as pd
from bric_analysis_libraries import standard_functions as std
# ## Data Prep
# convenience functions
def sample_... |
import base64
import os
import arrow
import httpx
import streamlit as st
import sweat
from bokeh.models.widgets import Div
import pandas as pd
import datetime
APP_URL = os.environ["APP_URL"]
STRAVA_CLIENT_ID = os.environ["STRAVA_CLIENT_ID"]
STRAVA_CLIENT_SECRET = os.environ["STRAVA_CLIENT_SECRET"]
STRAVA_AUTHORIZATI... |
#!/usr/bin/env python3
import argparse
import codecs
import operator
import re
import sys
from datetime import datetime, timedelta
timestamp_format = '%b %d %H:%M:%S'
line_pattern = re.compile(r"""
(?P<timestamp>\w+\s+\d+\s+\d+:\d+:\d+)\s+ # timestamp: Oct 8 07:02:22
(?P<hostname>\w+)\s+ ... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 5 01:30:35 2020
@author: a
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
from torch.autograd import Function
from matplotlib import pyplot as plt
from itertools import product
EPS =... |
class World(object):
pass
class Field(object):
pass
from typing import Union
import numpy as np
import random
import math
from tocenv.env import TOCEnv
import tocenv.components.item as items
import tocenv.components.agent as agent
import tocenv.components.skill as skills
import tocenv.components.block as... |
import pathlib
import tempfile
import cairo
from gi.repository import Pango, PangoCairo
from Definitions import *
import subprocess
import Colour
end_cap_round = object()
class Canvas:
def __init__(self, corner, width, height, surface=None, context=None):
"""Create a new drawing surface.
corne... |
import torch
import torch.nn as nn
from torch.utils.data import Dataset
import numpy as np
RICO_LABELS_LOWER = [
'text',
'image',
'icon',
'list item',
'text button',
'toolbar',
'web view',
'input',
'card',
'advertisement',
... |
import sys
import cv2
import math
import os
import json
import pandas as pd
import numpy as np
import json
stroke_data = {
"data" : []
}
stroke_data_ = open('result.json', 'r')
stroke_data = json.loads(stroke_data_.read())
print(stroke_data['data'])
stroke_data_.close()
speed_for_each_stroke = {}
def read_coor... |
#
# Copyright (c) 2021 Project CHIP Authors
#
# 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 i... |
import pandas as pd
import os
def prepare_legends(mean_models, models, interpretability_name):
bars = []
y_pos = []
index_bars = 0
for nb, i in enumerate(mean_models):
if nb % len(models) == int(len(models)/2):
bars.append(interpretability_name[index_bars])
index_bars +=... |
# https://github.com/Womsxd/YuanShen_User_Info
import os
import re
import sys
import json
import time
import string
import random
import hashlib
import requests
from settings import *
def md5(text):
md5 = hashlib.md5()
md5.update(text.encode())
return md5.hexdigest()
# Github-@lulu666lulu https://github... |
import math
import copy
import numpy as np
import torch.nn as nn
import torch
import torch.nn.functional as F
from torch.nn import CrossEntropyLoss
from transformers import RobertaTokenizer, RobertaModel, BertModel, BertForMaskedLM, BertConfig, RobertaForMaskedLM
MAX_LENGTH = 512
class CrossEntropy(nn.Module):
... |
import torch
import torch.nn as nn
from loss_functions import AngularPenaltySMLoss
class Stem_layer(nn.Module):
def __init__(self, in_ch, out_ch, kernel_size, drop_rate, pool_size):
super().__init__()
dilation = 1
self.conv = nn.Conv1d(
in_ch,
out_ch,
ke... |
from netCDF4 import Dataset
from numpy import *
import os
import sys
from scipy.interpolate import NearestNDInterpolator, RegularGridInterpolator
sose_path = os.path.join(os.environ['projdir'],'data','preprocessing','external','sose')
sys.path.append(sose_path)
from mds import *
import scipy.io as sio
run = 'waom2'
#... |
"""
Module allows the grabbing of dose rate factors for the calculation of radiotoxicity. There are four dose rates provided:
1. external from air (mrem/h per Ci/m^3)
Table includes: nuclide, air dose rate factor, ratio to inhalation dose (All EPA values)
2. external from 15 cm of soil (mrem/h per Ci/m^2)
T... |
import pickle
import numpy as np
import tensorflow as tf
import librosa
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from mpl_toolkits.axes_grid1 import make_axes_locatable
import os
import json
import glob
from Input import Input
import Models.UnetAudioSeparator
import Models.UnetSpectrogramSep... |
import loja_funcoes_auxiliares as aux
def adicionar_produto_carrinho(estoque, carrinho):
"""
Adiciona um produto do estoque ao carrinho (se nao estiver adicionado ainda)
:param estoque: lista com o estoque mais atualizado
:param carrinho: lista com carrinho de compras mais atualizado
:retu... |
import torch
from torch import nn as nn
from typing import Any
from collections import OrderedDict
import pandas as pd
class Trader(nn.Module):
def __init__(self, days, state_size=7):
super(Trader, self).__init__()
self.days = days
self.state_size = state_size
self.buyer = self._c... |
import sys
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from utils.modules.vggNet import VGGFeatureExtractor
class TVLoss(nn.Module):
def __init__(self, weight=1.0):
super(TVLoss, self).__init__()
self.weight = weight
self.l1 = nn.L1Loss... |
import time
import pymsteams
from datetime import datetime
from reporter.reporter import generate_report
from services.billing_service import BillingService
from services.folders_service import FoldersService
from services.projects_service import ProjectsService
from config import dry_run
from config import credenti... |
#
# (c) 2021 <NAME>
#
__author__ = '<NAME>'
__date__ = '2021/09'
import time
import click
from cuilib import Cui
from . import __prog_name__, __version__
from . import NeoPixel
from . import robot_eye
from . import get_logger
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
@click.group(invoke_without_c... |
import sys
import subprocess
# use pip to install numpy:
subprocess.check_call([sys.executable, '-m', 'pip', 'install',
'numpy'])
# use pip to install matplotlib:
subprocess.check_call([sys.executable, '-m', 'pip', 'install',
'matplotlib'])
# use pip to install pandas:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/8/16 17:12
# @Author : zzy824
# @File : emojify_main.py
import numpy as np
from emo_utils import *
import emoji
import matplotlib.pyplot as plt
""" Baseline model: Emojifier-V1 """
X_train, Y_train = read_csv('data/train_emoji.csv')
X_test, Y_test = ... |
# Create dummy variables for categorical features with less than 5 unique values
import pandas as pd
from sklearn.preprocessing import LabelEncoder
import gc
import datetime
import calendar
import xgboost as xgb
# import logger.py
from logger import logger
# set iteration
iteration = '3'
logger.info('Start data_pre... |
from re import X
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..utils import Conv_BN_ReLU
class ChannelAttention(nn.Module):
def __init__(self, in_planes, pool_size, ratio=16):
super(ChannelAttention, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(pool_size)
... |
import numpy as np
import pandas as pd
import sqlite3
import datetime as dt
from bs4 import BeautifulSoup as BS
from os.path import basename
import time
import requests
import csv
import re
import pickle
def name_location_scrapper(url): # scrapes a list of teams and their urls
r = requests.get(url)
sou... |
import argparse
from io import BytesIO as _BytesIO
from pathlib import Path
import numpy as _np
import pandas as _pd
from urllib import request as _rqs
from datetime import datetime
from scipy.interpolate import InterpolatedUnivariateSpline
from gn_lib.gn_io.common import path2bytes
from gn_lib.gn_datetime import gps... |
"""
<NAME>
Calculation of curvature using the method outlined in <NAME> et. al 2004
Per face curvature is calculated and per vertex curvature is calculated by weighting the
per-face curvatures. I have vectorized the code where possible.
"""
import numpy as np
from numpy.core.umath_tests import inner1d
from ... |
#!/usr/bin/env python
import argparse
import sys, subprocess, os
import re
import datetime
import math
# Generate customized SLURM submit scripts to run RAxML-ng.
# Takes a directory of alignmets, runs the raxml-ng --parse
# function to get estimates of RAM and CPU needs for the job.
# Then uses a templates sba... |
#!/usr/bin/env python
# Copyright 2016-2019 Biomedical Imaging Group Rotterdam, Departments of
# Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obt... |
# -*- coding: utf-8 -*-
"""
Copyright (c) Microsoft Corporation. All Rights Reserved.
Licensed under the MIT license. See LICENSE file on the project webpage for details.
XBlock to allow for video playback from Azure Media Services
Built using documentation from: http://amp.azure.net/libs/amp/latest/docs/index.html
"... |
#!/usr/bin/env python
from __future__ import print_function
# Core
import collections
from functools import wraps
import logging
import pprint
import random
import re
import time
import ConfigParser
from decimal import *
# Third-Party
import argh
from clint.textui import progress
import html2text
from PIL import Ima... |
# Copyright 2020 The TensorFlow Ranking Authors.
#
# 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 ag... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Extract methylation from fast5 files into a RocksDB file. Also has an interface to read those values.
Created on Thursday, 25. July 2019.
"""
import glob
import os.path
def main():
import argparse
parser = argparse.ArgumentParser(description="Extract methylat... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 14 13:15:24 2021
Animates streams of points/particles given their starting and ending locations
and number of particles in each flow.
@author: Mateusz
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from numpy.random import unifo... |
# -*- coding: utf-8 -*-
import os
import sys
# ensure `tests` directory path is on top of Python's module search
filedir = os.path.dirname(__file__)
sys.path.insert(0, filedir)
while filedir in sys.path[1:]:
sys.path.pop(sys.path.index(filedir)) # avoid duplication
import pytest
import numpy as np
import matplotl... |
#!/bin/python
import httplib2
import os
import io
from apiclient import discovery
from apiclient.http import MediaIoBaseDownload
from oauth2client import client, file, tools
from oauth2client.file import Storage
import openpyxl
from openpyxl import Workbook
# import employees
try:
import argparse
flags = ... |
import os
import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import graphviz as gv
class HiddenMarkovModel:
def __init__(
self,
observable_states,
hidden_states,
transition_matrix,
emission_matrix,
title="HMM",
):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 20 14:29:03 2020
@author: <NAME>
Script used to create the formatted table for lag phase calculation by DMFit
DMFit requires data to be formatted in a specific way to be analysed by the
Excel add-in DMFit. In brief, the excel file needs to have tw... |
import random
STATE_WIDTH = 7
STATE_HEIGHT = 6
MAX_CONSECUTIVE = 4
PLAYER = True
AI = False
MEMOIZATION_MIN = dict()
MEMOIZATION_MAX = dict()
'''
Game play functions
'''
def print_state(state) -> None:
filled_state = fill_empty_entry(state)
for row in range(STATE_HEIGHT - 1, -1, -1):
... |
"""
Model for mecctable objects :
Structures, link between them and exams
"""
from django.db import models
from django.utils.translation import ugettext as _
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
class Stru... |
import math
import cv2
import numpy as np
from PIL import Image
from skimage import exposure
from DataToCloud import dataToCloud
def calc_projection_image (ptCloud, pcloud, messyValidRGB):
ptCloudPoints = np.asarray(ptCloud.points)
validIndices = np.argwhere(
np.isfinite(ptCloudPoints[:, 0]) & np.i... |
# See LICENSE file for full copyright and licensing details.
import time
from odoo import models, fields, api, _
from odoo.exceptions import ValidationError
class ProductTemplate(models.Model):
_inherit = "product.template"
name = fields.Char('Name', required=True)
class ProductCategory(models.Model):
... |
"""Encoder, Decoder and Seq2Seq standard implementations.
"""
import math
import time
import torch
from torch import nn, optim
from tqdm import tqdm
import textformer.utils.exception as e
import textformer.utils.logging as l
logger = l.get_logger(__name__)
class Encoder(torch.nn.Module):
"""An Encoder class i... |
# Copyright 2018 The TensorFlow Probability Authors.
#
# 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 o... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 17 16:45:30 2017
@author: RunNing
"""
import random
import numpy as np
import matplotlib.pyplot as plt
import abc
class Algorithm(metaclass=abc.ABCMeta):
@abc.abstractmethod
def reset(self):
return
@abc.abstractmethod
def sel... |
import random
import string
from typing import Optional, List
from datetime import datetime, timedelta
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from fastapi.middleware.cors import CORSMiddleware
from jose import JWTError, jw... |
"""This module implements uploading videos on YouTube via Selenium using metadata JSON file
to extract its title, description etc."""
from typing import DefaultDict, Optional
from selenium_firefox.firefox import Firefox, By, Keys
from collections import defaultdict
import json
import time
from youtube_uploader_sel... |
# Copyright 2015 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.
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
... |
from math import nan
import pandas as pd
import re
import requests
from textblob import TextBlob # For sentiment analysis.
class NoResults(Exception):
pass
def url_encode(string: str):
"""Take a raw input string and URL encode it."""
replacements = {"!": "%21", "#": "%23", "$": "%24", "&": "%26", "'":... |
#!/usr/bin/env python3
#
# (c) 2017 Fetal-Neonatal Neuroimaging & Developmental Science Center
# Boston Children's Hospital
#
# http://childrenshospital.org/FNNDSC/
# <EMAIL>
#
from argparse import RawTextHelpFormatter
from argparse im... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 24 16:32:08 2020
@author: LionelMassoulard
"""
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, ClassifierMixin, RegressorMixin, is_classifier, is_regressor
from sklearn.preprocessing import OrdinalEncoder, KBinsDiscretizer
from aikit.too... |
"""
eval auc curve
"""
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import roc_auc_score,roc_curve,auc,average_precision_score
from net.utils.parser import load_config,parse_args
import net.utils.logging_tool as logging
from sklearn import metrics
import os
import scipy.io as scio
import ma... |
import click
import inspect
import os
import logging
import gym
import time
import yaml
import traceback
from importlib_metadata import version
from evestop.generic import EVEEarlyStopping
from pathlib import Path
from importlib_resources import files
import cibi
import cibi.codebases
from cibi import bf
from cibi i... |
# -*- coding: utf-8 -*-
# Author : tyty
# Date : 2018-6-21
from __future__ import division
import numpy as np
import pandas as pd
import tools as tl
class AritificialNeuralNetworks(object):
def __init__(self, layers, learningRate, trainX, trainY, testX, testY, epoch):
# input params
self.layers ... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# sources: coinomiwallet.proto
# plugin: python-betterproto
from dataclasses import dataclass
from typing import List
import betterproto
class KeyType(betterproto.Enum):
ORIGINAL = 1
ENCRYPTED_SCRYPT_AES = 2
DETERMINISTIC_MNEMONIC = 3
DETERMI... |
import itertools
from os import path
from pdb import set_trace
import pickle
from typing import Dict, List, Tuple
from explicit import waiter, XPATH
from selenium import webdriver
import selenium
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.chrome.options import Options
from se... |
#----------------------------------------------------------------------------#
# Imports
#----------------------------------------------------------------------------#
from app import app, db, login_manager
from flask import Flask, render_template, request, redirect, g, url_for, flash, session
from app.classes import *... |
import numpy as np
import keras
import json
from tqdm import tqdm
import cv2
import random
import matplotlib.pyplot as plt
from keras.applications.vgg16 import preprocess_input
from keras.preprocessing import image as keras_image
import pickle
def augment_patch(patch, augmentation):
if augmentation=='H-Flip':
... |
""" adaptation of part of <NAME>'s libvaxdata test suite for <NAME>'s PyVAX wrapper
Authors
-------
| <NAME> (<EMAIL>)
<NAME>
University of California, Los Angeles.
"""
import pyvax as pv
import numpy as np
from pytest import approx
def func_i2(x):
fstr = pv.from_vax_i2(x)
print(np.frombuffer(fstr, dtyp... |
import numpy as np
#---------------------------------------------------------
#Read in transition counts between cells (N_alpha_beta)
#---------------------------------------------------------
def compute_Nab_Ta(trajectory_crossings,N,i):
'''
Compute N_a_b and T_a for one individual trajectory at one individ... |
import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
__all__ = ['FixupResNet', 'fixup_resnet18', 'fixup_resnet34', 'fixup_resnet50', 'fixup_resnet101', 'fixup_resnet152']
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_pla... |
import pytorch_wavelets.dwt.lowlevel as lowlevel
import pywt
import torch
__all__ = [
"DWTForwardOverwrite",
"DWTInverse",
"construct_filters_from_2d",
"construct_2d_from_filters",
]
class DWTForwardOverwrite(torch.nn.Module):
"""
Mirrors the setup of the matlab function `FWT2_PO_fast`.
T... |
import middleend
import hlir
import expr
import dataflow
import utils
import vmcall
class Propagation(middleend.Optimization):
def safe_to_propagate(self, use_point, definition, paths):
# first we must check the instruction type
def_ins = definition.point.ins
if def_ins.type != hlir.ins_types.assign:
# calls... |
from sqlalchemy import and_, or_, func
from datetime import datetime
from flask import Blueprint, request, make_response, render_template, flash, g, session, redirect, url_for, jsonify, abort, current_app
from flask.ext.babel import gettext
from dataviva import db, lm, view_cache
# from config import SITE_MIRROR
from ... |
import copy
import json
from decimal import Decimal
from typing import Optional
from enum import Enum
import boto3
from boto3.dynamodb.types import TypeSerializer, TypeDeserializer
from botocore import exceptions
class InsufficientArgumentsException(Exception):
pass
class IndexNotValidException(Exception):
... |
from flare.algorithm_zoo.distributional_rl_algorithms import C51
from flare.model_zoo.distributional_rl_models import C51Model
from flare.algorithm_zoo.distributional_rl_algorithms import QRDQN
from flare.model_zoo.distributional_rl_models import QRDQNModel
from flare.algorithm_zoo.distributional_rl_algorithms import I... |
from anytree import NodeMixin, iterators, RenderTree
import math
def Make_Virtual():
return SwcNode(nid=-1)
def compute_platform_area(r1, r2, h):
return (r1 + r2) * h * math.pi
#to test
def compute_two_node_area(tn1, tn2, remain_dist):
"""Returns the surface area formed by two nodes
"""
r1 = tn1.... |
import numpy as np
import fvcore.nn.weight_init as weight_init
import torch.nn.functional as F
from torch import nn
import torch
from torch.nn.modules.utils import _pair
from detectron2.layers import CNNBlockBase,ShapeSpec,Conv2d,get_norm,FrozenBatchNorm2d
from detectron2.layers.deform_conv import deform_conv
from de... |
from __future__ import print_function
import os
import sys
import time
import argparse
import numpy as np
import xml.dom.minidom as xdom
from os.path import realpath, join, isdir, isfile, dirname, splitext
from ..core.environ import environ
U_ROOT = u"SimulationData"
U_JOB = u"job"
U_DATE = u"date"
U_EVAL = u"Evaluati... |
import os
import sys
import click
import logging
from . import get_rezup_version, __version__
from .container import Container, iter_containers
_default_cname = Container.DEFAULT_NAME
_log = logging.getLogger("rezup")
def _disable_rezup_if_entered(ctx):
_con = os.getenv("REZUP_CONTAINER")
if _con:
... |
# Copyright 2011 OpenStack LLC.
# 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 b... |
from django.contrib import admin
from django.forms import ModelForm, ModelMultipleChoiceField
from server.models import *
from server.utils import reload_plugins_model
class BusinessUnitFilter(admin.SimpleListFilter):
title = 'Business Unit'
parameter_name = 'business_unit'
def lookups(self, request, mo... |
import pytest
from subtypes import Str
@pytest.fixture
def default_string():
return Str("Hello World!")
@pytest.fixture
def casing_test_string():
return Str("| HiThis_is a CASINGTest-case &")
class TestCase:
pass
class TestReprMixin:
pass
class TestRegexAccessor:
class TestSettings:
... |
"""CS 61A Presents The Game of Hog."""
from email import message
from unittest import result
from dice import six_sided, four_sided, make_test_dice
from ucb import main, trace, interact
GOAL_SCORE = 100 # The goal of Hog is to score 100 points.
######################
# Phase 1: Simulator #
######################
... |
from discord.ext import commands
from xml.etree import ElementTree
import discord, os, requests, time, re, random
from azure.cognitiveservices.language.textanalytics import TextAnalyticsClient
from msrest.authentication import CognitiveServicesCredentials
tts_subscription_key = '<KEY>'
text_analytics_subscription_key ... |
import os
import json
from pathlib import Path
import pem
from Crypto.PublicKey import RSA
from jupyterhub.handlers import BaseHandler
from illumidesk.authenticators.utils import LTIUtils
from illumidesk.lti13.auth import get_jwk
from tornado import web
from urllib.parse import urlencode
from urllib.parse import ... |
from nose.tools import *
import os
import pysam
from collections import OrderedDict
try:
from index_bam_by_read_id.index_bam_by_read_id import IndexByReadId,UnsortedBamError
except ImportError:
from index_bam_by_read_id import IndexByReadId,UnsortedBamError
_f = 'test_data/test.bam'
_s = "test_data/test_rid_... |
"""
Copyright (c) 2016-17 <NAME> http://www.keithsterling.com
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, mer... |
import pandas as pd
import houghtest
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
import cv2
import numpy as np
import pickle
from multiprocessing import Process
import tim... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_parse_time
Tests for `parse_time` module.
"""
import unittest
import nose
import arrow
import json
import os
from functools import wraps
import re
from mock import patch
import parsley
from xlseries.strategies.clean.parse_time import ParseComposedYear1
from xlse... |
#!/usr/bin/env python3
# encoding: utf-8
from collections import defaultdict
from copy import deepcopy
from typing import Dict, List
import numpy as np
from mlagents_envs.environment import UnityEnvironment
from mlagents_envs.side_channel.engine_configuration_channel import \
EngineConfigurationChannel
... |
"""
`myplotlib.tests`
commands to help preview the custom styles (function names are self-descriptive). available functions are:
* testColormaps
* testColors
* testScatter
* testPlot
* testErrorbar
* testPlot2d
* testVectorPlot2d
* testAll
"""
import myplotlib.plots as myplt
import myplotlib
import matplotlib
impor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.