text
stringlengths
3.07k
22.1k
# 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. import math from fairseq import metrics, utils from fairseq.criterions import FairseqCriterion, register_criterion import torch from fairseq....
# _*_ coding: utf-8 _*_ """ python_sqlalchemy.py by xianhu """ import sqlalchemy import sqlalchemy.orm import sqlalchemy.ext.declarative # 利用数据库字符串构造engine, echo为True将打印所有的sql语句, 其他数据库的链接方式可自行百度 # engine = sqlalchemy.create_engine("mysql+pymysql://username:password@hostname/dbname", encoding="utf8", echo=True) engin...
#!/usr/bin/env python """ LDD Corral Tool to corral all the LDDs """ import logging import os import sys import traceback from argparse import ArgumentParser, RawDescriptionHelpFormatter from datetime import datetime import yaml from github3 import login from lxml import etree from shutil import rmtree from pkg_r...
from numpy.core.numeric import full, zeros_like import pyvisa import time import csv import matplotlib.pyplot as plt import numpy as np import math from math import sqrt, copysign import csv from dataclasses import dataclass def setup(type="current"): ''' Setup of electronic load for given type of measurement...
# coding=utf-8 import keyboard import airsim import cv2 import numpy as np import time import threading import os import re import subprocess import random import math from tf import transformations as tfs # Calculates Rotation Matrix given euler angles. def eulerAnglesToRotationMatrix(angles1) : theta = np.zero...
""" Download and parse data from CDEC, California Data Exchange Center, cdec.water.ca.gov cdec_dataset(...) is the main entry point. """ import datetime import os import logging import re import six import numpy as np import xarray as xr import pandas as pd from six.moves import StringIO import requests log=logging....
# encoding: utf-8 import concurrent.futures import hashlib import logging import time from datetime import datetime, timedelta from pathlib import Path import requests import get_muted_vod import mpv_py as mpv logger = logging.getLogger(__name__) formatter = logging.Formatter('[%(asctime)s : %(name)s]: %(message)s')...
import glob import os import pandas as pd import argparse import numpy as np import cv2 import time import json from fire import Fire from tqdm import tqdm import random from track_and_detect import Track_And_Detect, data_process ''' For posetrack dataset, the output keypoints is as follow "keypoints": { 0: "nose"...
import numpy as np import chainer from chainer import functions as F from chainer import links as L from chainermn import links as MNL def get_num_channel(channels, alpha): if channels is None or alpha is None: return None, None l_channels = int(alpha * channels) h_channels = channels - l_channels ...
''' ================================================ ## VOICEBOOK REPOSITORY ## ================================================ repository name: voicebook repository version: 1.0 repository link: https://github.com/jim-schwoebel/voicebook author: <NAME> author contact: <EMAIL> descr...
""" Created on Sun Feb 2 13:28:48 2020 @author: matias """ import numpy as np from numpy.linalg import inv from matplotlib import pyplot as plt import time #import camb #No lo reconoce la compu del df from scipy.integrate import cumtrapz as cumtrapz from scipy.integrate import simps as simps from scipy.interpolate im...
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Morphological models for astrophysical gamma-ray sources. """ from __future__ import absolute_import, division, print_function, unicode_literals from collections import OrderedDict import numpy as np from astropy.modeling import Parameter, ModelDefinit...
# Copyright 2021 MIT Probabilistic Computing Project # Apache License, Version 2.0, refer to LICENSE.txt import os import random import matplotlib.pyplot as plt import numpy as np from hirm import HIRM from hirm.util_io import to_txt_hirm from three_relations_plot import xlabels from three_relations_plot import ylab...
import enum from typing import Set import numpy as np import torch import torchvision from src.models.utils import infer_model_device class HookPhase(enum.Enum): INIT = 0 END = 1 EPOCH_START = 2 EPOCH_END = 3 LOGGING = 4 MODEL_FORWARD = 5 MODEL_FORWARD_END = 6 BACKWARD = 7 OPT_ST...
#!/usr/bin/env python3 """ lang.py Type: module Description: a parser for a file type that makes it easier to implement various languages in a game Classes: - LangNode - LangEval Functions: - load(path, encoding, as_dict) - loads(s, encoding, as_dict, file) Lang syntax =========== The file c...
# Imports here import numpy as np import torch from torch import nn from torch import optim import torch.nn.functional as F from torchvision import datasets, transforms,utils, models from torch.utils.data import Dataset, DataLoader #import helper import matplotlib.pyplot as plt from collections import Ord...
# load general packages and functions import torch import math # load program-specific functions #from parameters.constants import constants as C ''' class parameters(): def __init__(self, max_nodes, edge_features, node_features): self.enn_depth = 4 self.enn_dropout_p = 0 self.enn_hidden_...
import unittest from fishpy.geometry import LatticePoint class TestLatticePointProperties(unittest.TestCase): def setUp(self): self.p1 = LatticePoint(2, 4) def test_x(self): self.assertEqual(self.p1.x, 2) self.p1.x = 1 self.assertEqual(self.p1.x, 1) try: s...
import pandas as pd import collections import re from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt # from sklearn.cross_validation import Bootstrap import numpy as np import requests import os # http://pir.georgetown.edu/cgi-bin/comp_mw.pl?ids=P53039&seq=&submit=Submit # http://web.exp...
import os import shutil import asyncio import json from datetime import datetime, timezone from sqlitedict import SqliteDict from discord import Embed, PermissionOverwrite, Member from discord.ext import commands from discord.ext.commands import Context from discordbot.core.discord_bot import DiscordBot from discordb...
import chess class Heuristics: # The tables denote the points scored for the position of the chess pieces on the board. pTable = [ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0], [1.0, 1.0, 2.0, 3.0, 3.0, 2.0, 1.0, 1.0], ...
# 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. import inspect import io import os import pkgutil import unittest from typing import Any, Dict, cast from unittest import TestCase import matpl...
""" Module for market cog specific discord embeds """ from random import sample import discord from discord import Embed, Colour from typing import Optional from unsigned_bot.utility.time_util import timestamp_to_datetime from unsigned_bot.utility.price_util import get_average_price, get_min_prices from unsigned_bot....
import numpy as np from scipy.integrate import nquad from math import isclose def about_zero(num): return isclose(0.0, num, abs_tol=1.0E-14) def magnitude(vec): return np.sqrt(vec @ vec) def normalize(vec): return vec / magnitude(vec) def get_displacement_vector(from_vec, to_vec): return to_vec - ...
import hashlib import os, tarfile, pandas as pd, numpy as np import plotly.figure_factory as ff import plotly.offline as py from beeprint import pp import cufflinks as cf from numpy.polynomial import Polynomial from sklearn.cross_validation import cross_val_score from sklearn.ensemble import RandomForestRegressor fro...
# # Copyright (c) 2020, Hyve Design Solutions Corporation. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright # notice, th...
#!/usr/bin/env python # coding: utf-8 import re import operator operators = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv, } op_precedences = [ # extract content between innermost parentheses - highest precedence r'\(\s*([^()]+)\)', # extract higher pre...
import copy from collections import OrderedDict from usaspending_api.awards.v2.data_layer.orm_mappers import ( FABS_AWARD_FIELDS, FPDS_CONTRACT_FIELDS, OFFICER_FIELDS, FPDS_AWARD_FIELDS, FABS_ASSISTANCE_FIELDS, ) from usaspending_api.awards.models import Award, TransactionFABS, TransactionFPDS, Par...
# Licensed under a 3-clause BSD style license - see LICENSE.rst import abc import collections.abc import copy import numpy as np from gammapy.maps import Map from gammapy.modeling.models import Models, ProperModels from gammapy.utils.scripts import make_name, make_path, read_yaml, write_yaml from gammapy.utils.table im...
# -*- coding: utf-8 -*- """ Created on Sat Mar 13 17:02:16 2021 @author: <NAME> """ import pandas as pd import altair as alt import streamlit as st country_code = pd.read_csv('country_code.csv') df = pd.read_csv("suicide_population.csv") year_counts = df.groupby('country')['year'].unique().apply(len) ten_year_plu...
from copy import deepcopy import json import os import shutil import time from utils.utils import snake_case def escape_str(s): return s.replace("'", "\\'").replace('"', '\\"') def format_variable(v): if isinstance(v, str): return "'{}'".format(escape_str(v)) else: return str(v) class ...
#!/usr/bin/env python """ The data are stored in Blocks, with a Header The Main Controller Data Structure is as follows: [0x01]<Header, 31Bytes>[0x02]<Data, N Bytes>[0x03] Offset NumBytes Value/Type Description 00 1 [0x01] SOH, Start of Header 01 2 [A-Z0-9] Identifier for Instrument/DataType 03 5 [0-9]...
# Multiple Object Tracking Metrics # This is the basic algorithm for most # Multiple-Object tracking Metrics import numpy as np from pak.utils import extract_eq from math import ceil, floor from scipy.optimize import linear_sum_assignment HIGH_VALUE = 999999999 def evaluate(Gt, Hy, T, calc_cost, debug_info=False): ...
import sys import numpy import pyfits def weighted_quadrupole(im, centroid, sigma): y, x = numpy.indices(im.shape) gaussian = lambda y1, x1: numpy.exp(-0.5 * ((y1 - centroid[0])**2 \ + (x1 - centroid[1])**2)/sigma**2) weighted_image = im * gaussian(y, x) ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author : <NAME> # E-mail : <EMAIL> # Description: # Date : 05/08/2018 6:04 PM # File Name : kinect2grasp_python2.py # Note: this file is inspired by PyntCloud # Reference web: https://github.com/daavoo/pyntcloud import numpy as np from scipy.spatial import...
#!/usr/bin/env python3 # URL: https://python-gtk-3-tutorial.readthedocs.io/en/latest/treeview.html # URL: https://github.com/jamalex/notion-py import gi gi.require_version("Gtk", "3.0") from gi.repository import Gtk from gi.repository import Gdk from notion.client import NotionClient import threading # Global variab...
import numpy as np import plotly.graph_objects as go import plotly.express as px import plotly.io as pio from plotly.subplots import make_subplots from scipy.optimize import minimize # from easymh import mh from .utils import Id from .empirical import Region, Epidemic from .law import Bin, Poi __all__ = ['SIRQ',...
# UpdateDeviceTable.py # # This Python 3 script will download the Zaber Device Database from the # Zaber website, decompress it, extract data, output the data to # a .CSV file in the format expected by the Zaber A-Series Control Panel.vi example, # then optionally delete the downloaded database file. # # You may wish ...
import os import physical_validation as pv from physical_validation.data.simulation_data import SimulationData from physical_validation.data.observable_data import ObservableData from physical_validation.data.ensemble_data import EnsembleData from physical_validation.data.unit_data import UnitData from physical_v...
from __future__ import print_function, absolute_import, division #makes KratosMultiphysics backward compatible with python 2.6 and 2.7 #### TIME MONITORING START #### # time control starts import time as timer print(timer.ctime()) #### TIME MONITORING END #### #import kratos core and applications from KratosMultiph...
# --------------------------------------------------------------- # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # This work is licensed under the License # located at the root directory. # --------------------------------------------------------------- import re from collections import OrderedDict, d...
"""Script to evaluate a network on a dataset. This script is a refactored version of https://github.com/timy90022/One-Shot-Object-Detection/blob/master/test_net.py """ import os import sys import argparse import time import pprint import numpy as np import cv2 import torch import _init_paths from lib.roi_data_layer...
"""This file takes arrays and writes them into dictionaries""" import csv from math import inf import numpy as np from bound_evaluation.change_enum import ChangeEnum from bound_evaluation.manipulate_data import remove_full_nan_rows from bound_evaluation.monte_carlo_dist import MonteCarloDist from nc_arrivals.arrival_...
"""Collection of utilities to detect properties of the underlying architecture.""" from subprocess import PIPE, Popen import numpy as np import cpuinfo import psutil from devito.logger import warning from devito.tools.memoization import memoized_func __all__ = ['platform_registry', 'INTEL64', 'SNB', 'IVB...
from django.http import JsonResponse from django.core.exceptions import ObjectDoesNotExist from django.core.validators import validate_email from ipware import get_client_ip from ratelimit.decorators import ratelimit from easy_thumbnails.files import get_thumbnailer from .models import ArticleAnalysis, Article, Messag...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import torch import torch.nn as nn import torch.nn.functional as F from typing import Dict, List, Optional, Tuple from detectron2.config import configurable from detectron2.layers import ShapeSpec, cat, get_norm from detectron2.modeling import PROP...
import asyncio import aiohttp import functools import importlib import logging from .communicaton import JsonRpcRequest from .auth import DummyAuthBackend from .protocol import ( encode_notification, JsonRpcMsgTyp, encode_result, encode_error, decode_msg, ) from .exceptions import ( RpcGeneri...
#!/usr/bin/env python # Copyright 2020 <NAME> # License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) import torch as th import torch.nn as nn from typing import Optional, Tuple, List from aps.sse.enh.dcunet import Encoder, Decoder, parse_1dstr, parse_2dstr from aps.sse.base import SseBase, MaskNonLinear ...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime import random from odoo import api, models, fields, _ from odoo.addons.website.models.website import slug from odoo.tools.translate import html_translate from odoo.tools import html2plainte...
""" Provides helping function for issues. """ import copy from json import JSONDecodeError from math import ceil from typing import Optional, List, Collection, Dict import arrow from pyramid.request import Request from slugify import slugify from dbas.database import DBDiscussionSession from dbas.database.discussion_...
import os import cv2 import numpy as np import matplotlib.pyplot as plt import imutils from skimage.feature import local_binary_pattern # , hog from cyvlfeat.hog import hog import random ###############################################################################################################################...
from datetime import datetime, timedelta from typing import List, Optional from fastapi import APIRouter, Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from jose import JWTError, jwt from helpers import settings, global_storage from pydantic import BaseMode...
# -*- coding: utf-8 -*- import numpy as np import pandas as pd import matplotlib.ticker as mticker import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import statsmodels.tsa.api as smt import statsmodels.api as sm import scipy.stats as scs def ts_plot(y, lags=None, figsize=(10, 8), style='bmh'): ...
from datetime import datetime, timedelta from database.common import * class UnavailableSongError(Exception): def __init__(self, *args, song_id=None, song_title=None): super().__init__(*args) self._song_id = song_id self._song_title = song_title @property def song_id(self): ...
from __future__ import absolute_import from abc import ABCMeta, abstractproperty from logging import getLogger import sys import uuid import eventlet from eventlet.event import Event from eventlet.greenpool import GreenPool from greenlet import GreenletExit # pylint: disable=E0611 from nameko.constants import ( ...
#!/usr/bin/env python import os import shutil import argparse import textwrap import subprocess import psutil import sys from beautifuldiscord.asar import Asar class DiscordProcess: def __init__(self, path, exe): self.path = path self.exe = exe self.processes = [] def terminate(self):...
#!/usr/bin/env python # # colourbar.py - The ColourBar class. # # Author: <NAME> <<EMAIL>> # """This module provides the :class:`ColourBar` class, which generates a bitmap rendering of a colour bar. """ import numpy as np import fsl.utils.notifier as notifier import fsleyes_props ...
"""Adds config flow for Ledfxrm.""" from homeassistant import config_entries from homeassistant.core import callback import asyncio import aiohttp import async_timeout import voluptuous as vol import logging import requests from custom_components.ledfxrm.const import ( # pylint: disable=unused-import CONF_HOST, ...
import warnings import unittest import urllib.request import urllib.error import urllib.parse from openid import fetchers # XXX: make these separate test cases def _assertEqual(v1, v2, extra): try: assert v1 == v2 except AssertionError: raise AssertionError("%r != %r ; context %r" % (v1, v2,...
from __future__ import print_function from __future__ import unicode_literals from py._path.local import LocalPath as Path import pytest from testing import ( get_scenario, run, strip_coverage_warnings, venv_update, venv_update_symlink_pwd, TOP, ) from sys import version_info PY33 = (version_i...
#!/usr/bin/env python #-*- coding: utf-8 -*- #pylint: disable= # Author: <NAME> <<EMAIL> AT gmail [DOT] com> """ Spark script to parse DBS and Condor records on HDFS. """ # system modules import os import re import sys import gzip import time import json # pyspark modules from pyspark import SparkContext, StorageLeve...
import numpy as np import json, copy, os import math import logging, traceback from concurrent.futures import ThreadPoolExecutor from multiprocessing import cpu_count import tempfile import trimesh from skimage import measure from neurogen import mesh as ngmesh from neurogen import info as nginfo from neurogen impor...
import json import os from types import coroutine import numpy as np import mayavi.mlab as mlab from numpy.core.defchararray import center from numpy.lib.function_base import append import pandas as pd import math class_names=[ 'CAR', 'VAN', 'TRUCK', 'BIG_...
import pytest import os import shutil from copy import deepcopy from functools import partial import storefact import pandas as pd from pyhive import hive import pandas.testing as pdt from kartothek.serialization.testing import get_dataframe_not_nested from kartothek.io.eager import store_dataframes_as_dataset, read_...
import torchvision import os import wandb import torch import matplotlib.pyplot as plt import matplotlib.colors as colors import numpy as np def plot_recon(x, xhat, s_dir, e, wandb_on): x_path = os.path.join(s_dir, f'{e}_x.png') xhat_path = os.path.join(s_dir, f'{e}_xrecon.png') diff_path = os.path.join(s...
from copy import deepcopy from typing import List import numpy as np from sklearn import datasets from sklearn.base import BaseEstimator from sklearn.metrics import r2_score from sklearn.model_selection import cross_val_score from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeReg...
import logging import os import pickle from logging import handlers import gensim import numpy import convert_points_to_grid import convert_tweet_to_grid_and_gensim import settings as s logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) fh = logging.handlers.RotatingFileHandler('log.log', maxBytes=1...
from pickle import load import os import logging # removed pandas import, replace if necessary import spacy from psycopg2 import sql from psycopg2.extras import DictCursor from sklearn.neighbors import NearestNeighbors from .. route_tools.connection import Connection from .. route_tools.gb_search import GBWrapper fro...
import torch import torch.nn as nn import torch.nn.functional as F from ..basemodel import BaseModel # Unet 3D class ContBatchNorm3d(nn.modules.batchnorm._BatchNorm): def _check_input_dim(self, input): if input.dim() != 5: raise ValueError(f'expected 5D input (got {input.dim()}D input)') ...
import matrix import validate import complex import fraction as frac from typing import Union import string as StringTools FRACTION_ERR_CODE = 1 MATRIX_COL_ERR_CODE = 3 FIELD_VALS = ["r", "c"] YES_NO_VALS = ["y", "n"] FRAC_PT_ONE = {frac.NumberType.RealNum.value: 1, frac.NumberType.ComplexNum.value: "...
"""OCFL Object Store library.""" import hashlib import json import os import os.path import re import logging from shutil import copyfile, copytree try: from urllib.parse import quote_plus # py3 except ImportError: # pragma: no cover -- py2 from urllib import quote_plus # pragma: no...
import math import matplotlib.pyplot as plt import numpy as np import data_class as dc import json ROOT = 0.176923 def algebraic_equasion_function(x): """ This function makes a calculation for an Algebraic equasion It calculates f(x) with the given equasion and x as a parameter """ formula = x**2...
#!/usr/bin/env python3 from collections import OrderedDict from pathlib import Path from socket import gethostbyname from urllib.parse import urlparse from fire import Fire from requests.exceptions import SSLError from requests.sessions import Session from urllib3 import disable_warnings from urllib3.exceptions impor...
import os import torch import torch.nn as nn import numpy as np from torch.optim.lr_scheduler import ReduceLROnPlateau from config import Config from torchmetrics.functional import accuracy, f1, cohen_kappa from models.model import contrast_loss, ft_loss from sklearn.metrics import ConfusionMatrixDisplay, balanced_accu...
"""Validate the CO2eq parameters.""" import datetime import json import numbers import re import unittest def get_possible_modes(): """Get the set of possible modes.""" modes = set() with open("web/src/helpers/constants.js", encoding="utf-8") as file_: # The call to `eval` is a hack to parse the ...
#encoding: utf-8 """ grid.analysis.compare -- Omnibus spatial map comparison function and associated figure plot function Exported namespace: compare_AB, compare_AB_figure Written by <NAME>, 12/19/2008 Copyright (c) 2008 <NAME>. All Rights Reserved. """ # Library imports import numpy from scipy.stats impor...
# pylint: disable=protected-access from collections import OrderedDict from inspect import getmembers from rest_framework.decorators import action from rest_framework import viewsets as vsets from ..exceptions import VSTUtilsException def __get_nested_path(name, arg=None, arg_regexp='[0-9]', empty_arg=True): path...
from random import randint import numpy as np import pygame from math import sin,cos from pygame import font # //////////////////////////////// Usage //////////////////////////////////////// # first the programm will ask the number of Points the shape have which we want...
#!/usr/bin/env python3 #========================================================================= # # Copyright (c) 2018 <NAME>, PhD # # 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 # # ...
import gym import math import random import numpy as np import matplotlib import matplotlib.pyplot as plt from collections import namedtuple, deque from itertools import count from gym.wrappers.monitoring.video_recorder import VideoRecorder import torch import torch.nn as nn import torch.optim as optim import torch.nn...
#!/usr/bin/env python3 #################################################################################################################### # # *****smartRemotes created by HeadHodge***** # # HeadHodge/smartRemotes is licensed under the MIT License # # A short and simple permissi...
from pydub import AudioSegment import soundfile as sf import numpy as np import math import os import pathlib #Convert audio files from 24 bit to 16 bit for King College dataset r_hc24_data_dir = '/Users/oredata/Desktop/parkinson/26-29_09_2017_KCL/ReadText/HC/' r_pd24_data_dir = '/Users/oredata/Desktop/parkinson/26-29...
# Copyright (c) 2017, Teriks # All rights reserved. # # pake is distributed under the following BSD 3-Clause License # # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the ab...
from ntc_templates.parse import parse_output import os import re excluded_commands = ['terminal length 0', 'show tech-support', 'show running-config', ' ', ''] def split_interface(interface): try: num_index = interface.in...
#! /usr/bin/env python # -*- coding: utf-8 -*- """ Unit Tests for Complementary DNA Module .. moduleauthor:: <NAME> <<EMAIL>> """ import pytest from .. import code_wars # Test .alternate_sort() alternate_sort = { 'even length': ([5, 2, -3, -9, -4, 8], [-3, 2, -4, 5, -9, 8]), 'odd length': ([5, -42, 2, -3, ...
import requests import xmltodict from repoze.lru import LRUCache, lru_cache from utils import * class BustimeError(Exception): pass class BustimeWarning(Exception): pass class BustimeAPI(object): """ A `requests` wrapper around the Port Authority's bustime API with some basic error handling and some usef...
"""resnet in pytorch [1] <NAME>, <NAME>, <NAME>, <NAME>. Deep Residual Learning for Image Recognition https://arxiv.org/abs/1512.03385v1 """ import torch import torch.nn as nn import torchvision.models as models class BasicBlock(nn.Module): """Basic Block for resnet 18 and resnet 34 """ #Basic...
"""Core functionality.""" from abc import ABC, abstractmethod import typing as t from warnings import warn #: Registry of string keys to :class:`.ProgressConfig` instances. REGISTRY = dict() # type Dict[str, ProgressConfig] class AbstractProgressMonitor(ABC): """ Abstract base class for an object which tracks t...
# Copyright 2020 trueto # 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 writi...
from typing import List import plotly.graph_objects as go from ..beam_class import Beam from ..constants import ( COLOR_WIRE_FRAME_BEAM, COLOR_WIRE_FRAME_DETECTOR, COLOR_WIRE_FRAME_PAD, COLOR_WIRE_FRAME_TABLE, ) from ..phantom_class import Phantom def create_wireframes(beam: Beam, table: Phantom, pa...
import time import os import os.path as path import sys import yaml import json import math import numpy as np import pandas as pd from getting_data import load_sample from ranker_helper import get_scores from s2search_score_pdp import compute_pdp pd.options.display.float_format = '{:,.10f}'.format pd.set_option('displ...
#!/usr/bin/env python3 # std from abc import ABC, abstractmethod from typing import Optional from pathlib import PurePath, Path import random import subprocess import collections import re # 3rd import networkx as nx # ours from verzettler.note import Note from verzettler.markdown_reader import MarkdownReader from v...
import cv2 import config as cfg import numpy as np import os def eval_img2(gt, pred): cls_acc = [] TP_num = [] pos_all_total = [] for i in range(1, cfg.NUM_OF_CLASSESS): # ignore 0 gt_i = np.zeros(gt.shape, np.int) pred_i = np.zeros(gt.shape, np.int) zero = np.zeros(gt.shape...
import cv2 import face_recognition import time import os import models import numpy as np # Global variables MODEL_PATH = 'static/model_195.h5' # Read webcam feed for a frame every half a second WEBCAM_FRAME_READ_TIME = 0.5 # Read every third frame from uploaded video VIDEO_FRAME_READ_RATE = 3 CLASS_LAB...
"""Command line functions for transcribing corpora""" from __future__ import annotations import os import shutil import time from typing import TYPE_CHECKING, Optional from montreal_forced_aligner.command_line.utils import validate_model_arg from montreal_forced_aligner.config import ( TEMP_DIR, load_basic_tr...
from tkinter import * import cv2 from PIL import Image, ImageTk import numpy as np import os class RecognizerGUI: def __init__(self, root): root.title("Face Recogniser and Trainer v1.0") root.minsize(1000, 600) root.maxsize(1000, 600) root.resizable(False, False) ...
# -*- coding: utf-8 -*- import os import click import json import quandl import pprint import collections pp = pprint.PrettyPrinter(indent=4) quandl.ApiConfig.api_key = "<KEY>" def flatten(config=None, parent_key='', sep='.'): """Flattens a dictionary to the form of key_a.key_b.value :param config: str...
import logging import os import torch import torch.nn as nn import numpy as np logger = logging.getLogger(__name__) def recall(sentence, srl_string): matches = 0 for word in sentence.split(): if word in srl_string: matches += 1 if len(sentence.split()) > 0: return float(matc...
# 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. import itertools import os import torch import numpy as np from fairseq import options, utils from fairseq.data import ( ConcatDataset, ...
# Import data management libraries import numpy as np import pandas as pd # Import Natural Language Processing Libraries import nltk from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer from nltk.tokenize import word_tokenize, sent_tokenize nltk.download(['stopwords', 'punkt', 'averaged_perceptron...