text stringlengths 3.07k 22.1k |
|---|
import enum
from typing import Optional
import cv2
import numpy as np
from attr import attrib, attrs
from ..geometry import solve_pnp
from ..util import as_float, require
from .intrinsics import CameraIntrinsics, CameraModel, DistortionModel
__all__ = [
"ImageExtent",
"InterpolationMethod",
"OpenCvUndist... |
import structlog
import pandas as pd
import json
import os
import tarfile
import datetime
import frictionless
from urllib.request import urlretrieve
from django.utils.translation import gettext_lazy as _
from django.db.models import Q
from django.views.decorators.http import require_GET
from django.http import HttpRes... |
# To run the solutions, you must have bokeh 0.12.0 and pyproj installed.
# To install these packages, in a terminal/commandline run
#
# conda install bokeh==0.12.0
# conda install pyproj
#
# This lab also includes data sets you will need to download. To download
# the needed data, in ipython run
#
# i... |
from math import sin, cos, tan, sqrt
# size of buffer in one container
CONTAINER_MAX_LENGTH = 200
# time slice between two entries in buffer
# time slice down, accuracy up, cost of space up
# should be between 0 and 1
CONTAINER_TIME_SLICE = 1
def prettyStrDict(dictionary):
return "{"+", ".join(["'"+st... |
# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use ... |
import pytest
from aleph.handlers.storage import handle_new_storage
from aleph.storage import ContentSource, RawContent
import json
from aleph.exceptions import UnknownHashError
@pytest.fixture
def fixture_message_file():
return {
"_id": {"$oid": "621908cb378bcd3ef596fa50"},
"chain": "ETH",
... |
"""
This test format currently uses code generation to assemble the tests
as the current test infra does not have a facility to dynamically
generate tests that can be seen by ``pytest``.
This will likley change in future releases of the testing infra.
NOTE: To add additional scenarios, add test cases below in ``_gene... |
from typing import Optional
from deca.gui.vfs_widgets import used_color_calc
from deca.db_processor import VfsNode
from deca.db_view import VfsView
from deca.ff_types import *
import PySide2
from PySide2.QtCore import QAbstractTableModel, QModelIndex, Qt, Signal
from PySide2.QtGui import QColor
from PySide2.QtWidgets i... |
# -*- coding: utf-8 -*-
"""Helper functions for YoAPI."""
# Only certain functions in the string module are deprecated.
# pylint: disable=deprecated-module
import calendar
import inspect
import random
import string
import sys
import time
from datetime import datetime
from functools import update_wrapper
import ge... |
from bottle import default_app
from bottle import redirect
from bottle import request
from bottle import response
from bottle import route
from bottle import run
from bottle import view
import csv
import datetime
import importlib
import itertools
import os
import psycopg2
import psycopg2.extras
import random
import req... |
# Copyright (c) 2012-2016 Seafile Ltd.
import json
import logging
from rest_framework import status
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from seaserv i... |
from qiskit import Aer, IBMQ, QuantumRegister, ClassicalRegister, QuantumCircuit, execute
import getpass, random, numpy, math
def title_screen ():
print("\n\n\n\n\n\n\n\n")
print(" ██████╗ ██╗ ██╗ █████╗ ███╗ ██╗████████╗██╗ ██╗███╗ ███╗ ")
print(" ██╔═══██╗██║ ██... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
from mashcima.CanvasOptions import CanvasOptions
import numpy as np
from typing import List, Optional
from mashcima.vocabulary import get_pitch, to_generic
from mashcima.vocabulary import is_accidental
from mashcima.vocabulary import parse_annotation_into_token_groups
from mashcima.vocabulary import KeySignatureTokenGr... |
from unittest.mock import AsyncMock, MagicMock, PropertyMock
import pytest
import abstracts
from envoy.base.runner import AsyncRunner
from envoy.base import utils
from envoy.distribution import repo
@abstracts.implementer(repo.ARepoBuildingRunner)
class DummyRepoBuildingRunner:
def add_arguments(self, parser... |
"""
Contains implementations of the Public facing API: EmissionsTracker, OfflineEmissionsTracker and @track_emissions
"""
from abc import abstractmethod, ABC
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime
from functools import wraps
import logging
import os
import time
... |
import os
import sys
import string
from string import punctuation
import collections
from collections import defaultdict
import spacy
from spacy.pipeline import EntityRuler
import csv
import scispacy
from negspacy.negation import Negex
from spacy.matcher import PhraseMatcher
from spacy.matcher import Matche... |
"""This module contains the general information for KmipServer ManagedObject."""
from ...imcmo import ManagedObject
from ...imccoremeta import MoPropertyMeta, MoMeta
from ...imcmeta import VersionMeta
class KmipServerConsts:
ADMIN_ACTION_DELETE = "delete"
ADMIN_ACTION_TEST_CONNECTION = "test-connection"
cl... |
import os
import sys
import matplotlib.pyplot as plt
import numpy as np
import openpyxl
import seaborn as sns
def plot_evaluation(file_workbook, tlt):
if os.path.exists(file_workbook):
book = openpyxl.load_workbook(file_workbook)
else:
print("Wrong file path")
sys.exit()
results ... |
"""
Classes used for modular modeling of different regression methods
Defines the Regressor Abstract Base Class that can be used to create
custom regression methods
Subclasses of Regressor can be used with the CurveExtension class
in the hrosailing.pipeline module
"""
import inspect
import logging.handlers
from abc... |
from queue import Full
from util.agent import math, Vector
def cap(x, low, high):
# caps/clamps a number between a low and high value
return max(min(x, high), low)
def cap_in_field(agent, target):
if abs(target.x) > 893 - agent.me.hitbox.length:
target.y = cap(target.y, -5120 + agent.me.hitbox.... |
import tensorflow as tf
import numpy as np
from tensorflow.keras.callbacks import TensorBoard, ModelCheckpoint, Callback
import _common.utils as c_ut
class CustomTensorBoard(TensorBoard):
""" to log the loss after each batch
"""
def __init__(self, log_every=1, **kwargs):
super(CustomTensorBoard, ... |
# The following was adapted from install_poetry.py from Poetry,
# published under the MIT License:
from __future__ import absolute_import
import argparse
import functools as ft
import json
import os
import re
import shutil
import site
import subprocess
import sys
from contextlib import closing
from io import Unsuppor... |
from socket import inet_aton
import struct
from charmhelpers.core.hookenv import (
config,
related_units,
relation_get,
relation_ids,
status_set,
log,
)
from charmhelpers.core.templating import render
import common_utils
import docker_utils
config = config()
MODULE = "analytics"
BASE_CONFIG... |
from __future__ import print_function
import keras
import tensorflow as tf
from keras.models import Sequential, Model, load_model, save_model
from keras.layers import Input, Dense, TimeDistributed, LSTM, Dropout, Activation
from keras.layers import Convolution2D, MaxPooling2D, Flatten, Conv2D
from keras.layers.normali... |
import numpy as np
import queue
class IVGraphNode:
data = None
x = None
y = None
def __init__(self, x, y, data):
self.data = data
self.x = x
self.y = y
def __str__(self):
return "[" + str(self.data) + "]"
class IVGraph:
nodes = None
... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Dict, List, Mapping, Optional, Tuple, Union
from .. import ... |
import sys
import csv
import re
import configparser
from collections import defaultdict
def validate(func):
def read_config(config_path):
config = configparser.ConfigParser()
config.read(config_path)
return config
def get_reqs_dict(config_path):
config = read_config(config_p... |
# -*- coding:utf-8 -*-
from __future__ import division, absolute_import
from simple_ml.base.base_model import *
from simple_ml.base.base_enum import *
from simple_ml.base.base_error import *
import numpy as np
from collections import Counter
from simple_ml.evaluation import *
__all__ = [
'ID3',
'CART'
]
c... |
import numpy as np
from collections import deque
import json
def debug_gradient(model, losses):
model.zero_grad()
for name, loss in losses:
print(name)
loss.backward(retain_variables=True)
stats = [
(p.grad.norm().data[0],
p.grad.max().data[0],
p.... |
from django.test import Client
from wagtail.tests.utils import WagtailPageTests
from coderedcms.models.page_models import (
CoderedArticleIndexPage,
CoderedArticlePage,
CoderedEventIndexPage,
CoderedEventPage,
CoderedFormPage,
CoderedLocationIndexPage,
CoderedLocationPage,
CoderedPage,
... |
from django.contrib import admin
from django.urls import path
from django.contrib.messages import success
from django.core.exceptions import PermissionDenied
from django.http import Http404, HttpResponseRedirect
from django.template.response import TemplateResponse
from django.utils.decorators import method_decorator
f... |
from transformers import BertPreTrainedModel
from transformers.utils import logging
from BERT_explainability.modules.layers_ours import *
from BERT_explainability.modules.BERT.BERT import BertModel
from BERT_explainability.modules.BERT.GPT2 import GPT2Model
from torch.nn import CrossEntropyLoss, MSELoss
import to... |
from django.shortcuts import render,get_object_or_404,redirect
from .models import Main
from category.models import Category
from subcategory.models import subCategory
from news.models import News
from contantform.models import Cont
from django.core.files.storage import FileSystemStorage
import datetime
from django.con... |
# coding=utf-8
# Copyright 2020 The TF-Agents 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 la... |
"""
Mesh net model.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import flags
import numpy as np
import torch
import torchvision
import torch.nn as nn
from torch.autograd import Variable
from torch.nn import init
from ..utils import mesh
fr... |
import os
import numba
from numba import types
from numba.typed import Dict, List
from numba import njit
import numpy as np
# paths
BASE_PATH = os.path.dirname(__file__)
IMG_PATH = os.path.join(BASE_PATH, "img")
STYLE_PATH = os.path.join(BASE_PATH, "style")
DOCS_PATH = os.path.join(BASE_PATH, "docs")
DATA_PATH = os.pa... |
#!/usr/bin/env python
# coding: utf-8
# # Adding a New Dataset
#
# There exist two different options to use a different dataset within the `neuralHydrology` library.
#
# 1. Preprocess your data to use the `GenericDataset` in `neuralhydrology.datasetzoo.genericdataset`.
# 2. Implement a new dataset class, inheriting ... |
import torch, math, random, time
VISUALIZE_POINTS = 100
CONSTANT_SLICE = 0.5
TRUE_MASK = None
def create_from_str(dataname, N, D, noise):
dataset = search(dataname)
return create_from_dataset(dataset, N, D, noise)
def create_from_dataset(dataset, N, D, noise):
torch.manual_seed(5)
T = dataset.g... |
#//
#//------------------------------------------------------------------------------
#// Copyright 2007-2011 Mentor Graphics Corporation
#// Copyright 2007-2011 Cadence Design Systems, Inc.
#// Copyright 2010-2011 Synopsys, Inc.
#// Copyright 2019-2020 <NAME> (tpoikela)
#// All Rights Reserved Worldwide
#//
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 3 15:45:02 2019
@author: Mijael
"""
import nltk
import re
import spacy
import json
import xml.etree.ElementTree as ET
from collections import defaultdict
from allennlp.predictors.predictor import Predictor
from spacy.matcher import Matcher
from nltk.chunk import RegexpP... |
from Bio import SeqIO
from Bio.Seq import MutableSeq
from Bio.Seq import Seq
import sys
import numpy as np
# input for overall script, just fasta file of codon-aligned sequences
fastaInput = sys.argv[1]
# DNA alphabet, could be changed but probably not
alphabet = ["A", "T", "G", "C"]
### Determine expect... |
import numpy as np
import warnings
from aenum import Enum, extend_enum
from ..tree.tree import copy_tree
def metrics_greater_than_zero(metrics: np.array) -> np.array:
"""
Changes metric array to be sure that each metric is greater than zero.
Firstly it finds the minimum_value which is the value to replac... |
"""
Custom RNN Cell definition.
Default RNNCell in TensorFlow throws errors when
variables are re-used between devices.
"""
import tensorflow as tf
from tensorflow.contrib.rnn import BasicRNNCell
from tensorflow.python.util import nest
from tensorflow.python.training import moving_averages
from tensorflow.python.ops i... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Project Name: ComputerVision
File Name: inception_v1.py
"""
__author__ = 'Welkin'
__date__ = '2019/6/19 02:51'
import torch
import torch.nn as nn
import torch.nn.functional as F
from .util_modules import conv_bn_relu
__all__ = ['inception_v1', 'inception_v1_b... |
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import base64
import collections
import copy
import httplib
import json
import logging
import os
import re
import socket
import sys
import time
import httpl... |
from model import ABHUE, GlobalModule
from losses import DistanceClusterLoss
import preprocess
import torch
import torch.optim as optim
import torch.nn as nn
import os
import time
from k_means import Kmeans
import inference
import argparse
import importlib
from natsort.natsort import natsorted
from memCheck import usi... |
"""
Base classes for pipeline input steps.
"""
# Standard library imports
import abc
import importlib
# Local imports
import brokkr.pipeline.base
import brokkr.pipeline.datavalue
import brokkr.pipeline.decode
import brokkr.pipeline.utils
import brokkr.utils.misc
# --- Core base classes --- #
class ValueInputStep(b... |
from typing import Tuple
import numba as nb
import numpy as np
from nptyping import NDArray
SQRT2 = np.float32(np.sqrt(2))
SQRT6 = np.float32(np.sqrt(6))
SQRT32 = np.float32(np.sqrt(3 / 2))
SQRT12 = np.float32(np.sqrt(1 / 2))
SQRT16 = np.float32(np.sqrt(1 / 6))
@nb.njit(nb.types.UniTuple(nb.float32[:], 2)(nb.float3... |
#!/usr/local/bin/python3
"""
This is written by <NAME> to try out Solutions 1-4
from [Sceenivasan, 2017].
Reference for Solutions 1, 2, 3, and 4 [Sceenivasan, 2017]:
<NAME>, "How to implement a switch-case statement
in Python: No in-built switch statement here," from JAXenter.com,
Software {\rm \&}\ Support ... |
# coding: utf-8
# In[1]:
import pandas as pd ## biblioteca de estruturação e analise de dados
import numpy as np ## biblioteca de algebra linear entre outras utilidades
## --------------------- ##
## plotly/dash libraries ##
## --------------------- ##
import dash
import plotly.graph_objs as go
from dash.dependen... |
# -*- coding: utf-8 -*-
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext as _
from django.contrib.gis.db import models
from django.db.models.query import Q
from mptt.models import MPTTModel, TreeForeignKey
from mptt.managers import TreeManager
from parler.model... |
import os
import ipdb
import matplotlib
import torch as t
from tqdm import tqdm
import numpy as np
from scipy.misc import imsave
from utils.config import opt
from data.dataset import Dataset, TestDataset, inverse_normalize
from model import FasterRCNNVGG16
from torch.autograd import Variable
from torch.utils import d... |
import numpy as np
import math
from vars import pargs
import warnings
import pdb
warnings.filterwarnings("error")
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# physical/external base state of all entites
class EntityState(object):
def __init__(self):
# physical position
self.p_pos = None
# physical velocity... |
import math
import random
from torch.utils.data import Dataset
from package.definition import EOS_TOKEN, logger, SOS_TOKEN
from package.feature import spec_augment, get_librosa_melspectrogram
from package.utils import get_label, save_pickle
class BaseDataset(Dataset):
"""
Dataset for audio & label matching
... |
'''
Copyright 2017, Fujitsu Network Communications, Inc.
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 w... |
"""Utilities for accessing JSTOR Data for Research Corpus"""
import itertools as _itertools
import re as _re
from nltk.probability import FreqDist
from nltk.util import ngrams
from nltk.collocations import AbstractCollocationFinder, BigramCollocationFinder
from nltk.metrics import BigramAssocMeasures, TrigramAssocMea... |
# -*- coding: utf-8 -*-
"""
Sample a space-time raster dataset at specific vector points
"""
import pickle
import tempfile
from flask import jsonify, make_response
from flask.json import dumps as json_dumps
from copy import deepcopy
from flask_restful_swagger_2 import swagger
from actinia_core.resources.common.respons... |
from contextlib import suppress
from functools import partial
from unittest.mock import Mock, patch
import pytest
from sqlalchemy import MetaData, Table, create_engine, event, select
from sqlalchemy.exc import NoSuchTableError
from sqlalchemy.schema import CreateTable
from sqlalchemy_aio import TRIO_STRATEGY
from sql... |
from django.contrib import messages
from django.shortcuts import render, get_object_or_404, redirect
from .forms import *
from .models import Usuario
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User
from django.views.dec... |
# 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://aws.amazon.com/apache2.0/
#
# or in the "license" file acc... |
from makefun import with_signature, add_signature_parameters
from decopatch.utils_modes import SignatureInfo, make_decorator_spec
from decopatch.utils_disambiguation import create_single_arg_callable_or_class_disambiguator, disambiguate_call, \
DecoratorUsageInfo, can_arg_be_a_decorator_target
from decopatch.utils_... |
""" +=========================================================================================+
|| Lab 8: Sudoku ||
|| Name: <NAME> Date: 11/4/14 ||
+===================================... |
'''
Author: <NAME>
Date: 2021-06-15 11:17:02
LastEditTime: 2021-06-15 18:36:41
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: /NetProject/classification/classification.py
'''
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import sys
sys.path.append('./feature/')
sys.pat... |
# ----------------------------------------------------------------------------
# - Open3D: www.open3d.org -
# ----------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2018 www.open3d.org
#
# Permission is her... |
r"""Tool to help populate doc/release_notes/*.rst entries by automatically
adding commit messages' content into a structured document template.
This program is intended only for use by Drake maintainers who are preparing
Drake's release notes documentation.
This program is supported only on Ubuntu Bionic 18.04.
The ... |
import unittest
from balancebot.driver import Driver
from balancebot.driver_set import DriverSet
class TestEquality(unittest.TestCase):
def test_equality_for_driver_sets_containing_same_drivers(self):
driver1 = Driver(9135924, '<NAME>', 1889)
driver2 = Driver(7540813, '<NAME>', 1309)
driver3 = Drive... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilitie... |
'''
Session 07
Sorting
'''
from code07_timing import Stopwatch
'''
Python Sorting
https://developers.google.com/edu/python/sorting
The easiest way to sort is with the sorted(list) function, which takes a list and returns a new list with those elements in sorted order. The original list is not changed.
It's mos... |
# Copyright (c) 2018 <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, publish, distribute, ... |
import torch
import torch.autograd as autograd
from torch import nn
from torch.nn.utils.spectral_norm import spectral_norm
import copy
from gan.config import GANConfig
GENERATOR = 'Generator'
DISCRIMINATOR = 'Discriminator'
def get_value(t):
if isinstance(t, torch.Tensor):
return t.item()
return t
... |
# interface graphique pour les drones
from tkinter import *
# Mise en place de parametres importants
window = Tk()
# Premier objectif : Creer un portail d'accueil pour lancer le drone, ou pour superviser le drone
"""
# Creation d'image pour le fond d'ecran de la page d'accueil
width = 700
height = 500
image = Photo... |
#!/usr/bin/env python
"""Basic test of the Calc module on 2D data."""
import datetime
from os.path import isfile
import shutil
import unittest
import pytest
import itertools
import cftime
import numpy as np
import xarray as xr
from aospy import Var
from aospy.calc import Calc, _add_metadata_as_attrs, _replace_pressur... |
import torch
import torch.autograd
import torch.nn as nn
from .block_sparse import BlockSparseMatrix
import typing
class BlockSparseLinearFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, input, weight_data, weight):
check = False
verbose = False
if verbose or check:
... |
#!/bin/env python
#
# module to wrap bosco_cluster and related functionality
# .bosco/clusterlist
# .bosco/.pass
# entry=griddev03.racf.bnl.gov max_queued=-1 cluster_type=slurm
#
import logging
import os
import subprocess
import shutil
import threading
import time
# Added to support running module as script from arbi... |
import tensorflow as tf
import numpy as np
import time
import scipy.sparse as sp
from sklearn.metrics import roc_auc_score, average_precision_score, roc_curve, precision_recall_curve, auc
from preprocessing import construct_feed_dict
from outputs import viz_train_val_data, viz_roc_pr_curve, max_gmean_thresh
def trai... |
from pynput.keyboard import Key, KeyCode
from pynput.keyboard import Controller as KeyController
import time
from winelf import global_settings
__all__ = ['Key', 'KeyboardElf']
# 动作延迟
def _keyboardSecurityDelay(func):
def wrapper(*args, **kwargs):
self = args[0]
# 前置延迟
before_delay = kwar... |
"""
quaternion.py
<NAME>
2015-08-03
Defines two classes: Quaternion, which describes mathematical quaternions, and QList, which describes a list of quaternions with support for element-wise operations.
"""
import numpy as np
class Quaternion:
def __init__(self, *args, **kwargs):
"""A Quaternion... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 24 21:05:53 2018
@author: Luke
"""
#==============================================================================
#SUMMARY
#==============================================================================
# 12 March 2020
# This script processes ... |
""" Python Character Mapping Codec generated from 'CP856.TXT' with gencodec.py.
Written by <NAME> (<EMAIL>).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
(c) Copyright 2000 <NAME>.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return c... |
#!/usr/bin/env python3
'''
This script was born from the need to auto-generate a set of training genes given
a selection of pre-generated evidence from tools like GeneMark-ES, CEGMA, AAT and
transcript evidence aligned with GMAP.
Initially written to support the annotation of 40+ mucormycosis-causing genomes,
this ma... |
import torch
import numpy as np
from torch import nn
from einops import repeat, rearrange
from einops.layers.torch import Rearrange
from module import ConvAttention, PreNorm, FeedForward
from TokenLearner import TokenLearnerModule, TransformerBlock
from torchsummary import summary
class Transformer(nn.Modul... |
import csv
import glob
import json
import os
import sys
from pathlib import Path
import cv2
import numpy as np
import pandas as pd
from PIL import Image
from PIL.ImageQt import ImageQt
from PyQt5.QtCore import QEvent, QSize, Qt, pyqtSignal, qDebug
from PyQt5.QtGui import (QColor, QFont, QFontMetrics, QGuiApplication, ... |
from ignite.engine import Engine
from ignite.metrics import PSNR, SSIM
from torchvision import transforms
from tqdm import tqdm
from torch.autograd import Variable
from PIL import Image
import sys
import copy
import argparse
import os
import glob
from os import path
import torch
import torch.optim as optim
import torc... |
#!/bin/env python3
import sys
import os
opts = [opt for opt in sys.argv[1:] if opt.startswith("-")]
camos = [
"Atomic",
"Dark-Aether"
]
cat = [
"Assault-Rifles",
"SMGs",
"Shotguns",
"LMGs",
"Marksman-Rifles",
"Sniper-Rifles",
"Handguns",
"Launchers",
"Melee"
]
half_camo = [... |
from collections import Counter
from ceph_medic import metadata, daemon_types
from ceph_medic.util import configuration, str_to_int
#
# Utilities
#
def get_fsid(data):
# FIXME: might want to load this thing into ConfigParser so that we can fetch
# information. ceph-deploy is a good example on how to do this.... |
from shapely.wkb import loads
import json
from ... import getTile
from ...Core import KnownUnknown
def get_tiles(names, config, coord):
''' Retrieve a list of named TopoJSON layer tiles from a TileStache config.
Check integrity and compatibility of each, looking at known layers,
correct JSON ... |
import random
import numpy as np
def read_puzzle(in_line):
"""
reads a sudoku puzzle from a single input line
:param in_line: 9 space-separated 9-digit numbers ranging from 0-9
:return: returns the numbers in a numpy array
"""
arr = np.zeros((9,9), dtype=int)
for i, line in enumerate(in_li... |
#!/usr/bin/env python
import os
import sys
import argparse
import traceback
import json
import math
import re
import logging
from contextlib import redirect_stdout
import ndex2
import igraph
logger = logging.getLogger(__name__)
DEFAULT_BOX_SIZE = 550.0
"""
Default size of bounding box to fit layout
into
"""
DEFA... |
import pandas as pd
from csv import DictWriter
import os
import json
import logging
import pickle
import datetime
import time
from ast import literal_eval
from pymongo import MongoClient
logging.root.setLevel(logging.NOTSET)
logging.basicConfig(
level=logging.NOTSET,
format='%(asctime)s %(module)s - %(funcName... |
from django.shortcuts import render
from django.views.generic import ListView, DetailView
# (Seungeon)
from django.contrib.auth.models import User
from users.models import Profile, Property
from messages.models import Message
from django.db.models import Q
import requests
def home(request):
profile = Profile.obj... |
# Copyright 2017 Mycroft AI Inc.
#
# 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 writin... |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 7 14:30:37 2021
@author: vedhs
"""
import pyglet
import gravitySim as gs
#interface variables
width=1280
height=720
#generating window
win = pyglet.window.Window(width,height,'2D gravity simulator')
win.set_vsync(False)
batch=pyglet.graphics.Batch()
#Showing labels
... |
#!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible is distribut... |
import concurrent.futures
import contextlib
import os
import subprocess
import tempfile
import threading
from dataclasses import dataclass
from pathlib import Path
from typing import Generator, List, Optional
from judge.schema import CompareMode, History, JudgeStatus, TestCasePath, TimerMode
from judge.tools import co... |
import collections
class KeyError(object):
pass
class Mf(collections.defaultdict):
"""Wrapper for collections.defaultdict which enables multi-factor indexing through a ranked defaultdict.
The integer rank defines the number of independent factors which can be used in the indexing.
Example:
-----... |
# -*- coding: utf-8 -*-
import argparse
import glob2
import itertools
import logging
import logging.config
from logging.handlers import RotatingFileHandler
import platform
import re
import os
import os.path
import sys
import yaml
import json
import beaver
MAGIC_BRACKETS = re.compile('({([^}]+)})')
IS_GZIPPED_FILE = r... |
from z3 import z3
from teether.evm.exceptions import SymbolicError
from teether.memory import UninitializedRead
from teether.util.z3_extra_util import concrete, get_vars_non_recursive
class Stack(list):
def __init__(self, *args):
super(Stack, self).__init__(*args)
def push(self, v):
self.app... |
import pandas as pd
import numpy as np
import cvxpy as cvx
#### file to make the simulation of people that we can work with
class Person():
""" Person (parent?) class -- will define how the person takes in a points signal and puts out an energy signal
baseline_energy = a list or dataframe of values. This is data... |
import os
import sys
import click
import json
import logging
from collections import OrderedDict
from time import sleep
from signal import signal, SIGPIPE, SIG_DFL
from ..helpers.sequence_helpers import get_seqio_fasta_record
from ..helpers.file_helpers import return_filehandle, check_stdin
signal(SIGPIPE, SIG_DFL) ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.