text stringlengths 3.07k 22.1k |
|---|
# -*- coding: utf-8 -*-
'''
File name : kalman_filter.py
File Description : Kalman Filter Algorithm Implementation
Author : <NAME>
Date created : 07/14/2017
Date last modified: 07/16/2017
Python Version : 3.6
Fyi : https://github.com/srianant/kalman_... |
# Copyright 2012 OpenStack Foundation
#
# 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... |
import time, os
import pickle
import xml.etree.ElementTree
from farmware_tools import log
from farmware_tools import send_celery_script
import CeleryPy as cp
##List of functions and classes for ease of use
"""
classes:
PlantType(name, lightNeeded, growthTimeS, growthTimeP, growthTimeF)
Plant(kind, pot)
Pot(region, po... |
from copy import deepcopy
from time import time
import logging
from django.core.cache import cache
from django.db import transaction
from sympy import symbols, And, Or, Implies, Equivalent
from sympy.logic.boolalg import BooleanTrue
from sympy.logic.inference import satisfiable
from ringapp import models
log = loggin... |
import os
import sys
import numpy as np
import hickle as hkl
from Mask_RCNN.mrcnn.config import Config
from Mask_RCNN.mrcnn import utils
from GeneralUtils import reverse_dict, AllocateGPU
# =================================================================
# Paths
if os.getlogin() == 'tageldim':
is_laptop = True... |
from contextlib import suppress
from functools import lru_cache
from typing import Any, Dict, Generator, List
import requests
from hypothesis.strategies import SearchStrategy
from ...constants import DEFAULT_RESPONSE_TIMEOUT
from ...models import APIOperation, Case
from ._hypothesis import PARAMETERS, get_case_strate... |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
#
# This source code is licensed under the BSD license found in the
# LICENSE file in the root directory of this source tree.
import math
import torch
import torch.nn as nn
from fairscale.nn.moe.moe_layer import MOELayer
from fairscale.nn.moe.to... |
"""
Equations of State for Seawater
===============================
This module provides a few simple equations of state that can be used for
seawater. Some are very good (e.g., density) and others are just taken from
tables in the Handbook of Physics and Chemistry for pure water (e.g., surface
tension). Eventually... |
import os.path
import tempfile
import webbrowser
import pygraphviz as pgv
from .elements import ObjectProperty, ClassNode, DataNode, Column
from .elements import DataLink, ColumnLink, ObjectLink, ClassInstanceLink, SubClassLink
class BaseVisualizer(object):
"""
Basic Visualizer object for drawing a BaseSema... |
from decimal import Decimal
import pandas as pd
from core.simple_transaction import SimpleTransaction
from core.typings import TransactionType
from tests.test_piecash_helper import TestPiecashHelper
import pytest
@pytest.fixture(scope="class")
def piecash_helper():
return TestPiecashHelper()
class TestSimpleTr... |
# (c) 2012-2013 Continuum Analytics, Inc. / http://continuum.io
# All Rights Reserved
#
# conda is distributed under the terms of the BSD 3-clause license.
# Consult LICENSE.txt or http://opensource.org/licenses/BSD-3-Clause.
from __future__ import print_function, division, absolute_import
import re
import os
import s... |
#!/usr/bin/env python
# Copyright 2018 The Kubeflow Authors All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless... |
import yaml
import argparse
import numpy as np
from math import sqrt
import xml.etree.ElementTree as ET
from qepy import xml
from qepy import bravais
from copy import deepcopy
from command_line import band_plots
"""
Script to produce band structure data and visualization from QE.
It reads data-file-schema.xml found i... |
"""
Mask R-CNN
Train on the toy layout dataset.
------------------------------------------------------------
Usage: import the module (see Jupyter notebooks for examples), or run from
the command line as such:
# Train a new model starting from pre-trained COCO weights
python3 layout.py train... |
"""
Some key layers used for constructing a Capsule Network. These layers can used to construct CapsNet on other dataset,
not just on MNIST.
Author: <NAME>, E-mail: `<EMAIL>`, Github: `https://github.com/XifengGuo/CapsNet-Pytorch`
"""
import torch.nn.functional as F
import torch
from torch import nn
from torch.autogr... |
# -*-coding:Utf-8 -*
# ----------------------------------------------------------------------
#
# ----------------------------------------------------------------------
# External libraries
# ----------------------------------------------------------------------
import sys
import os
# Full path of this file
full_path... |
# Copyright 2019-2020 QuantumBlack Visual Analytics 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
#
# THE SOFTWARE IS PROVIDED "AS IS"... |
import wawmembers.variables as v
'''
Converts numbers to text descriptions.
'''
def training_display(cur, maxt):
try:
ratio = float(cur)/float(maxt)
except:
ratio = 0
if 0 <= ratio < 0.2:
return 'Ragtag'
elif 0.2 <= ratio < 0.4:
return 'Disorganised'
elif 0.4 <= rat... |
#
# Copyright 2019, Couchbase, Inc.
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... |
'''
The file contains the edges of a directed graph. Vertices are labeled as positive integers from 1 to 875714. Every row indicates an edge,
the vertex label in first column is the tail and the vertex label in second column is the head (recall the graph is directed, and the edges are
directed from the first column ... |
from enum import Flag
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
from typing import Any, Callable, Dict, List, Optional, Tuple
import numpy as np
import flwr as fl
from flwr.server.strategy import FedAvg, FedYogi, FedAdam, FedAdagrad
from mypkg import (
ServerArg,
ModelNameGenerator,
secure_mkdir,... |
import logging
import time
import csv
import os
import functools
import numpy as np
import tensorflow as tf
from abc import abstractmethod
from pathlib import Path
from tensorflow.keras.models import Sequential
from envs.utils import get_avg_reward, create_eval_video
tf.config.run_functions_eagerly(True)
tf.compat.v1.... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
##
## pb.py
##
## Created on: Mar 13, 2019
## Author: <NAME>
## E-mail: <EMAIL>
##
"""
===============
List of classes
===============
.. autosummary::
:nosignatures:
EncType
PBEnc
==================
Module descri... |
import struct
import gzip
from array import array
from collections import abc
import sys
from io import BytesIO
__all__ = [
'NbtError',
'NbtUnpackError',
'NbtInvalidOperation',
'Tag',
'TagByte',
'TagShort',
'TagInt',
'TagLong',
'TagFloat',
'TagDouble',
'TagByteArray',
'TagString',
'TagList',
'TagCompound... |
"""
"""
import os
from typing import Any, Callable, List, Optional, Tuple
from PIL import Image
from .utils import (
check_integrity,
download_and_extract_archive,
download_url,
verify_str_arg,
)
from .vision import VisionDataset
class _LFW(VisionDataset):
base_folder = "lfw-py"
download_ur... |
from gmssl import sm2, sm3, sm4, func
import random
import math
import GM.sm2genkey as sm2genkey
ecc_table = sm2.default_ecc_table
n = int(ecc_table['n'], 16)
p = int(ecc_table['p'], 16)
a = int(ecc_table['a'], 16)
b = int(ecc_table['b'], 16)
g = ecc_table['g']
gx = g[0:len(g)//2]
gy = g[len(g)//2:]
klen = 16
w = mat... |
from __future__ import annotations
import typing as t
from dataclasses import dataclass, field
from piccolo.columns import And, Column, Or, Secret, Where
from piccolo.custom_types import Combinable
from piccolo.querystring import QueryString
from piccolo.utils.sql_values import convert_to_sql_value
if t.TYPE_CHECKIN... |
######################################################################################################################
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# ... |
from .._utils import IntermediateLayerGetter
from ..utils import load_state_dict_from_url
from .. import mobilenetv3
from .. import resnet
from .deeplabv3 import DeepLabHead, DeepLabV3
from .fcn import FCN, FCNHead
from .lraspp import LRASPP
__all__ = ['fcn_resnet50', 'fcn_resnet101', 'deeplabv3_resnet50', 'deeplabv3... |
# Copyright 2019-present MongoDB, 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 wr... |
import os
import time
from threading import Thread
import cpuinfo
import GPUtil
import psutil
from tensorboardX import SummaryWriter
class Monitor(Thread):
"""Monitor Class."""
def __init__(self, log_dir, delay=1, gpu_id=0, verbose=False):
"""Initialize monitor, log_dir and gpu_id are needed."""
... |
"""
Matrix operations for neuroswarms models.
Author: <NAME> (<EMAIL>)
Affiliation: Johns Hopkins University
Created: 2019-05-12
Updated: 2020-11-16
Related paper:
<NAME>., <NAME>., <NAME>. et al. Cognitive swarming in complex
environments with attractor dynamics and oscillatory computing. Biol Cybern
... |
"""
This module contains method related to team logs.
"""
import os.path
import feather
import pandas as pd
import pyarrow
from tqdm import tqdm
from scrapenhl2.scrape import organization, parse_pbp, parse_toi, schedules, team_info, general_helpers as helpers, \
scrape_toi, manipulate_schedules
def get_team_pb... |
from mesa import Agent
import random
import numpy as np
import Egg
import math
from functools import cache
# Returns an array of integer tuples within the given radius
@cache
def getradiusarray(radius) -> np.array:
radiusarray = []
for x in range(-radius, radius, 1):
for y in range(-radius, radius, 1)... |
import ugame
import stage
import utils
GAME = None
#######################################################
# Game
class Game(stage.Stage):
"""Base class for a game and its display"""
# TODO: add game state machine
# TODO: make each screen a state, and make a transition between them when player overlaps with t... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
xarray-based ocean analysis library
The successor of Vacumm.
"""
# Copyright 2020-2021 Shom
#
# 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... |
# Copyright (C) GRyCAP - I3M - UPV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
#!/home/daniel/anaconda3/bin/python
# -*- coding: utf-8 -*-
"""
================================================
rewrite_monitoring
================================================
This program rewrites a monitoring time series files into the correct
time order
"""
# Author: fvj
# License: BSD 3 clause
import date... |
import logging
import os
import pytest
import time
import grpc
import requests
from docker import Client
from tools.minicluster.main import setup, teardown, config as mc_config
from tools.minicluster.minicluster import run_mesos_agent, teardown_mesos_agent
from host import start_maintenance, complete_maintenance, wait... |
"""CSC110 Fall 2021 Project
This module interacts directly with the Twitter API to download tweets and users.
It contains functions related scraping users/tweets, including:
- getting the tweets of a user
- downloading many users by checking their followers and follower's followers, etc.
"""
import json
import math
im... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
import tensorflow as tf
import os
import time
def make_training_data():
n_samples = 500 #Number of training data samples
n_inputs = 2 #Number of input parameters
n_out... |
# Copyright (c) 2011 OpenStack Foundation
# 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 ... |
#!/usr/bin/env python3
import sys
import re
import os.path
from time import time
# import logging
import click
import numpy as np
from PIL import Image
from daedalus import Maze
from .scheme import Graph
# vars for determining filetype
IMAGE = 1
TEXT = 2
VIDEO = 3
METHODS = {
'astar': Graph.astar,
'dijkstra': Grap... |
import tqdm
import time
import glob
import numpy as np
import igraph as ig
import search_methods # minha implementação dos métodos de busca
import instance_generation # minha implementação da geração de instâncias
import matplotlib.pyplot as plt
'''
Método auxiliar para registrar o tempo médio, em segundos... |
# This file is part of the MicroPython project, http://micropython.org/
#
# The MIT License (MIT)
#
# Copyright (c) 2020-2021 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without ... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
""" Class description goes here. """
"""Deserialization code related to DataClay objects
The code implemented in this module is (at "this moment") identical to the ones
implemented in the Java package client.CommonLib. Specifically, the deserialize*
functions are more or less adapted here.
"""
from io import BytesI... |
import datetime
import numpy as np
import pandas as pd
import networkx as nx
from . import dtutil
TYPE_VARIABLE = "variable"
TYPE_BINARY_VARIABLE = "binary"
TYPE_COUNTABLE_VARIABLE = "countable"
TYPE_TIMESERIES_EVENT = "tsevent"
class Variable(object):
"""Continuous Variable that follows Linear model.
Caus... |
from warnings import warn
from . import overlap
def fractional_slice(task, axes):
"""
>>> fractional_slice(('x', 5.1), {0: 2}) # doctest: +SKIP
(getitem, ('x', 6), (slice(0, 2),))
>>> fractional_slice(('x', 3, 5.1), {0: 2, 1: 3}) # doctest: +SKIP
(getitem, ('x', 3, 5), (slice(None, None, None... |
# Copyright 2020-2021 Huawei Technologies Co., Ltd.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 ... |
import json
import torch
from torchaudio.models.wav2vec2 import (
wav2vec2_base,
wav2vec2_large,
wav2vec2_large_lv60k,
)
from torchaudio.models.wav2vec2.utils import import_huggingface_model
from parameterized import parameterized
from torchaudio_unittest.common_utils import (
get_asset_path,
skip... |
#!/usr/bin/env python
"""
Train a CNN on CIFAR.
Author: <NAME> (<EMAIL>)
Usage:
python run_cifar_train.py --model [MODEL NAME] \
--config [CONFIG FILE] \
--env [ENV FILE] \
... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
try:
from unittest.mock import patch
except ImportError:
from mock import patch
from odoo.exceptions import AccessError
from odoo.tests.common import TransactionCase
from odoo.addons.crm.tests.common import Test... |
"""this module has all the methods and classes in order to compute and help represent RRT
"""
import math
import random
import pygame
from pygame import rect
class RRTMap:
"""generates the obstacles, start and end point"""
def __init__(self, start, goal, map_dimensions, obs_dim, obs_num):
self.start... |
# -*- coding: utf-8 -*-
# This file is kept only for backwards compatibility. Edit the one in ../mapgen
import os
from symbol import VectorSymbol, Pattern
from xml.etree import ElementTree as etree
from lookup import Lookup
from instructions import get_command, CS, SY
from cs import lookups_from_cs
from filters impor... |
"""
Base BZT classes
Copyright 2019 BlazeMeter 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... |
import re
from pathlib import Path
from typing import Optional
import numpy as np
from .base import *
class ShaderUniform:
def __init__(self, name: str, type, size, location):
self.name = name
self.type = type
self.size = size
self.location = location
class Shader(OpenGlBaseObj... |
#
# Python 3 script for validating and importing translations from a crowdin
# build zip.
#
from glob import glob
from subprocess import run, PIPE
import sys
import os
import re
import shutil
import tempfile
import xml.etree.ElementTree as ET
from optparse import OptionParser
class bcolors:
HEADER = '\033[95m'
... |
##########################################################################
#
# Copyright (c) 2013, Image Engine Design 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:
#
# * Redistrib... |
import face_recognition
import easygui as eg
import numpy as np
import cv2
import os
#Directory containing known faces directories
knownf_dir = "known faces"
#Directory containing unknown faces
unknownf_dir = "unknown faces"
print("LOADING KNOWN FACES")
#Just some variables
known_facesf,known_namesf,answer=[],[],'n... |
import requests
import lxml.html
from collections import namedtuple
# named tuples:
# used for parsed data and themes
Date = namedtuple('Date', ['year' # e.g. '2018'
,'season' # '01'-'03' which means 3rd season
,'season_name' # e.g. 'Bahar' or 'Spring'
... |
from dataclasses import dataclass
from datetime import timedelta
from decimal import Decimal
from enum import Enum
import dateutil
import pytz
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.postgres.fields import JSONField
from django.db import models
from django.db... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""VCF utility functions.
:Author: <NAME> <<EMAIL>>
:Date: 2018-01-20
:Copyright: 2018, <NAME>
:License: CC BY-SA
"""
import re
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class VCFError(Error):
"""Exception raised for ... |
# -*- coding: utf-8 -*-
"""Functionality to enhance checking of queue mainly during unit testing.
This module should not need to import from any other modules in
stdlib_utils.
"""
from __future__ import annotations
from collections import deque
import multiprocessing
import multiprocessing.queues
import queue
from qu... |
import torch, sys, os, pdb
import numpy as np
from PIL import Image
from scipy.spatial import Delaunay
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
from .aligned_reid_utils import load_state_dict
from models.yolo_models import Darknet
from .featurepointnet_model_util import ... |
import discord
import asyncio
client = discord.Client()
member = discord.Member
user = discord.User
server = discord.Server
game = discord.game
lastedit = "June 12, 2016"
ver = "build 0.04 0x001 - Styrofoam"
prefix = "*"
owner = "SporadicToast"
ownerid = 169064821382316032
clid = 191088734345625600
@client.event
asyn... |
from collections import OrderedDict
from typing import Any, Callable, Optional, Sequence, Tuple, TypeVar, Union
from urllib.parse import urlencode
from uuid import uuid4
from python_aioarango.connection import Connection
from python_aioarango.exceptions import (
AsyncExecuteError,
BatchExecuteError,
BatchS... |
import os
import re
from jellylib.parsing import Whitespaces, Parser, Newlines, EOF, Spaces
from jellylib.error import Error
import string
import json
import jellylib.log as log
SubstRegexp = re.compile("\$\(([a-zA-Z0-9_\-]+)\)")
class FormattedWriter:
def __init__(self, stream):
self.stream = stream
def __del... |
import copy
import random
import numpy as np
class NPuzzle:
"""N-Puzzle simulator"""
def __init__(self, n=15, start_blank=None):
self.n = int(n)
self.width = int(np.round(np.sqrt(n+1)))
assert self.width**2-1 == self.n
self.state = np.arange(self.n+1).reshape(self.width, self.... |
#MIT License
#
#Copyright (c) 2020 <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, di... |
import numpy as np
import vectormath as vm
from vectormath import Vector3
import math
from math import sqrt
class Material():
def __init__(self, diffuse, ambient, specular, reflective, phong_power):
self.diffuse = diffuse
self.ambient = ambient
self.specular = specular
self.reflective = reflective
self.phon... |
import uuid
import json
import collections
import gevent
import rlp
from web3.utils.crypto import sha3
from web3.utils.string import force_text
from web3.utils.address import to_address
from web3.utils.types import (
is_string,
is_object,
)
from web3.utils.encoding import (
to_decimal,
encode_hex,
... |
__author__ = '<NAME>'
import math
# Computer
eps = 256 * (7/3 - 4/3 - 1)
# Market
r = 0.07
# Underlying
s0 = 100.0
sigma = 0.2
# Derivative
T = 1.0
k = 90.0
def pos(x):
return x if (x > 0) else 0
def getTree(s0, sigma, n, t):
"""Generate the tree of stock prices"""
s = [[0]*(i+1) for i in range(n+1)]
s[0]... |
# Asignatura: Inteligencia Artificial (IYA051)
# Grado en Ingeniería Informática
# Escuela Politécnica Superior
# Universidad Europea del Atlántico
# Caso Práctico (CE_Práctica_01)
# En esta práctica se busca el máximo de una función utilizando computación evolutiva
# Se utiliza un algoritmo genético
# Impor... |
import os
import collections
import logging
import yaml
import torch
import joblib
import numpy as np
from mathtools import utils, metrics, torchutils
from kinemparse import sim2real
from blocks.core.blockassembly import BlockAssembly
from blocks.core import definitions as defn
from blocks.core import labels as labe... |
import uuid
from datetime import datetime
from flask import current_app
from sqlalchemy.schema import Sequence
from app import cbc_proxy_client, db, notify_celery, zendesk_client
from app.clients.cbc_proxy import (
CBCProxyFatalException,
CBCProxyRetryableException,
)
from app.config import QueueNames
from ap... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
"""
MSAL based RESTful API wrapper
"""
from typing import Dict, Optional
import sys
import os
import contextlib
import json
import logging
import atexit
import time
import jwt
import msal
import requests
from requests.utils import urlparse
from ... |
import pkg_resources
from flask import (
Blueprint,
request,
flash,
url_for,
current_app,
abort,
render_template,
redirect,
session,
)
from flask_babel import gettext as _
from werkzeug.datastructures import CombinedMultiDict, FileStorage
from .forms import (
LoginForm,
Pass... |
#!/usr/bin/python
#
# Copyright 2018 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
# -*- coding: utf-8 -*-
"""
ErplyAPI
~~~~~~~~
Simple Python wrapper for Erply API
:copyright: (c) 2014-2016 by <NAME>
:license: BSD, see LICENSE for details.
"""
from contextlib import closing
from datetime import datetime
from time import sleep
import csv
import requests
import logging
try:
... |
##############################################################################
# Copyright 2016 IBM Corp.
#
# 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/LI... |
#!/usr/bin/python
import math, numpy as np, scipy as sp, scipy.stats
################################################################################
#
# Gaussian mixture model functions
#
################################################################################
# Define functions.
def pdf(x, mu=0.0, sigma=1.... |
"""
Chain
====================
Manipulate the chain of spin systems (also called images), e.g. add, remove or change active image.
Get information, such as number of images or energies and reaction coordinates.
"""
import spirit.spiritlib as spiritlib
import spirit.parameters as parameters
import spirit.system as sys... |
"""Setup that is responsible for building the C++ python extensions.
"""
import os
import platform
import subprocess
import shutil
import glob
import signal
from typing import Callable
from setuptools import setup, find_packages, Extension, Command
from setuptools.command.test import test
import pybind11
ROOT_DIR = ... |
# -*- coding: utf-8 -*-
__author__ = """<NAME>"""
__email__ = "<EMAIL>"
import pytest
from schalter import Schalter
def test_schalter():
Schalter.clear()
@Schalter.configure
def add_constant(x: int, *, constant_value: int = 1):
return x + constant_value
assert Schalter["constant_value"] ==... |
"""CNN model
Builds the CNN model for HSI data.
Implements the _inference/loss/training pattern_ for model building.
1. cnn_2d() - Builds the model as far as is required for running the network forward to make predictions.
2. loss() - Adds to the inference model the layers required to generate loss.
3. training() - A... |
#! /usr/bin/env python3
from abc import ABC, abstractmethod
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
class Simulation:
def __init__(self, seed=None, ants=5, num_rivers=0, x=100, y=100):
# seed random number generator
np.random.seed(seed... |
import cv2
import numpy as np
from keras.layers import Activation, Conv2D, Dense, Flatten, Input, MaxPool2D, Permute, Reshape
from keras.layers.advanced_activations import PReLU
from keras.models import Model, Sequential
import utils
def create_Pnet(weight_path):
"""
搭建Pnet网络,粗略获取人脸框, 输出bbox位置和是否有人脸
"""
... |
# -*- coding: utf-8 -*-
import os
import time
from functools import lru_cache
from io import BytesIO
import requests
import telebot
from mixpanel import Mixpanel
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton
from strings import strings
token = os.environ['TELEGRAM_TOKEN']
MIXPANEL_TOKEN = os.e... |
#!/usr/bin/python
# Copyright (C) 2015-2021 Swift Navigation Inc.
# Contact: https://support.swiftnav.com
#
# This source is subject to the license found in the file 'LICENSE' which must
# be be distributed together with this source. All other rights reserved.
#
# THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT ... |
import numpy as np
from scipy.stats import expon
from pfb.opt.power_method import power_method
from pfb.opt.pcg import pcg
from pfb.opt.primal_dual import primal_dual
from pfb.operators.psi import DaskPSI
from pfb.operators.psf import PSF
from pfb.prox.prox_21 import prox_21
from pfb.utils.fits import save_fits
from pf... |
## Trying different peakfinders from the web. All functions should be made compatible in terms of input type
## also try: http://pythonhosted.org/PeakUtils/
## also try: https://github.com/steinmann/pypeak/blob/master/pypeak.py
import numpy as np
"""Detect peaks in data based on their amplitude and other features."""... |
#!/usr/bin/env python
# Tags: phoenix-port, py3-port
import wx
import wx.dataview as dv
import os, sys
import csv
import pandas as pd
import Config
#---------------------------------------------------------------------------
#----------------------------------------------------------------------
# This model class ... |
import asyncio
import logging
from collections import deque
import json
import discord
import discord.ext.commands as commands
import bot.extensions as ext
from bot.clem_bot import ClemBot
from bot.consts import Colors, OwnerDesignatedChannels, DesignatedChannels, Moderation
log = logging.getLogger(__name__)
MAX_ME... |
# Copyright 2014 - Mirantis, Inc.
# Copyright 2015 - StackStorm, Inc.
# Copyright 2017 - Brocade Communications Systems, Inc.
# Copyright 2018 - Extreme Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You ma... |
CRED = u'\33[31m'
CGREEN = u'\33[32m'
CYELLOW = u'\33[33m'
CBLUE = u'\33[34m'
CEND = u'\033[0m'
UCHECK = CGREEN + u"v" + CEND
UCROSS = CRED + u"x" + CEND
URING = CYELLOW + u"o" + CEND
def _gethashoffile(file_name):
import hashlib
try:
with open(file_name, 'r') as file_to_check:
# read... |
import math
from django.utils.datastructures import SortedDict
from django import template
from django.core.paginator import Paginator, EmptyPage
from django.utils.translation import ugettext as _
from django.utils.html import escape
from django.http import Http404
from django.utils.encoding import smart_unicode
from d... |
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim.lr_scheduler import *
import time
import os
import numpy as np
from model import build_r3d_classifier, load_r3d_classifier
import parameters_BL as params
import config as c... |
import logging
import azure.functions as func
import re
from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from azure.cognitiveservices.vision.computervision.models import OperationStatusCodes
from azure.cognitiveservices.vision.computervision.models import VisualFeatureTypes
from msrest.au... |
from decimal import Decimal, getcontext
from copy import deepcopy
from vector import Vector
from plane import Plane
from hyperplane import Hyperplane
getcontext().prec = 30
class LinearSystem(object):
ALL_PLANES_MUST_BE_IN_SAME_DIM_MSG = 'All planes in the system should live in the same dimension'
NO_SOLUT... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.