text stringlengths 3.07k 22.1k |
|---|
import datetime
from types import MethodType
import uuid
from django.conf import settings
from django.contrib.auth import get_user_model, user_logged_in
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.timezone import now
from django.utils.translation import gettext_la... |
#!/usr/bin/env python3
from numpy import zeros
from os import system
from sys import argv
from mopacamk import MOPACamk
from ase.constraints import ExternalForce,Hookean
from ase.io import read, write
from ase.md.velocitydistribution import (MaxwellBoltzmannDistribution,Stationary, ZeroRotation)
from ase import units... |
# all imports
import numpy as np
import h5py
import matplotlib.pyplot as plt
import scipy
from PIL import Image
from scipy import ndimage
#%matplotlib inline
def load_dataset():
train_dataset = h5py.File('datasets/train_catvnoncat.h5', "r")
train_set_x_orig = np.array(train_dataset["train_set_x"][:]) # ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pandas_datareader.data as pdr_data
import numpy as np
import time
import os
import sys
from collections import deque
import tensorflow as tf
#from tensorflow.models.nn import rnn
#from tf.nn.rnn_cell im... |
import xml.etree.cElementTree as ElementTree
import requests
NAMESILO_OPERATIONS = {
'add_account_funds': 'addAccountFunds',
'add_auto_renew': 'addAutoRenewal',
'add_contact': 'contactAdd',
'add_dns_record': 'dnsAddRecord',
'add_email_forward': 'configureEmailForward',
'add_portfolio': 'portf... |
from typing import Union, Any, Optional, Dict, Tuple
import multiprocessing as mp
import enum
import logging
import os
import numpy as np
import quaternion
from habitat.core.simulator import Simulator, Observations, AgentState
from habitat.config.default import Config
from habitat.sims import make_sim
_logger = log... |
import ast
import builtins
import io
import sys
import token
from collections import defaultdict
from tokenize import TokenInfo, tokenize
import astpretty
from termcolor import colored
from pprint import pprint as pp
from ast import iter_fields, AST
class ASTVisitor(ast.NodeVisitor):
def __init__(self):
... |
# coding: utf-8
"""
Contains code for the X11 window list/interaction interface.
"""
from gi.repository import GdkPixbuf
from ewmh import EWMH
import threading
import Xlib
from Xlib import X
from aspinwall.shell.interfaces.window import Window, ProtocolSpecificInterface
class X11Window(Window):
"""Represents an X11 ... |
# ----------------------------------------------------------------
# Copyright 2016 Cisco Systems
#
# 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/LICENS... |
# Copyright 2017 British Broadcasting Corporation
#
# 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... |
import os
import numpy as np
import jax
import jax.numpy as jnp
from io import StringIO
from fe import math_utils, system
from rdkit import Chem
from training import setup_system
from training import service_pb2
from matplotlib import pyplot as plt
import pickle
from fe.pdb_writer import PDBWriter
from simtk.openmm... |
import sys
import signal
import rclpy
import time
import csv
import os
import math
import numpy
import ast
from dorna2_driver import dorna
import json
from rclpy.node import Node
from sensor_msgs.msg import JointState
from robot_msgs.msg import GuiToRobot
from robot_msgs.msg import RobotToGui
from robot_msgs.msg impo... |
"""
Collection of utilities used for model learning and evaluation.
============================================================================================================================
This code is provided under the MIT License and is meant to be helpful, but WITHOUT ANY WARRANTY;
November 2020 by <NAME> and... |
import requests
import pandas as pd
import json
import time
import warnings
import logging
import ConfigParser
import os
import sys
import ast
environment = sys.argv[1]
root = os.path.dirname(os.path.abspath(__file__))
# changing working directory
os.chdir(root)
# getting paths from config file
config = ConfigParser... |
# -*- coding: utf-8 -*-
"""EAFA searcher and helpers"""
__author__ = "fraser"
import logging
import re
import requests
from bs4 import BeautifulSoup
from cache import Cache, Store, conditional_headers
from . import kodilogging
from . import kodiutils as ku
EAFA_URI = "http://www.eafa.org.uk/"
EAFA_SEARCH_URI = "{... |
import numpy as np
from dash import html, dcc
from dash.dependencies import Input, Output, State
import plotly.express as px
import plotly.graph_objs as go
from app import app
from datasets import db
import apps.utilities as util
possible_plot = ['Line', 'Scatter']
dropdown_type = html.Div([
dcc.Dropdown(
... |
from collections import OrderedDict
import operator
from sklearn.metrics import roc_curve, auc, f1_score, precision_recall_curve, accuracy_score
from tqdm import tqdm_notebook
import pandas as pd
import numpy as np
from scipy.sparse import coo_matrix
import pdb
def create_gen_marginal_df(L_data, models, lfs_columns,... |
import traceback
import warnings
from joblib import Parallel, delayed
from ..io import dump_object
from .DTAIExperimenterExecutor import DTAIExperimenterShellExecutor
from .Executor import Executor, ShellCommandExecutor, ShellExecutor
from .pinac import generate_nodefile
try:
from tqdm import tqdm
from dask ... |
from config import *
from flask import Flask
from flask import abort, Response, request, send_from_directory
from flask_restful import reqparse
from werkzeug.utils import secure_filename
from env import *
import logging
from datetime import datetime
from botocore.client import Config
from botocore.exceptions import Cli... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import sys
def summary_to_file():
# idea for sys.stdout: https://stackoverflow.com/questions/3263672/the-difference-between-sys-stdout-write-and-print
sys.stdout = open ("analysis_summary.txt","w")
print ("\n")
... |
#%% [markdown]
"""
pop 1 is a DC-SBM, 2 block, affinity the difference between it and pop 2 is that for
pop 1, the promiscuity parameter is 0.5 for all vertices and for pop 2, vertex 1 has a
different promiscuity parameter
similar analysis as before, but this time, we compare doing things "edge-wise" to doing
things "... |
from nose import with_setup
from nose.tools import raises
from sql.magic import SqlMagic
from textwrap import dedent
import os.path
import re
import tempfile
ip = get_ipython()
def setup():
sqlmagic = SqlMagic(shell=ip)
ip.register_magics(sqlmagic)
def _setup():
ip.run_line_magic('sql', 'sqlite:// CREATE... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, division, print_function, absolute_import
import os
import datetime
import testdata
from prom import query, InterfaceError
from prom.interface.sqlite import SQLite
from prom.interface import configure
from prom.model import Orm
from prom.config import F... |
#! /usr/env/python
#
# Utility to scan for available phidgets
#
import time
import re
import argparse
from Phidget22.Devices.Manager import Manager
from Phidget22.Net import Net, PhidgetServerType
from Phidget22.ChannelClass import ChannelClass
from Phidget22.ChannelSubclass import ChannelSubclass
from Phidget22.De... |
import os
from itertools import takewhile
import logging
from bs4 import BeautifulSoup
try:
import selenium
from selenium.webdriver import Chrome
except:
class Chrome:
def __init__(self):
raise Exception("Selenium is not available")
from tabulate import tabulate
logger = logging.ge... |
"""
Buffer protocol support.
"""
# The implementation of the buffer protocol. The basic idea is that we
# can ask any app-level object for a 'buffer' view on it, by calling its
# __buffer__() special method. It should return a wrapped instance of a
# subclass of the Buffer class defined below. Note that __buffer__(... |
import base64, json, collections
import brutejudge._http.types as bjtypes
from .oauth import do_oauth
from ..base import Backend
from ..ejudge import get, post
from ...error import BruteError
from ..html2md import html2md
def b64encode(s):
return base64.b64encode(s).replace(b'=', b'').replace(b'/', b'_').replace(b... |
'''Trains infoGAN on Cifar10 using Keras
[1] Chen, Xi, et al. "Infogan: Interpretable representation learning by
information maximizing generative adversarial nets."
Advances in Neural Information Processing Systems. 2016.
'''
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorfl... |
"""
functions used in cmd_asap.py
"""
"""for loading in_file"""
def load_in_file(in_file):
"""Here goes the routine to compute the descriptors according to the state file(s)"""
with open(in_file, 'r') as stream:
try:
from yaml import full_load as yload
state_str = yload(strea... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
## For Testing Matrix2vec on dataset MNIST
## PCA, Kernel PCA, ISOMAP, NMDS, LLE, LE
import logging
import os.path
import sys
import numpy as np
import multiprocessing
import argparse
import datetime
import operator
import scipy.io
# import matrix2vec_rxl
import matrix2v... |
"""
:Name: populationWL.py
:Date: 2015, 2019
:Author: <NAME>, <<EMAIL>>
:Description: Some useful classes and functions for population weak lensing (lensing by foreground objects such as galaxies, clusters, or voids)
:Package: mkstuff
"""
import glob
import os
import re
import numpy as np
from astropy.io impo... |
import os
import isce3
import h5py
import numpy as np
from osgeo import gdal
from dataclasses import dataclass
@dataclass
class BlockParam:
'''
Class for block specific parameters
Facilitate block parameters exchange between functions
'''
# Length of current block to filter; padding not included
... |
# Copyright 2021 Alibaba Group Holding Limited. 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 ... |
# Copyright (c) 2019, NVIDIA 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/licenses/LICENSE-2.0
#
# Unless required by applic... |
from django_tables2 import RequestConfig
from django.shortcuts import render
from django.forms import modelformset_factory
from django.views.decorators.csrf import csrf_protect
from django.contrib.auth.decorators import login_required
from .tables import SKUBranchTable
from .commons import *
from .models import SKUBran... |
"""
Converts data from con to brat. Enter input and output directories as command line arguments.
Each '.con' file must have a '.txt' file in the same directory with the same name, minus the extension.
Use '-c' (without quotes) as an optional final command-line argument to copy the text files used
in the conversion pro... |
import time
import shutil
import torch
# global variables
best_acc1 = 0
# Average Value Computer Class
class AverageMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
... |
################################################################################
# Copyright (c) 2018 Advanced Micro Devices, Inc. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in th... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from core.models import Squadra, Giocatore, Partita, Evento, DettaglioPartita
import core.registra_partita
import pymodel.abstract
import tkMessageBox
from Tkinter import *
import ttk
import sys
import os
finestre = {}
conndb = None
def todo():
pass
def destroy(o)... |
import ipaddress
import random
# seems to work finding the smallest subnet that also contains all the networks given.
def one_net(_subnets):
"""
Get the one IP network that covers all subnets in input or None is subnets are disjoint.
"""
if len(_subnets) == 0:
return None
minimum_length =... |
# -*- coding: utf-8 -*-
"""
fysql.columns
~~~~~~~~~~~~~
:copyright: (c) 2016 by <NAME>
:license: MIT, see LICENSE for more details.
"""
from __future__ import unicode_literals
import json
import _pickle as cPickle
from .entities import SQLColumn, SQLCondition, SQLQuotedEntity
from .exceptions import Fy... |
from .rman_translator import RmanTranslator
from ..rman_sg_nodes.rman_sg_mesh import RmanSgMesh
from ..rman_utils import object_utils
from ..rman_utils import string_utils
from ..rman_utils import property_utils
import bpy
import math
def _get_mats_faces_(nverts, material_ids):
mats = {}
for face_id, num_ver... |
#!/usr/bin/python
import cv2
import platform
from socket import *
import numpy as np
import ball_finder
import target_finder
import time
import sys
TEAM = "red"
CAMERA_PATH = "/dev/v4l/by-path/"
# With hub
# BALL_CAMERA_ID = CAMERA_PATH + "platform-3530000.xhci-usb-0:2.4:1.0-video-index0"
# HOOP_CAMERA_ID = CAMERA_PA... |
from __future__ import division
import os
import numpy as np
import math
import csv
from time import localtime, strftime
from PIL import Image
import scipy.misc
import subprocess
import matplotlib.pyplot as mp
def loadDemo(data_path, resize_size):
# Read human_demo.txt
txt_name = [ss for ss in os.listdir(dat... |
import json
import pickle
#all station list to search sttaion names in corpus
with open('station_list.txt') as f:
temp = f.read().splitlines()
with open('station_to_station_code.txt', 'r') as f:
data = json.load(f)
with open('station_code_to_zone.txt', 'r') as f:
data_2 = json.load(f)
with open('tr... |
'''
Implements the three body decay kinematics as described in 1609.01770 for the decay Pi(0) -> V -> XX
'''
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ja')
plt.rcParams['axes.facecolor'] = 'white'
SMALL_SIZE = 16
MEDIUM_SIZE = 16
BIGGER_SIZE = 20
plt.rc('font', size=SMALL_SIZE) # con... |
import os
from typing import Optional
import numpy as np
from PIL import Image
from numba import jit
from numpy.linalg import inv
import cv2
def read_pc_from_bin(bin_path):
"""Load PointCloud data from bin file."""
p = np.fromfile(bin_path, dtype=np.float32).reshape(-1, 4)
return p
def read_image(path):
... |
from seamless.highlevel import Context, Cell, Transformer, Module
ctx = Context()
# HACK: X3DNA computation is non-reproducible. Never forget a result!
from seamless.core.cache.buffer_cache import buffer_cache
buffer_cache.LIFETIME_TEMP = 999999
buffer_cache.LIFETIME_TEMP_SMALL = 999999
####
ctx.pdb_code = "1B7F"
ct... |
import os
import numpy as np
import matplotlib.pyplot as plt
def run_gmmpbsa():
bash_cmd = """
export MMPBSA=/opt/g_mmpbsa/bin
export GMX=/opt/gromacs-5.1.2
export GMXLIB=$GMX/share/gromacs/top
export PYTHON=python3.7
export LIG=OUT
export REC=Protein
$GMX/bin/gmx -qui... |
#!/usr/bin/env python3
"""Python script to run PgOSM Flex.
Designed to be ran in Docker image:
https://hub.docker.com/r/rustprooflabs/pgosm-flex
"""
import configparser
import logging
import os
from pathlib import Path
import sys
import subprocess
import click
import osm2pgsql_recommendation as rec
import db, ge... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 16 17:28:03 2017
@author: rwilson
"""
import shelve
import pickle
import numpy as np
import pandas as pd
from sqlalchemy import create_engine
class utilities:
'''A logical collection of functions for interacting with
'''
@staticm... |
# Copyright (c) 2019 <NAME>.
# Uranium is released under the terms of the LGPLv3 or higher.
import base64
import json
import os
from typing import Optional, Tuple
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitiv... |
import os
import random
import re
import subprocess
import sys
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
from threading import Thread
from typing import NoReturn, Tuple
import requests
from bs4 import BeautifulSoup
from googlehomepush import GoogleHome
from googlehomepush.http_ser... |
import enum
import logging
from typing import Optional, Union, Tuple, Iterable
import numpy as np
from .azimuthalcurve import AzimuthalCurve
from .curve import Curve
from .header import Header
from ..algorithms.matrixaverager import ErrorPropagationMethod, MatrixAverager
from ..algorithms.radavg import radavg, autoq,... |
# http.py
#
# Copyright 2018 <NAME> <<EMAIL>>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice,... |
import os
import time
import pytest
import logging
from cassandra import ConsistencyLevel
from cassandra.query import SimpleStatement
from dtest import Tester, create_ks
from tools.assertions import assert_one
from tools.data import rows_to_list
from tools.misc import retry_till_success
since = pytest.mark.since
log... |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
functions to manage layers
-------------------
begin : 2019-05-17
git sha : $Format:%H$
author : <NAME>
***********... |
import argparse
from tqdm import tqdm
import sys
import random
from sklearn.metrics import f1_score
from pyHGT.data import *
from pyHGT.model import *
from warnings import filterwarnings
filterwarnings("ignore")
import torch
import torch.nn.functional as F
from ogb.nodeproppred import PygNodePropPredDataset, Evaluat... |
from typing import Tuple, Set, List, Optional, Union
from anytree import PreOrderIter, LevelOrderIter, AnyNode
from anytree.exporter import DictExporter
from anytree.importer import DictImporter
from license_expression import Licensing, ExpressionError
from license_sh.normalizer import normalize
from license_sh.proje... |
import json
from html import escape
from typing import List, Optional
import spacy
from bleach import linkify
from textile import textile
from fastapi import Depends, FastAPI, HTTPException, Header
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session
from sql_controller import crud, m... |
from datetime import datetime
import logging
import re
from google.appengine.api import memcache
from google.appengine.api.labs.taskqueue import TaskAlreadyExistsError
from google.appengine.api.urlfetch import DownloadError
from google.appengine.ext import db
from google.appengine.ext import deferred
import simplejso... |
#!/usr/bin/env python
import argparse
import numpy as np
import logging
import matplotlib.pyplot as plt
import os
from optparse import OptionParser
import glob
import sys
try:
import python_antenna_pattern.config as config
from python_antenna_pattern.core import AntennaPattern
from python_antenna_pattern.core imp... |
#
# Darknet RegionLoss
# Copyright EAVISE
#
import logging
import math
import numpy as np
import torch
import torch.nn as nn
try:
import pandas as pd
except ModuleNotFoundError:
pd = None
__all__ = ['CornerLoss']
log = logging.getLogger(__name__)
class CornerLoss(nn.modules.loss._Loss):
""" Computes... |
#!/usr/bin/env python3
import argparse
import atexit
import queue
import shutil
import subprocess
import sys
import threading
import time
from pathlib import Path
from typing import List, Iterable, Dict, Set, Tuple, Union
from weakref import WeakSet
from hfstol.shared import Header, Alphabet
from hfstol.transducer imp... |
from keras.layers.convolutional import Conv2D
from keras.layers.core import Activation
from keras.layers.pooling import MaxPooling2D
from keras.layers.merge import Add
from keras.layers.normalization import BatchNormalization
from keras.models import Model
from keras.regularizers import l2
from ..utils.net_utils impor... |
"""
All rights reserved to cnvrg.io
http://www.cnvrg.io
cnvrg.io - AI library
Written by: <NAME>
Last update: Oct 06, 2019
Updated by: <NAME>
random_forest_regressor.py
==============================================================================
"""
import argparse
import pandas as pd
from sklearn.model_sel... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import cv2
import numpy as np
import math
import time
def check_point(point, map):
feasibility = True
if map[point[1], point[0]] == 0:
feasibility = False
return feasibility
def check_path(point_current, point_other, map):
# 路径检查的采样点数,取路径横向与纵向... |
#!/usr/bin/env python3
# std
import copy
import collections
from typing import Optional, Union, List, Callable
from pathlib import PurePath, Path
# 3rd
import pandas as pd
import tqdm.auto
# ours
from clusterking.stability.stabilitytester import (
AbstractStabilityTester,
SimpleStabilityTesterResult,
)
from ... |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import pickle
import argparse
import random
import copy
from transformers import AutoTokenizer
import torch
import torch.nn as nn
from eval import get_token_segments, confusion_matrix_tokens, evaluate_model_answer_spans, get_jaccard_score
CRA_TOKEN... |
from dataclasses import dataclass
from typing import Any, Dict, Generic, Iterable, List, Set, Tuple, TypeVar
from feast.base_feature_view import BaseFeatureView
from feast.diff.property_diff import PropertyDiff, TransitionType
from feast.entity import Entity
from feast.feature_service import FeatureService
from feast.... |
import os
import pandas as pd
import json
from pytorch_pretrained_bert import BertTokenizer
import torch
import codecs
"""
- Simple function to rid data on txt file and split by ids
- You can read the txt file as dataframe by using the section function
"""
tokenizer = BertTokenizer.from_pretrained("bert-base-uncased... |
#!/usr/bin/env python
# coding: utf-8
# # This program is to split a dataset into a training set and a testing set
#
# Written on 2019/03/22 and modified on 2019/09/28 by <NAME>.
# In[1]:
# -*- coding: UTF-8 -*-
import time
time_Start = time.time()
from sklearn import model_selection
import pandas, numpy
import sy... |
import time
from hw5_lib import *
PART1 = False
PART2 = False
PART3 = False
PART4 = False
PART5 = False
def setupButtons(window, botton_width, botton_height, space_from_side, space_from_bottom):
win_width, win_height = window.getWidth(), window.getHeight()
start_btn = Rectangle(Point(space_from_sid... |
import math
from math import pi, cos, sin, sqrt, atan
def sign(x):
if x > 0:
return 1
elif x < 0:
return -1
else:
return 0
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return '({:.2f}, {:.2f})'.format(self.x, self.... |
import torch
import torch.nn
import torch.nn.functional as F
from torch.nn import init
# import numpy as np
# =============================================================================
#
# Two rotationally invariant non-linearties
# > RadRelu - the radial relu
# > VecRelu - the directional relu, as in "Vector Ne... |
from app import app
from app import util
from flask import jsonify
from flask import request
from requests.exceptions import ConnectionError
from requests.exceptions import Timeout
from apscheduler.schedulers.background import BackgroundScheduler
import time
import logging
import requests
ERROR_MSG_CLUSTER_NOT_REACH... |
import random
import os
import numpy as np
import cv2
from PIL import Image
from torchvision import transforms
import torchvision.transforms.functional as tf
# 图像变换函数
from albumentations import (
HorizontalFlip, VerticalFlip, IAAPerspective, CLAHE, RandomRotate90, ElasticTransform, RandomGamma,
Transpose, Shift... |
import os
import pickle
import random
import tempfile
import threading
import pytest
import torch
import numpy as np
from falkon.ooc_ops import gpu_lauum
from falkon.center_selection import FixedSelector
from falkon import kernels, FalkonOptions, InCoreFalkon
from sklearn import datasets
from falkon.utils import de... |
# coding=utf-8
#
# Versão do Python: 3.6.5
#
# Trabalho LINGUAGENS FORMAIS E AUTOMATOS
#
# Grupo:
# 00230091 - <NAME>
# 00229724 - <NAME>
# 00217052 - <NAME>
#
import NormalFormOfChomsky
import Subword
def run(grammar, word):
# Removendo whitespace e resolvendo o caso em que os terminais possuem mais de um carac... |
import torch
import numpy as np
from .layer import FeaturesLinear, MultiLayerPerceptron, FeaturesEmbedding
class FactorizationMachine(torch.nn.Module):
def __init__(self, reduce_sum=True):
super().__init__()
self.reduce_sum = reduce_sum
def forward(self, x):
"""
:param x: Flo... |
import ldap.filter
import srusers
from team import Team
from college import College
import constants
class User(object):
@classmethod
def create_user(cls, username, password=None):
if User.can_authenticate(username, password):
return AuthenticatedUser(username, password)
else:
... |
import asyncio
import inspect
import unittest
import unittest.mock
import discord
from tests import helpers
class DiscordMocksTests(unittest.TestCase):
"""Tests for our specialized discord.py mocks."""
def test_mock_role_default_initialization(self):
"""Test if the default initialization of MockRol... |
from collections import (
defaultdict,
)
import json
import logging
import os
from typing import (
ClassVar,
List,
Mapping,
Optional,
Sequence,
Set,
Tuple,
Union,
)
from uuid import (
UUID,
uuid5,
)
import attr
from furl import (
furl,
)
from github import (
Github,
... |
import yaml
import argparse
import numpy as np
import matplotlib.pyplot as plt
from models import *
import torch
from torchvision import transforms, datasets
import torchvision.utils as vutils
from torch.utils.data import DataLoader
from PIL import ImageFile
from sklearn.manifold import TSNE
from torchvision.datasets ... |
from glob import glob
import pandas as pd
from multiprocessing import cpu_count, Pool
from os.path import isdir, join, isfile
from functools import partial
from os import scandir
from collections.abc import Iterable
from sqlalchemy import (create_engine, engine, Column,
Text, Table, MetaData, St... |
# SPDX-License-Identifier: Apache-2.0
"""
An example console application that uses the subarulink package.
For more details about this api, please refer to the documentation at
https://github.com/G-Two/subarulink
"""
import argparse
import asyncio
from datetime import datetime
import logging
import os.path
from pprin... |
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
from OpenGL.GL.shaders import *
import numpy as np
import sys
global COORDS, COLORS, X_AXIS, Y_AXIS, Z_AXIS, \
PITCH, ROLL, YAW, MODE, VERTEX_VBO, COLOR_VBO
def display_cpu():
global X_AXIS, Y_AXIS, Z_AXIS, \
PITCH, ROLL, YAW, COORDS, COL... |
# ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by <NAME> (<EMAIL>)
# Modified by <NAME> (<EMAIL>)
# ------------------------------------------------------------------------------
from __future__ import absolute_impo... |
import re
from django.views.decorators.debug import sensitive_post_parameters
from corehq.apps.hqwebapp.models import MySettingsTab
from corehq.apps.style.decorators import use_bootstrap3, use_select2
from dimagi.utils.couch.resource_conflict import retry_resource
from django.contrib import messages
from django.contrib... |
import unittest
from common_utils import TestCase, run_tests
from common_cuda import TEST_CUDA
from collections import namedtuple
import itertools
import torch
import sys
def namedtensor_enabled():
return '-DBUILD_NAMEDTENSOR' in torch.__config__.show()
skipIfNamedTensorDisabled = \
unittest.skipIf(not named... |
import abc
import itertools as itools
import numpy as np
from numpy import linalg as la
from . import util
from .simplex import simplex_coordinates1
from .util import __SLACK__
class ColorMapBase(object):
__metaclass__ = abc.ABCMeta
def __init__(self, coords, colors, verbose=False, **kargs):
super()... |
import os.path
import tensorflow as tf
import helper
import numpy as np
from glob import glob
import tensorflow.contrib.slim as slim
from tensorflow.python.tools import freeze_graph
from tensorflow.python.tools import optimize_for_inference_lib
from network import *
def optimize(nn_last_layer, correct_label, learni... |
# Copyright 2016 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.
# TODO(http://crbug.com/669639): there are lots of ways to make the code
# in this file better. We avoid having separate todos per task; instead
# see that m... |
# -*- coding: utf-8 -*-
"""Python Backend controlling Mantarray."""
from __future__ import annotations
import argparse
import base64
import copy
import hashlib
import json
import logging
import multiprocessing
import os
from os import getpid
import platform
import queue
from queue import Queue
import socket
import sys... |
#!/usr/bin/env python3
import itertools
import argparse
import socket
import curses
import time
from multiprocessing import Process
from subprocess import Popen, PIPE, DEVNULL
import pychromecast
import chardet
from twisted.web import http
from twisted.web.server import Site, Request, NOT_DONE_YET
from twisted.web.reso... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# pylint: disable=E1120, E1123
import random
from hashlib import md5
from datetime import datetime, timedelta
import jsonschema
from pony import orm
from flask import current_app
from smilepack.bl.utils import BaseBL
from smilepack import schemas
from smilepack.databa... |
# -*- coding: utf-8 -*-
"""Classes for elastic backscatter calculation"""
from ELDAmwl.bases.factory import BaseOperation
from ELDAmwl.bases.factory import BaseOperationFactory
from ELDAmwl.component.registry import registry
from ELDAmwl.errors.exceptions import NoValidDataPointsForCalibration
from ELDAmwl.rayleigh imp... |
import numpy as np
import math
import scipy.special as bessel
def coef_pi_tau(theta, x):
"""Compute the angle-dependant functions (pi and tau) using upward recurrence.
Per Bohren and Huffman (1983) eq. 4.47, the angle-dependant functions :math:`\pi_n` and
:math:`\\tau_n` can be computed using upward rec... |
import numpy as np
from scipy.interpolate import UnivariateSpline, interp1d
from scipy.integrate import quad
import imripy.merger_system as ms
from scipy.special import jv
def h_2(sp, t, omega_s, R, dbg=False, acc=1e-13):
"""
This function calculates the gravitational waveform h_+,x according to eq (25) in ht... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, bikbuk and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
import json
import pytz
from datetime import datetime as dt
from frappe.model.document import Document
from vet_website.vet_website.doctype.vetop... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.