text stringlengths 3.07k 12.6k |
|---|
from __future__ import absolute_import
import pandas as pd
from io import StringIO
import zlib
from .. import encode, decode
from ..handlers import BaseHandler, register, unregister
from ..util import b64decode, b64encode
from .numpy import register_handlers as register_numpy_handlers
from .numpy import unregister_ha... |
# -*- coding: utf-8 -*-
# Copyright 2017 <NAME> (Nagoya University)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
from __future__ import division
from __future__ import print_function
import fnmatch
import os
import sys
import threading
import h5py
import numpy as np
def check_hdf5(hdf5_name, hdf5_p... |
import typing
from pydantic import BaseModel, Field
class TemperatureModuleLiveData(BaseModel):
"""Temperature Module live data"""
currentTemp: float = \
Field(...,
description="The current temperature of the module")
targetTemp: typing.Optional[float] = \
Field(...,
... |
#!/usr/bin/python
import os, sys, inspect
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)
import common
import config ... |
##
## MIT License
##
## Copyright (c) 2016 <NAME>
##
## 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,... |
#!/usr/bin/env python
# test_notify.py - unit test for async notifications
#
# Copyright (C) 2010-2011 <NAME> <<EMAIL>>
#
# psycopg2 is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of... |
"""Helper functions to create and test Blender scene geometry data"""
# ***** BEGIN LICENSE BLOCK *****
#
# Copyright © 2005, NIF File Format Library and Tools contributors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the f... |
from ns_portal.core.resources.restviews import (
IRESTview
)
from ns_portal.core import (
corsConfig
)
from zope.interface import implementer
# from webargs.pyramidparser import parser
from webargs.pyramidparser import PyramidParser
class Parser(PyramidParser):
DEFAULT_VALIDATION_STATUS = 400
parser = P... |
import pygame, sys, random
from pygame.locals import *
def hacerSuperposicionRects(rect1, rect2):
for a, b in [(rect1, rect2), (rect2, rect1)]:
# Verifica si las esquinas de a se encuentran dentro de b
if ((puntoDentroDeRect(a.left, a.top, b)) or
(puntoDentroDeRect(a.left, a.bott... |
# Copyright (c) 2021 PaddlePaddle 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 app... |
# full binary tree - all the nodes have 0 or two children
# complete binary tree - all the levels are completely filled
# binary tree vs binary search tree - https://www.geeksforgeeks.org/difference-between-binary-tree-and-binary-search-tree/
class Node:
def __init__(self, data):
self.left = None
... |
import pandas as pd
import numpy as np
import re
def vendor_label(element):
'''docstring for vendor_label'''
element = element.upper()
if 'INNOVA' in element:
#print(element)
vendor = 'INNOVA'
elif 'WHAM' in element:
#print(element)
vendor = 'WHAM-O'
elif 'DISCRAFT'... |
import faiss
import time
import sys
import re
import numpy as np
from multiprocessing.dummy import Pool as ThreadPool
embedding_dim = 384
vec = np.fromfile('/data/computed_embeddings/realnewslike/c4-train.00306-of-00512', dtype='float32')
vec = vec.reshape(-1, embedding_dim)
print("Loaded vector shape: ", vec.shape)... |
#!/usr/bin/python3.4
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
# 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 app... |
from __future__ import division
from iotbx.bioinformatics import ebi_wu_blast_xml
import unittest
class TestParse(unittest.TestCase):
HSEARCH = None
def setUp(self):
if self.__class__.HSEARCH is None:
import libtbx.load_env
root = libtbx.env.under_dist( "iotbx", "bioinformatics" )
impo... |
from musictaxonomy.database import Base
from musictaxonomy.graph import constants as graph_constants
from sqlalchemy import Column, ForeignKey, Integer, String
class Artist(Base):
__tablename__ = "artists"
id = Column(Integer, primary_key=True)
spotify_id = Column(String(255), nullable=False, index=True)... |
# -*- coding:utf-8 -*-
from __future__ import unicode_literals
import time
import logging
try:
from sqlalchemy import (
Table, Text, Column, Integer, String, Float, BigInteger)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import mapper
except ImportError:
... |
from flask import ( # type:ignore
Flask,
render_template,
request,
g,
flash,
redirect,
jsonify,
)
import sqlite3
from flask_login import ( # type:ignore
LoginManager,
login_user,
UserMixin,
current_user,
logout_user,
)
from datetime import datetime, date
import os
from... |
'''
Smol, an unopinionated static site generator.
'''
from datetime import datetime, timedelta
import json
import logging
from pathlib import Path
import shutil
import time
from typing import Any, Dict
import argparse
from httpwatcher import HttpWatcherServer
import jinja2
from jinja2.exceptions import TemplateError
f... |
""" Base parser definitions shared between most cli utilities. """
import argparse
import logging
import os
import cgitb
import platform
import sys
from .. import __version__
from ..arch.target_list import target_names, create_arch
from ..build.tasks import TaskError
from ..common import logformat, CompilerError
from ... |
import torch;
import numpy as np;
from torch import nn;
from torch import optim;
import torch.functional as func;
from torchvision import datasets, transforms, models;
from collections import OrderedDict
import time;
import os;
from os import path;
import PIL;
from PIL import Image
def obtain_pretrained_model(model_na... |
from torch.utils.data import Dataset, DataLoader
from torch.nn.utils.rnn import pad_sequence
import os, csv, ipdb, torch, random
from transformers import BertTokenizer
from tqdm import tqdm
def read_query(path):
with open(path) as f:
csv_f = csv.reader(f, delimiter='\t')
dataset = [line[1] for line... |
import hashlib
import logging
from bs4 import BeautifulSoup
import cchardet
import feedparser
import mimeparse
import trio
import w3lib.encoding
import yarl
logger = logging.getLogger(__name__)
chardet = lambda s: cchardet.detect(s).get('encoding')
class CrawlExtractor:
''' Extract URLs from crawled items and ... |
import re
import urllib
REGEXP_TYPE = type(re.compile(''))
PATH_REGEXP = re.compile('|'.join([
# Match escaped characters that would otherwise appear in future matches.
# This allows the user to escape special characters that won't transform.
'(\\\\.)',
# Match Express-style parameters and un-named par... |
# Copyright 2018 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.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in ... |
# -*- coding: utf-8 -*-
__author__ = 'ffuentes'
from datetime import datetime
from django.conf import settings
from django.contrib.auth.middleware import get_user
from django.contrib.auth.models import User
from django.contrib.sessions.models import Session
from django.contrib.sessions.backends.base import UpdateError... |
import cv2
import numpy as np
import os
from non_max_suppression import non_max_suppression_fast as nms
if not os.path.isdir('CarData'):
print('CarData folder not found. Please download and unzip '
'http://l2r.cs.uiuc.edu/~cogcomp/Data/Car/CarData.tar.gz '
'or https://github.com/gcr/arc-evalua... |
from typing import Tuple, Type, Union
import numpy as np
import torch
from shapely.geometry import Polygon
from sklearn.mixture import GaussianMixture
def predict(model, feature_arr: Union[np.ndarray, torch.Tensor]) -> np.ndarray:
"""
Makes a prediction with a trained NN
"""
device = "cuda" if torch.... |
import os
import cv2
import numpy as np
import random as rnd
def path_creator(path, img_count,staring_string,extension):
img_count_str = str(img_count)
while True:
if(len(img_count_str)<6):
img_count_str = "0" + img_count_str
else:
break
img_path = "{0}{1}{2}{3}".... |
import datetime
import logging
import os
import requests
import tempfile
import urllib.request
from base.utils import get_model_object
from challenges.utils import get_challenge_model, get_challenge_phase_model
from django.utils import timezone
from participants.utils import get_participant_team_id_of_user_for_a_chall... |
#########################################################
#
# Utility routines for Spherical expansion
#
# MSP 5.1.2016
#
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
from scipy import interpolate
# pull in exptool C routines
try:
from exptool.basis._accu... |
import os
import glob
import pandas as pd
import numpy as np
import polars as pl
import re
from polars import col
from datatable import dt, fread, f, g, by, sort
from .utilities import harmonize_df_columns
# -- Enable logging
from loguru import logger
import sys
logger_config = {
"handlers": [
{"sink": ... |
import subprocess
import threading
import os, uuid, pathlib
import shutil
import boto3
import time, datetime
from botocore.exceptions import ClientError
MAX_WORKERS = 1
PROJECT_ROOT = os.path.dirname( os.path.dirname( os.path.abspath( __file__ ) ) )
VOICES_ROOT = os.path.join( PROJECT_ROOT, 'temp' )
region = os.enviro... |
import numpy as np
import chainer
from chainer import cuda
import chainer.functions as F
import chainer.links as L
from chainercv.links.model.faster_rcnn.utils.generate_anchor_base import \
generate_anchor_base
from chainercv.links.model.faster_rcnn.utils.proposal_creator import \
ProposalCreator
class Regi... |
import os, sys
cwd = os.path.dirname(os.path.realpath(__file__))
files = ["a_example.txt", "b_lovely_landscapes.txt", "c_memorable_moments.txt", "d_pet_pictures.txt", "e_shiny_selfies.txt"]
# functions
def loaddata(fname):
cwd = os.path.dirname(os.path.realpath(__file__))
f = open(cwd + "/" + fname)
picc... |
import tensorflow as tf
from tensorflow import keras
import os
from tqdm import tqdm
import numpy as np
import matplotlib.pyplot as plt
# tf.config.set_visible_devices([], 'GPU')
# physical_devices = tf.config.list_physical_devices("GPU")
# tf.config.experimental.set_memory_growth(physical_devices[0], True)
def load_... |
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_daq as daq
import plotly.graph_objs as go
from dash.dependencies import Input, Output
from datetime import datetime
from model import run_SEIR
# Step 1. Launch the application
external_stylesheets = ['https://codepen.io/chri... |
from django.shortcuts import render, redirect
from django.http import HttpResponse, Http404
import datetime as dt
from django.db.models import F
from .models import Image, Profile, Comments, Followers, PhotoLikes
from django.contrib.auth.decorators import login_required
from .forms import NewImageForm, EditProfile,Comm... |
import re
import io
from plotly.subplots import make_subplots
import plotly.graph_objs as go
import plotly.express as px
import base64
import streamlit as st
import numpy as np
import pandas as pd
def V2nm(V):
"""
This function converts applied voltage to nm based on the piezoscanner calibration in the software
... |
"""Definition of the WordHippoEngine."""
import argparse
from collections.abc import Callable, Iterable
from dataclasses import dataclass
from enum import IntEnum
from typing import IO, Optional
from urllib.parse import quote
import lxml.etree
import requests
from dict.colors import COLOR_HIGHLIGHT, COLOR_RESET
from ... |
import os
import aiohttp
import datetime
import secrets
from os.path import splitext
from fastapi import FastAPI, HTTPException
from starlette.middleware.sessions import SessionMiddleware
from starlette.requests import Request
from starlette.responses import RedirectResponse, PlainTextResponse
from starlette.templatin... |
#!/usr/bin/env python
import asyncio
import json
import websockets
from pathlib import Path
import threading
from multiprocessing import Process, Value, Array
import sys
import signal
import time
import Adafruit_DHT
import RPi.GPIO as gpio
import VL53L1X
from ctypes import CDLL, CFUNCTYPE, POINTER, c_int, c_uint, p... |
# -*- coding: utf-8 -*-
"""
Maze creation Algorithms
"""
# Maze manipulation
import numpy
def walls_check(walls_list, cell_loc, horizontal_walls, vertical_walls):
# What walls exist for cell_loc
ver_wall_shape = numpy.shape(vertical_walls)
hor_wall_shape = numpy.shape(horizontal_wal... |
import numpy as np
import pandas as pd
from itertools import groupby
from scipy.io import savemat
from typing import List
from mednickdb_pysleep import pysleep_defaults
import os
module_path = os.path.dirname(os.path.abspath(__file__))
def convert_epochstages_to_eegevents(epochstages: List[str], epoch_len: int=pyslee... |
# Copyright 2014 Midokura SARL
#
# 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... |
"""Several dataclasses for storing all transcript related data.
Statements are split into two varietes, embedded and speaker statements. Embedded statement appears
as part of a speaker statement. Embedded statements contain only minimal amount of information
while speaker statements can have more associated data.
Sta... |
"""
Command handler for chat session
"""
import os
def append_to_chatlog(chatlog_filepath, question, answer):
"""Append a question and answer to the chat log.
Args:
chatlog_filepath: Path to the chat log file
question: the question string entered by the user
answer: the ... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 NEC Corporation. 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... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import os
from glob import glob
import astropy.units as u
import numpy as np
from astropy.io import ascii
from astropy.tests.helper import pytest
from astropy.utils.data import get_pkg_data_filename
from ..analysis import save_diagnostic_plots, save_resu... |
from ..aws import region_names
from app.es.awsmetric import AWSMetric
from app.es.awsstat import AWSStat
from collections import defaultdict
import time
def get_rds_instances(session):
for region_name in region_names:
client = session.client('rds', region_name=region_name)
paginator = client.get_pa... |
###DON'T TOUCH THIS FILE###
import json
import os
import random
import sys
import xml.etree.ElementTree as ET
import numpy as np
KNOWN_TOKEN_TYPES = {
"org.apache.ctakes.typesystem.type.syntax.NewlineToken",
"org.apache.ctakes.typesystem.type.syntax.PunctuationToken",
"org.apache.ctakes.typesystem.type.... |
from .context.tokens import *
from .context import base
from .util import listify
from importlib import import_module
from collections import namedtuple
from types import ModuleType, SimpleNamespace
try:
from functools import cache
except importError:
from functools import lru_cache as cache
# For diffs
# Th... |
#!/usr/bin/env python3
'''
This script converts IE/Ridley_serial output into a form that can be used by
the WAM-IPE team. The hemispheres are combined into a single grid, and
coordinates converted from geomagnetic to geographic. The new output is
written to a NetCDF file.
'''
import numpy as np
from scipy.io.netcd... |
# Copyright 2020 The Bazel 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 la... |
###########################################################################################
# Title : Prediksi Indeks Harga Saham dengan menggunakan Recurrent Neural Network
# Author : <NAME>
# Aims : 1. Menerapkan metode neural network berbasis time series dengan program Python
# 2. Meramal harga indeks s... |
import numpy as np
import matplotlib.pyplot as plt
from arm.obstacle import Obstacle
from arm.goal import GoalEndPose, GoalCollection
from frame2d import Frame2D
class Box(object):
BOX_SIZE = 0.4
def __init__(self, x, y, theta=0, name="box"):
self.obstacle = Obstacle(Frame2D(theta, x, y), Box.BOX_SIZ... |
import utils
import torch
import torch.nn as nn
from tqdm import tqdm
import numpy as np
import re
import config
from apex import amp
def loss_fn(start_logits, end_logits, start_positions, end_positions):
loss_fct = nn.CrossEntropyLoss()
start_loss = loss_fct(start_logits, start_positions)
end_loss = los... |
import math
def main():
print("What do you want to calculate?")
print('\n- type "a" for annuity monthly payment amount.')
print('- type "n" for number of monthly payments.')
print('- type "p" for loan principal.')
print('- type "d" for differentiated payments.')
while True:
calc = inp... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
import argparse
import time
import os
#setup training parameters
parser = argparse.ArgumentParser(description='PyTorch MNIST Trai... |
import gym
import logging
logging.basicConfig(level=logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
import numpy as np
import sys
sys.path.append(r"code\Reforcement-Learning\DQN-CartPole")
from agent import Agent
from model import MyModel
f... |
import json
import boto3
import base64
from nacl.signing import VerifyKey
from nacl.exceptions import BadSignatureError
from botocore.exceptions import ClientError
import time
PING_PONG = {"type": 1}
RESPONSE_TYPES = {
"PONG": 1,
"CHANNEL_MESSAGE_WITH_SOURCE": 4,
"DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE": 5,
... |
# Copyright (c) 2018, 2019, Oracle and/or its affiliates.
# Copyright (c) 2013, 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:
#
# 1. Redistributions of ... |
# https://github.com/andrewliao11/gail-tf
# import lib.tf_util as U
import tensorflow as tf
import numpy as np
import lib.layer as layer
# ================================================================
# Flat vectors
# ================================================================
def var_shape(x):
out = x.g... |
import os
import sys
import itertools
from operator import ge, le, eq
import copy
import pandas as pd
import tqdm
import csv
from pybkb import bayesianKnowledgeBase as BKB
from pybkb.core.common.bayesianKnowledgeBase import BKB_I_node, BKB_component, BKB_S_node
from pybkb.core.python_base.fusion import fuse
sys.path.... |
"""backup filters."""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.errors import AnsibleFilterError
import json, os
# Return backup name without . or -
# e.g. myapp_0_1_0_daily
def backup_name_underscored(role,vars,schedule = None):
bmn = '_'.join([role,var... |
import os
import numpy as np
import cv2
from scipy.io import loadmat
import argparse
from glob import glob
from joblib import Parallel, delayed
import matplotlib.pyplot as plt
'''
Convert .mat data to the image and label data for test
'''
parser = argparse.ArgumentParser()
parser.add_argument("--dataset", type=str, d... |
from keras.layers import Conv2D, BatchNormalization, Activation, MaxPool2D, AveragePooling2D, GlobalAveragePooling2D, Flatten, Dense, Input, Concatenate
from keras.models import Model
from keras.datasets import cifar10
from keras.optimizers import Adam
from keras.callbacks import LearningRateScheduler, Callback
from ke... |
from weakref import WeakKeyDictionary, WeakValueDictionary, ref
from collections import defaultdict
import logging
logger = logging.getLogger(__name__)
def silent_logger():
'''
Silent logger for unless we have a error message.
'''
logger.setLevel(logging.ERROR)
# comment out the line below to re-enabl... |
# Copyright (C) 2020-2021 Intel Corporation
#
# SPDX-License-Identifier: MIT
from contextlib import (
ExitStack, contextmanager, redirect_stderr, redirect_stdout,
)
from io import StringIO
from typing import Iterable, Optional
import importlib
import os
import os.path as osp
import re
import shutil
import subproce... |
#
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import copy
import time
import gym
import hydra
import torch
import torch.nn as nn
import torch.nn.functional as F
from gym.wrappers impo... |
from collections import Counter # To compare two lists' contents
import re
import os
from PySide2.QtWidgets import QMessageBox, QTableWidgetItem, QComboBox
from hexrd.ui.hexrd_config import HexrdConfig
from hexrd.ui.ui_loader import UiLoader
class LoadImagesDialog:
def __init__(self, image_files, manual_assig... |
# coding=utf-8
import logging
__author__ = '<NAME> <<EMAIL>>'
# Adapted from Marty Alchin: http://martyalchin.com/2008/jan/10/simple-plugin-framework/
def find_plugins(entrypoint):
try:
import pkg_resources
except ImportError:
pkg_resources = None
if pkg_resources is None:
return... |
# SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors)
#
# SPDX-License-Identifier: MIT
# Run with 'python tools/extract_pyi.py shared-bindings/ path/to/stub/dir
# You can also test a specific library in shared-bindings by putting the pat... |
from django.shortcuts import render, redirect, HttpResponse
from app import models
import uuid
from utils.pay import AliPay
# Create your views here.
def goods(request):
goods_list = models.Goods.objects.all()
# print(goods_list)
# <QuerySet [<Goods: Goods object (1)>, <Goods: Goods object (2)>, <Goods: G... |
from functools import partial
import threading
from PyQt5.QtWidgets import (QVBoxLayout, QLabel, QGridLayout,
QWidget, QTabWidget)
from lynx_code.gui.qt.util import WindowModalDialog, Buttons, CloseButton
from lynx_code.i18n import _
from lynx_code.plugin import hook
from lynx_code.util i... |
#!/usr/bin/env python
"""
A module for visualizing labeled images.
Info:
type: eta.core.types.Module
version: 0.1.0
Copyright 2017-2021, Voxel51, Inc.
voxel51.com
"""
# pragma pylint: disable=redefined-builtin
# pragma pylint: disable=unused-wildcard-import
# pragma pylint: disable=wildcard-import
from __futu... |
# Copyright 2015 Huawei Technologies Co., Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
import curses
import random
import argparse
import time
import threading
import sys
# ---------------------------------------
# Initialize Variables and Strings
# ---------------------------------------
# Dropping Speed
SPEED = [1, 0.8 ,0.6 ,0.4, 0.2, 0.1, 0.07, 0.05, 0.03, 0.01]
def init():
global obstacles... |
# Copyright (c) 2020 The Plankton Authors.
# All rights reserved.
#
import rclpy.time
from rclpy.clock import ClockType
from rcl_interfaces.srv import GetParameters
import time
def time_in_float_sec(time: rclpy.time.Time):
"""
From a Time object, returns the associated time in float seconds
"""
sec_n... |
"""
@ <NAME> (<EMAIL>)
Generals.io Automated Client - https://github.com/harrischristiansen/generals-bot
Generals Bot: Common Move Logic
"""
import logging
import random
from pprint import pprint
from base import bot_base
from .client.constants import *
# ======================== Move Priority Capture ===... |
from __future__ import absolute_import, division, print_function
from six.moves import map
import numpy as np
import matplotlib as mpl
import utool as ut
#(print, print_, printDBG, rrr, profile) = utool.inject(__name__, '[custom_constants]', DEBUG=False)
ut.noinject(__name__, '[custom_constants]')
# GENERAL FONTS
SMAL... |
# encoding: utf-8
"""
@author: <NAME>
@contact: <EMAIL>
"""
from torch import nn
import torch
import torch.nn.functional as F
from fastreid.layers import *
from fastreid.modeling.heads.build import REID_HEADS_REGISTRY
from fastreid.utils.weight_init import weights_init_classifier, weights_init_kaiming
class Occlusi... |
from qsnake_run import extract_version, extract_name_version
def test1():
assert extract_version("onlinelab-9934211") == "9934211"
assert extract_version("termcap-1.3.1.p1") == "1.3.1.p1"
def test2():
tests = {
"onlinelab-9934211": "9934211",
"termcap-1.3.1.p1": "1.3.1.p1",
... |
import logging
import numpy as np
from data.dataset import Metric
def add_performance_data(df, simulated_cores, thread_rate_method):
"""Add performance information to a dataframe containing node information."""
df = df.copy()
def logical_cores(physical_cores, jobslots):
return 2 * physical_cor... |
'''
Test export to GADF format
'''
import astropy.units as u
import numpy as np
from astropy.io import fits
import pytest
import tempfile
e_bins = np.geomspace(0.1, 100, 31) * u.TeV
migra_bins = np.linspace(0.2, 5, 101)
fov_bins = [0, 1, 2, 3] * u.deg
source_bins = np.linspace(0, 1, 101) * u.deg
@pytest.fixture
def... |
from atlas.modules import constants, utils
from atlas.conf import settings
class SwaggerOutputWriter:
@staticmethod
def write(log, problem, solution):
solution = solution or ""
if log in {"warning", "error"}:
print(f"Swagger Validation {log}: {problem}. {solution}")
def erro... |
# Copyright (C) 2015-2021 Regents of the University of California
#
# 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 app... |
from PIL import Image
import os
import sys
class ImageBatchGenerator(object):
"""given a tied image and labelgenerator
generates from both, good for multi labeled
images that are not split into class directories
Attributes:
batch_size (int)
imgen : Image generator with a next &... |
import sys
import traceback
import os
from PyQt5.QtWidgets import QMainWindow, QAction, \
QStatusBar, QFileDialog
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QObject, QRunnable, pyqtSignal, pyqtSlot, \
QThreadPool
from scgv.models.model import DataModel
from scgv.models.featuremat_model import F... |
import discord
import time
import asyncio
import random
import json
import os
from fractions import Fraction
from discord.ext import commands
active = 0
bets = {}
outcome1 = ""
outcome2 = ""
pool1 = 0
pool2 = 0
bm = "bookmaker"
class Casino(commands.Cog):
def __init__(self, bot):
self.bot = bot
#... |
import bpy
import mathutils
import gpu
def helper_shader():
"""Returns a GPU shader for viewport helper geometry"""
vertex_shader = '''
uniform mat4 ModelViewProjectionMatrix;
in vec3 pos;
out vec3 position;
out vec3 ec_pos;
void main()
{
position =... |
import os
import sys
import cv2
import time
import numpy as np
import scipy.io
import argparse
import timm
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributed as dist
import torch.multiprocessing as mp
import albumentations as A
from glob import glob
from torch.utils.data import ... |
from copy import deepcopy
import json
from datetime import datetime
from flask_login import current_user
from portality import models, lock
from portality.core import app
from portality.tasks.redis_huey import main_queue
from portality.decorators import write_required
from portality.background import AdminBackgroun... |
from numpy import isinf, array, zeros, arange, add, subtract, cumsum, insert, unique, repeat, max, lexsort, empty
from numpy.linalg import norm
from numpy.random import rand
import numpy as np
from scipy.spatial.distance import cdist
import warnings
warnings.filterwarnings('ignore', category=RuntimeWarning)
def get... |
# Copyright 2019 The Keras Tuner 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
"""
Graph Suite
***********
Contains all functionality needed to plot functions easily.
Uses pyplot from matplotlib.
IntervalPlot3D -- takes a function in R3, an x domain, and a y domain, and plots the function at all points on those domains.\n
barGraph -- takes some data points and plots them as a series of bars, wi... |
import numpy as np
from scipy import linalg
from sklearn.neighbors import kneighbors_graph, NearestNeighbors
from sklearn.utils import check_array
from sklearn.base import BaseEstimator, TransformerMixin
class LocalityPreservingProjection(BaseEstimator, TransformerMixin):
"""Locality Preserving Projection
P... |
# -*- coding: utf-8 -*-
# @Date : 2/17/21
# @Author : <NAME> (<EMAIL>)
# @Link : None
# @Version : 0.0
import logging
from copy import deepcopy
import numpy as np
import torch
import torch.nn as nn
from torchvision.utils import make_grid
from tqdm import tqdm
from metrics import calculate_fid_given_paths_torc... |
class EWSConsts:
DCL_name = 'digital computer lab'
ECE_name = 'electrical and computer engineering building'
EH_name = 'engineering hall'
GELIB_name = 'grainger engineering library'
MEL_name = 'mechanical engineering lab'
SIEBL_name = 'siebel center'
TB_name = 'transportation building'
... |
import os
import signal
import contextlib
from pathlib import Path
from tempfile import TemporaryDirectory
from concurrent.futures import ThreadPoolExecutor, wait
import pytest
from muttlib.file_processing import ( # merge_result_dfs,; split_res,
DONE_PREFIX,
FAIL_PREFIX,
READY_PREFIX,
RenameByResult... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.