text stringlengths 3.07k 12.6k |
|---|
from dash import dcc
from dash import html
import dash_bootstrap_components as dbc
import altair as alt
from dash.dependencies import Input, Output
from data.data import energy_df_full
from ..app import app
from .style import plot1a_style,plot1b_style,whole_tab_style,label_style_active,label_style_init
alt.data_tran... |
#Import required libraries
import pandas as pd
import numpy as np
import spacy
from tqdm import tqdm
import re
import time
import pickle
pd.set_option('display.max_colwidth', 100)
# read train and test dataset
train = pd.read_csv("train.csv")
test = pd.read_csv("test.csv")
print(train.shape, test.shape)
# Check di... |
class DiGraph:
def __init__(self, edges=[]):
self.vertexList = VertexList(edges)
for e in edges:
self.addEdge(e)
## Modification
# for directed graph, we only need to store one direction - (in, out)
# self.addEdge((e[1],e[0]))
def addEdge(self, ed... |
import os
from shutil import copy
import PyPDF2
import pytest
from pdf_manager import get_file_list, get_pdfs, concat_pdfs, create_budget
from pdf_manager.core import PdfTypes, PDF
from pdf_manager.main import parse_args
class Memory:
dummy_a4 = ''
dummy_a4_inverted = ''
dummy_slide = ''
tmp_path = ... |
from pycricbuzz import Cricbuzz
c=Cricbuzz()
def first():
#fetching match data
match_data = c.matches()
#print(match_data)
matches = []
mt_id = []
status = []
mtype = []
mnums = []
m_srs = ... |
import json
import numpy as np
from copy import deepcopy
from io import BytesIO
from .. import MAGIC_SEAMLESS, _integer_types, _float_types, _string_types
from .util import get_buffersize, get_buffersize_debug, \
sanitize_dtype
from ...json_util import json_encode
def _convert_np_void(data):
if not isinstance(d... |
#!/usr/bin/env python3
import argparse
import gzip
import sys
import os
if not __package__:
sys.path.insert(1, os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
from mementomap import __VERSION__
from mementomap.cli import compact, generate, lookup
def run_generate(**kw):
if kw["infile"].endswi... |
# For division
from __future__ import division
import pandas as pd
from pandas import Series,DataFrame
import numpy as np
# For Visualization
import matplotlib.pyplot as plt
import seaborn as sns
import seaborn.linearmodels as snslin
sns.set_style('whitegrid')
#%matplotlib inline
# For reading stock data from yahoo
f... |
# Mostly based on the code written by <NAME>:
# https://github.com/mrharicot/monodepth/blob/master/utils/evaluate_kitti.py
from __future__ import division
import sys
import cv2
import os
import numpy as np
import argparse
from depth_evaluation_utils import *
parser = argparse.ArgumentParser()
parser.add_argument("--k... |
import numpy as np
from deep_np import utils
def _pool_forward(X, pool_fun, size=2, stride=2):
n, d, h, w = X.shape
h_out = (h - size) // stride + 1
w_out = (w - size) // stride + 1
X_reshaped = X.reshape(n * d, 1, h, w)
X_col = utils.im2col_indices(
X_reshaped, size, size, padding=0, stride=stride)... |
import os
import requests
import sys
import threading
import tqdm
import pump.utils as utils
import uuid
from math import ceil
from time import sleep
from typing import IO, Dict
from urllib.parse import urlparse
GLOBAL_THREAD_LOCK = threading.Lock()
class Downloader(threading.Thread):
"""Downloader for single c... |
from LambdaQuery.reroute import *
def sub_sql(self):
return sql(self, reduce=False, subquery=True)
def tableGen(self, reduce=True, debug=False, correlated=False, subquery=False):
alltables = self.getTables()
if correlated:
correlated_tables = self.groupbys.getTables()
alltables... |
'''
Created on May 27, 2016
@author: cesar
'''
from scipy.stats import norm, pareto, lognorm, gamma, weibull_min, weibull_max, gengamma, expon
import numpy as np
from scipy.stats import kstest
import sys
from matplotlib import pyplot as plt
from scipy import interpolate
from scipy.integrate import quadrature
from sci... |
import os
import numpy as np
import pandas as pd
import collections
import pickle
import sys
import psutil as ps
import random
import csv
import json
from utils.timeseries import TimeSeries
class Shapelet(object):
def __init__(self):
self.id = id(self)
self.name = 0.0
self.Class = ''
... |
"""
<NAME>
CSE 163
Quiz Section AA
Final Project Part Two
This file contains the functions used to analyze the cleaned and
merged NBA from the data_processing file.
"""
import data_processing # noqa: F401
import matplotlib.pyplot as plt
import seaborn as seabornInstance
import seaborn as sns
# hw2_manual.max_level(m... |
#!/usr/bin/env python3
from sys import stdin, stdout, stderr
from random import choice
from string import ascii_uppercase
from collections import deque
from parent import Track
from time import sleep
from os import system
resources = []
maze = []
player = ()
path = deque()
enemy = {}
other_player = ""
# track_maze =... |
"""test tts module."""
import random
import string
import unittest
try: # py3
from unittest import mock
except ImportError: # py2
import mock
import pytest
try:
from melissa.tts import tts
except IOError:
# NOTE: don't test with existing profile.
# taken from http://stackoverflow.com/a/8658332
... |
# -*- coding: utf-8 -*-
# Global imports
import argparse as ap
import numpy as np
from sklearn import cluster
# Local variable
Backbone_atoms = ["_CA_","_C__","_N__","_O__","_OXT","_HA_","_HA2","_HA3","_H__","_H1_","_H2_","_H3_"]
# Script information
__author__ = "<NAME>"
__license__ = "MIT"
__version__ = "1.0.1"
__... |
# -*- coding: utf-8 -*-
# @Time : 2021/9/19 下午5:43
# @Author : DaiPuWei
# @Email : <EMAIL>
# @File : yolov4_tiny.py
# @Software: PyCharm
"""
这是YOLOv4-tiny模型定义脚本
"""
import os
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input
from tensorflow.keras.layers import Lambda
fr... |
import torch
from architecture import Net, L1_Charbonnier_loss
from lap_dataset import DatasetFromFolder
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from torch.utils.data import DataLoader
from data import get_training_set, get_test_set
import argparse
from os.path imp... |
from discord.ext import commands
from cogs.aux_functions import *
import discord
class Help(commands.Cog):
"""
Sends this help message
"""
def __init__(self, bot, prefix):
self.bot = bot
self.prefix = prefix
@commands.command()
# @commands.bot_has_permissions(add_reactions=Tru... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Utilities for bounding box manipulation and GIoU.
"""
import torch
from torchvision.ops.boxes import box_area
def box_cxcywh_to_xyxy(x):
x_c, y_c, w, h = x.unbind(-1)
b = [(x_c - 0.5 * w), (y_c - 0.5 * h),
(x_c + 0.5 * w), (y_... |
"""
Module for web houses urls parsing
"""
import os
import csv
import time
from collections import defaultdict
from typing import Any, List, Tuple
import pandas as pd
from bs4 import BeautifulSoup
from loguru import logger
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.c... |
import numpy as np
import scipy
import scipy.optimize
def cov_se(x, xp, lengthscales, signal):
return signal**2 * np.exp(-0.5 * np.linalg.norm((x - xp)/lengthscales)**2)
def cov_main(str_cov, X, Xs, hyps, jitter=1e-5):
num_X = X.shape[0]
num_d_X = X.shape[1]
num_Xs = Xs.shape[0]
num_d_Xs = Xs.sha... |
import unittest
from conans.test.utils.tools import TestClient, TestServer
from conans.paths import CONANFILE
from conans.util.files import load
import os
from nose_parameterized import parameterized
class VersionRangesMultiRemoteTest(unittest.TestCase):
def setUp(self):
self.servers = {"default": TestSe... |
#!/usr/bin/env python3
import json
import random
import string
import re
import networkx as nx
import matplotlib.pyplot as plt
from networkx.readwrite import json_graph
from enum import IntEnum
# from logging import logging
import logging
# TODO: make this multiline nicer
DESCRIPTION = "The Decentralized Index of Kn... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as matplotlib
from torch import nn, Tensor, sqrt, pi, stack, optim
class Normalization(nn.Module):
def __init__(self, S_low, S_up, a_low, a_up, **kwargs):
super(Normalization, self).__init__(**kwargs)
self.l... |
#!/usr/bin/env python
'''
Preprocessing for training and inference on DeepMind's Inception-v1 Inflated 3D CNN for action recognition.
The model is introduced in:
Quo Vadis, Action Recognition? A New Model and the Kinetics Dataset
<NAME>, <NAME>
https://arxiv.org/pdf/1705.07750v1.pdf.
'''
__author__ = "<NAME>"
__... |
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, <NAME>. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# ... |
import unittest2 as unittest
from asp.codegen.cpp_ast import *
import xml.etree.ElementTree as ElementTree
class GenerationTests(unittest.TestCase):
# these are simply regression tests for some of the more complicated ast
# nodes to make sure we don't muck them up when fixing our handling of
# semicolons.
... |
import tensorflow as tf
import numpy as np
# tensorflow >= 2.0
def discriminator_loss(Ra, real_logit, fake_logit):
# Ra = Relativistic
if Ra:
fake_logit = tf.exp(tf.nn.log_softmax(fake_logit, axis=-1))
real_logit = tf.exp(tf.nn.log_softmax(real_logit, axis=-1))
num_outcomes = real_log... |
from django.shortcuts import render
from django.views import generic
from django.contrib.auth import logout
from django.shortcuts import redirect
from django.utils import timezone
from django.contrib.auth.forms import UserChangeForm
from django.urls import reverse
from .forms import ImageForm, ItemForm
from .forms impo... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as tick
from scipy.stats.kde import gaussian_kde
from scipy.interpolate import UnivariateSpline
def mean(s):
calc = sum(s)/len(s)
return calc
def stdev(s):
calc1 = mean(s)
calc2 = [(s[i]-calc1)**2 for i in... |
# coding=utf-8
# =================== Imports ===================
from pydub import AudioSegment
from argparse import ArgumentParser
import os, sys, inspect
current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parent_dir = os.path.dirname(current_dir)
sys.path.insert(0, parent_dir)
fr... |
#!/usr/bin/env python3
import os
import lgsvl
import time
import sys
import logging
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from lib.utils import *
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%m-%d %H:%M:%S')
logging.debug('Initializing Simulation Varia... |
import data
import copy, logging
import numpy as np
def minimize_states_and_actions_to_iterate():
logging.info("Minimizing states and actions to iterate for each engine type...")
for engine_subtype in data.engine_subtypes:
num_working_engines = data.engines_info[engine_subtype]['NUM_WORKING_ENGINES']
current_sta... |
import os
import sys
import cv2
import numpy as np
import tensorflow as tf
import hdr_utils
import tensorkit as tk
from config import config
from model.unetpps import UnetppGeneratorS
from tensorkit import logger, logging_to_file
UnetGeneratorS, UnetppGenerator = None, None
class TestData(object):
def __init_... |
#
# Copyright 2020 Haiku, Inc. All rights reserved.
# Distributed under the terms of the MIT License.
#
# Authors:
# <NAME>, <EMAIL>
#
"""
Transparent HTTP proxy.
"""
import http.client
import http.server
import optparse
import socket
import sys
import urllib.parse
class RequestHandler(http.server.BaseHTTPRequestH... |
import discord
import json
from discord.ext import commands
import random
TEAM = [
899722893603274793,
883004373519716372,
685180177419993102
]
crime_success = [
"You stole <en> ZeroBux from a small Café",
"You commited Tax Fraud and earned <en> ZeroBux",
"You robbed a bank and got <en> ZeroBux!"
]
crime_... |
"""
Functions used for LCI formatting.
"""
import collections
import pandas as pd
import scipy as sp
from scipy import linalg
from lib.parameters import *
def compartment_coords(lci, compartments, new_names=None):
"""
Gets the coordinates of given compartments in a Simapro LCI export.
If new_names is ... |
"""General matrix math functions."""
# Author: <NAME>
import numpy as np
from numpy import linalg as la
from scipy.linalg import solve_discrete_lyapunov, solve_discrete_are
from functools import reduce
from extramath import quadratic_formula
def vec(A):
"""Return the vectorized matrix A by stacking its columns.... |
from src.env_wrappers import wrap_dqn
from src.models import Nature
import tensorflow as tf
import numpy as np
nonlin_dict = {
'elu': tf.nn.elu,
'relu': tf.nn.relu,
'sigmoid': tf.nn.sigmoid,
'tanh': tf.nn.tanh
}
# If you add a new network you should add "string --> class" mapping here.
network_dict ... |
# Copyright (c) 2018 <NAME>.
# Cura is released under the terms of the LGPLv3 or higher.
import configparser # An input for some functions we're testing.
import os.path # To find the integration test .ini files.
import pytest # To register tests with.
import unittest.mock # To mock the application, plug-in and contain... |
# TODO: implement BatchNorm2d and Swish
# aka batch_norm, pad, swish, dropout
# https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/efficientnet-b0-355c32eb.pth
# a rough copy of
# https://github.com/lukemelas/EfficientNet-PyTorch/blob/master/efficientnet_pytorch/model.py
import io
import numpy as n... |
import argparse
import copy
import ctypes
import glob
import json
import os
import re
import sys
import elftools
import elftools.construct.macros as macros
import elftools.elf.elffile as elffile
import elftools.elf.structs as structs
from jsonmerge import merge
symbols = {}
rules = {}
fut = None
_mapping_table = {
... |
from pudzu.charts import *
from pudzu.sandbox.bamboo import *
import seaborn as sns
# generate map
FONT = verdana
df = pd.read_csv("datasets/eufemaleleaders.csv")
df = df.assign_rows(assign_if='hosdate:exists or hogdate:exists', date=lambda d: min(get_non(d,'hosdate',2018), get_non(d,'hogdate',2018)))
df = df.set_ind... |
# ------------------------------------------------------------------------------
# Copy from https://github.com/HRNet/HRNet-Image-Classification
# Modified by us
# ------------------------------------------------------------------------------
from __future__ import absolute_import
from __future__ import division
from ... |
import numpy as np
import re
from kmer import *
def motif_emnumeration(gen, k, d):
p = set()
for kmer in generate_kmer(k):
if all(any(hamming(kmer, gen_kmer) <= d for gen_kmer in enumerat_kmer(gen_string, k)) for gen_string in gen):
p.add(kmer)
return list(p)
def median_string(gen, k)... |
# Copyright (c) 2013, <NAME> and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import cstr
__all__ = ["execute"]
def execute(filters={}):
return get_columns(filters), \
get_data(filters)
def get_conditions(filters):
"""
R... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
""" This module contains functions to determine where configuration and
data/cache files used by Astropy should be placed.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import os
import sy... |
"""
Loqed API integration
"""
import logging
import aiohttp
#from .apiclient import APIClient
from typing import List
import os
import json
from abc import abstractmethod
from asyncio import CancelledError, TimeoutError, get_event_loop
from aiohttp import ClientError, ClientSession, ClientResponse
from typing import L... |
import tensorflow as tf
import numpy as np
import os
from PIL import Image
import math
def variable(name, shape, initializer, trainable = True, dtype = tf.float32):
out = tf.get_variable(name, shape, dtype, initializer, trainable = True)
return out
def reshape(input, out_shape, n_in, scope = 'reshape'):
with tf.... |
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.conf import settings
from django.utils.decorators import method_decorator
from django.shortcuts import render, redirect, get_object_or_404
from django.views import View
from django.db import transaction
from django... |
"""
Module for robustly opening an output file.
Rationale
---------
Suppose the following scenario. A program needs to perform some analysis and save its results to an output file (usually
chosen by the user). The most natural and intuitive structure for this program would be:
- Perform the analysis and store the re... |
# Functions fid_features_to_statistics and fid_statistics_to_metric are adapted from
# https://github.com/bioinf-jku/TTUR/blob/master/fid.py commit id d4baae8
# Distributed under Apache License 2.0: https://github.com/bioinf-jku/TTUR/blob/master/LICENSE
import numpy as np
import scipy.linalg
import torch
from tor... |
"""
Module containing main DLPOLY class
"""
import subprocess
import os.path
import os
import shutil
from dlpoly.control import Control
from dlpoly.config import Config
from dlpoly.field import Field
from dlpoly.statis import Statis
from dlpoly.cli import get_command_args
class DLPoly:
""" Main class of a DLPOLY... |
try:
from rgbmatrix import graphics
except ImportError:
from RGBMatrixEmulator import graphics
def render_team_banner(canvas, layout, team_colors, home_team, away_team, full_team_names, short_team_names_for_runs_hits):
default_colors = team_colors.color("default")
away_colors = __team_colors(team_colo... |
import loading_data
import numpy as np
import scipy.stats
import itertools
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
dataset_to_metric = {"sst": "acc", "mrpc": "acc_and_f1", "cola": "mcc", "rte": "acc"}
dataset_to_failurenum = {"sst": 0, "mrpc": 0.75, "cola": 0.1, "rte": .5}
def main... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
TOF Fault Injector For Camera FI Demo Tool
"""
import os
from os import listdir
from os.path import isfile, join
import random
from class_fi_offline_ui import OfflineImageFault as ofi
#from class_list_creator import ListCreator as img_list
def main(ndir_name, fdir_na... |
import keras
import os
import numpy as np
import import_data
def fit(model, train_set, valid_set, batch_size, epochs, train_version, freq):
"""
freq: freq (in step) of recording train history
"""
# train
train_steps = int(train_set[0].shape[0]/batch_size)
last_step_batch_size = train_set[0].sh... |
#!/usr/bin/python3
# Example of adding/removing models to gazebo simulator
import argparse
import rospy
import numpy as np
import copy
from ur_gazebo.gazebo_spawner import GazeboModels
from ur_gazebo.model import Model
from ur_gazebo.basic_models import SPHERE, PEG_BOARD, BOX, SPHERE_COLLISION
rospy.init_node('gazebo... |
"""
Non-Residential Efficiency preprocessing
----------------------------------------
preprocessing functions for Non-residential Efficiency component
"""
#~ import os.path
#~ from pandas import read_csv
# preprocessing in preprocessor
import os
from pandas import read_csv, concat, DataFrame
import numpy as np
impor... |
# egion IMPORTS
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.keys import Keys
import os
import time
import job_list
# region END
# Fill your personal details
INFORMATION = {
"fir... |
#from MongoDB import MongoDB
from constants import *
import datetime
import time
get_date = lambda ts: datetime.datetime.fromtimestamp(ts/1000).strftime("%Y-%m-%d")
get_days = lambda d1,d2: (datetime.datetime.strptime(d2, "%Y-%m-%d") - \
datetime.datetime.strptime(d1, "%Y-%m-%d")).days
'最长高强度同传时间'
def get_room_name... |
from ctypes import *
import ctypes.util
from ctypes_configure import configure
# Note: OpenSSL on OS X only provides md5 and sha1
libpath = ctypes.util.find_library('ssl')
if not libpath:
raise ImportError('could not find OpenSSL library')
lib = CDLL(libpath) # Linux, OS X
lib.EVP_get_digestbyname.restype = c_void... |
#!/usr/bin/env python
# Filename: pixel_evaluation
"""
introduction:
authors: <NAME>
email:<EMAIL>
add time: 13 December, 2019
"""
from optparse import OptionParser
import os,sys
import rasterio
import basic_src.basic as basic
import basic_src.io_function as io_function
import parameters
import gdal
import numpy as ... |
from django.shortcuts import render, get_object_or_404
from rest_framework import viewsets
from rest_framework import permissions
from .serializers import PlantSerializer
# from rest_framework.views import APIView
# from rest_framework.response import Response
from rest_framework import permissions #, authentication... |
# Optimization helper functions
import numpy as np
from sklearn.metrics import log_loss
from numpy import sum, maximum, exp, log, log1p
from scipy.optimize import fmin_l_bfgs_b as bfgs
from scipy.optimize.lbfgsb import _minimize_lbfgsb
from scipy.optimize.optimize import MemoizeJac, wrap_function
from scipy.optimize... |
import datetime
import json
import os
import urllib
import psycopg2
import psycopg2.extras
import pandas as pd
import redis
import pmdarima as pm
from mlxtend.preprocessing import TransactionEncoder
from mlxtend.frequent_patterns import apriori
A_PRIORI_LENGTH = 40
PERIOD_LENGTH = datetime.timedelta(hours=12)
NUM_PER... |
'''https://www.reddit.com/r/dailyprogrammer/comments/6qutez/20170801_challenge_325_easy_color_maze/
Program tries to be efficient by never visiting the same step multiple times (even from different input paths)
Can also handle no valid solution i.e. all possible paths are dead ends or get stuck in endless loops
'''
f... |
from pathlib import Path
import cv2
import dlib
import numpy as np
import argparse
from contextlib import contextmanager
from wide_resnet import WideResNet
from keras.utils.data_utils import get_file
from os import path as osp
import glob
import json
pretrained_model = "https://github.com/yu4u/age-gender-estimation... |
# Copyright (c) 2008, <NAME>. All rights reserved.
#
# 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, merg... |
#!/usr/bin/env python3
import yaml
import os
import logging
import logging.config
import sys
import time
import datetime
import argparse
import threading
import traceback
import signal
import timeit
import functools
import subprocess
import faulthandler
from prometheus_client.twisted import MetricsResource
from prome... |
import vim
import json
import subprocess
import io
import os
import sys
import tempfile
import logging
tempdir = tempfile.gettempdir()
logging.basicConfig(filename='%s/vim-rtags-python.log' % tempdir,level=logging.DEBUG)
def get_identifier_beginning():
line = vim.eval('s:line')
column = int(vim.eval('s:start'... |
from ctypes import *
import math
import random
import os
import cv2
import numpy as np
import time
from . import darknet
netMain = None
metaMain = None
altNames = None
def convertBack(x, y, w, h):
xmin = int(round(x - (w / 2)))
xmax = int(round(x + (w / 2)))
ymin = int(round(y - (h / 2)))
ymax = int... |
"""hls_streaming.py.
Module with objects to handle HLS streaming.
"""
import io
import asyncio
from contextlib import nullcontext
from collections import OrderedDict
# Third-party imports.
from tornado import web
# Local imports.
from pysdrweb.util import misc
from pysdrweb.util.auth import authenticated
from pysdrweb... |
import sys
DEBUG = False
def main():
row_c, col_c, vehicle_c, ride_c, bonus, step_c = sys.stdin.readline().strip().split(" ")
row_c, col_c, vehicle_c, ride_c, bonus, step_c = int(row_c), int(col_c), int(vehicle_c), int(ride_c), int(bonus), int(step_c)
if DEBUG:
print("CONFIG")
print(f"Row... |
"""
This module performs subspace system identification.
It enforces that matrices are used instead of arrays
to avoid dimension conflicts.
"""
import numpy as np
from scipy import linalg
__all__ = ['subspace_det_algo1', 'prbs', 'nrms']
def block_hankel(data, f):
"""
Create a block hankel matrix.
f : nu... |
from typing import List
import numba as nb
import numpy as np
from astropy.io import fits
__all__ = ["makeaperpixmaps", "distarr", "subdistarr", "apercentre", "aperpixmap"]
def makeaperpixmaps(npix: int, folderpath=None) -> None:
'''Writes the aperture binary masks out after calculation.
Parameters
---... |
"""
Contains the code related for face recognition/verification.
"""
from typing import Union, Tuple, Optional
import torch
import torchvision.transforms as T
import numpy as np
from torch import nn
from facenet_pytorch import MTCNN, InceptionResnetV1
from PIL import Image
import matplotlib.pyplot as plt
from scipy.sp... |
#!/usr/bin/env python
# coding: utf-8
# # Illustrates function iteration, Newton, and secant methods
#
# **<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> 20... |
#Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.
#This program is free software;
#you can redistribute it and/or modify
#it under the terms of the MIT License.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 13 13:55:08 2018
@author: herminarto.nugroho
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import optim
from torchvision.utils import save_image
from custom_datasets import CustomDatasetFromImages, CustomSplitLoader
# Device configura... |
import json
import codecs
from typing import NamedTuple, Dict, List, Optional
import ir_datasets
from ir_datasets.util import GzipExtract, Cache, Lazy
from ir_datasets.datasets.base import Dataset, YamlDocumentation, FilteredQueries
from ir_datasets.formats import BaseQueries, BaseDocs, BaseQrels, TrecQrel
from ir_data... |
# 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 use ... |
#!/usr/bin/env python3
'''
stat_assembly -- stat genome assemblies and get the following statistic values:
1:length 2:number_contigs 3:GC_content 4:N50 5:L50 6:N25
7:L25 8:N75 9:L75 10:N90 11:L90 12:minimum_len
13:median 14:m... |
import time
import pytest
from helpers.cluster import ClickHouseCluster
from helpers.network import PartitionManager
from helpers.test_tools import TSV
cluster = ClickHouseCluster(__file__)
instance_test_reconnect = cluster.add_instance(
"instance_test_reconnect", main_configs=["configs/remote_servers.xml"]
)
in... |
#!/usr/bin/env python3
from graph_tool.all import Graph, graph_draw, radial_tree_layout
from urllib.parse import urlparse
import os
import re
import requests
guid_pattern = re.compile('[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}', re.I)
class CfApi(object):
root_path = '/v3'
def __init__(... |
import numpy as np
from collections import defaultdict
class Tarjan:
"""
adopted from : https://github.com/jcyk/Dynet-Biaffine-dependency-parser/blob/master/lib/tarjan.py
"""
def __init__(self, prediction, tokens):
"""
:param prediction: A predicted dependency tree where predic... |
import torch
from torch import nn
from torch.nn.functional import dropout
def top_T(x, T):
values, indices = torch.topk(x.abs(), T, dim=1)
dropped = torch.zeros_like(x).scatter(1, indices, values)
dropped = dropped * x.sign() # <-- this should be included
return dropped
def dropout(x, p, seed=None)... |
from src.sat_utilities import *
from src.optimizer import *
import math
def generate_sat_qasm(expr_string, cnot_mode, sat_mode, apply_optimization=True, connected_qubit=None):
"""
Generate the QASM needed to evaluate the SAT problem for a given boolean expression.
Args:
expr_string: A boolean exp... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file contains the definition of the XFoil OpenMDAO Component and its helper functions.
"""
import numpy as np
import time
from multiprocessing.pool import ThreadPool
from xfoil import XFoil
from xfoil.model import Airfoil
from .. import rank
from .airfoil import ... |
import adsk.core, adsk.fusion, adsk.cam, traceback
from datetime import datetime
from pathlib import Path
from typing import NamedTuple, List, Set
import re
import hashlib
import os
handlers = []
class Ctx(NamedTuple):
''' Context manager. Passed between functions to provide paramaters
'''
folder: str
... |
"""
PRIVATE MODULE: do not import (from) it directly.
This module contains implementations of common functionality that can be used
throughout `jsons`.
"""
import builtins
import warnings
from importlib import import_module
from typing import Callable, Optional, Tuple, TypeVar, Any
from jsons._cache import... |
"""Airfow DAG and helpers used in one or more istio release pipeline."""
"""Copyright 2017 Istio 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.o... |
import argparse
import os
import os.path as osp
import mmcv
import numpy as np
import torch
from mmcv import Config, DictAction
from mmcv.parallel import collate, scatter
from mmaction.apis import init_recognizer
from mmaction.datasets.pipelines import Compose
from mmaction.utils import GradCAM
def parse_args():
... |
# Copyright 2018 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
'''
Created on 29 Jun 2015
@author: @willu47
This module provides the basic infrastructure for plotting charts for the
Method of Morris results
The procedures should build upon and return an axes instance::
import matplotlib.plot as plt
Si = morris.analyze(problem, param_values, Y, conf_level=0.95,
... |
from abc import ABC
import pprint
import logging
from lark import Lark, Tree, Token
from .parse_tabs import tabs_to_codeblocks
from .la_builtins import LaBuiltins, LaInteger, LaBoolean, LaString, LaFunction, LaArgument
import la.errors as errors
grammar = open("la/grammar.lark", "r").read()
code = tabs_to_codebloc... |
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt
"""Code coverage measurement for Python"""
# Distutils setup for coverage.py
# This file is used unchanged under all versions of Python, 2.x and 3.x.
import os
im... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.