text
stringlengths
3.07k
22.1k
import discord import sys import os import io import asyncio import aiohttp import random import subprocess import json import ezjson import inspect import traceback from contextlib import redirect_stdout from collections import Counter from inspect import getsource from discord.ext import commands ...
from sympy import Symbol, Wild, sin, cos, exp, sqrt, pi, Function, Derivative,\ abc, Integer, Eq, symbols, Add, I, Real, log, Rational, Lambda, atan2 def test_subs(): n3=Rational(3) n2=Rational(2) n6=Rational(6) x=Symbol("x") c=Symbol("c") e=x e=e.subs(x,n3) assert e == Rational...
################################################################################ # # # __ __ _____ ____ ____ _ # # | \/ | ___| _ \ / ___| __ _ _ __ ___ (_)_ __ __ _ ...
from queue import LifoQueue import sys sys.path.append('..') from components.board import Board class Solver(): """ This class takes the Sudoku board class as a parameter and implements a stack of instructions for solving it, that grows/ dynamically changes as numbers are found. Abstract - to help build other sol...
#!/usr/bin/python # $ sudo python test.py # $ sudo python test.py owp:dg:v1 # Works with LocalUDP variant also, as owpshell has same syntax (port and # rate are ignored). from __future__ import print_function import subprocess import unittest import sys import os READ_INFO = 0x01 # return generic sensor info READ...
"""Copyright (c) 2021 <NAME> All rights reserved. This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. """ import os from random import randint, random import numpy as np import pandas import scipy.io as sio from sklearn.preprocessing import StandardScal...
import threading import numpy as np import rospy import os import yaml import rospy from mesh_msgs.msg import MeshGeometryStamped, MeshGeometry, MeshMaterial, \ MeshMaterials, MeshMaterialsStamped, MeshFaceCluster, \ MeshVertexCostsStamped, MeshVertexCosts from me...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2016-2017 China Telecommunication Co., 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/lice...
import cPickle from cython_bbox import bbox_overlaps import numpy as np def nms(boxes, score, trace, th = 0.3): idx = score.argmax() choice = boxes[idx] target_trace = trace[idx] del(trace[idx]) t = score[idx] score = np.delete(score, idx) del(boxes[idx]) sss = np.zeros((score.size)) for i in xrange(...
import numpy as np import matplotlib.pyplot as plt import copy class Optimizer: def __init__(self, x, fitness, n_generations=5, population_size=5, constraint=None): """Initialize the optimizer x: list that contains a series of dictionaries that define the x values for the optimizer where ty...
''' This package provides a function to symbolically determine the differential equation describing the dynamics of a system. As inputs the `Solve` function takes the elemental and constraint equations of a system. These equations must be in the forms specified by Rowell and Wormley in "System Dynamics: An Introduction...
# Copyright (c) 2015-2016 <NAME> <<EMAIL>> # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html # For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER """Astroid hooks for numpy.""" import astroid def numpy_random_mtrand_transform(): return astroid.parse(''...
#!/usr/bin/env python3 from __future__ import annotations from argparse import ArgumentParser, RawDescriptionHelpFormatter from pathlib import Path from typing import Any, Optional import dataclasses import json import os import subprocess import sys try: import yaml YAML_SUPPORTED = True except ModuleNotFound...
import cv2 import numpy as np import utils def recolorRC(src, dst): """Simulate conversion from BGR to RC (red, cyan). The source and destination images must both be in BGR format. Blues and greens are replaced with cyans. Pseuocode: dst.b = dst.g = 0.5 * (src.b + src.g) dst.r = src.r ""...
import numpy as np import pandas as pd from scipy.stats import norm import statsmodels.base.wrapper as wrap import statsmodels.regression.linear_model as lm from statsmodels.tools.decorators import cache_readonly from statsmodels.base.model import GenericLikelihoodModel, GenericLikelihoodModelResults, _LLRMixin from st...
# Copyright 2020 <NAME>, <NAME> # 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, ...
import logging import random from collections import deque import numpy as np from keras.callbacks import ReduceLROnPlateau from pyschieber.player.base_player import BasePlayer from pyschieber.trumpf import Trumpf from pyschieber.card import from_string_to_card from pyschieber.rules.stich_rules import allowed_cards f...
import _curses import sys from typing import TYPE_CHECKING, Iterable, Sized, List, Tuple, Optional import asciimatics.widgets as widgets from asciimatics.event import KeyboardEvent from asciimatics.exceptions import ResizeScreenError from asciimatics.scene import Scene from asciimatics.screen import Screen, _CursesScr...
import numpy as np import matplotlib import matplotlib.pyplot as plt from skimage.draw import circle from matplotlib.animation import ArtistAnimation from matplotlib.animation import FFMpegWriter from matplotlib.patches import Rectangle def extract_frames_from_clip(video_data, istart, iend, channel=0): """ Ex...
# coding=utf-8 import time import logging import tornado.web from . import BaseHandler from bson.objectid import ObjectId from .utils import make_content class TopicListHandler(BaseHandler): def get(self): topics = self.db.topics.find(sort=[('last_reply_time', -1)]) topics_count = topics.count()...
# ------------------------------------------------------------------------------ # Copyright (c) Microsoft # Licensed under the MIT License. # Written by <NAME> (<EMAIL>) # ------------------------------------------------------------------------------ from __future__ import absolute_import from __future__ import divis...
# coding: utf-8 import codecs import json import logging import os import re import subprocess import coverage import requests from .exception import CoverallsException from .reporter import CoverallReporter log = logging.getLogger('coveralls') class Coveralls(object): config_filename = '.coveralls.yml' ...
# Author: <NAME> import pandas as pd import numpy as np import re from unit_converter.converter import convert, converts def build_data_dict(df): """ Receives of DataFrame of compiled data and appropriately calculates/reformats data into final structure. Parameters ----------------- ...
import gc import multiprocessing from multiprocessing import Queue from .dataset import * from .base import * class StageRunner(object): def __init__(self, max_procs): self.max_procs = max_procs def launch_process(self, p_id, input_q, output_q): raise NotImplementedError() def run(self, ...
# etl.py - module to clean up incoming covid 19 datasets for ingenstion __version__ = '0.1' __all__ = ['FetchData', 'GetCTPData', 'ProcessCTPData', 'FormatDates'] """ @TODO - should have own getargs.py """ import csv import os import datetime import pandas as pd from common import utils from Datasets.__meta__.state...
""" Full assembly of the parts to form the complete network """ import torch import torch.nn as nn import torch.nn.functional as F class DoubleConv(nn.Module): """(convolution => [BN] => ReLU) * 2""" def __init__(self, in_channels, out_channels, mid_channels=None): super().__init__() if not m...
import torch import torch.nn as nn import numpy as np import torch.nn.functional as F from scipy.signal import get_window import torchaudio as audio_nn def istft(stft_matrix, hop_length=None, win_length=None, window='hann', center=True, normalized=False, onesided=True, length=None): # keunwoochoi's im...
import configparser import json from pathlib import Path import random import sys import time import requests import webbrowser import urllib.parse import datetime import pyaudio import spotipy import sounddevice import vosk MODEL = "vosk-model-small-en-us-0.15" AUDIO_BITRATE = 44100 AUDIO_BUFFER = ...
import numpy as np import matplotlib.pyplot as plt from neural_network.train import SGDNetwork, BatchNetwork from neural_network.layer import make_layers, Layer from neural_network.preprocess import (MIN_MAX_SCALAR, make_train_set, apply_k_fold, scaling) from neural_network.utilit...
# -- coding: utf-8 -- import geopandas import json import csv import time import threading import concurrent.futures import re import math from ...model.point import Point from ...model.baidu import poi as poi_model from ...model.baidu.hexagon import Hexagon from ...repository.baidu import poi as poi_repo from ...model...
''' Main functions for estimating SparCC ''' from glob import glob from numba import njit from typing import List,Any import h5py import warnings import logging import dask.array as da import numpy as np from .core_methods import to_fractions from .compositional_methods import run_clr,variation_mat try: from s...
# -*- coding: utf-8 -*- """ pygments.lexers.julia ~~~~~~~~~~~~~~~~~~~~~ Lexers for the Julia language. :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from pygments.lexer import Lexer, RegexLexer, bygroups, combined, \ ...
#!/usr/bin/env python import os import sys import argparse import numpy as np import mdtraj as md import matplotlib.pyplot as plt from matplotlib.collections import LineCollection from LLC_Membranes.llclib import physical, topology, file_rw import tqdm def initialize(): parser = argparse.ArgumentParser(descript...
import turtle import random from Draw import* from AStarSearch import* from Dijkstra import* from GreedySearch import* from AStarPickPoint import* from HelpAnimation import* def readData(f): with open(f, "r") as fp: line=fp.readline() cnt=1 data=list() while line: ...
from django.core.urlresolvers import reverse from django.db import models, transaction from django.db.models import Count from django.utils.translation import ugettext_lazy as _, ugettext from events.models import Event from iportalen import settings from organisations.models import Organisation from utils import time ...
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import random from typing import Any from .utils import BasicBrain class PERD3QNAgent(BasicBrain): """ Prioritized Experience Replay Dueling Double Deep Q Network Parameters: ----------- input_dim : int, default 153...
import torch import torch.nn as nn from torch.nn import init from torch.autograd import Variable import os import numpy as np import time import random from sklearn.metrics import f1_score from sklearn.metrics import recall_score from sklearn.metrics import precision_score from collections import defaultdict from gra...
import logging import numpy as np import astropy.constants as const import astropy.units as au def powersph_error(power, tsys, nfeeds, tobs, xarclen, yarclen, fwhm, nu_min, nu_max, dnu, nu0, k, cosmo): """ Get instrument sensitivity in power spectrum, provided a set of instrument parameters Require...
from .swift_scenario import CellState, AudioAction from multiagent.core import Action from .swift_scenario import CellState import numpy as np from multiagent.utils import Point, doIntersect # def handcraft_policy(agent, world): DELTA = 1/8 def handcraft_policy(agent, world)->Action: # action: one hot \in R^9,...
import os from pathlib import Path import numpy as np def remove_zero_entries(d: dict): new_d = {k: v for k, v in d.items() if v != 0} return new_d class DatasetSplit: def __init__(self, data_folder: Path, examples_file_name: str, definitions_file_name: str, ...
""" Process a document into publishable blog format. """ import json import os import sys import webbrowser from functools import partial from io import StringIO from typing import List from doc_utils import element_type from doc_utils import para_type from doc_utils import paragraphs_from from docs import SQLDoc from...
# SPDX-FileCopyrightText: 2022 <NAME> <<EMAIL>> # # SPDX-License-Identifier: MIT import datetime import uuid from django.contrib.auth import get_user_model from django.contrib.auth.models import Group from django.core.exceptions import ValidationError from django.db import models from django.db.models import Max, Min...
from . import util class KNXIPFrame: SEARCH_REQUEST = 0x0201 SEARCH_RESPONSE = 0x0202 DESCRIPTION_REQUEST = 0x0203 DESCRIPTION_RESPONSE = 0x0204 CONNECT_REQUEST = 0x0205 CONNECT_RESPONSE = 0x0206 CONNECTIONSTATE_REQUEST = 0x0207 CONNECTIONSTATE_RESPONSE = 0x0208 DISCONNECT_REQUEST ...
import pandas as pd, numpy as np, scipy as sp import functools, collections, time, contextlib, os, torch, gc, warnings from torch.utils.data import DataLoader from datetime import datetime from pytorch_lightning import LightningModule from backports.cached_property import cached_property from .score_array import * cl...
''' This includes the module to realize the transformation between mesh and location map. Part of the codes is adapted from https://github.com/Lotayou/densebody_pytorch ''' from time import time from tqdm import tqdm from numpy.linalg import solve from os.path import join import torch from torch import nn import os im...
from __future__ import division import sys from statistics import mean from sklearn.ensemble import BaggingClassifier from sklearn.metrics import accuracy_score from sklearn.model_selection import GridSearchCV from sklearn.multiclass import OneVsRestClassifier from sklearn.svm import SVC from tools.classifier.evalua...
import random import torch import torch.nn as nn import torch.nn.functional as F # Helper function for returning deprocessing of decorrelated tensors def get_decorrelation_layers(image_size=(224,224), input_mean=[1,1,1], device='cpu', decay_power=0.75, decorrelate=[True,None]): mod_list = [] if decorrelate[0]...
from flask import Flask import config import dash import dash_core_components as dcc import dash_html_components as html import dash_bootstrap_components as dbc from dash.dependencies import Input, Output, State from dash.dependencies import Input, Output import os import pandas as pd pd.options.mode.chained_assign...
import json import sys import logging import collections import re import census from census.core import supported_years import census.math import esridump from .lodes import OnTheMap from .core import AreaFilter, GEO_URLS try: # Python 2.7+ from logging import NullHandler except ImportError: class NullHand...
import tensorflow as tf # import sys # import os # sys.path.append(os.path.abspath(os.path.join( # os.path.dirname(__file__), "../bert"))) from bert import tokenization from est_cls import InputFeatures vocab_file = "/home/johnsaxon/github.com/Entity-Relation-Extraction/pretrained_model/chinese_L-12_H-768_A-12/v...
# credit: https://github.com/wfbradley/CDF-confidence # Compute confidence interval for a quantile. # # Suppose I'm interested in estimating the 37th percentile. The # empirical CDF gives me one estimate for that. I'd like # to get a confidence interval: I'm 90% confident that the 37th percentile # lies between X and...
# standart modules import threading import struct import os # blender modules import bpy import bmesh # addon modules import taichi as ti import numpy as np from .engine import mpm_solver from . import types from . import particles_io from . import nodes WARN_SIM_NODE = 'Node tree must not contain more than 1 "Simu...
import csv import math import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.patches as patches import numpy as np import os from PIL import Image from skimage import transform import torch import torch.nn.functional as F from utils import imsmooth, normalize, str2bool data_dirs = {...
# -*- coding: utf-8 -*- from inspect import isfunction from core.utils.base import get_varible_name, pprint import time import sys def none_fun(*args): pass class Blackboard(object): def __init__(self): self.__tag = 'Blackboard' self.con = {} def set_value(self, member, value): ...
""" A utility for guessing which file and line of a local source repo are the best referent for a line in a diffscuss file. Intended mainly for use in editors to facilitate jumping to source from a diffscuss file. """ from collections import namedtuple from optparse import OptionParser import os import re import sys f...
import numpy as np import math from sardem.dem import main as load_dem from numba import jit, prange from typing import Tuple, NamedTuple, Dict import gdal class RPCCoeffs(NamedTuple): height_off: float height_scale: float lat_off: float lat_scale: float line_den_coeff: np.array line_num_coeff...
# Copyright (C) 2014 Universidad Politecnica de Madrid # # 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 la...
# Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT import enum import sentry_sdk import time from copr.v3 import Client from datetime import datetime, timedelta, date from os import getenv from github import InputGitAuthor from github.Commit import Commit from ogr.services.github import ...
#!/usr/bin/env python3 import pybullet as p import numpy as np import time from mp.utils import Transform, filter_none_elements, repeat from pybullet_planning import plan_wholebody_motion from collections import namedtuple from trifinger_simulation.tasks.move_cube import _ARENA_RADIUS, _min_height, _max_height from mp....
import pytest from pg13 import sqparse2,pgmock def test_parse_arraylit(): v=sqparse2.ArrayLit((sqparse2.Literal(1),sqparse2.Literal(2),sqparse2.Literal("three"))) assert v==sqparse2.parse("array[1,2,'three']") assert v==sqparse2.parse("{1,2,'three'}") def test_parse_select(): # this is also testing nesting an...
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import base64 import binascii import imghdr import decimal import functools import json import os import secrets import uuid from concurrent.futures import ThreadPoolExecutor, as_completed import boto3 from boto...
import os import contextlib import hou import sys from collections import deque import pyblish.api import openpype.api import openpype.hosts.houdini.api.usd as hou_usdlib from openpype.hosts.houdini.api.lib import render_rop class ExitStack(object): """Context manager for dynamic management of a stack of exit c...
from reddit_analysis.app.util.sa_logger import logger from collections import Counter import re import streamlit as st from wordcloud import WordCloud, STOPWORDS from stqdm import stqdm stqdm.pandas() import matplotlib.pyplot as plt import seaborn as sns # set Seaborn Style sns.set(style='white', context='notebook...
"""Application factory for the aiohttp.web-based app. """ __all__ = ('create_app',) import asyncio import logging import os from pathlib import Path import ssl import sys from aiohttp import web, ClientSession from aiokafka import AIOKafkaProducer import structlog from kafkit.registry.aiohttp import RegistryApi fro...
import os import pickle import numpy as np class Metric(object): """Base metric class. Subclasses must override score() and can optionally override various other methods. """ def __init__(self): print("Generating the entropy dictionary.") #f = open('C:/Users/Gsw/Desktop/entropy.txt') with open('/h...
import pandas as pd import os import cv2 import numpy as np import random def get_diff_scaled(img1,img2,scale): return ((np.clip((img1.astype('int32') - img2.astype('int32')) * scale, -255, 255) + np.ones_like( img1) * 255) / 2).astype('uint8') def get_diff(img1,img2): return ((img1.astype('int32')-im...
""" Get information about a repository. """ import os import re from time import localtime, strptime, strftime from git import Repo, GitCmdObjectDB class RepoDetails: """ The repo details class """ def __init__(self, repo_path, tag_prefix='', ...
from matplotlib import pyplot as plt class Circle(): """ Circle class similar to plt.Circle and mpl.patches.Wedge (for two semi-circles). Parameters ================ xy : tuple, list Center location of circle. radius : int,...
"""main API module.""" from __future__ import annotations import dataclasses from dataclasses import dataclass from enum import Enum from typing import Any, Union, cast import aiohttp from siyuanhelper import exceptions data_type = Union[dict, list, None] class Siyuan: """Siyuan Helper Instance.""" def...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from dataclasses import dataclass, field from math import log import torch from fairseq import utils from fairseq.data import LanguagePairData...
# @file # Script to Build EmulatorPkg UEFI firmware # # Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: BSD-2-Clause-Patent ## import os import logging import io from edk2toolext.environment import shell_environment from edk2toolext.environment.uefi_build import UefiBuilder from edk2toolext.invocables....
# XXX NOT a SCons tool module; instead, a library for the msvs_* tool modules import os import os.path import functools import SCons.Errors import SCons.Tool import SCons.Tool.MSCommon.vs import SCons.Warnings import msvs_preprocessed # Disables "MSVC_USE_SCRIPT set to False" warnings. Unfortunately, also disables "...
#!/usr/bin/env python # -*- coding: utf-8 -*- # A few words on the division of labour here... # - The conversation builder determines the order in which things get said # - The grammar-based token expander determines what gets said # - The phrase substitution personalizer determines how it's said # Offer: A line s...
import tensorflow as tf import math from tensorpack.tfutils.argscope import argscope, get_arg_scope from tensorpack.tfutils import get_current_tower_context from tensorpack.tfutils.common import get_global_step_var from tensorpack.models import (MaxPooling, Conv2D, GlobalAvgPooling, BatchNorm, FullyConnected, layer_re...
# -- Import necessary modules -- # from getpass import getpass import os, sys, pexpect, json import cryptography.fernet from cryptography.fernet import Fernet def _generate_key(): # -- Generate a new encryption key -- # return Fernet.generate_key() def _encrypt(key, token): f = Fernet(key) return f.en...
"""This module contains functions and classes to read and check input files.""" import json import math from typing import Dict, NamedTuple, List import networkx as nx import pandas as pd # Type aliases used to make the types for the functions below easier to read Age = str Compartment = str NodeName = str # Curre...
''' (*)~--------------------------------------------------------------------------- Pupil - eye tracking platform Copyright (C) 2012-2017 Pupil Labs Distributed under the terms of the GNU Lesser General Public License (LGPL v3.0). See COPYING and COPYING.LESSER for license details. -----------------------------------...
import os,inspect from collections import OrderedDict import numpy as np from scipy.optimize import brentq import pypospack.utils from pypospack.eamtools import create_r from pypospack.potential.eamdens_mishin2004 import func_density_mishin2004_w_cutoff from pypospack.potential.pair_general_lj import (func_cutoff_mi...
import numpy as np import sys import torch from tqdm import tqdm import scipy as sp import sklearn import torch.nn.functional as F from IPython.display import HTML as html_print from matplotlib import colors import string from math import log, e # import sparsify import sparsify_PyTorch # import lime from lime.lime_t...
""" Reduction of slice objects """ # Author: <NAME> # Created: June 2020 import itertools def reduced(s, size): """Return reduced slice with respect to given size. Notes ----- If `x = list(range(size))` then `x[s] == x[reduced(s, size)]` for any slice instance `s`. """ start, stop, step =...
# -*- coding: future_fstrings -*- # MIT License # Copyright (c) 2017 Cosmic Open Source Projects # 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 limit...
import pytest from pathlib import Path import pickle import numpy as np import pandas as pd from scipy import sparse as sp from scipy.stats import mannwhitneyu from numpy.random import negative_binomial, binomial, seed from anndata import AnnData from scanpy.tools import rank_genes_groups from scanpy.tools._rank_gen...
import json import threading import time from datetime import datetime, timedelta from socket import * from privledge import daemon from privledge import ledger from privledge import settings from privledge import utils lock = threading.Lock() # Message Class # class Message: def __init__(self, msg_type, msg=No...
from inspect import signature from functools import wraps from typing import ( Any, Union, Callable, Optional, TypeVar, Tuple, Dict, List, Iterator, overload, ) from contextlib import contextmanager from weakref import WeakValueDictionary __all__ = ["Model", "Control", "view", ...
"""A script for viewing and transforming real-time event streams with KQL""" import os import sys import traceback import json import clr import struct # Adding reference C# DLL References calc = struct.calcsize(("P") * 8) if calc == 64: REAL_TIME_KQL_LIBRARY = os.path.join(os.path.dirname(__file__), 'lib', 'RealT...
# -*- coding: utf-8 -*- # # Copyright 2011 <NAME> <<EMAIL>> # # 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 ap...
import copy DOUBLE_PRIMARIES = True SPLIT_PRIMARIES = True def coalesce(l): l = list(l) idx = 0 while idx < len(l) - 1: comb = l[idx].combine_with(l[idx + 1]) if comb is not None: del l[idx:idx + 2] l.insert(idx, comb) else: idx += 1 return l...
# # Copyright (C) 2022 Vaticle # # 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...
import sys, platform, os sys.path.insert(1, '/home1/jacklone/Mat_project/hmvec/hmvec') import matplotlib from matplotlib import pyplot as plt import numpy as np import camb from camb import model, initialpower from scipy.interpolate import interp1d, interp2d from params import default_params print('Using CAMB %s insta...
import pytest import numpy as np from differentiable_sorting import ( bitonic_matrices, bitonic_woven_matrices, bitonic_indices, ) from differentiable_sorting import diff_sort_indexed, diff_sort_weave from differentiable_sorting import softmax, smoothmax, softmax_smooth from differentiable_sorting import di...
# coding: utf-8 # ### Libraries # In[1]: import csv import nltk import os import pandas as pd import re import time import numpy as np from autocorrect import spell from hashtag_separator import infer_spaces from nltk.corpus import stopwords from sklearn import svm from sklearn.metrics import * from sklearn.model...
import gc import os from dataclasses import dataclass, field from typing import List import cv2 import imageio import numpy as np import torch import vispy from injector import inject from vc.service.file import FileService from vc.service.helper.diagnosis import DiagnosisHelper as dh from vc.service.helper.inpaintin...
from pathlib import Path from typing import List, Dict, Any import tarfile import hashlib import os import shutil import inspect import git import tomli import rootpath DEFAULT_ARCHIVE_BASE_DIR = "./.arc/archive" SHORT_HASH_LENGTH = 7 def obj_module_path(obj: Any) -> str: """Get a module path for any given obje...
""" This program creates a virtual hibike device for testing purposes. usage: $ socat -d -d pty,raw,echo=0 pty,raw,echo=0 2016/09/20 21:29:03 socat[4165] N PTY is /dev/pts/26 2016/09/20 21:29:03 socat[4165] N PTY is /dev/pts/27 2016/09/20 21:29:03 socat[4165] N starting data transfer loop with FDs [3,3] and [5,5] $ py...
import re import math from collections import Counter import os import string from read import * import pandas as pd from pandas import ExcelWriter, ExcelFile import numpy as np import matplotlib.pyplot as plt import spacy from nltk.corpus import stopwords import nltk from sklearn.linear_model import LinearRegression f...
from __future__ import annotations __all__ = ["TimeValue", "TimeInterval"] from dataclasses import dataclass from datetime import datetime from dateutil.relativedelta import relativedelta from hijri_converter import Gregorian, Hijri from . import constants class TimeValue(relativedelta): def __init__( ...
from ..cashflow import NullCashflow, Present, Future, Annuity, Perpetuity from ..utilities import get_final_period from math import isinf def npw(cashflows, i, title=None) -> Present: """ Computes the Net Present Worth of a sequence of cashflows Converts each Cashflow in a sequence of cashflows to their Pres...
""" Sudoku solver This program solves arbitrary Sudoku puzzle utilizing the following techniques: - only choice - automatically filling boxes that can have a single value only - elimination - if one value is set, it removes that value from all boxes in the same unit(s) - naked twins - if a unit has two values with the...
import copy import os import random import numpy as np import tensorflow as tf from tqdm import tqdm import utils.data_generation.data_utils from experiments import config from models.prednet import data_utils from models.prednet.train_prednet import check_action, create_model, print_results def test(scenario="nois...
# Copyright 2016-2018, Rigetti Computing # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. """ Unittests for QuantumFlow Gate Decompositions """ import numpy as np from numpy import pi import scipy.stats import pytest i...