text
stringlengths
3.07k
22.1k
from __future__ import print_function from os.path import dirname, abspath import pandas as pd import numpy as np import glob import pysam from Bio import SeqIO from optaux import resources resource_dir = resources.__path__[0] here = dirname(abspath(__file__)) strain_to_characteristic = \ {'hisD': ['2,400,257'...
# This file is part of Indico. # Copyright (C) 2002 - 2022 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. import json import pytest from flask.ctx import _AppCtxGlobals from marshmallow import EXCLUDE, INCLUDE, ...
# -*- coding: utf-8 -*- import io from odoo import models, fields, api import base64 import datetime from odoo.exceptions import AccessError, UserError, RedirectWarning, ValidationError, Warning import csv class res_partner(models.Model): _inherit = 'res.partner' allow_consignment = fields.Boolean("SOC") ...
#!/usr/bin/env python """ Created on 26/01/21 Author: <NAME> Emails: <EMAIL> - <EMAIL> Description: this file contains some useful functions. """ import numpy as np import argparse import os import json import matplotlib as pl import matplotlib.pyplot as plt import matplotlib.patches as patches import cv2 import torch...
import os import sys sys.path.insert(0, '../../') import time import glob import numpy as np import torch import nasbench201.utils as ig_utils import logging import argparse import shutil import torch.nn as nn import torch.utils import torchvision.datasets as dset import torch.backends.cudnn as cudnn import sota.cnn.ge...
import os import glob import time import torch import numpy as np from config import params from tensorboardX import SummaryWriter from torch import nn, optim from torch.utils.data import TensorDataset, DataLoader from AudioDataLoader import audioDataLoader import torch.backends.cudnn as cudnn import torch.nn.functiona...
import pandas as pd import numpy as np import scipy as sp import os import errno from sklearn.decomposition import PCA import umap.distances as dist from sklearn.utils.extmath import svd_flip from sklearn.utils import check_array, check_random_state from scipy import sparse import sklearn.utils.sparsefuncs as sf from u...
# Ross-thick Li-sparse model in: # <NAME>., <NAME>., & <NAME>. (2000). # An algorithm for the retrieval of albedo from space using semiempirical BRDF models. # IEEE Transactions on Geoscience and Remote Sensing, 38(2), 977-998. # Python Native import logging import os import re # 3rd-party import numpy import raste...
from model import model_list, normalization, input_shape from model import mnist_model_toy, cifar_model_toy, mnist_model_tiny, cifar_model_tiny from utils import data_loaders import argparse import os import numpy as np import torch import torch.optim as optim from torch import nn name_mapping = { ...
# Copyright (C) 2019-2022, Pyronear. # This program is licensed under the Apache License version 2. # See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details. """ Based on https://github.com/pytorch/pytorch/blob/master/torch/utils/collect_env.py This script outputs relevant sys...
"""The WaveBlocks Project Plot the energies of the different wavepackets as well as the sum of all energies for the original and spawned wavepacket in a single graph. @author: <NAME> @copyright: Copyright (C) 2011 <NAME> @license: Modified BSD License """ import sys from numpy import * from matplotlib.pyplot import ...
import csv import logging import os import re from cogs.exceptions import ApplyError from cogs.helpers import ( get_tracked_sheets, update_data_validation, get_sheet_formats, get_sheet_notes, update_note, update_format, validate_cogs_project, set_logging, ) from gspread_formatting impor...
import cv2 import numpy as np import time # Open Camera object cap = cv2.VideoCapture(0) # Decrease frame size cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1000) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 600) def nothing(x): pass # Function to find angle between two vectors def Angle(v1, v2): dot = np.dot(v1, v2) x_mod...
from typing import Callable, Type from math import gcd import torch.nn as nn from torchvision.models._utils import IntermediateLayerGetter from torchvision.models import mobilenet from torchvision.models.segmentation.deeplabv3 import DeepLabHead, DeepLabV3 from fcn import FCN, FCNHead __all__ = ['fcn_mobilenetv2', ...
# ***************************************************************** # Copyright 2013 MIT Lincoln Laboratory # Project: SPAR # Authors: SY # Description: The code that handles the generation of the correntness # section of the final report # # Modifications: # D...
#coding=utf-8 import socket import select import socketserver import logging import json #import time from multiprocessing import Process #import threading with open('config.json', 'rb') as f: config = json.load(f) #port = int(config['loaclport']) serverdd = config['server'] port = int(config[...
from math import log, sqrt import random from typing import Counter import matplotlib.pyplot as plt import numpy as np import pandas as pd import statistics as stat print("We will assert that the pseudo random number we gnerate is statistically reliable, i,e consistent with law of large numbers") roullete_log={} fr...
import re class Element: html_quote_map = { "&": "&amp;", '"': "&quot;", "'": "&apos;", ">": "&gt;", "<": "&lt;", } def __init__(self, children = None): self.children = [] if children: self.add_children(children) def add_child(self...
''' Download PDF files for a series of law chapter numbers found in our training CSV file provided by partners. Then extract the chapter texts from those PDFs. Finally insert the chapter text into a new column 'Text' of our training CSV. Note: each PDF contains a bit of the previous chapter and following one. ''' impor...
import unittest from clusto.test import testbase import clusto from clusto.schema import * from clusto.drivers.base import * from clusto.drivers import BasicDatacenter, Pool, BasicServer, IPManager from sqlalchemy.exceptions import InvalidRequestError class TestClustoPlain(testbase.ClustoTestBase): def testInitC...
#!/usr/bin/env python import imp import inspect import markdown import mdown import os import re import pydoc import public import readme_md.tables import requests import setupcfg import sys import values # # sorted(_attrs(cls), key=lambda kv: "__" in kv[0]) @public.add class Readme: """README.md generator""" ...
from __future__ import print_function # Copyright (c) 2015, Danish Geodata Agency <<EMAIL>> # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # ...
#!/usr/bin/env python ''' Generate compilable .osl files from .mx templates <NAME> ''' # Copyright Contributors to the Open Shading Language project. # SPDX-License-Identifier: BSD-3-Clause # https://github.com/AcademySoftwareFoundation/OpenShadingLanguage from __future__ import print_function, absolute_import impo...
import csv import itertools import os import sqlite3 import tempfile import uuid import requests from flask import (Blueprint, current_app, flash, jsonify, redirect, render_template, request, send_file, url_for) from flask_login import current_user from sqlalchemy import select from werkzeug.utils i...
''' PLTW Lesson 1.2.4 @authors: <NAME>, <NAME> ''' #####-Imports-##### #Import turtle library for drawing functions and display import turtle as trtl #Import random library to generate random values to be used later import random as rand #####-Game Config-##### #Create turtle to generate the simple ma...
# https://github.com/mozilla/DeepSpeech-examples/blob/r0.8/mic_vad_streaming/mic_vad_streaming.py import threading import collections import queue import os import os.path import numpy as np import wave from datetime import datetime from malaya_speech.utils.validator import check_pipeline from herpetologist import che...
# # 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, software # ...
import unittest import specrel.geom as geom import specrel.spacetime.physical as phy import specrel.visualize as vis def _arrays_to_lists(arrarr, precision=7): """Get the data of a nested numpy array as a list of lists, rounded to some precision. """ return [[round(p, precision) for p in arr] for arr ...
#!/usr/bin/env python3 import json import os import csv from time import perf_counter import requests def process_file_name(file_name, tavern_tests_dir): return file_name.replace(tavern_tests_dir, "").lstrip("/") def abs_rel_diff(a, b): return abs((a - b) / float(b)) * 100. def parse_csv_files(root_dir): ...
from __future__ import print_function, division from keras.layers import Input from keras.layers import BatchNormalization, Activation from keras.layers.convolutional import Conv2D, Conv2DTranspose from keras.models import Sequential, Model from keras.optimizers import Adam import argparse import pickle import sys try...
#### Model code and custom functions go here #### from tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D,AveragePooling2D,Input, Dropout, Flatten, BatchNormalization from tensorflow.keras.optimizers import Adam from tensorflow.keras.models import Model from tensorflow.keras.utils import Sequence, to_categor...
# Copyright 2011 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
import pylab # import seaborn as sns from scipy.sparse import diags from scipy.sparse.linalg import cg MAX_VAL = 255.0 from scipy.sparse import csr_matrix import numpy as np from scipy.sparse.linalg import inv RGB_TO_YUV = np.array([ [ 0.299, 0.587, 0.114], [-0.168736, -0.331264, 0.5], [ 0.5,...
import numpy as np import joblib from .rbm import RBM from .utils import sigmoid # TODO(anna): add sparsity constraint # TODO(anna): add entroty loss term # TODO(anna): add monitoring kl divergence (and reverse kl divergence) # TODO(anna): run on the paper examples again # TODO(anna): try unit test case? say in a 3x3...
# Copyright 2018 Xanadu Quantum Technologies 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 agre...
import io import os import re import shutil import sys from pathlib import Path from typing import Generator from unittest import mock import pytest from _pytest._io import terminalwriter from _pytest.monkeypatch import MonkeyPatch # These tests were initially copied from py 1.8.1. def test_terminal_width_COLUMNS(...
# This is a component of AXIS, a front-end for emc # Copyright 2004, 2005, 2006 <NAME> <<EMAIL>> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License,...
"""Add plugins here. - bandit - safety - dodgy - dlint - semgrep Functions return finding dictionary ```json { title: str description: str file: str evidence: list[Line] severity: Level confidence: Level line: int _other: dict[str, str] } ``` """ from __future__ import annotations import subprocess from io ...
#!/usr/bin/env python from tollan.utils.log import get_logger from tollan.utils.fmt import pformat_yaml from tollan.utils.registry import Registry, register_to from ..utils.runtime_context import RuntimeInfo from ..utils import RuntimeContext from . import main_parser, config_loader from astropy.utils.console import ...
# # SPDX-License-Identifier: BSD-3-Clause # # Copyright (c) 2016-2021, <NAME> <<EMAIL>> # import struct import sys import threading from dbus.mainloop.glib import DBusGMainLoop try: from gi.repository import GLib, GObject except ImportError: import gobject as GObject import sys import numpy from matplotlib.pylab...
import itertools import os import pickle import random import re import sys import warnings from pathlib import Path from typing import * import numpy as np import pandas import pyplant from Siamese.config import SiameseConfig from Siamese.data_loading import load_ensemble_member_metadata, load_member_volume from Pyt...
#!/usr/bin/env python # <NAME>, Broad Institute # Implemented: 13 June 2018 # This program will demultiplex BioRad # scATAC from v2.1 scheme ##### IMPORT MODULES ##### import os import re import regex import sys import gzip from barcodeHelp import * # local python script from optparse import OptionParser from multip...
#-*- coding: utf-8 -*- import argparse def str2bool(v): return v.lower() in ('true', '1') arg_lists = [] parser = argparse.ArgumentParser() def add_argument_group(name): arg = parser.add_argument_group(name) arg_lists.append(arg) return arg # Network net_arg = add_argument_group('Network') net_arg.a...
''' ******************************************************************************** Python Script: grfblock Module Writter: <NAME> Date: 16 February 2019 This Python script is compatible with Python 3.x. The script is used to define GfrBlock class in Blodiator. This class is a child of GrfBlockCore class. ...
from json import JSONDecodeError import logging import os import shutil from typing import Any, Dict, List, Tuple, Union from aiohttp import web from opentrons.config import (advanced_settings as advs, robot_configs as rc, feature_flags as ff, ...
"""make_plots. This program makes plots Usage: make_plots.py -h | --help make_plots.py --brd <BRD> --pl <PL> --out <OUT_NAME> --reports <reports> -h --help Show this message. -i --brd BRD The circuit file. -o --out OUT -p --pl PL -r --reports reports -apl --anim_pl animate_re...
# -*- coding: utf-8 -*- """ @author: truthless """ import os import logging import json import numpy as np import torch import torch.nn as nn from torch import optim import torch.utils.data as data from convlab2.util.train_util import to_device from convlab2.policy.vector.dataset import ActStateDataset from convlab2.po...
""" http://pypi.python.org/pypi/cluster/1.1.1b3 """ from __future__ import absolute_import, division, print_function # # This is part of "python-cluster". A library to group similar items together. # Copyright (C) 2006 <NAME> # # This library is free software; you can redistribute it and/or modify it under # the ter...
# -*- coding: utf-8 -*- # Copyright 2022, SERTIT-ICube - France, https://sertit.unistra.fr/ # This file is part of eoreader project # https://github.com/sertit/eoreader # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may ob...
import os import json import copy import torch import logging import torch.nn as nn from torchcrf import CRF from transformers.tokenization_bert import BertTokenizer from .module import IntentClassifier, SlotClassifier logger = logging.getLogger(__name__) VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"} PRETRAINED_VOC...
import collections import copy import datetime import logging from six.moves.urllib import parse from uareach import util logger = logging.getLogger(__name__) class FieldKey(util.Constant): KEY_CLASS = 'Field' CHANGE_MESSAGE = 'changeMessage' FORMAT_TYPE = 'formatType' HIDE_EMPTY = 'hideEmpty' ...
#!/usr/bin/python """ Tests for the OpenDaylight REST API interface Copyright 2013 The University of Wisconsin Board of Regents 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...
import asyncio import inspect from typing import Any, Callable, Coroutine, Dict, List, Optional, Tuple, Union from discord.abc import Messageable from discord.ext.commands import AutoShardedBot, Bot, CommandError, UserInputError from discord import Color, Embed, Emoji, Member, Message, Reaction, User from .converter...
import json import logging import random import time from typing import Dict, Optional, Union import numpy as np import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable from pagnn import init_gpu, settings from pagnn.models import AESeqAdjApplyExtra from pagnn.utils import (...
"""Action to support type hints.""" import inspect import os import re import yaml from argparse import Action from collections.abc import Iterable as abcIterable from collections.abc import Sequence as abcSequence from enum import Enum from typing import Any, Dict, Iterable, List, Sequence, Set, Tuple, Type, Union t...
"""Userinfo et. al.""" import codecs import re from datetime import datetime from datetime import timedelta from datetime import timezone from dango import dcog, Cog import discord from discord.ext import commands from discord.ext.commands import command from discord.ext.commands import errors import humanize import ta...
from collections import namedtuple from .nodes import * import re ConditionalBlock = namedtuple('ConditionalBlock', 'parent source output skip_to_end') class ParamStr(str): def __new__(cls, s, args, n): self = super().__new__(cls, s) self._args = args self._arg_idx = n return sel...
import argparse import logging from asyncio import Protocol, Transport import shlex from functools import partial from typing import Optional, List, Any, Dict, Callable, cast from tarpn.ax25 import AX25Call, AX25StateType, L3Protocol from tarpn.ax25.datalink import DataLinkManager, L3Handler from tarpn.events import E...
# -*- coding: utf-8 -*- """This module define utility classes for performing concurrent operations. """ from typing import Optional, Sequence, Dict, Union, Tuple, Callable, Any import os import asyncio # noinspection PyProtectedMember from asyncio.subprocess import Process import subprocess import multiprocessing fr...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np from six.moves import xrange import tensorflow as tf from tensorflow.python.platform import flags import logging, os, sys, pickle, argparse sys.path.a...
"""Plotting tools. """ from corona.utils import * from corona.maths import * import matplotlib as mpl import matplotlib.pyplot as plt plt.ion() from datetime import datetime, timedelta, timezone import matplotlib.dates as mdates import mpl_tools # Coloschemes - https://www.schemecolor.com palettes = {} palettes["...
from __future__ import print_function import random import os from os.path import join from tqdm import tqdm import numpy as np import networkx as nx import argparse import torch import sklearn from sklearn import preprocessing from sklearn.model_selection import StratifiedKFold from utils import settings...
##Program requires installatioon of SciKit from https://scikit-learn.org/stable/install.html ##Program demo can be found at https://www.datacamp.com/community/tutorials/svm-classification-scikit-learn-python # Import necessary packages. import time startTime = time.time() import math import csv ##Define ...
import calendar import operator from datetime import datetime, date from lib.core.component import Component from lib.helper import to_float, flatten_dict, is_float from lib.schedule_job import has_scheduled_job def get_constraint(app, config): platform = config['platform']; if platform == 'state': r...
""" pim The YANG\-module for Protocol Independent Multicast (PIM). The module defines configuration and operational data for the following features\: PIM Sparse Mode (PIM\-SM) PIM Source\-Specific Multicast (PIM\-SSM) Bidirectional PIM (Bidir\-PIM) Anycast\-RP for PIM Bootstrap Router (BSR) for PIM PIM Dense Mode...
import requests import json import pandas as pd from pandas.io.json import json_normalize from sklearn.externals import joblib import os import datetime as dt import time from time import gmtime, strftime from pandas.tseries.offsets import Second from six.moves.urllib.request import urlopen from datetime import date f...
# (c) 2016-2017 Adobe. All rights reserved. # This file is licensed to you 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...
# -*- coding: utf-8 -*- import datetime import decimal import hashlib import json import logging import time import traceback from http.cookies import Morsel import config import re from tornado.options import options from concurrent.futures import ThreadPoolExecutor import jsonschema import peewee from tornado.web i...
""" Copyright (c) 2019, <NAME> See LICENSE for details Blobber API: A Blobber is a class that byte-encodes and decodes a specific type. The two methods required of a Blobber are blob(obj) obj: an instance of the object for the blobber to encode. unblob(b): b: bytes to decode into an i...
import pandas as pd import os def file_search(path=".", doctype="csv", like=[""], strict=False): """ This function creates a list of all files of a certain type, satisfying the criteria outlined in like = [...] parameter. The function only searches for files in the specified folder of the curr...
# Copyright 2021 BlobCity, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
""" This creates Figure 4, fitting of multivalent binding model to Gc Data. """ import os import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from sklearn.metrics import r2_score from scipy.optimize import minimize from copy import copy from .figureCommon import subplotLabel, g...
# -*- coding: utf-8 -*- # Copyright (C) 2012, <NAME> # # Visvis is distributed under the terms of the (new) BSD License. # The full license can be found in 'license.txt'. """ The GTK backend. """ import os, sys import visvis from visvis import BaseFigure, events, constants from visvis.core.misc import getResourceDir...
""" Core module of annt-python This module provides functions related Boudning Box and Annotation information, which are important for handling annotation information. """ import os import json import cv2 import numpy as np from . import color from . import utils KEY_OBJECTS = 'objects' KEY_TYPE = 'typ' KEY_TAGS = ...
import os import sys import torch import shutil import random import numpy as np from tensorboardX import SummaryWriter from Datasets.dataset_shapenetpart import ShapeNetPartDataset from Datasets.dataset_samplers import RandomSampler, Sampler from Models.model_PN2 import PointNet2 from Models.model_mRes import mRes f...
# Copyright (c) SenseTime Research and its affiliates. All Rights Reserved. """Centralized catalog of paths.""" import os from copy import deepcopy class DatasetCatalog(object): DATA_DIR = "datasets" DATASETS = { ####################### ImageNet VID ####################### "DET_train_30classes...
from argparse import ArgumentParser import sh import torch.nn from sklearn.metrics import f1_score, accuracy_score, roc_auc_score from disaster_tweets_data_module import * # sh.rm('-r', '-f', 'lightning_logs/disaster_tweets_rnn_glove') class DisasterTweetsClassifierRNN(pl.LightningModule): def __init__(self,...
# create country attributes file import os import sys import json from pathlib import Path from datetime import datetime import config import modify from covid_package.data_funcs.store_data import read_json_data, write_json_data, rename_file, convert_owid_data def islands(iso): islands = ['AIA', 'ATG', 'ABW',...
#!/usr/bin/env python # encoding: utf-8 import numpy import random import argparse from sklearn.model_selection import train_test_split from sklearn.model_selection import cross_val_score from sklearn.model_selection import cross_val_predict from sklearn.model_selection import KFold from sklearn.preprocessing import St...
# # Copyright (c) 2018-2020 by <NAME> <<EMAIL>>. # # This software is available under the terms of the MIT license. Parts are licensed under # different terms if stated. The legal terms are attached to the LICENSE file and are # made available on: # # https://opensource.org/licenses/MIT # # SPDX-License-Identifier:...
#Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. #This program is free software; you can redistribute it and/or modify it under the terms of the BSD 3-Clause License. #This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of ...
__author__ = "<NAME>", "<NAME>" __version__ = "0.1p" import random import re from enum import Enum import os import csv import requests import time import datetime class MessageTone(Enum): POSITIVE = 1 NEUTRAL = 0 NEGATIVE = -1 class WarningLevel(Enum): WARNING = 0 MUTE = 1 BAN = 2 clas...
#!python3 """ Utilities for conducting simulations on random utility profiles. Author: <NAME> Date: 2019-07 """ import pandas, numpy as np from pandas import DataFrame import matplotlib.pyplot as plt from partitions import equalPartitions import operator from timeit import default_timer as timer from PrefProfile ...
# Add mouse controls # add half size paddle after hitting back wall import math, pygame, sys, shutil, getpass from pygame.locals import * pygame.init() fpsClock = pygame.time.Clock() screen = pygame.display.set_mode((640, 480)) # create screen - 640 pix by 480 pix pygame.display.set_caption('Breakout') # set title ...
""" Script to process wind farm & turbine csv downloaded from: https://eerscmap.usgs.gov/uswtdb/data/ Metadata description can be found at https://eerscmap.usgs.gov/uswtdb/assets/data/uswtdb_v1_0_20180419.xml Disregarding the following attributes for now: t_rsa turbine rotor swept area square meters t_ttlh turbine tot...
import numpy as np import properties import z_order_utils class BaseMetadata(properties.HasProperties): name = properties.String("Name of the block model", default="") description = properties.String("Description of the block model", default="") # Other named metadata? class BaseOrientation(properties.H...
import os import numpy as np from lib.utils.utils import unique from visualization.utils_name_generation import generate_image_name import cv2 colormap = { 0: (128, 128, 128), # Sky 1: (128, 0, 0), # Building 2: (128, 64, 128), # Road 3: (0, 0, 192), # Sidewalk 4: (64, 64, 128)...
# Extracted from scanpy, thanks! from functools import lru_cache from typing import Union, Sequence from typing_extensions import Literal import numpy as np from matplotlib import pyplot as pl from matplotlib import rcParams from matplotlib.axes import Axes from matplotlib.figure import SubplotParams as sppars from ma...
# ****************************************************************************** # Copyright 2017-2018 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apa...
# -*- coding: utf-8 -*- '''Test cases for the ``ldap`` state module This code is gross. I started out trying to remove some of the duplicate code in the test cases, and before I knew it the test code was an ugly second implementation. I'm leaving it for now, but this should really be gutted and replaced with somethi...
import inspect import contextlib _GLOBAL_CUSTOM_OBJECTS = {} _GLOBAL_CUSTOM_NAMES = {} OBJECT_UNDEFINED_CONFIG_KEY = 'object was saved without config' class CustomObjectScope(object): """Provides a scope that changes to `_GLOBAL_CUSTOM_OBJECTS` cannot escape. Code within a `with` statement will be able t...
""" VMC Networks state module Add new network/segment, update existing network/segment and delete existing network/segment from an SDDC. Example usage : .. code-block:: yaml ensure_network: vmc_networks.present: - hostname: sample-nsx.vmwarevmc.com - refresh_key: <KEY> - authorizat...
from flask import Flask,render_template,request,flash,url_for,redirect,jsonify import face_recognition import numpy as np import json import time import cv2 #import threading #from werkzeug.utils import secure_filename #import json #import random #import tablib ############################################### #l=lea...
import argparse import sys, os import imageio import tensorflow as tf import Classification_BatchDataset import TensorflowUtils as utils import pickle import time from tensorflow.keras.models import Sequential, Model from tensorflow.keras.layers import Conv2D, MaxPool2D, Dropout, Flatten, Dense, Input, Lambda from ...
import numpy as np import matplotlib.pyplot as plt def plot_decision_boundary(pred_func, X, y, filename): # Set min and max values and give it some padding x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5 y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5 h = 0.01 # Generate a grid of poin...
"""Tools for finding duplicate files.""" from hashlib import sha1 from bag.pathlib_complement import Path from subprocess import check_call class GdbmStorageStrategy: """Stores file hashes and file paths in a GNU DBM file.""" def __init__(self, path='./file_hashes.gdbm', mode='c', sync='s'): from db...
# -*- coding: utf-8 -*- ''' Module for manageing PagerDuty resource :configuration: This module can be used by specifying the name of a configuration profile in the minion config, minion pillar, or master config. The default configuration profile name is 'pagerduty.' For example: .. code-block:: yam...
import random import numpy from collections import defaultdict import itertools from pace.definitions import * from pace.data import load_dataset from typing import NamedTuple, Optional, Set def score_by_ppv(truth, predictions, top_n=None): """ Score a set of predictions by ranking them and determining what f...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging import math import os import re from . import util logger = logging.getLogger(__name__) def make_rect(xmin, ymin, xmax, ymax): rect = dict(xmin=xmin, ymin=ymin, xmax=xmax, ymax=ymax) ...
import warnings from bidict import bidict import numpy as np from endoanalysis.similarity import SimilarityMeasure def targets_mapping( similarity, sim_thresh, targets_gt, targets_pred, scores, multiclass=True ): """ Maps ground truth targets to predictions for a single class. Parameters ----------...