text
stringlengths
3.07k
22.1k
import numpy as np import pytest from numpy.testing import ( assert_allclose, assert_almost_equal, assert_array_equal, assert_array_less, assert_equal, assert_raises, assert_warns, ) from sklearn.metrics import pairwise_distances from sklearn.metrics.pairwise import pairwise_kernels from .....
# ECBM E4040 Final Project: WSAE-LSTM # Author: <NAME> # This is a utility function to help you download the dataset and preprocess the data we use for this homework. # requires several modules: _pickle, tarfile, glob. If you don't have them, search the web on how to install them. # You are free to change the code as y...
#! /usr/bin/env python """Setup.py for installing OpenTimelineIO For more information: - see README.md - http://opentimeline.io """ import os import re import sys import platform import subprocess import unittest import pip from setuptools import ( setup, Extension, find_packages, ) import setuptools.c...
# Copyright 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import json import logging import subprocess import test_runner LOGGER = logging.getLogger(__name__) def _compose_simulator_name(platform, version): ""...
# To run this sample, install the following modules. # pip install azure-cognitiveservices-language-luis # <Dependencies> from azure.cognitiveservices.language.luis.authoring import LUISAuthoringClient from azure.cognitiveservices.language.luis.runtime import LUISRuntimeClient from msrest.authentication import C...
""" Collection of helpers for ivy unit tests """ # global import ivy try: import numpy as _np except ImportError: _np = None try: import jax.numpy as _jnp except ImportError: _jnp = None try: import tensorflow as _tf _tf_version = float('.'.join(_tf.__version__.split('.')[0:2])) if _tf_vers...
from typing import List, Iterable from general import floored_root, three_dimensional_plot from multidimensional_box import multidimensional_box_unpairing, multidimensional_box_pairing def multidimensional_szudzik_product(*streams: Iterable): n = len(streams) if n == 0: # The Cartesian product of no...
#!/usr/bin/env python3 import argparse import csv import os import pprint import sys import tempfile import urllib.request import subprocess slug = os.getenv("TRAVIS_REPO_SLUG", None) prebuilt_repo_name = 'HDMI2USB-firmware-prebuilt' if slug: prebuilt_repo_owner = slug.split('/',1)[0] else: prebuilt_repo_own...
import abc import logging import os from baconian.common.misc import construct_dict_config from baconian.common import files as files from baconian.core.global_var import get_all from baconian.config.global_config import GlobalConfig from functools import wraps from baconian.common.error import * class BaseLogger(ob...
# Copyright (c) 2017-present, Facebook, 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...
from math import atan2, pi from numpy import array, dot from dynamic_graph import plug from dynamic_graph.sot.core.task_pd import TaskPD from dynamic_graph.sot.dynamic_pinocchio import (Dynamic, Inverse_of_matrixHomo, Multiply_matrixHomo_vector, Multiply_of_matrixHomo,...
from func import lcmp, sdth, ins, BinConv, rBinConv, conv, stb, bts import time import colorama from colorama import Fore, Style class Num: def __init__(self): self.polynom = "10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000...
#!/usr/bin/env python # -*- coding: utf-8 -*- # + # import(s) # - from ocs_common import * from astropy.time import Time import argparse import re import sys # + # __doc__ string # - __doc__ = """ This file, $TS_OCS_COMMON_SRC/ocs_id.py, contains code for manipulating (unique) identifiers in the OCS. These identif...
import os import shutil from os import path import json import tensorflow as tf import numpy as np import cv2 # Importa datasets from datasets.AOBDataset.aob_dataset import load_dataset from datasets.data_aug import * # Import model stuff from models.mobilenetv2 import MobileNetV2 from models.custom_layers import Co...
from typing import List, cast from constants import recycle_time, role_cleanup, role_link_manager, role_recycling, target_closest_energy_site from creeps.base import RoleBase from creeps.roles.spawn_fill import SpawnFill from jstools.screeps import * from utilities import movement __pragma__('noalias', 'name') __prag...
# Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file acc...
# Driver for SIM800L module (using AT commands) # MIT License; Copyright (c) 2017 <NAME> import pyb import math # kludge required because "ignore" parameter to decode not implemented def convert_to_string(buf): try: tt = buf.decode('utf-8').strip() return tt except UnicodeError: tmp ...
"""Climate platform for Advantage Air integration.""" from __future__ import annotations from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( FAN_AUTO, FAN_HIGH, FAN_LOW, FAN_MEDIUM, HVAC_MODE_AUTO, HVAC_MODE_COOL, HVAC_MODE_DRY, ...
import logging import os import tempfile import threading from contextlib import contextmanager from typing import TYPE_CHECKING, Dict from funcy import retry, wrap_with from dvc.exceptions import ( FileMissingError, NoOutputInExternalRepoError, NoRemoteInExternalRepoError, NotDvcRepoError, Output...
""" Job handling for AWS Batch. """ import re from botocore.exceptions import ClientError from copy import deepcopy from operator import itemgetter from time import time from typing import Callable, Generator, Iterable, Mapping, List, Optional from ... import hostenv, aws from ...errors import UserError from ...util i...
import torch import torch.nn.functional as F import numpy as np import logging def test(step, dataset_test, filename, n_share, unk_class, G, C1, threshold): G.eval() C1.eval() correct = 0 correct_close = 0 size = 0 class_list = [i for i in range(n_share)] class_list.append(unk_class) pe...
"""Test GatewayClient""" import os import json import uuid from datetime import datetime from io import StringIO from unittest.mock import patch import nose.tools as nt from tornado import gen from tornado.web import HTTPError from tornado.httpclient import HTTPRequest, HTTPResponse from notebook.gateway.managers imp...
import auto import auto_domain from config import config import constants import datetime import json import os from pathlib import Path import urllib.request import requests import time def make_url(config_section): """ function that reads the specified configuration category related settings for protocol, IP add...
# Original work Copyright 2018 The Google AI Language Team Authors. # Modified work Copyright 2019 <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/license...
""" Logic for wavefunction optimization. """ import time from jax.flatten_util import ravel_pytree from deeperwin.bfgs import build_bfgs_optimizer, calculate_metrics_bfgs from deeperwin.configuration import OptimizationConfig, EvaluationConfig, ClippingConfig, LoggingConfig from deeperwin.evaluation import evaluate_wav...
import logging import os import shutil import sys import time import numpy as np import torch import torch.nn as nn import torch.nn.functional as F class AverageMeter(object): def __init__(self): self.reset() def reset(self): self.avg = 0 self.sum = 0 self.cnt = 0 def up...
# Natural Language Toolkit: Viterbi Probabilistic Parser # # Copyright (C) 2001-2020 NLTK Project # Author: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # URL: <http://nltk.org/> # For license information, see LICENSE.TXT from functools import reduce from nltk.tree import Tree, ProbabilisticTree from nltk.parse.api im...
""" Tests for s3encrypt """ from unittest.mock import AsyncMock from s3encrypt.s3encrypt import ( S3EncryptError, validate_directory, compress_directory, store_to_s3, compress_encrypt_store, s3encrypt_async, ) from concurrent.futures import ThreadPoolExecutor from unittest import mock import py...
#!/usr/bin/env python2 ## -*- coding: utf-8 -*- ## ## <NAME> - 2016-08-01 ## ## Description: Solution of the baby-re challenge from the Defcon Quals 2016. ## In this solution, we fully emulate the CheckSolution() function and we solve ## each branch to go through the good path. The emulation start from a memory ## ...
import warnings warnings.filterwarnings("ignore") import re import sys from prompt_toolkit import Application from prompt_toolkit.buffer import Buffer from prompt_toolkit.enums import EditingMode from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.layout.containers import VSplit, Window, HSplit fro...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import csv import os import shutil from PIL import Image import torch import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim import torch.utils.data import torch.utils...
## for debug def dummy_transform(img,text='dummy_transform'): print ('\t\t%s',text) return img ## custom data transform ----------------------------------- ## https://github.com/pytorch/vision/blob/master/test/preprocess-bench.py ## http://pytorch-zh.readthedocs.io/en/latest/torchvision/models.html ## Al...
# # This file is part of pyasn1 software. # # Copyright (c) 2005-2019, <NAME> <<EMAIL>> # License: http://snmplabs.com/pyasn1/license.html # try: from collections import OrderedDict except ImportError: OrderedDict = dict from pyasn1 import debug from pyasn1 import error from pyasn1.type import base from pyasn...
import deepspeech as ds import numpy as np import jamspell import googletrans import sys import wave import webrtcvad import collections import time import textwrap import sys import getopt import locale import os import codecs import sys # workaround to ignore CPU optimizations os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2...
# # -*- coding: utf-8 -*- """ config. """ import logging import six import wandb from wandb.util import check_dict_contains_nested_artifact, json_friendly_val from . import wandb_helper from .lib import config_util logger = logging.getLogger("wandb") # TODO(jhr): consider a callback for persisting changes? # if ...
""" This package will create the simplified comix matrix needed by simple_network_sim basing itself in the following data: - The CoMix matrix: https://cmmid.github.io/topics/covid19/reports/20200327_comix_social_contacts.xlsx - The Scottish demographics (NRS): ftp://boydorr.gla.ac.uk/scrc/human/demographics/scotland/d...
import bs import random defaultPowerupInterval = 8000 class PowerupMessage(object): """ category: Message Classes Tell something to get a powerup. This message is normally recieved by touching a bs.Powerup box. Attributes: powerupType The type of powerup to be grant...
import math from typing import List, Dict import numpy as np import torch from torch import nn from torch.nn import functional as F from detectron2.layers import ShapeSpec from detectron2.modeling.proposal_generator.build import PROPOSAL_GENERATOR_REGISTRY from adet.layers import DFConv2d, IOULoss, NaiveGroupNorm, GC...
#!/usr/bin/env python # encoding: utf-8 ''' @author: Sally @time: 2018/5/31 22:32 ''' from django.http import JsonResponse from sign.models import Event, Guest from django.core.exceptions import ValidationError, ObjectDoesNotExist from django.db.utils import IntegrityError import time # 添加发布会接口 def add_event(request)...
#!/usr/bin/env python3 # 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 typing import Optional from parlai.core.params import ParlaiParser from parlai.core.opt import Opt from pa...
#!/usr/bin/env python """ Filters for different surveys """ __author__ = "<NAME>" import yaml import numpy as np from matplotlib import mlab import numpy.lib.recfunctions #import ugali.utils.mlab with open('config.yaml', 'r') as ymlfile: cfg = yaml.load(ymlfile) survey = cfg['survey'] basis_1 = cfg[surv...
import socket import threading import time import sys # Define constant parameters ALL_CONN = [8080,8181,8282,8383] SERVER_PORT = 8181 IP_ADDR = "127.0.20.1" ADDR = (IP_ADDR,SERVER_PORT) CLIENT_ADDR = list(IP_ADDR) CLIENT_ADDR[-1] = str(int(CLIENT_ADDR[-1]) + 1) CLIENT_ADDR = "".join(CLIENT_ADDR) CONFIG_PATH = "con...
# 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 pytest import os asyncio = pytest.importorskip("asyncio") httpx = pytest.importorskip("httpx") import vcr # noqa: E402 from vcr.stubs.httpx_stubs import HTTPX_REDIRECT_PARAM # noqa: E402 class BaseDoRequest: _client_class = None def __init__(self, *args, **kwargs): self._client_args = args...
import sys from mpi4py import MPI import numpy as np from scipy.interpolate import interp1d sys.path.append('/Users/bl/Dropbox/repos/Delight/') from delight.io import * from delight.utils import * from delight.photoz_gp import PhotozGP from delight.photoz_kernels import Photoz_mean_function, Photoz_kernel import scipy...
# Copyright (c) achao2013. All rights reserved. #coding=utf-8 import torch import torch.nn as nn import math import torch.nn.functional as F from torch.autograd import Variable import numpy as np from torch.nn.parameter import Parameter import torch.utils.data from torch.nn import functional as F from torch.nn.functi...
# Code generation functions. # # (c) Mit authors 1994-2020 # # The package is distributed under the MIT/X11 License. # # THIS PROGRAM IS PROVIDED AS IS, WITH NO WARRANTY. USE IS AT THE USER’S # RISK. from code_util import Code, unrestrict, disable_warnings, c_symbol from stack import StackEffect, Size, type_words de...
#!/usr/bin/env python3 import numpy import random import traceback class ConsolePlayer: def __init__(self, name): self.name = name def start(self, player_num): self.name = input("Enter the name for player {} :".format(player_num)) def get_move(self, grid): print("Move for {}"...
import numpy as np import torch import torch.nn as nn import math import copy from typing import Union from torch.distributions import Categorical import os import yaml import random device = torch.device("cuda:0") if torch.cuda.is_available() else torch.device("cpu") def setup_seed(seed): torch.manual_seed(seed)...
import argparse import pathlib import shutil import statistics import subprocess import time from os.path import join import constants from constants import RESULTS_DIR, DISTANCE_NORMS, CONSISTENT_DRAWS, NUM_THREADS, MODEL_TYPES, DISTANCE_NORM, \ NUM_ADV_CHECKS from datasets import get_epsilon from result import g...
import os import sys import matplotlib as plt import numpy as np import scipy.io as sio import scipy.misc import tensorflow as tf from matplotlib.pyplot import imshow from PIL import Image from scipy import io as sio OUTPUT_DIR = "output/" STYLE_IMAGE = "data/starry_night.jpg" CONTENT_IMAGE = "data/marilyn_monroe_in...
import logging from dataclasses import dataclass from datetime import datetime import discord import discord.ext.commands as commands from bot.consts import Colors, Claims from bot.data.tag_repository import TagRepository import bot.extensions as ext from bot.messaging.events import Events log = logging.getLogger(__...
from bs4 import BeautifulSoup as bs import subprocess import requests import hashlib import hmac import uuid import json import time import sys AUTO_MODE = True #Stolen from YTDL AKAMAI_ENCRYPTION_KEY = None if not AKAMAI_ENCRYPTION_KEY: print("No encryption key, can't proceed") sys.exit(0) d...
#!/usr/bin/env python3 # SPDX-License-Identifier: GPL-2.0 """ tdc.py - Linux tc (Traffic Control) unit test driver Copyright (C) 2017 <NAME> <<EMAIL>> """ import re import os import sys import argparse import json import subprocess from collections import OrderedDict from string import Template from tdc_config impo...
# Copyright (c) 2015-2019 Vector 35 Inc # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, ...
""" Code for twitter tipping bot """ import logging import time import os import requests import tweepy from dotenv import load_dotenv load_dotenv(verbose=True) logging.basicConfig(level=logging.INFO) LOGGER = logging.getLogger() API_KEY = os.getenv("API_KEY") API_SECRET = os.getenv("API_SECRET") ACCESS_TOKEN = os....
import torch import torch.nn as nn import torch.nn.functional as F import os import math try: # CUDA kernel assert not ('FORCE_NATIVE' in os.environ and os.environ['FORCE_NATIVE']) # add FORCE_NATIVE in env to force native from cuda_op.fused_act import FusedLeakyReLU, fused_leaky_relu from cuda_op.upfird...
from ..functions_on_data import iterable_data_array, data_array_builder import pandas as pd import numpy as np from scipy.optimize import curve_fit __all__ = ( "window", "fit_sine", "center_yaxis", "shift", "scale", "invert", "average_over_same_angle", ) def window(data_dict, key="Y", wi...
# -*- coding: utf-8 -*- ################################################################### # Author: <NAME> # Date : 2018.5 # Email : <EMAIL> ################################################################### """ Some helper functions for handling color and formatter. """ import six import collections import dateti...
import math from unittest import TestCase from helper import ( merkle_parent, ) class MerkleTree: def __init__(self, total): self.total = total # compute max depth math.ceil(math.log(self.total, 2)) self.max_depth = math.ceil(math.log(self.total, 2)) # initialize the nodes p...
import utils from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from tqdm import tqdm import numpy as np import pandas as pd from itertools import combinations, permutations import heapq # Here we created a class in order to store the index...
#!/usr/bin/env python # # This file is based on # https://github.com/llvm-mirror/clang-tools-extra/blob/5c40544fa40bfb85ec888b6a03421b3905e4a4e7/clang-tidy/tool/clang-tidy-diff.py # # ===- clang-tidy-diff.py - ClangTidy Diff Checker ----------*- python -*--===# # # Part of the LLVM Project, under the Apache License v2....
#!/usr/bin/env python import datetime import json import os import os.path import shutil import sys import traceback from distutils import log from distutils.command.build import build as BuildCommand from distutils.core import Command from subprocess import check_output from setuptools import find_packages, setup fro...
# -*- coding: utf-8 -*- import math import os from collections import defaultdict from pprint import pprint import numpy as np from tqdm import tqdm from configs import total_info from utils.misc import get_gt_pre_with_name, get_name_list, make_dir from utils.recorders import ( CurveDrawer, MetricExcelRecorde...
import math import colorsys import scipy import scipy.cluster import operator import math from PIL import Image import numpy as np import random WIDTH = 1700 HEIGHT = 540 def rgb_to_gray(r, g, b, a = None): return 0.299 * r + 0.587 * g + 0.114 * b def get_avg_gray(pix, x, y, radius, sample_size = 0.1): nsamp...
import numpy as np import json5 import logging from collections import defaultdict from itertools import combinations from ._optimize import MatchCost from . import util class dotdict(dict): """ quick and dirty addition to allow access to bus defs using just dot operator dot.notation access to dictionary a...
# Copyright 2018 ICON Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
from stream_framework.feeds.base import UserBaseFeed from stream_framework.tasks import follow_many, unfollow_many from stream_framework.tasks import fanout_operation from stream_framework.tasks import fanout_operation_hi_priority from stream_framework.tasks import fanout_operation_low_priority from stream_framework.ut...
import sys import time from binascii import hexlify class cs_buffer(): """ Buffering for the packets received during downloading. """ def __init__(self): self.__rx_buffer = [] def get_num_rx(self): """ Add packet to buffer """ return(len(self.__rx_buffer)) def add(self, packet...
"""Entity definition for Innova 2.0 HVAC.""" from __future__ import annotations from datetime import timedelta from homeassistant import config_entries from homeassistant.components.climate import (ClimateEntity, ClimateEntityFeature, HVACAction, ...
import json import os import stripe from django.contrib import messages from django.conf import settings from django.contrib.auth import login, logout, authenticate from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExis...
"""Tests for the JUnit XML parser.""" import os import pytest from test_reporting.junit_xml_parser import validate_junit_xml_stream, validate_junit_xml_file from test_reporting.junit_xml_parser import validate_junit_xml_archive, parse_test_result, JUnitXMLValidationError VALID_TEST_RESULT = """<?xml version="1.0" en...
import os import sys import numpy as np import scipy.io import zipfile import types import PIL from PIL import Image, ImageOps import math import tensorflow as tf from tensorflow.contrib.learn.python.learn.datasets import mnist sys.path.append('/home/leminen/Documents/RoboWeedMaps/GAN/weed-gan-v1') import src.utils ...
"""Support for Hikvision event stream events represented as binary sensors.""" from __future__ import annotations import datetime from datetime import timedelta import logging import time # from pyhik.hikvision import HikCamera from .utils import HikCamera, REGION_IDS, REGION_SENSORS import voluptuous as vol from ho...
import platform import os import wfdb import glob import numpy as np import pandas as pd from os.path import join from biosppy.signals import ecg from Helpers.Physionet import LoadFile, PhysionetConstants from Helpers.Metrices import * from subprocess import call from collections import namedtuple ChannelDescription =...
import copy import time import torch import argparse import numpy as np from torch.utils.data import DataLoader from deepsnap.batch import Batch from deepsnap.dataset import GraphDataset from torch_geometric.datasets import TUDataset def arg_parse(): parser = argparse.ArgumentParser(description='Pagerank argument...
# -*- coding: utf-8 -*- # file: data_utils.py # author: albertopaz <<EMAIL>> # Copyright (C) 2019. All Rights Reserved. import re import os import pickle import numpy as np import spacy import itertools import pandas as pd from tqdm import tqdm from dan_parser import Parser from torch.utils.data import Dataset def m...
import unittest import torch import os from fastNLP.modules.tokenizer.gpt2_tokenizer import GPT2Tokenizer from fastNLP.embeddings import GPT2WordPieceEncoder, GPT2Embedding from fastNLP import DataSet, Vocabulary class TestGPT2Embedding(unittest.TestCase): @unittest.skipIf('TRAVIS' in os.environ, "Skip in travi...
import math import torch import torch.nn as nn import torch.nn.functional as F from model.module.Linear_super import LinearSuper from model.module.layernorm_super import LayerNormSuper from model.module.multihead_super import AttentionSuper from model.module.embedding_super import PatchembedSuper from model.utils impo...
import os import inspect from google.auth import credentials, environment_vars from google.auth.exceptions import RefreshError from google.api_core.gapic_v1.client_info import ClientInfo from google.cloud import bigquery from google.cloud.exceptions import Forbidden from google.cloud.bigquery._http import Connection fr...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from typing import TYPE_CHECKING from fnmatch import fnmatch import re import io import defusedxml import functools from refinery.units import Arg, Unit from refinery.lib.structures import MemoryFile if TYPE_CHECKING: from pyxlsb2.records import SheetRecord defuse...
#!/usr/bin/env python # coding: utf-8 # ### In this notebook we tried to investigate simple ResNet on PDU data # ### Importing the libraries # In[1]: import torch import torch.nn as nn import torch.utils.data as Data from torch.autograd import Function, Variable from torch.optim import lr_scheduler import torc...
from django.shortcuts import render from wechatpy.utils import check_signature from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from wechatpy import WeChatClient, parse_message from wechatpy.replies import TextReply from wechatpy.events import ScanCodeWaitMsgEvent from wechatpy....
# coding=utf-8 # Copyright 2021 The Edward2 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 o...
""" source: https://github.com/timesler/facenet-pytorch/blob/master/examples/infer.ipynb """ import os from pathlib import Path import cv2 import numpy as np from PIL import Image, ImageDraw import torch from torchvision import transforms from facenet_pytorch import MTCNN, InceptionResnetV1 class ...
import math import numpy as np from scipy.optimize import least_squares from Resources.helpers import * class BaseMeasurement: ''' Base class for all measurements. Child classes need to implement the _measure method that takes a dictionary of landmark positions and returns a float value and a s...
# Lint as: python2, python3 # Copyright 2018 The TensorFlow 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 # ...
""" Converts GML CSV into Spider artifacts - schema json file, tables json, sqlite db. Example input: CSV generated from https://docs.google.com/spreadsheets/d/1og_gZ9oINInEO4CHpdPMIvg106qlj49fKNxVFWGL5Ww/edit#gid=1302477593 """ import argparse import csv import json import inflection import nltk import os from pathli...
import itertools import logging import pandas as pd import torch from pytorch_lightning import LightningModule from metrics import clustering_metrics, Metrics from utils import preprocess_input, tensor_sizes class ClusteringEvaluator(LightningModule): def register_hooks(self): # Register hooks for embed...
import os import sys import re import time import uuid import argparse def parse_lrc_line(line): try: ret = re.search(r"^\s*\[(\d+):(\d+\.\d+)\](.*)$", line) minute = int(ret.group(1)) second = float(ret.group(2)) text = ret.group(3) return [minute, second, text] except...
# Copyright 2019 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
import argparse import matplotlib matplotlib.use('Agg') from models import * from data.data_utils import * DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu' def apply_mask(mem_y, out, n_classes): """ Apply mask on the predicted outputs based on the given task - assuming task-incremental learning setup :par...
# Copyright 2021 The Magenta 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 ...
""" Copyright (c) 2015, 2019 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. Reads input from OpenShift v3 """ import json import os from osbs.constants import USER_PARAMS_KIND_SOURCE_CONTAINER_BUILDS from atomic_...
### ©2020. Triad National Security, LLC. All rights reserved. ### This program was produced under U.S. Government contract 89233218CNA000001 for Los Alamos National Laboratory (LANL), which is operated by Triad National Security, LLC for the U.S. Department of Energy/National Nuclear Security Administration. All rights...
import os import threading import time import pygame import tkinter.messagebox from tkinter import * from tkinter import filedialog from tkinter import ttk from pygame import mixer import mutagen from mutagen.mp3 import MP3 from mutagen.flac import FLAC from mutagen.id3 import ID3 # creating new window root = T...
"""Implementation of sample attack.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os #from cleverhans.attacks import FastGradientMethod #from cleverhans.attacks import BasicIterativeMethod from attacks import BasicIterativeMethod import numpy a...
# (C) British Crown Copyright 2011 - 2018, Met Office # # This file is part of cartopy. # # cartopy is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option)...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import os import utils from config import config from vkapi import VKLightOauth, VKLight, VKLightError, VKLightOauthError from handlers import APIHandler, LoadMusicHandler from threads import DownloadsFile, LoadMusic from .window import auth from .window import mainwindow...
from train.loss.utils import pairwise_distance import tensorflow as tf """ All the code below is referenced from : * https://github.com/omoindrot/tensorflow-triplet-loss * https://omoindrot.github.io/triplet-loss """ def _pairwise_distances(embeddings, squared=False): """Compute the 2D matrix of distances between...