text stringlengths 3.07k 22.1k |
|---|
# -*- encoding: utf-8 -*-
# Copyright (c) 2020 <NAME> <<EMAIL>>
# ISC License <https://choosealicense.com/licenses/isc>
"""
"""
import sys
from string import printable
from typing import Optional
from unittest.mock import patch
import pytest
from hypothesis import given
from hypothesis.strategies import (
binary... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author : 陈坤泽
# @Email : <EMAIL>
# @Date : 2020/06/03 09:52
from pyxllib.prog.pupil import check_install_package
check_install_package('bidict')
check_install_package('sqlalchemy')
check_install_package('mysqlclient')
import math
from bidict import bidict
import p... |
#!/usr/bin/env python
#ckwg +28
# Copyright 2011-2020 by Kitware, Inc.
# All rights reserved.
#
# 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,... |
#
# Copyright (C) Mellanox Technologies Ltd. 2021. ALL RIGHTS RESERVED.
#
# See file LICENSE for terms.
import requests
import configparser
import json
import logging
import os
import argparse
import time
import datetime
import sys
from pyfluent.client import FluentSender
PLUGIN_NAME = "UFM_API_Streaming"
CONFIG_FIL... |
import pyroomacoustics as pra
import numpy as np
from pydub import AudioSegment
from sklearn.utils import shuffle
from glob import glob
import random
import json
import malaya_speech.train as train
import malaya_speech.config
import malaya_speech.train.model.transducer as transducer
import malaya_speech.train.model.con... |
"""
Create WEEKLY-REPORT-<DATE>.json for all the orgs and projects,
and save then inside _data directory.
Similarly for MONTHLY report as well.
Also call report_posts.py module to create _posts reflecting the reports.
"""
from glob import glob
import datetime
import json
import os
import re
import report_posts
PATH_... |
# !/usr/bin/env python
#============================ 导入所需的库 ===========================================
import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.layers import Conv2D, Activation, MaxPool2D, Flatten, Dense, Dropout, LSTM
# import cv2
import sys
import random
import numpy... |
import numpy as np
import cv2, os, argparse
from glob import glob
from tqdm import tqdm
from plate_number import random_select, generate_plate_number_white, generate_plate_number_yellow_xue
from plate_number import generate_plate_number_black_gangao, generate_plate_number_black_shi, generate_plate_number_black_ling
fr... |
# This file is part of Hypothesis, which may be found at
# https://github.com/HypothesisWorks/hypothesis/
#
# Most of this work is copyright (C) 2013-2020 <NAME>
# (<EMAIL>), but it contains contributions by others. See
# CONTRIBUTING.rst for a full list of people who may hold copyright, and
# consult the git log if yo... |
"""Utilities to deal with sympy.Matrix, numpy and scipy.sparse."""
from sympy import Matrix, I, Expr, Integer
from sympy.matrices import eye, zeros
from sympy.external import import_module
__all__ = [
'numpy_ndarray',
'scipy_sparse_matrix',
'sympy_to_numpy',
'sympy_to_scipy_sparse',
'numpy_to_symp... |
import os
from typing import Dict
from .parser import parser # parser(directory).parser(module)
from .utils import check_path
from .exceptions import InvalidKeyError
class PrefsBase:
FIRST_LINE = "#PREFS"
SEPARATOR_CHAR = "="
ENDER_CHAR = "\n"
CONTINUER_CHAR = ">"
COMMENT_CHAR = "#"
INDENT_CHAR = "\t"
KEY_PAT... |
"""Get features from a grayscale image.
Features of NGTDM are uncertain.
"""
import os
import sys
import matplotlib.pyplot as plt
import numpy as np
def main():
"""Main function."""
# Load an image as grayscale.
img = load_img()
assert img.ndim == 2, 'The image is not 2-dimentional ndarray.'
#... |
import json
from abc import abstractmethod
from dataclasses import dataclass
from enum import Enum
from functools import reduce
from typing import Dict, Type, Union, List, Iterable, Any, Tuple, Set
import pypika
from pypika import Query, Order
from pypika.enums import Arithmetic, Comparator
from pypika.functions impor... |
import re
arrayoflocations=[] #not for colleges, but for front end
def addToList(self, str_to_add):
if str_to_add not in self:
self.append(str_to_add)
branches=['','Aeronotical','Automobile', 'Automobile', 'BioMedical', 'BioTechnology', 'Chemical', 'Civil', 'Computer', 'ElectricalAndElectronics', 'Elec... |
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Auxiliary functions library for reports extractor and dicom anonymization
# Copyright (C) 2017 <NAME>
# Licensed under MIT License.
#
from __future__ import absolute_import
import csv
import os
import re
from .distance import distance
try:
from scandir import wal... |
import collections
import contextlib
import hashlib
import json
import os
from typing import Dict, Iterator, List, Optional
from .api import API
from . import buildroot
from . import host
from . import objectstore
from . import remoteloop
from .devices import Device, DeviceManager
from .inputs import Input
from .mount... |
import argparse
import ast
import collections
import configparser
import contextlib
import os.path
import re
import subprocess
import tokenize
from typing import DefaultDict
from typing import Generator
from typing import List
from typing import NewType
from typing import Optional
from typing import Pattern
from typing... |
#
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
import argparse
import io
import json
from os import PathLike
from typing import Any, Dict, Iterable, List, Mapping, Union
from unittest.mock import ANY
import pytest
from airbyte_cdk.destinations import Destination
from airbyte_cdk.models import (
Airb... |
from abc import abstractmethod
import contextlib
from typing import Union
from datetime import datetime, timedelta
import sirius_sdk
from sirius_sdk.agent.pairwise import Pairwise
from sirius_sdk.hub import CoProtocolP2P
from sirius_sdk.agent.ledger import Ledger
from sirius_sdk.agent.aries_rfc.utils import utc_to_str... |
import csv
import requests
import json
import sys
"""The WormCSV module holds classes that make up the infrastructure of the data layer in WormBait
All classes in this module are used, in one way or another, to manipulate the data that makes
up the core of the WormBait run. There is a class for each of reading input ... |
"""
link to text widget documentation : https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/text-methods.html
Changelog:
1. Added a modification check flag for New file and open file.
2. Added a save confirmation to the open file method.
"""
from tkinter import *
from tkinter import filedialog, mess... |
"""
test_model.py
Tests for the GreynirTopic Model and TupleModel modules
Copyright (C) 2020 by <NAME>.
This software is licensed under the MIT License:
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
... |
import os.path as op
import numpy as np
from glob import glob
from PIL import Image
import zipfile
from tfrecords.readers.reader_base import DataReaderBase
from tfrecords.tfr_util import resize_depth_map, apply_color_map
class DrivingStereoReader(DataReaderBase):
def __init__(self, split=""):
super().__i... |
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 18 10:53:00 2020
@author: <NAME>
This script generates the figures for
IBPSA.Media.Antifreeze.EthyleneGlycolWater.
"""
from __future__ import division, print_function, absolute_import
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.t... |
import numpy as np
import os
from astronomaly.base.base_pipeline import PipelineStage
try:
from keras.models import load_model
from keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D
from keras.models import Model
except ImportError:
print("Failed to import Keras. Deep learning will be unava... |
# -*- coding: utf-8 -*-
"""
Tools for searching bytecode for key statements that indicate the need for additional resources, such as data files
and package metadata.
By *bytecode* I mean the ``code`` object given by ``compile()``, accessible from the ``__code__`` attribute of any
non-builtin function or, in PyInstalle... |
from pathlib import Path
import joblib
import pytest
import numpy as np
from scipy import sparse
import anndata as ad
from anndata.tests.helpers import asarray, gen_adata, assert_equal, subset_func
subset_func2 = subset_func
# -------------------------------------------------------------------------------
# Some tes... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import argparse
import cv2
from maskrcnn_benchmark.config import cfg
from predictor import COCODemo
from refinenet.code.linemod_tools import LabelInfo
import time
import os
import json
import numpy as np
import glob
from evaluatio... |
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
from .fixed_data_teacher i... |
#!/usr/bin/env python
import logging
import os
import time
import string
import subprocess
import sys
import re
import socket
from collections import OrderedDict
import requests
logger = logging.getLogger(__name__)
# Config ENV
BACKEND_PORT = os.getenv("BACKEND_PORT", os.getenv("PORT", "80"))
FRONTEND_PORT = os.get... |
# Copyright 1999-2021 Alibaba Group Holding Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
from flask import Flask, render_template, jsonify, json, url_for, request, redirect, Response, flash, abort, make_response, send_file
import requests
import io
import os
import csv
import datetime
import investmentportfolio
print ('Running Portfolio Analyze')
app = Flask(__name__)
# On IBM Cloud, get the port number ... |
#!/usr/bin/env python3
import sys
import shared
def import_nodes(nodes_dmp, log_file, quiet):
message = 'Importing file {0}.'.format(nodes_dmp)
shared.give_user_feedback(message, log_file, quiet)
taxid2parent = {}
taxid2rank = {}
with shared.open_maybe_gzip(nodes_dmp, 'rt') as f1:
... |
#!/usr/bin/python
# Copyright (c) 2017, 2021 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for d... |
#!/usr/bin/env python
# -*- coding: utf-8
# Copyright (C) 2013 <NAME> <<EMAIL>>
# All rights reserved.
#
# 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 copyrig... |
from Jumpscale import j
from wsgidav import compat
import mimetypes
import types
class FILE(j.data.bcdb._BCDBModelClass):
def _schema_get(self):
return j.data.schema.get_from_url("jumpscale.bcdb.fs.file.2")
_dir_model_ = None
@property
def _dir_model(self):
if not self._dir_model_:
... |
# #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module that contains functions and classes related with IKs
"""
from __future__ import print_function, division, absolute_import
import maya.cmds
from tpDcc import dcc
from tpDcc.libs.math.core import scalar
from tpDcc.dccs.maya.core import attribute as attr_util... |
# coding=utf-8
# author: al0ne
# https://github.com/al0ne
import re
import base64
import urllib3
import glob
import itertools
import concurrent.futures
import logging
import ssl
import chardet
import socket
import OpenSSL
import requests
import random
from urllib import parse
from bs4 import BeautifulSoup
from lib.ver... |
import os
import sys
import json
import collections
import numpy as np
from tqdm import tqdm
import mercantile
from rasterio.crs import CRS
from rasterio.transform import from_bounds
from rasterio.features import rasterize
from rasterio.warp import transform
from supermercado import burntiles
import psycopg2
from r... |
import asyncio
import bisect
import random
from . import logger, util
from .constants import ValueType
from .encodings import ValueRepresentation
"""
Update interval between update runs (in seconds).
"""
DEFAULT_UPDATE_FREQUENCY = 5
"""
Interval between reinit runs (in seconds).
"""
DEFAULT_REINIT_RATE = 60
class ... |
#!/usr/bin/env python3
"""
Tetris for Python / Tkinter
<NAME>
https://github.com/olemb/tetris/
http://tetris.wikia.com/wiki/Tetris_Guideline
"""
import random
from dataclasses import dataclass, replace
import tkinter
shapes = {
# See README.md for format.
'O': ['56a9', '6a95', 'a956', '956a'],
'I': ['45... |
"""
These are video related models.
"""
from dataclasses import dataclass, field
from typing import Optional, List
import isodate
from isodate import ISO8601Error
from pyyoutube.error import ErrorCode, ErrorMessage, PyYouTubeException
from .base import BaseModel
from .common import (
BaseApiResponse,
Base... |
# racetrack route planner
# based on apex cone locations and track widths, get a
import numpy as np
maxv = 10
laterala = 8
maxk = 1.5
bw_v = np.pi*2*0.7
bw_w = np.pi*2*1.5
# track is a set of points and radii (positive or negative if track goes CCW/CW
# around each point)
# so first we determine the nearest point
... |
from Snake import Snake
from Apple import Apple
import pygame
import random
import tflearn
import math
from tflearn.layers.core import input_data, fully_connected
from tflearn.layers.estimator import regression
from statistics import mean
from collections import Counter
import numpy as np
class Game:
def __init_... |
from traceback import format_exception
from urllib.parse import urljoin
from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.fields import GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.db import model... |
from __future__ import unicode_literals
import sys
sys.path = sys.path[1:]
from django.contrib.sessions.backends.db import SessionStore
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render, render_to_response
from django.core.mail import send_mail
from django.conf import setti... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
from rpy import r
def platt(light, etr, ini=None):
"""
Adjust a curve of best fit, following the Platt model.
Parameters
----------
light : arr
Generally PAR values. Where Photosynthetic Active Radiance
interfer on... |
from __future__ import division, print_function, absolute_import
import numpy as np
from numpy.testing import assert_array_equal, assert_equal
from scipy.optimize._constraints import (NonlinearConstraint, Bounds,
PreparedConstraint)
from scipy.optimize._trustregion_constr.canoni... |
import numpy as np
from copy import deepcopy
from utils import normalize, normalize_all, rotate
class BaseAgent:
"""Base class for lead and follower agents.
This class is used as a container for basic attributes and shared private
methods. The actual functionality is implemented within its subclasses.
... |
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license... |
import argparse
import os
import io
import time
import base64
from datetime import datetime
import threading
import signal
from screeninfo import get_monitors
import socket
from firebase import firebase
from google.cloud import storage
from PIL import Image
import imutils
import cv2
import numpy as np
import torch... |
import mongoengine as mongo
from collections import defaultdict
from django.db import models
from django.contrib.auth.models import User
from apps.rss_feeds.models import Feed
class FeatureCategory(models.Model):
user = models.ForeignKey(User)
feed = models.ForeignKey(Feed)
feature = models.CharField(max_l... |
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. 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 requir... |
"""
Author: <NAME>
Copyright: (C) 2019-2020 <http://www.dei.unipd.it/
Department of Information Engineering> (DEI), <http://www.unipd.it/ University of Padua>, Italy
License: <http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0>
"""
import os
import torch
from model_3 import Model... |
#!/usr/bin/python
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import logging
import hashlib
import base64
import hmac
import datetime
import urllib
from azure.storage.blob import BlobServiceClient, ContainerClient, PublicAccess
from azure.storage.queue import QueueS... |
import itertools
import torch
import networkx as nx
from torch_geometric.utils import convert
from torch_geometric.data import Data
def check_edge_index_are_the_same(upper_index, edge_index):
"""Checks that two edge/cell indexes are the same."""
# These two tensors should have the same content but in differe... |
import pandas as pd
import numpy as np
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import os
from random import choice, sample
import cv2
from imageio import imread
from keras.preprocessing.text import Tokenizer, one_hot
from keras.preprocessing.seq... |
# Copyright 2018 ARM Limited
#
# 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... |
from .util import load_lib, is_otf
import tempfile
import numpy as np
import tifffile as tf
import os
import ctypes
import logging
logger = logging.getLogger(__name__)
OTFLIB = load_lib("libradialft")
if not OTFLIB:
logger.error("Could not load libradialft!")
else:
try:
shared_makeotf = OTFLIB.makeO... |
import os
import struct
from numpy import newaxis as na
import numpy as np
from py_wake.deficit_models.deficit_model import DeficitModel
from py_wake.superposition_models import LinearSum
from py_wake.wind_farm_models.engineering_models import PropagateDownwind, All2AllIterative
class FugaDeficit(DeficitModel):
a... |
##############################################################################
#
# Copyright (c) 2003 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... |
# $LicenseInfo:firstyear=2010&license=mit$
# Copyright (c) 2010, Linden Research, Inc.
#
# 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... |
import yaml
from timeit import default_timer
from typing import Dict
from datetime import datetime
import os
import logging
import argparse
import shutil
import pickle
import pdb
import torch
import torch.nn as nn
import numpy as np
from sklearn.preprocessing import MinMaxScaler
class Timer():
def __init__(self,... |
'''
File: isg.py
Author: <NAME> (<EMAIL>)
Date: 25 Jan 2016
* Copyright (c) 2014/2015/2016, <NAME> and Data61/NICTA
* All rights reserved.
*
* Developed by: <NAME>
* Data61 / NICTA
* http://www.nickmattei.net
* http://www.preflib.org
*
* Redistributio... |
import numpy
import math
import os
import gc
import cv2
import pandas
from tensorflow.keras.utils import Sequence
import girder_client
from sklearn.utils import shuffle
import random
class CNNSequence(Sequence):
def __init__(self,datacsv,indexes,batchSize,labelName,gClient = None,tempFileDir = None,shuffle=True,a... |
"""Hexapawn, by <NAME> <EMAIL>
A pawn-only chess variant where you must try to move one of your
pawns to the opposite end of the board. You also win if you block
your opponent from making a move. The original Hexapawn had a 3x3
board with six pawns, but this program lets you use boards of any
size. Based on Martin Gard... |
# Applications using Tkinter
# 1. Import tkinter
from tkinter import *
'''------------------------ Functions --------------------------'''
# function to compute and display Multiplcation Table
def multiplication_table():
txtTable_MT.delete("1.0", END)
try:
n = int(entNumber_MT.get())
... |
from re import match, findall
from threading import Thread, Event
from time import time
from math import ceil
from html import escape
from psutil import virtual_memory, cpu_percent, disk_usage
from requests import head as rhead
from urllib.request import urlopen
from telegram import InlineKeyboardMarkup
from bot.helpe... |
import sys
import os
from glob import glob
import pickle
import configparser
import logging
import logging.config
from tzlocal import get_localzone
from pytz import timezone
from pytz.exceptions import UnknownTimeZoneError
from tablo.api import Api
logger = logging.getLogger(__name__)
# For batch Api call
MAX_BATCH = ... |
from __future__ import division, print_function, absolute_import
print('Importing libraries...')
import numpy as np
import imageio
import math
import pandas as pd
import tensorflow as tf
from PIL import Image
from skimage import transform #For downsizing images
from sklearn.model_selection import train_test_split
print... |
import collections
import random
import math
from utils.xfg_util.xfg import *
import utils.xfg_util.rgx_utils as rgx
import pickle
from tools import Parameters
import tensorflow as tf
def get_tag_dict():
tag_dict = collections.OrderedDict()
list_tags = list()
for fam in rgx.llvm_IR_stmt_families[1:]:
... |
from libs import (
NAP_DIGIT_PRECISION,
NAP_DIVIDEND_TAX,
NAP_DATE_FORMAT,
RECEIVED_DIVIDEND_ACTIVITY_TYPES,
TAX_DIVIDEND_ACTIVITY_TYPES,
)
from libs.calculators.utils import get_avg_purchase_price, adjust_quantity, adjust_stock_data, aggregate_purchases
from collections import deque
import logging... |
# Copyright (c) 2020-2021, <NAME>
# License: MIT License
import logging
from typing import (
TYPE_CHECKING,
Iterable,
Callable,
Optional,
cast,
Dict,
List,
Any,
)
from ezdxf.entities import factory
from ezdxf.entities.boundary_paths import (
PolylinePath,
EdgePath,
LineEdge,... |
# coding: utf-8
"""
Main pyramlson decorators: api_service and api_method
"""
import re
import os
import logging
from email.utils import parsedate
from inspect import getmembers
from collections import namedtuple, defaultdict
import venusian
from pyramid.path import (
AssetResolver,
DottedNameResolver
)
from... |
import numpy as np
import tensorflow as tf
import math
import time
from src.tools.common import Timer, setup_logger
LOGGER = setup_logger(__name__)
@Timer.measure_runtime
def load_image(image_path: str,
target_size: tuple or int = 640,
scaling: bool = True
):
if isin... |
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
class Embedding(nn.Embedding):
def reset_parameters(self):
print("Use uniform to initialize the embedding")
self.weight.data.uniform_(-0.05, 0.05)
if self.padding_idx is not None:
... |
"""
Bottleneck Transformers for Visual Recognition.
adapted from https://github.com/CandiceD17/Bottleneck-Transformers-for-Visual-Recognition
"""
import torch
from einops import rearrange
from torch import einsum, nn
try:
from distribuuuu.models import resnet50
except ImportError:
from torchvision.models impor... |
import zmq
import json
import numpy as np
from base64 import standard_b64decode, standard_b64encode
from types import MethodType #dont delete this gets called in an exec
import warnings
import re
class PygellanBridge:
_DEFAULT_PORT = 4827
_EXPECTED_ZMQ_SERVER_VERSION = '2.3.0'
"""
Master class for co... |
from rcwa.shorthand import *
from rcwa import Material
class Layer:
"""
Class for defining a single layer of a layer stack used in a simulation
:param er: Permittivity of the layer
:param ur: Permeability of the layer
:param L: Thickness of the layer
:param n: Refractive index of the layer
:param crystal: Crys... |
#!/usr/bin/env python3
'''
Copyright (C) 2013 <NAME> <<EMAIL>>
This file is part of cppreference-doc
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 Lic... |
import numpy as np
import pytest
from numpy.testing import assert_allclose
from numpy.testing import assert_array_equal
from pygbm.plain.histogram import _build_histogram_naive
from pygbm.plain.histogram import _build_histogram
from pygbm.plain.histogram import _build_histogram_no_hessian
from pygbm.plain.histogram imp... |
# Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
import datetime
from django.test.client import RequestFactory
import pytz
from django.test import TestCase
from django.test.utils import override_settings
from scout.dao.space import add_foodtype_names_to_spot, add_cuisine_names, \
... |
#
# * This library is free software; you can redistribute it and/or
# * modify it under the terms of the GNU Lesser General Public
# * License as published by the Free Software Foundation; either
# * version 2.1 of the License, or (at your option) any later version.
# *
# * This library is distributed in the hope that ... |
import os
import argparse
import sys
import numpy as np
import math
import scipy.sparse as sp
import torch
from torch.nn.parameter import Parameter
from torch.nn.modules.module import Module
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
class GCN(nn.Module):
def __init__(self, ... |
#!/usr/bin/env python3
# vim: sts=4 sw=4 et
from tll import asynctll
import tll.channel as C
from tll.channel.base import Base
from tll.channel.prefix import Prefix
from tll.channel.logic import Logic
from tll.config import Url
from tll.error import TLLError
from tll.test_util import Accum
import common
import pytest... |
import numpy as np
import numpy
# from dolo import *
import pickle
# should be moved to markov
from numba import jit, njit
from dolo.numeric.grids import EmptyGrid, CartesianGrid, UnstructuredGrid
@njit
def choice(x, n, cumul):
i = 0
running = True
while i<n and running:
if x < cumul[i]:
... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
adult_csv = "./scripts/plots_tables/csvs/adult.csv"
mnist_csv = "./scripts/plots_tables/csvs/mnist.csv"
out_plots_folder = './scripts/plots_tables/plots/corrheatmaps/'
if not os.path.exists(out_plots_folder):
os.makedirs(out_... |
"""
The :mod:`paddy.writer` module contains built in data display functions.
Module functions are used to print specific data to terminal, formating
output in a user friendly manner, and quickly generate plots via the
`matplotlib.pyplot` module. Data is often passed via methods found in
:mod:`paddy.Paddy_Runner`.
Ro... |
from colors.models import Colourants
from folium.plugins import MarkerCluster
import folium
def format_number(n):
return n.split('/')
def chr_format(period_from, period_to, chr_from, chr_to):
if period_from == 'bce':
chr_f = 0 - chr_from
else:
chr_f = chr_from
if period_to == 'bce':... |
import torch
import argparse
import os
from torch.backends import cudnn
import random
import json
import time
import torch.distributed as dist
import torch.multiprocessing as mp
import warnings
def opts():
parser = argparse.ArgumentParser(description='Train script.')
### On data loader
parser.add_argument(... |
import os
import torch
from torchvision import transforms, datasets
import torchvision
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
import torch.optim a... |
# -*- coding: utf-8 -*-
from time import time
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
# Default configuration
contourParams = dict(
zdir='z',
alpha=0.5,
zorder=1,
antialiased=True,
cmap=cm.PuRd_r
)
surfaceParams = dict(
rstride=1,
cstride=1,
linewi... |
import boto3
from botocore.exceptions import ClientError
from cloudmesh.abstract.StorageDeprecatedABC import StorageABC
from cloudmesh.common.debug import VERBOSE
from cloudmesh.common.StopWatch import StopWatch
from cloudmesh.common.console import Console
from cloudmesh.common.util import banner
from cloudmesh.configu... |
import logging
from dataclasses import dataclass
from datetime import datetime
from pprint import pformat
from typing import Tuple, List
import dateutil.parser
import requests
from dacite import from_dict
from future.utils import lmap, lfilter
from nose.tools import assert_is_not_none
from foxylib.tools.auth.auth0.au... |
import math
from dataclasses import dataclass
from enum import IntEnum
class Heading(IntEnum):
UP = 0
RIGHT = 1
DOWN = 2
LEFT = 3
class RobotPuck(object):
def __init__(self, x=None, y=None, radius=None, angle=None, heading=None):
self._x = 0
self._y = 0
self._radius = 0
... |
from .token import Token
single_operators = {
"+": "add",
"-": "sub",
"*": "mul",
"/": "div",
"^": "pow",
"%": "mod",
"(": "lparens",
")": "rparens",
"[": "lbracket",
"]": "rbracket",
"{": "lcurly",
"}": "rcurly",
":": "colon",
".": "dot",
",": "comma",
... |
import sys
from PySide2.QtCore import Qt, Signal, QRect, QSize
from PySide2.QtGui import QFont, QTextCursor, QTextOption, QColor, QPainter, QTextFormat
from PySide2.QtWidgets import (QApplication, QCompleter, QHBoxLayout,
QLineEdit, QPlainTextEdit, QWidget)
class QLineNumberArea(QWidget... |
"""
This is a script that can be used to retrain the YOLOv2 model for your own dataset.
"""
import argparse
import os
# import matplotlib.pyplot as plt
import numpy as np
# import pandas as pd
import PIL
import tensorflow as tf
from keras import backend as K
from keras.layers import Input, Lambda, Conv2D
from keras.m... |
import numpy as np
import matplotlib.pyplot as plt
def set_3daxes_equal(ax):
'''Make axes of 3D plot have equal scale so that spheres appear as spheres,
cubes as cubes, etc.. This is one possible solution to Matplotlib's
ax.set_aspect('equal') and ax.axis('equal') not working for 3D.
Input
ax: a matplot... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.