text stringlengths 3.07k 22.1k |
|---|
from irc import bot
import logging, importlib, time
import random, traceback, os, os.path
import queue, threading
ERR_MSG = 'An error occurred in "%s" and it has been disabled. The MAGIC WORD is "%s".'
class MessageBus:
def __init__(self):
self.members = []
def post(self, src, msg, ar... |
#!/usr/bin/env python3
import math
import os
import sys
import argparse
import yaml
# load parent path of KicadModTree
sys.path.append(os.path.join(sys.path[0], "..", "..", ".."))
from KicadModTree import * # NOQA
from KicadModTree.nodes.base.Pad import Pad # NOQA
sys.path.append(os.path.join(sys.path[0], "..", ".... |
from asyncio import wait, FIRST_COMPLETED
from discord import Embed
from random import choice, randint
from cogs.errors import get_error_message
from cogs.globals import PRIMARY_EMBED_COLOR
from cogs.game.minigames.base_game.player import Player
from cogs.game.minigames.checkers.pieces import COLUMNS, UNDO, RESIGN, NU... |
"""
The MIT License (MIT)
Copyright (c) 2021 <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, merge,... |
import numpy as np
import torch
import torch.distributions as D
import pytorch_lightning as pl
from sklearn.mixture import BayesianGaussianMixture
from torch.utils.data import DataLoader, TensorDataset
from typing import Tuple
from sggm.definitions import OOD_X_GENERATION_AVAILABLE_METHODS
from sggm.model_helper impo... |
# -*- coding: utf8 -*-
import logging
import six
from tests.config import (
CLASSPATH,
MAX_INT
)
import py2jdbc
import pytest
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
cx = None
cu = None
def setup():
global cx, cu
cx = py2jdbc.connect('jdbc:sqlite::memory:', classpath=CLASSPATH)
... |
#
# Copyright (C) 2017 - Massachusetts Institute of Technology (MIT)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#... |
import numpy as np
def softmax(predictions):
'''
Computes probabilities from scores
Arguments:
predictions, np array, shape is either (N) or (batch_size, N) -
classifier output
Returns:
probs, np array of the same shape as predictions -
probability for every class, 0..1
... |
from . import archmageFb as archmageFb
from . import archmageTc as archmageTc
from . import bishop as bishop
from . import hero as hero
from . import paladin as paladin
from . import sniper as sniper
from . import windBreaker as windbreaker
from . import soulmaster as soulmaster
from . import luminous as luminous
from ... |
#<NAME>
#ilk değer x=0 noktası olarak alındı
from math import sqrt
#verilen sayıları m.dereceden polinoma yaklaştırır
def yaklastir(sayi_dizisi,m=2):
n = len(sayi_dizisi)
x_uzeri_toplamlari=[]# [0]->xtoplam [1]->x**2toplam [2]->x**3toplam...
for i in range(2*m):#toplamları ekleneceğinden tüm elema... |
import sys
import os
import json
import numpy as np
import glob
import argparse
import pdb
import scipy.optimize
import scipy.stats
import f0dl_bernox
def run_f0dl_experiment(json_fn,
max_pct_diff=100/6,
noise_stdev=1e-12,
bin_width=5e-2,
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 5 17:22:59 2020
@author:
Dr. <NAME>
MIT Kavli Institute for Astrophysics and Space Research,
Massachusetts Institute of Technology,
77 Massachusetts Avenue,
Cambridge, MA 02109,
USA
Email: <EMAIL>
GitHub: https://github.com/MNGuenther
Web: www.m... |
"""Module contains Functions that calculate the local absorption coefficient
alpha.
Method 1:
Analytical expression for alpha is used. Assume weakly relativistic Maxwellian
distriution, and weak absorption. [1]_
.. [1] 1983 Nucl. Fusion 23 1153
"""
import pickle
from scipy.integrate import quad
from scipy.interpola... |
import glob
from enum import Enum # python 3.4
import json
import threading
import gzip
import os
import re
import logging
from rest_framework import status
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse, HttpResponseBadRequest, HttpResponse
from django.conf import settings
... |
from telegram.bot import Bot
from telegram.ext import Updater, MessageHandler, Filters, CommandHandler
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from os import getenv
BOT_TOKEN = getenv("BOT_TOKEN")
users_perm = [1325010317]
channel_id = "-1001402527951"
group_id = "-1001190361827"
for_group = "... |
import copy
from django.forms.widgets import Widget, Media, TextInput
from django.utils.safestring import mark_safe
from django.core.validators import EMPTY_VALUES
from django.forms.util import flatatt
class ListWidget(Widget):
def __init__(self, contained_widget, attrs=None):
self.contained_widget = cont... |
#!/usr/bin/python
#
# Copyright (C) 2016 Google, Inc
# Written by <NAME> <<EMAIL>>
#
# SPDX-License-Identifier: GPL-2.0+
#
import copy
from optparse import OptionError, OptionParser
import os
import struct
import sys
# Bring in the patman libraries
our_path = os.path.dirname(os.path.realpath(__file__))
sys.path.appen... |
#!/usr/lib/tethys/bin/python
import netCDF4 as nc
import numpy as np
import time
import os
from zipfile import ZipFile
GRASS_HEADER_TEMPLATE = """north: {north}
south: {south}
east: {east}
west: {west}
rows: {rows}
cols: {cols}
"""
ARC_HEADER_TEMPLATE = """ncols {cols}
nrows {rows}
xllcorner {west}
yllcorner {south}
... |
import pytz
import json
import random
from datetime import datetime, timedelta
from rest_framework.generics import get_object_or_404
from django.db.models import Q
from django.contrib.auth.models import User
from rest_framework.exceptions import APIException
from rest_framework import exceptions
from user.serializers i... |
from dataclasses import dataclass
import pytest
from arango import ArangoClient, formatter
from arango.database import StandardDatabase
from arango.typings import Json
from tests.executors import (
TestAsyncApiExecutor,
TestBatchExecutor,
TestTransactionApiExecutor,
)
from tests.helpers import (
empty... |
from . import api
from flask import request, jsonify, session
from apps.utils.file_upload import upload_file_qiniu
import json
from apps import constant
from apps.models import CarImage, Car, Brande, User
from apps import db, redis_store
from apps.utils.login_required import login_required
@api.route('/upload_file', ... |
import vimeo
import requests
import urllib.parse
from requests import HTTPError
import os
# from os.path import join, dirname
from dotenv import load_dotenv
from pprint import pprint
# env_path = join(dirname(__file__), "../.env")
load_dotenv(override=True)
def create_vimeo_client():
"""create Vimeo client"""
... |
# Copyright (c) 2020-2021 impersonator.org authors (<NAME> and <NAME>). All rights reserved.
import time
from collections import OrderedDict
import pprint
import numpy as np
import torch
import torch.nn as nn
import torch.distributed
import torch.backends.cudnn as cudnn
import torch.optim
from torch.utils.data.distri... |
import numpy as np
import matplotlib.image as image
import matplotlib.pyplot as plt
import matplotlib.animation as animate
import random
import sys
import math as mt
from functools import reduce
sys.path.insert(0, "../")
from nn_models import model2 as md
from data import formatImage
import time
inputSize = 28 * 28 #... |
# Copyright 2013 IBM Corp
#
# Author: <NAME> <<EMAIL>>
#
# 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... |
# Copyright (c) 2019. Partners HealthCare and other members of
# Forome Association
#
# Developed by <NAME> based on contributions by <NAME>,
# <NAME>, <NAME> and other members of Division of
# Genetics, Brigham and Women's Hospital
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may no... |
# -*- coding: utf-8 -*-
"""
Execution module for handling MetalK8s checks.
"""
import ipaddress
import re
from salt.exceptions import CheckError
__virtualname__ = "metalk8s_checks"
def __virtual__():
return __virtualname__
def node(raises=True, **kwargs):
"""Check if the current Salt-minion match some re... |
#!/usr/bin/env python3
#
################################################################################
# Original Author: <NAME> (http://orcid.org/0000-0001-6497-753X), #
# CIEMAT - Sci-Track Group (http://rdgroups.ciemat.es/web/sci-track), #
# for the EOSC-Synergy project (EU H2020 RI Grant No 85... |
"""Exceptions module for ORM package"""
import traceback
from typing import Any, Dict, Iterable, Optional
# Reexport
from psycopg2.errors import InvalidTextRepresentation # noqa: F401
# This is copied from ns_python_core for convenience but definitely belongs
# somewhere else.
ERROR_INFO_KEYS = [
"internal_statu... |
from datetime import datetime, timedelta
from logging import getLogger
from hashlib import md5
from os import environ
from uuid import uuid4
from threading import Thread
from queue import Queue
from pymongo import mongo_client
class EventHandler(Thread):
def __init__(self):
self.q = Queue()
supe... |
from schafkopf.game_modes import PARTNER_MODE, SOLO, WENZ
from schafkopf.players.data.data_scraper import DataScraper
from schafkopf.ranks import SEVEN, EIGHT, NINE, TEN, KING, UNTER, OBER, ACE
from schafkopf.suits import ACORNS, LEAVES, HEARTS, BELLS
import pytest
with open('login_data.txt') as f:
username = f.r... |
# (c) Copyright 2022 <NAME>
#
# Methods for capturing and reloading state from running Arduino.
import os.path
import threading
import time
import arduino_dbg.debugger as debugger
import arduino_dbg.io as io
import arduino_dbg.protocol as protocol
import arduino_dbg.serialize as serialize
SERIALIZED_STATE_KEY = 'sta... |
#!/usr/bin/env python
#
# Copyright (c) 2017 <NAME> <<EMAIL>>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND TH... |
from filter_octomap.msg import table
import numpy as np
import random
import rospy
import moveit_commander
import geometry_msgs.msg
import sys
from copy import deepcopy
# For sending joint level controlls
import actionlib
from control_msgs.msg import FollowJointTrajectoryAction, FollowJointTrajectoryGoal
from trajecto... |
from django.dispatch import receiver
from django.core.exceptions import ValidationError, ObjectDoesNotExist
from django.utils.translation import gettext_lazy as _
from django.db.models import Value, CharField
from django.db.models.query import QuerySet
from django.db.models.functions import Concat
from danceschool.cor... |
"""Parsers for extracting alchemical data from `NAMD <http://www.ks.uiuc.edu/Research/namd/>`_ output files.
"""
import pandas as pd
import numpy as np
import logging
from .util import anyopen
from . import _init_attrs
from ..postprocessors.units import R_kJmol, kJ2kcal
logger = logging.getLogger("alchemlyb.parsers.N... |
#!/usr/bin/python
# 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")... |
from .doc import Doc
from .vocab import Vocab
from syft.generic.object import AbstractObject
from syft.workers.base import BaseWorker
from syft.generic.string import String
import pickle
from typing import List, Union
class TokenMeta(object):
"""
This class holds some meta data about a token from the te... |
"""
@author: <NAME>
@contact: <EMAIL>
"""
import numpy as np
import copy
import torch
from config import cfg
from lib.utils.post_3d import get_3d_points
joint_to_limb_heatmap_relationship = cfg.DATASET.PAF.VECTOR
paf_z_coords_per_limb = list(range(cfg.DATASET.KEYPOINT.NUM))
NUM_LIMBS = len(joint_to_limb_heatmap_rela... |
#coding:utf-8
# 向量搜索 暴力算法
import numpy as np
import time
from scipy.spatial.distance import cosine
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.metrics.pairwise import pairwise_distances
# 把字向量转化为句向量,简单相加
def seg_vector (txt, dict_vector, emb_size=768):
seg_v = np.zeros(emb_size)
for w i... |
import numpy as np
import cv2
import math
import time
import obstacle_map
from queue import PriorityQueue
import argparse
import imageio
def load_map(fname = None,rc=0):
if fname is not None :
map_ = cv2.imread(fname)
return map_
world= 255*np.ones((200, 300, 3))
obstacle_map.obstacle_circ... |
# -*- coding: utf-8 -*-
"""
Python script to assign commodity flows on the road network
Created on Wed Nov 26 2017
@author: <NAME>
"""
import pandas as pd
import os
import psycopg2
import networkx as nx
import csv
from sqlalchemy import create_engine
import subprocess as sp
import configparser
import csv
import glo... |
import numpy as np
from itertools import product
from collections import deque, defaultdict
from .generalFunctions import *
from math import pi
class QLearner():
def __init__(self, federate, numericactions, states, seed = 0):
self.states = states
self.stateDict = {e: i for i,e in enumerate(self.sta... |
import unittest
import numpy as np
import openmdao.api as om
import numpy.testing as npt
import wisdem.commonse.environment as env
from wisdem.commonse import gravity as g
from openmdao.utils.assert_utils import assert_check_partials
npts = 100
myones = np.ones((npts,))
class TestPowerWind(unittest.TestCase):
d... |
import dataclasses
import io
import aiohttp
import discord
from dateutil.parser import parse
from discord.ext import commands
from sqlalchemy import select
from common import guild_level, conf
from common.db import session
from common.genshin_server import ServerEnum
from datamodels.spiral_abyss import SpiralAbyssRot... |
#
# Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope ... |
from app.modules.shogi import Koma
emoji_prefix = "slackshogisss_"
emoji_separetor = ":"
koma2emoji = {
Koma.empty: emoji_separetor + emoji_prefix + "mu" + emoji_separetor,
Koma.fu: emoji_separetor + emoji_prefix + "fu" + emoji_separetor,
Koma.kyosha: emoji_separetor + emoji_prefix + "kyou" + emoji_separ... |
from spira.yevon.process.all import *
from spira.yevon.process import get_rule_deck
RDD = get_rule_deck()
# FIXME: Move a geometry bridge class.
RDD.LCAR_DEVICE = 1
RDD.LCAR_CIRCUIT = 100
# ---------------------------------- GDSII ---------------------------------------
RDD.GDSII = ParameterDatabase()
RDD.GDSII.TEX... |
# voom_mode_python.py
# Last Modified: 2014-04-13
# VOoM -- Vim two-pane outliner, plugin for Python-enabled Vim 7.x
# Website: http://www.vim.org/scripts/script.php?script_id=2657
# Author: <NAME> (<EMAIL> AT <EMAIL> DOT <EMAIL>)
# License: CC0, see http://creativecommons.org/publicdomain/zero/1.0/
"""
VOoM markup mo... |
"""Convolutional LSTM
针对Time × 240min x 58fac 量价数据封装类,
并参考GoogLeNet对inputs使用两层1D卷积核降维
猫狗大战 <EMAIL>
2017-11-30
"""
import numpy as np
import tensorflow as tf
# import sonnet as snt
from sonnet.python.modules.rnn_core import RNNCore as sntRNNCore
from sonnet.python.modules.conv import Conv2D as sntConv2D
from params im... |
"""Plotting utilities."""
import collections
import itertools
import logging
import math
import numpy as np
from . import core, params
from skgenome.rangelabel import unpack_range, Region
MB = 1e-6 # To rescale from bases to megabases
def plot_chromosome_dividers(axis, chrom_sizes, pad=None, along='x'):
"""G... |
"""Ties & transform API"""
import typing
from ._binding import Target, coerce_binding
class Transform:
"""
**Execution order: Recursive Left to Right**
"""
def __init__(self):
self.args = {}
self.next = []
def transform(self, transform):
"""
Add a transform to cha... |
from queue import deque
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def getTreeHeight(root: None) -> int:
if root is None:
return 0
leftTreeHeight = getTreeHeight(root.left) + 1
rightTreeHeight = getTreeHeight(root.right) + ... |
import os
import numpy as np
from itertools import cycle
import torch
import torch.optim as optim
from torchvision import datasets
from torch.autograd import Variable
from torch.distributions import Normal, Bernoulli
from utils import weights_init
from utils import transform_config
from networks import Encoder, Decode... |
import numpy as np
from andes.core import (Algeb, ConstService, ExtAlgeb, ExtParam, ExtService,
HardLimiter, IdxParam, Lag, LeadLag, NumParam,)
from andes.core.block import IntegratorAntiWindup
from andes.core.service import (FlagValue, InitChecker, NumSelect, ParamCalc,
... |
# This relies heavily on the Spacy 2 architecture and pre-trained Word2Vec models. I've tried both the Law2Vec model
# (200-dimension vetors) and Spacy en_core_web_lb (300-dimensions). Law2Vec appears to have a slightly better F-score
# BUT both are pretty bad at the moment. I think this is due to the relatively small ... |
from http import HTTPStatus
from pathlib import Path
import yaml
from rich.progress import (
TaskID,
Progress,
BarColumn,
TextColumn,
SpinnerColumn,
TimeElapsedColumn,
TotalFileSizeColumn,
TransferSpeedColumn,
)
from starwhale.utils import console
from starwhale.consts import HTTPMetho... |
#! /usr/bin/env python3
# -*- coding:utf-8 -*-
# @Author: Vincent (<NAME>)
# @Date: 2022-6-16
"""
======================================================
Do a simple QC of fMRIPrep preproc results, check whether the files in fMRIPrep_qc_dict and Freesurfer_qc_dict are present in the fMRIPrep output folder.
Input: --d... |
import argparse
import os
import sys
from strictyaml import load, Map, MapPattern, Str, Seq, YAMLError
from modules.classes import SmartFormatter, UserInput
from modules.utils import Font, regex_test
def check_input():
""" Checks user input values"""
parser = argparse.ArgumentParser(
us... |
# coding=utf-8
# Copyright 2020 <NAME>.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... |
import igraph
import numpy
import automates.model_analysis.graph_manipulation as gm
from copy import deepcopy
# expr, simp, steps, primes and prune options from causal.effect in R are not implemented here
def identifiability(y, x, g, z=None, steps=False, stop_on_noid=True):
"""
Performs the appropriate Shpits... |
# Imports
from OpenGL.GL import *
from profiling import *
from settings import CHUNK_SIZE, MAX_HEIGHT, FLOATS_PER_VERTEX, FLOATS_PER_DEBUG_VERTEX,\
VERTS_PER_BLOCK, INDICES_PER_FACE
# Temp settings
facesPerBlock = 6
from ctypes import sizeof, c_void_p
def toGLfloats(array : list):
return (GLfloat * len(array... |
"""Shrub configuration for an evergreen build variant."""
from dataclasses import dataclass
from itertools import chain
from typing import Any, Dict, Optional, Set, FrozenSet, Sequence, List
from shrub.v2.task import Task, TaskGroup, RunnableTask, ExistingTask
from shrub.v2.dict_creation_util import add_existing_from_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2021 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license (see the COPYING file).
""" Test QiPackage """
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ impor... |
import torch
import torchvision.utils
import torch.optim as optim
import numpy as np
import pprint
import os
import time
from shutil import copyfile
from collections import Counter, namedtuple
import aux_funcs as af
import model_funcs as mf
from cmd_args import cmd_args
import network_architectures as arcs
from mode... |
# -*- coding: utf-8 -*-
"""Simple standalone script to manage dependencies with pip
Author: <NAME>
Version: 1.0
License: Apache License 2.0
It is assumed that you're using pip and `requirements.txt` to manage
dependencies, and that `pip` can be called without specifying absolute path.
USAGE:
1. In the directory tha... |
import requests
from time import sleep, perf_counter
from web3.main import Web3
from celery import shared_task
from celery_progress.backend import ProgressRecorder
from django.db.models import OuterRef, Func, Subquery
from djsniper.sniper.models import NFTProject, NFT, NFTAttribute, NFTTrait
from concurrent.futures ... |
# coding=utf-8
"""Evaluate embeddings on downstream tasks."""
import os
import math
import torch
import pprint
import numpy as np
from tqdm import tqdm
import utils.logging as logging
from torch.utils.tensorboard import SummaryWriter
from utils.parser import parse_args, load_config, setup_train_dir
from models import... |
import nibabel as nib
import numpy as np
import os
import distutils
import distutils.spawn
import glob
import tempfile
import shutil
from copy import deepcopy
import scipy.linalg as la
import subprocess
import threading
def check_file_or_dir(node_path, is_dir=False, do_raise_exception=True):
if not is_dir:
... |
import json
import logging
import time
import requests
import rlp
from ethereum import utils, transactions
from ethereum.abi import ContractTranslator
from pycoin.serialize import b2h, h2b
ADDITIONAL_START_GAS_TO_BE_ON_THE_SAFE_SIDE = 50000
INCREASED_GAS_PRICE_FACTOR = 1.1
log = logging.getLogger(__name__)
class E... |
#!/usr/bin/env python3
# -*- coding: utf8 -*-
import os
import datetime
import re
import html
import feedgenerator
from PIL import Image
from html.parser import HTMLParser
htmlparser = HTMLParser()
''' create navigation links '''
def navlinks(currentpage):
navbar = "\t\t<nav>\n"
if (currentpage > 0):
... |
from numpy import *
from scipy import optimize
import csv
def get_game_id_dict(datafile):
with open(datafile, mode='r') as infile:
reader = csv.reader(infile)
dict = {}
i = 0
for rows in reader:
dict[i] = rows[0]
i += 1
#dict = {rows[0]: rows[1] for ... |
import logging
import os
import re
import azure.mgmt.compute
import azure.mgmt.resource
from azure_runbook_util import util
from azure_runbook_util.ops_base import OpsBase
if not os.getenv("GITHUB_RUN_ID"):
from azure_runbook_util.azure_credentials import azure_credential, runas_connection
_VM_STATUS_RUNNING = ... |
###
# Discriminative Voxel-Based ConvNet Training Function
# <NAME>, 2016.
import argparse
import imp
import time
import logging
import math
import os
import numpy as np
from path import Path
import theano
import theano.tensor as T
import theano.sandbox.cuda.basic_ops as sbcuda
import lasagne
# import sys
# sys.p... |
import six
from collections import deque
from attr import attrs, attrib
from attr.validators import instance_of, provides
from zope.interface import implementer
from twisted.internet.defer import inlineCallbacks, returnValue
from twisted.internet.interfaces import (ITransport, IProducer, IConsumer,
... |
# Macros to handle a directory index
import logging, os
from .core import *
from .linking import NamespaceMacro
class IndexMacro(FileMacro):
'''Macro to create an index macro
Attributes:
- items (list<NamespaceMacro>): The import macros to the files under the
index
- index (Path): The absolute path to this... |
"""
Common tools for diagnosic tools frequently used in catchment hydrology.
"""
from typing import Union, Optional, Any
from matplotlib.axes import SubplotBase
from matplotlib.pyplot import Figure
import numpy as np
import pandas as pd
from datetime import datetime
from scipy.stats import rankdata
from hydrobox.plot... |
""" Train ImageNet on a multi-node environment.
Ref:
[1] https://research.fb.com/wp-content/uploads/2017/06/imagenet1kin1h5.pdf
[2] https://github.com/xu3kev/imagenet_dmux/blob/master/train_imagenet_multi.py
"""
import os
import argparse
import multiprocessing
from contextlib import ExitStack
import numpy as np
impo... |
# Copyright 2020 <NAME>, University of Pittsburgh
#
# 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 a... |
"""
Request and response models for limits request
"""
from typing import Optional
from pydantic import BaseModel
from datetime import datetime
from ....common.enums import ResponseStatus
from ....utils.decoders import build_loader, datetime_decoder
__all__ = ['LimitsRequestModel', 'LimitsResponseModel']
class Limi... |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 1 16:11:52 2019
@author: 86187
"""
import model as KGE
from Dataset import KnowledgeGraph
from Dataset_YG import KnowledgeGraphYG
import torch
import numpy as np
from time import time
from sklearn.utils import shuffle as skshuffle
import os
def mean... |
#combine.py: Script to combine the images from different observing periods.
#Created on 08-02-2016, updated (to Python 3.6) on 30-10-2018.
#<NAME>
#Note: This script assumes that the largest image covers all other images!
#Import the necessary packages.
import os
import numpy as np
from astropy.io import fits
... |
#!/usr/bin/python
import argparse
import codecs
import os
import os.path
import logging
import shutil
import sys
import time
import logging
import glob
import datetime
import dateutil.parser
import shutil
import http.server
import socketserver
import mimetypes
import boto3
import botocore
import watchdog
from watchdog... |
from parser.aggregate import aggregate_times, nan_to_zero, LAYER_TOTAL
from parser.naming import layers, names, phases, make_tag, subphases
from parser.naming import LAYER_APPLICATION, LAYER_CPU
from parser.naming import (PHASE_INITIALIZATION, PHASE_PREPARATION, PHASE_COMPILATION,
PHASE_INPUT... |
#! /usr/bin/env python
import numpy as np
import time
#Define the start state
start_state = np.array([[2,0,4],[6,7,1],[8,5,3]])
#Define the goal state
goal = np.array([[1,2,3],[4,5,6],[7,8,0]])
#Define predecessor for start_state
base = (np.array([0]*9)).reshape(3,3) #creates a 3x3 array of zeros
#My input to the ... |
# <NAME>
# for BroadInsitute
# in 2019
from __future__ import print_function
from matplotlib import pyplot as plt
import json
import os
import sys
import string
import subprocess
import pdb
import ipdb
import pandas as pd
import numpy as np
import itertools
import random
from taigapy import TaigaClient
tc = TaigaCli... |
import os
import re
from urllib import request
import requests
import subprocess
import sys
regex_info = re.compile(r".*<resultMsg>(?P<msg>[^']*)</resultMsg>"
r".*<downloadURI><!\[CDATA\[(?P<uri>[^']*)\]\]></downloadURI>"
r".*<versionCode>(?P<vs_code>\d+)</versionCode>",... |
# Copyright (c) OpenMMLab. All rights reserved.
import inspect
import numpy as np
import popart
import poptorch
import torch
import torch.nn as nn
from mmcv.utils import Registry
def _options_assigner(cfg, options_node):
# set popart.options by config
# cfg: dict, python data type
# options_node: python... |
import docs
import hashlib
import json
import os
import sys
import util
FLAG_NAME_MAP={"check_output":"Check Output","optimizable":"Optimizable"}
IGNORE_FLAG_NAME=["func","var","var_arg"]
def _add_data(nm,dt):
nm=nm.replace("\\","/")[:255].encode("ascii","ignore")
dt=dt[:16777215]
if (nm[-5:]==b".html"):
dt=... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import datetime
import calendar
import pathlib
import statistics
import pandas as pd
import numpy as np
import seaborn
import matplotlib.pyplot as plt
from activity import Activity, create_activity, parse_activities_csv, build_activity_dataframe, extract_activiti... |
# coding=utf-8
# Copyright (C) 2020 NumS Development Team.
#
# 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, modif... |
import tensorflow as tf
import tensorflow_probability as tfp
import tensorflow_hub as hub
tfd = tfp.distributions
tfb = tfp.bijectors
import numpy as np
def get_prior(latent_size):
return tfd.MultivariateNormalDiag(tf.zeros(latent_size), scale_identity_multiplier=1.0)
def init_once(x, name):
return tf... |
import numpy as np
import weighted
from astropy import table as table
from scipy import interpolate
import common_settings
from data_access.numpy_spectrum_container import NpSpectrumContainer
from mpi_accumulate import comm
from python_compat import range
settings = common_settings.Settings() # type: common_settings... |
from typing import Tuple
import matplotlib.pyplot as plt
import numpy as np
from sklearn import metrics
from ikfs_anomaly_detector.core.format.telemetry import TelemetryAttrs
from ikfs_anomaly_detector.core.printer import plot_telemetry, Subplot, Signal, Colours, Label
from ikfs_anomaly_detector.core.reader import Te... |
# Standard library
import os
# Third-party
import numpy as np
from numpy.lib.recfunctions import append_fields
# Project
from ._read_mist_models import IsoCmdReader, IsoReader
from ..log import logger
from ..filters import phot_system_list, get_filter_names
from ..util import MIST_PATH
phot_str_helper = {p.lower()... |
import io
import os
import random
import itertools
import numpy as np
import tensorflow as tf
import cv2
import matplotlib.pyplot as plt
from PIL import Image, ImageDraw
import math
import requests, zipfile
# Helper functions.
def _bytes_feature(value):
"""Returns a bytes_list from a string / byte."""
if isin... |
import json
import os
from collections import Counter
from functools import partial
from multiprocessing import Pool
from typing import Dict, List
from copy import deepcopy
import torch
from nltk import sent_tokenize
from tqdm import tqdm
from transformers import PreTrainedTokenizer
from transformers.tokenization_util... |
import os
import json
from typing import Text
from matplotlib.pyplot import text
import torch
import torch.nn as nn
import torch.nn.functional as F
import sys
# sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# print(sys.path)
# from speaker_model import SpeakerEmbedding
# fr... |
import sys
sys.path.insert(0,'.')
import os
import math
import torch
import torch.nn as nn
from torch.autograd import Variable
import pytorch_to_caffe
import torch.nn.functional as F
import csv
### pdn
def convert_NewLGC_NewTLGC_pdn_a_g8(args):
args.stages = '2-4-6-8-4'
args.growth = '8-8-16-... |
"""
Copyright 2020 <NAME>.
Released under the MIT License.
If you use this code, please cite the following paper:
<NAME>, <NAME>, <NAME>, <NAME>, and <NAME>.
CIE XYZ Net: Unprocessing Images for Low-Level Computer Vision Tasks.
arXiv preprint, 2020.
"""
__author__ = "<NAME>"
__credits__ = ["<NAME>"]
import argp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.