text stringlengths 3.07k 22.1k |
|---|
# -*- coding: utf-8 -*-
"""Canonical Correlation Analysis (CCA). http://en.wikipedia.org/wiki/Canonical_correlation
"""
import numpy as np
from sklearn.metrics import confusion_matrix
import functools
from ..classes.classifier import Classifier
from .reference_frequencies import generate_reference_signals
class CCA(C... |
"""
Implements 'propagation', whereby terms from the full ConceptNet graph are
assigned vectors from the embeddings produced by retrofitting against the
reduced graph.
"""
import numpy as np
import pandas as pd
from scipy.sparse import diags
from conceptnet5.builders.reduce_assoc import ConceptNetAssociationGraph
fro... |
# EMACS settings: -*- tab-width: 2; indent-tabs-mode: t; python-indent-offset: 2 -*-
# vim: tabstop=2:shiftwidth=2:noexpandtab
# kate: tab-width 2; replace-tabs off; indent-width 2;
#
# ==============================================================================
# Authors: <NAME>
#
# Cocotb Testbench: Least-Re... |
#
# Copyright 2022 The AI Flow Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... |
# -*- coding: utf-8 -*-
"""
pyzco.agent
~~~~~~~~~~~
Implements an Agent class that communicates over ZeroMQ.
:copyright: 2013 by <NAME>, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import os
import weakref
import threading
from collections import defaultdict
i... |
from flask import Flask, escape, jsonify, request, render_template
import googlemaps
from flask_cors import CORS, cross_origin
import time
import nearest_neighbour as nn
import brute_force as bf
from branch_and_bound import get_path, get_path_constrained
import api_model
import clustering
import math
import coordinate_... |
"""
Handle the IRC connection for the bot
"""
try:
from queue import Queue
except ImportError:
from Queue import Queue
from threading import Thread
from irc.bot import SingleServerIRCBot
from time import sleep, time
class Task(object):
"""
Container for a IRCWrapper task that can be ... |
# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import logging
from textwrap import dedent
from typing import Optional
from unittest.mock import Mock
from pants.base.specs import DescendantAddresses, OriginSpec, SingleAddress
from pant... |
import pickle, glob, sys, csv, warnings
import numpy as np
from feature_extraction_utils import _load_file, _save_file, _get_node_info
from sklearn.preprocessing import PolynomialFeatures
from sklearn.metrics import accuracy_score, confusion_matrix, auc, roc_curve
from sklearn.naive_bayes import GaussianNB
from sklear... |
import argparse
import os
import sys
from app.pyGrams.scripts.pipeline import Pipeline
from app.pyGrams.utils.argschecker import ArgsChecker
from app.pyGrams.scripts.utils.pygrams_exception import PygramsException
predictor_names = ['All', 'Naive', 'Linear', 'Quadratic', 'Cubic', 'ARIMA', 'Holt-Winters',
... |
import numpy as np
from scipy.stats import binom
from statsmodels.stats.multitest import multipletests
from .common import *
def predict_expression(transcripts, init_site_range, p):
""" Probability that at least the number of observed transcripts in the initiation site
is due to random chance assuming th... |
# 2020/02/29 by ausk
import utils
import warnings
warnings.filterwarnings("ignore")
import os, sys, time
import numpy as np
import cv2
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras import backend as K
# 处理块的名字
def handle_block_names(prefix, stage):
name = "{}_{}".form... |
'''
Encoding Visual Attributes in Capsules for Explainable Medical Diagnoses (X-Caps)
Original Paper by <NAME>, <NAME>, and <NAME> (https://arxiv.org/abs/1909.05926)
Code written by: <NAME>
If you use significant portions of this code or the ideas from our paper, please cite it :)
If you have any questions, please emai... |
import os
from typing import Optional, List, Tuple, Union, Iterable
from econtools.metrics.core import Results
from econtools.util.gentools import force_iterable
eol = " \\\\ \n"
sig_labels = {1: '', .1: '*', .05: '**', .01: '***'}
# TODO: Add options for basic statrow (r2, N)? (how to handle 2sls r2?)
def outreg(re... |
"""
Helper to plot data in iPython or similar tools
(c) TSM 2020
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
from sklearn.metrics import confusion_matrix, classification_report, roc_curve, roc_auc_score, average_precision_score
from sklearn.metrics import precision_recall_curve
f... |
"""
transform information from data block of cif file to class Data
"""
__author__="ikibalin"
__version__="28/08/2019"
from .item import str_to_comment, Item
from .items import Items
from .loop import Loop, find_name_comment_in_block
class Data(object):
"""
container for objects Items and list of Loop
""... |
import abc
import tensorflow as tf
if int(tf.__version__[0]) > 1:
from tensorflow.keras import optimizers
from tensorflow.keras import Model
from tensorflow.keras.regularizers import l2
from tensorflow.keras import backend as K
else:
from tensorflow.python.keras import optimizers
from tensorfl... |
#!/usr/bin/env python
"""Rechunk an existing MVF dataset"""
import argparse
import multiprocessing
import os
import re
import sys
import urllib.parse
import dask
import dask.array as da
import numpy as np
from katsdptelstate.rdb_writer import RDBWriter
from katdal.chunkstore import ChunkStoreError
from katdal.chunk... |
"""Performs post processing on the latest prod schema.
For testing, this script can be directly executed (in TEST mode):
python post_process.py
To reapply post-processing on the current prod schema, execute:
python post_process.py --disable_test_mode
"""
import argparse
import os
import numpy
import math
import ... |
import sys
import numpy as np
# sign_nonzero = lambda x: np.heaviside(x,1.0)*2.0-1.0
sign_nonzero = lambda x: -(np.signbit(x)*2.0)+1.0
def vertex_all_in_set(vertexids,vertexset):
for vertexid in vertexids:
if vertexid < 0:
return True
elif vertexid not in vertexset:
return ... |
from __future__ import annotations
import argparse
import http.server
import json
import threading
from pathlib import Path
from typing import List, Optional, Any
import jinja2
import requests_cache
ENCODING = "utf-8"
URL = "url"
LEVELS = "levels"
CACHE = "cache"
URL_DEFAULT = "https://hub.zebr0.io"
LEVELS_DEFAULT... |
#!/usr/bin/env python -u
##############################################################################
#
# Copyright (c) 2007 <NAME> and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the BSD-like license at
# http://www.repoze.org/LICENSE.txt. A copy of the license should acco... |
import tensorflow as tf
import numpy as np
import pandas as pd
from scipy import optimize, stats
from collections import OrderedDict
import argparse
# likelihood function for MK test
class SimpleMK(object):
def __init__(self,
neutral_div,
neutral_poly,
foreground... |
#!/usr/bin/env python
import curses, json, pycurl, subprocess, textwrap, urllib.parse
from io import BytesIO
print("[twitch-curses] Initializing")
stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
stdscr.keypad(1)
curses.curs_set(0)
lang = "fr"
query_limit = "75"
highlight = 0
page = 0
hl_cache = 0
p_cache = ... |
import mlrose_hiive as mlrose
import numpy as np
import pandas as pd
from time import clock
import os
import argparse
import data.DataProcessors as dp
import seaborn as sns
import matplotlib.pyplot as plt
os.environ['seed'] = '45604'
randomSeed = 45604
verbose = True
from sklearn.metrics import accuracy_score, log_l... |
#!/usr/bin/env python
import sys, os
import mmap # Thanks Steven @ http://stackoverflow.com/questions/4940032/search-for-string-in-txt-file-python
import subprocess
import readline
readline.set_completer_delims(' \t\n;')
readline.parse_and_bind("tab: complete")
readline.parse_and_bind("set match-hidden-files off"... |
# coding=utf-8
# Copyleft 2019 project LXRT.
import argparse
import random
import logging
import numpy as np
import torch
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt='%m/%d/%Y %H:%M:%S',
level=logging.INFO)
logger = logging.getL... |
# Adding Frames to Video
# imported necessary library
import tkinter
from tkinter import *
import tkinter as tk
import tkinter.messagebox as mbox
from tkinter import filedialog
from PIL import ImageTk, Image
import cv2
from moviepy.editor import *
# Main Window & Configuration
window = tk.Tk() # created a tkinter g... |
import time
from rlbot.agents.base_agent import SimpleControllerState
from maneuvers.dodge import DodgeManeuver
from maneuvers.recovery import RecoveryManeuver
from util import rendering
from util.rldata import Field, Ball, is_near_wall
from predict import ball_predict, next_ball_landing
from util.rlmath import *
c... |
#/usr/bin/env python3
import socket
import sys
import os
import select
import time
import datetime
from collections import OrderedDict
#Note:
#
#
#
# For more info: github.com/davidcawork
#Global vars
MSG_PROXPY_INACTIVE = '[ProxPy] Proxy inactive ...'
ERROR_TO_RCV_FROM_NAV = '[ProxPy] Error, cannot rec... |
#!/usr/bin/env python
"""Renderers for API calls (that can be bound to HTTP API, for example)."""
import logging
import yaml
from grr.lib import access_control
from grr.lib import config_lib
from grr.lib import rdfvalue
from grr.lib import registry
from grr.lib import stats
from grr.lib.rdfvalues import structs
fr... |
#!/usr/bin/env python
import requests
import numpy as np
import pandas as pd
import json
import pytz
def _GET(url):
req = requests.get(url)
data = req.json()
return data
def _get_data(url):
raw = _GET(url)
return json.dumps(raw['Data'])
def _get_dowjones_data(url):
... |
###############################################################################
# PyDial: Multi-domain Statistical Spoken Dialogue System Software
###############################################################################
#
# Copyright 2015 - 2019
# Cambridge University Engineering Department Dialogue Systems Grou... |
from itertools import chain
from pathlib import Path
import numpy as np
import pytest
from hypothesis import given
from hypothesis import strategies as st
from tesliper import Tesliper
fixtures_dir = Path(__file__).parent / "fixtures"
@pytest.fixture
def wanted_files():
return ["meoh-1.out", "meoh-2.out"]
@p... |
"""
MIT License
Copyright (c) 2019-2021 naoTimesdev
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, publi... |
# -*- coding: utf-8 -*-
"""
Utility functions and classes.
"""
import datetime
import math
import sys
from typing import Any, Callable, Dict, Iterable, Iterator, List, Tuple, Union
import argparse as ap
import numpy as np
import pandas as pd
def is_debugging():
"""
Check if the application is running under... |
import inspect
import threading
import os
from threading import local, get_ident, current_thread
from concurrent.futures import (
ThreadPoolExecutor, ProcessPoolExecutor, Future
)
from typing import (
List, Dict, Text, Tuple, Type, Callable, Union, Optional
)
from collections import deque, OrderedDict, namedtu... |
"""A collection of pnguin.api utility functions.
This module contains a collection of utility functions and helpers that are used throughout the pnguin project.
"""
import math
from collections import defaultdict
import numpy as np
from pnguin.models import Axis
def _format_to_cols(data):
"""Helper method to tak... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
import uuid
from .base import IDComparable
class UnitBase(IDComparable):
'''Anything that sits on a GameTile is based on this, subclasses/mixins
add further properties. `UUID4.hex` ids
'''
def __init__(self, player):
self.id = str(uuid.uuid4())
self.health = 0
self.vision = 0
... |
#
# Copyright 2013 Quantopian, 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... |
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... |
"""
Test that batch and run-order correction behaves sensibly with a combination of synthetic and model datasets.
"""
import scipy
import pandas
import numpy
import seaborn as sns
import sys
import unittest
import os
sys.path.append("..")
import nPYc
from generateTestDataset import generateTestDataset
class test_ro... |
"""Contains a parallel runner implementation, with support
for various backends
"""
from microscopes.common import validator
from microscopes.common.rng import rng
import warnings
import logging
import time
import tempfile
import pickle
import hashlib
import multiprocessing as mp
_logger = logging.getLogger(__name__... |
from ..numba import norm, _min, _max, _sign
from numpy import infty, zeros, float32, float64
from copy import copy
from ..utils import _float
def Orthogonalize(a, b):
A,B,_a,_b = abs(a), abs(b), _sign(a), _sign(b)
if b == 0:
return _a, 0, A
elif a == 0:
return 0, _b, B
elif B > A:
tau = a/b
s = _b/(1+ta... |
import pytest
from tri_declarative import (
class_shortcut,
dispatch,
Refinable,
)
from iommi import (
Fragment,
html,
Page,
register_style,
Style,
)
from iommi.member import ForbiddenNamesException
from tests.helpers import (
Basket,
Fruit,
)
def test_empty_collect():
ass... |
import socket
import struct
import pickle
import numpy as np
import json
import torch
import torch.nn as nn
from torch.optim import Adam, SGD
from threading import Thread
import time
#load data from json file
f = open('parameter_server.json', )
data = json.load(f)
#set parameters fron json file
host = data["host"]
po... |
import re
import fasttext
from flask import Flask, request, jsonify, render_template
import mwapi
app = Flask(__name__)
app.config["DEBUG"] = True
CUSTOM_UA = 'wikidata topic app -- <EMAIL>'
SESSION = mwapi.Session('https://www.wikidata.org',
user_agent=CUSTOM_UA)
FT_MODEL = fasttext.load_mode... |
# -*- coding: utf-8 -*-
"""Add a Table of Contents to any HTML via cElementTree and friends.
Largely based on an extraction from python-markdown, but can be run on
bare HTML (not a python-markdown-based ElementTree).
"""
from __future__ import unicode_literals
from __future__ import print_function
import re
from xml.... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
import logging
import torch
from reagent.evaluation.cpe import (
CpeEstimate,
CpeEstimateSet,
bootstrapped_std_error_of_mean,
)
from reagent.evaluation.evaluation_data_page import EvaluationDataPage
from reagent... |
import argparse
def get_common_parser():
parser = argparse.ArgumentParser()
parser.add_argument("--load_exp", type=str, default=None)
parser.add_argument("--mode", type=str, default='CB', help='CA / CB / CAS')
parser.add_argument("--seq_len", type=int, default=14)
parser.add_argument("--seq_typ... |
import math
import torch
from model.modules import MemCrompress
from sklearn.decomposition import PCA
import cv2
import math
import os
import numpy as np
from PIL import Image
def get_pca(feature, batch_idx=0, pca_num=3, name="feature"):
# feature [N, C, H, W]
N, C, H, W = feature.shape
feature = feature[b... |
# -*- coding: utf-8 -*-
#
# project-template documentation build configuration file, created by
# sphinx-quickstart on Mon Jan 18 14:44:12 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated fi... |
"""
MissX Imputer for Missing Data
Modified code of missforest (https://github.com/stekhoven/missForest)
- The imputer was modified so that...
- Custom predictors can be used
- Predictions are done in parallel (for faster calculation)
- Delete codes for classification
"""
import warnings
i... |
# Copyright (c) 2011-2020, <NAME>
# License: MIT License
from typing import TYPE_CHECKING, Dict, Iterable, List, cast, Optional
import logging
from ezdxf.lldxf.const import DXFKeyError, DXFValueError, DXFInternalEzdxfError
from ezdxf.lldxf.const import (
MODEL_SPACE_R2000, PAPER_SPACE_R2000,
TMP_PAPER_SPACE_NAM... |
#!/usr/bin/env python
# Copyright 2017 Calico 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 agr... |
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
class Tests:
look_modification_creation = (
"Look Modification Entity successfully created",
... |
# Copyright (c) 2021 PaddlePaddle 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 required by appli... |
#!/usr/bin/python3
from daemons import Daemon, Wallet
import random
import time
import shutil
import os
from os import path
import asyncio
import glob
from datetime import datetime
import uuid
datadirectory="testdata"
def coins(*args):
if len(args) != 1:
return tuple(coins(x) for x in args)
x = args... |
"""Platform for sensor integration."""
from datetime import timedelta
import logging
import asyncio
import async_timeout
from homeassistant.const import (
DEVICE_CLASS_POWER,
POWER_WATT,
ENERGY_WATT_HOUR,
ENERGY_KILO_WATT_HOUR,
)
from homeassistant.helpers.entity import Entity
from homeassistant.helpe... |
#!/usr/bin/python
"""
Module to test RO manager link command
See: http://www.wf4ever-project.org/wiki/display/docs/RO+management+tool
"""
__author__ = "<NAME> (<EMAIL>)"
__copyright__ = "Copyright 2011-2013, University of Oxford"
__license__ = "MIT (http://opensource.org/licenses/MIT)"
import os, os.path... |
# Libraries
import tensorflow as tf
from keras.preprocessing import image
import numpy as np
sess = tf.InteractiveSession()
# Operations
# mask
def mask(mask_type, num_inputs, num_outputs, kernel_size, num_channels):
ones_mask = np.ones([kernel_size[0], kernel_size[1], num_inputs, num_outputs])
kernel_c... |
import tkinter as tk
from PIL import Image, ImageTk
import utils
import os
import urllib.request
import threading
# If "result" and "replacement" folder don't exist, create it and download the images from the GitHub repository
if not os.path.exists("result"):
os.makedirs("result")
if not os.path.exists("replacemen... |
# -*- coding: utf-8 -*-
"""Models interfaces neural networks with the estimator api
Models transfer a network to a model function to use with the tf estimator api.
A model defines the goal/loss of the model, as well as training paramters.
"""
import pinn.networks
import tensorflow as tf
import numpy as np
from pinn.l... |
from __future__ import division
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from kid_readout.analysis import dataframe
def plot_sweeps(df, k, select_key='channel', color_key=None, norm=matplotlib.colors.LogNorm,
colormap=plt.cm.coolwarm, legend=False):
fig, ax = plt.subplot... |
# Copyright 2021 Rikai Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... |
"""
This module contains classes to express diverse requirements which a user needs to satisfy in order to use a view function.
The convenience functions :meth:`get_claim_requirement` and :meth:`get_vo_requirement` are recommended to construct individual requirements.
If you want to combine multiple requirements use ... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
# -*- coding: utf-8 -*-
from __future__ import division
from matplotlib.colors import ListedColormap
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
__all__ = ['decision_boundary_grid', 'plot_decision_boundary']
def decision_boundary_grid(clf, X, y, feat_list=None, cmap_bkg='RdBu', \
color_... |
"""
NOTE: below is some legacy code that is not compatible with current BayesFast
we will revise it later
"""
import numpy as np
from scipy.special import expit
import multiprocessing as mp
import warnings
import time
from ..samplers.pymc3.nuts import NUTS
from ..utils.warnings import SamplingProgess
from ..uti... |
import numpy as np
from panqec.codes import StabilizerCode
from panqec.decoders import BaseDecoder
from panqec.error_models import BaseErrorModel
from typing import Dict
import panqec.bsparse as bsparse
from panqec.bpauli import bcommute
from scipy.sparse import csr_matrix
PAULI_I = 0
PAULI_X = 1
PAULI_Y = 2
PAULI_Z ... |
"""This module contains all functions to build the corresponding objects based
on config values.Every framework related object (model, optimizer a.s.o) shall
be generated using one of the implemented builder functions. Missing builder
functions should be implemented in this file.
"""
import tensorflow as tf
from inspe... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2016, <NAME> <<EMAIL>>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... |
from permutation import permutations
from orientationcalc import calc_edge_orientations
from structs import ACTIONS, HALF_FACE, HALF_Z, QUARTER_X, QUARTER_Y, Cube, center, corner, edge, filter_actions, top
import pickle
def vector_id(x, y, z):
return chr((x+1)*9+(y+1)*3+(z+1)+97)
def orientation_id(os):
one... |
#!/usr/bin/env python3
"""
Copyright (C) 2021 Intel 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 ... |
import random
from copy import deepcopy
import torch
from tqdm import tqdm
from bbcm.data.datasets.csc import *
from bbcm.data.loaders.confusor import Confusor
from bbcm.utils.text_utils import is_chinese_char
class DataCollatorForCsc:
def __init__(self, tokenizer):
self.tokenizer = tokenizer
def __... |
#coding=utf-8
import os, sys, time
import os.path as osp
import numpy as np
import glob
import cv2
import json
import logging
import argparse
import multiprocessing as mp
import pdb
pdb.set_trace()
def save_crop_simple(image, frame_id, video_name, box, output_dir, pid2label=None):
if image is None:
return
... |
"""Module containing the allocators for SiPP pruning."""
import copy
import numpy as np
import cvxpy as cp
import torch
from ..base import BaseAllocator
class SiPPRandAllocator(BaseAllocator):
"""The layer allocator for randomized SiPP."""
def __init__(self, trackers, delta_failure, c_constant, **kwargs):
... |
from imblearn.metrics import classification_report_imbalanced as imbal_class_report
from scipy.stats import randint as sp_randint
from sklearn import metrics
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier, VotingClassifier, BaggingClassifier, \
AdaBoostClassifier, ExtraTreesClassifi... |
# Common cross-app functions to simplify code
# Copyright 2020 Deductiv 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 require... |
# Some snippets for the code in this file are referenced from
# https://github.com/davidtvs/pytorch-lr-finder
import os
import copy
import torch
import matplotlib.pyplot as plt
from torch.optim.lr_scheduler import _LRScheduler
from tensornet.engine.learner import Learner
from tensornet.utils.progress_bar import Prog... |
from __future__ import annotations
import abc
import logging
import os
import shutil
import tempfile
from datetime import datetime
from pathlib import Path
from typing import Text, Any, Optional, Tuple, List
from packaging import version
from sqlalchemy.engine import URL
from sqlalchemy.exc import OperationalError
f... |
import tensorflow as tf
import numpy as np
import argparse
import socket
import importlib
import time
import os
import scipy.misc
import sys
import h5py
import math
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(BASE_DIR, 'models'))
sys.path.append(os.path.j... |
import os
import numpy as np
import tensorflow as tf
from dopamine.discrete_domains import gym_lib
from dopamine.agents.dqn import dqn_agent
from dopamine.discrete_domains import run_experiment, atari_lib
from dopamine.colab import utils as colab_utils
from absl import flags
import gin.tf
# import trfl
from dopamine.d... |
from modeling import *
from redsmall_data import *
N, Cap = 20, 10
k = BZipf(1, 10) # BZipf(1, 5)
R = Uniform(1, 1)
b, beta_ = 10, 3 # 2.1
L = Pareto(b, beta_)
a, alpha_ = 1, 3
Sl = Pareto(a, alpha_)
def alpha_gen(ro):
return alpha_
ro0_l = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9] # [0.1]
d_l, ro0_scherid_X_l_... |
import argparse
import threading
import time
from pathlib import Path
from pose import getKeypoints, getValidPairs, getPersonwiseKeypoints
import cv2
import depthai as dai
import numpy as np
from imutils.video import FPS
parser = argparse.ArgumentParser()
parser.add_argument('-nd', '--no-debug', action="store_true", h... |
"""
Generate address space c++ code from xml file specification
xmlparser.py is a requirement. it is in opcua folder but to avoid importing all code, developer can link xmlparser.py in current directory
"""
import sys
import logging
# sys.path.insert(0, "..") # load local freeopcua implementation
#from opcua import xm... |
import rouge_scores
import os
import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
import itertools
import pickle
def generate_imgs(precision_path,recall_path):
precision_df=pd.read_csv(precision_path).iloc[:,1:]
recall_df=pd.read_csv(recall_path).iloc[:,1:]
print(... |
"""
Functions for color operations on tensors.
If needed, there are more conversions that can be used:
https://github.com/kornia/kornia/tree/master/kornia/color
https://github.com/R08UST/Color_Conversion_pytorch/blob/master/differentiable_color_conversion/basic_op.py
"""
import torch
import torch.nn as nn
import math... |
"""Platform for newer SystemAir AC units with Modbus adapter."""
import logging
from typing import List
import asyncio
import voluptuous as vol
from homeassistant.core import HomeAssistant
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from homeassistant.components.climate import PLATFORM_SCHE... |
'''
Process map grid cell JSON file into a GeoJSON file with polygons outlining
the areas where the species can be found.
Requires shapely iff SMOOTH == True.
'''
import sys, json
(inf, outf) = sys.argv[1 : ]
SMOOTH = True
MIN_SIZE = 5 # discard groups of contiguous cells smaller than this
data = json.load(open(i... |
#================================================================
# To learn how to Develop Advance YOLOv4 Apps - Then check out:
# https://augmentedstartups.info/yolov4release
#================================================================
from ctypes import *
import math
import random
import os
import cv2
import... |
from pystac.version import STAC_VERSION
from pystac.extension import Extension
class STACObjectType:
CATALOG = 'CATALOG'
COLLECTION = 'COLLECTION'
ITEM = 'ITEM'
ITEMCOLLECTION = 'ITEMCOLLECTION'
class STACJSONDescription:
"""Describes the STAC object information for a STAC object represented in ... |
import logging
from src import api_helpers
from src.utils.config import shared_config
from hashids import Hashids
from flask_restx import fields, reqparse
from src.queries.search_queries import SearchKind
from datetime import datetime
logger = logging.getLogger(__name__)
HASH_MIN_LENGTH = 5
HASH_SALT = "azowernasdfoi... |
#!/usr/bin/env python
# Path planning node returns a list of poses forming a path
# Subscibes to OccupancyGrid
# Run map_server with target map to publish OccupancyGrid messages
# Publishes PoseArray with name "path"
# subscribes to amcl_pose for starting pose
import rospy
from nav_msgs.msg import OccupancyGrid
from g... |
##############################################################################
#
# Copyright (c) 2009 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... |
from typing import Optional, Tuple, List, Callable
import logging
import numpy as np
from progressbar import progressbar
from scipy.interpolate import interp1d
from dat_analysis.core_util import data_row_name_append, get_data_index
from dat_analysis import useful_functions as U
logger = logging.getLogger(__name__)
... |
"""
Copyrighth
<NAME>
<EMAIL>
Projekt: Távvezérlés parancssora
Verzió:v1.3
"""
import requests
import ast
import os
import sys
if "G:\\Privát adatok\\Arduino\\Projektek\\Belepteto_fenti_szoba\\RasberryPi" not in sys.path:
sys.path.append("G:\\Privát adatok\\Arduino\\Projektek\\Belepteto_fenti_szoba\\Rasbe... |
import os
import glob
import tensorflow as tf
import tensorflow_datasets as tfds
from scipy.interpolate import interp1d
from astropy.table import Table
from astropy.io import fits
import numpy as np
import pandas as pd # To extract the SnapNumLastMajorMerger values from TNG100_SDSS_MajorMergers.csv
_DESCRIPTION = """
... |
# coding: utf-8
import numpy as np
import utils
####################################################
## Indices ##
####################################################
#' @param args Python dictionary
#' index B(i,j)(t) >= mu_i-mu_j at time t
class Index(object):
def __init__... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.