text
stringlengths
3.07k
12.6k
## import NLP packages from nltk import word_tokenize, sent_tokenize, PorterStemmer from nltk.corpus import stopwords import math def _create_frequency_table(text: str) -> dict: """ Returns a dictionary of words and their frequency in the text. :param text: The text to be summarized. :return: A dictio...
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
import sys import textwrap import threading from ievv_opensource.utils import ievv_colorize from ievv_opensource.utils.desktopnotifications import desktopnotificationapi class Logger(object): """ Logger class used by :class:`.LogMixin`. """ loggers = {} # messagelock = threading.Lock() DEBUG ...
from functools import update_wrapper from django.conf import settings from django.contrib import admin from django.contrib.admin import AdminSite from django.contrib.auth import REDIRECT_FIELD_NAME from django.shortcuts import resolve_url from django.urls import path, reverse from django.utils.http import is_safe_url ...
import atexit from clockify_idleless import clockify from ctypes import Structure, windll, c_uint, sizeof, byref from datetime import datetime from datetime import timedelta from datetime import timezone import json import os import threading import wx.adv import wx LOOP_TIME = int(clockify.config['idleless'].get('Ch...
import sys from PyQt5.QtWidgets import * from PyQt5.QtGui import QIcon, QPixmap, QTextCursor, QCursor, QFont, QColor from PyQt5.QtSql import QSqlTableModel, QSqlDatabase, QSqlQueryModel from PyQt5.QtCore import pyqtSlot, pyqtSignal, QObject, QTimer, Qt, QModelIndex, qInstallMessageHandler, QSize, QRect from submission...
""" Instance generator for residential Demand Response problems. This module contains functions to import numerical data and generate instances of residential DR problems, formulated as Mixed-Integer Linear Programs. Functions: load_data: import price, load, output and temperature data build_model: build ...
import inspect import numpy as np from matplotlib.image import AxesImage from matplotlib.transforms import (IdentityTransform, TransformedBbox, BboxTransformFrom, Bbox) __all__ = ['BaseImageArtist', 'supports_resize'] EMPTY_IMAGE = np.array([[np.nan]]) IDENTITY = IdentityTransform...
#! /usr/bin/env python3 from math import gcd #from numba import jit from random import choice, getrandbits, randrange from bjorklund import bjorklund #@jit def random_index (array): return randrange (0, len (array)) #@jit def random_bool (): return bool (getrandbits (1)) def relative_primes (n, minn=1, ...
# import packages import cProfile import time from chains.core import metrics as m from chains.core import node_factory as f, initializers as init from chains.core import optimizers as gd, graph as g, env from chains.core.shape import Dim from coursera.course2.w1.reg_utils import * from coursera.utils import plot_cost...
"""Basic analyser implementation for images. This basic analyser is set up to receive images from the EventBus, analyse them using basic image analysis functions and send a decision parameter back to the EventBus to be handed on to an interpreter. """ import logging import numpy as np import time from PyQt5.QtCore i...
""" Tests pane functionality """ from pytest import fixture from tmux_session_utils.utils import assert_objects_equal from tmux_session_utils.tmux_utils import get_pane_syntax from tmux_session_utils.builder.object_tracker import ObjectTracker from tmux_session_utils.builder.pane import Pane, SPLIT_HORIZONTAL, SPLIT_V...
# # Traffic sign classification with BiT # # In this script, we'll finetune a [BigTransfer] # (https://arxiv.org/abs/1912.11370) (BiT) model from [TensorFlow # Hub](https://tfhub.dev/) to classify images of traffic signs from # The German Traffic Sign Recognition Benchmark using TensorFlow 2 / # Keras. This notebook is...
import argparse import os import pandas as pd import time import subprocess import pdb dirname_script = os.path.dirname(__file__) # no need to include a "DNA" folder because the files should come from other folders # os.path.join(dirname_script, 'source_csvs/dna.csv'), PATHS_DEFAULT = [ os.path.join(dirname_scri...
#!/usr/bin/python # Copyright (c) 2015 Hewlett-Packard Development Company, L.P. # # This module 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 3 of the License, or # (at your option) any later...
import numpy as np import os from PIL import Image from matplotlib import pyplot as plt from torch.distributions.uniform import Uniform import torch import torchvision.transforms as T from torch.utils.data import Dataset, DataLoader from torchvision import datasets as torch_dataset from torchvision.utils import make...
import os import codecs # version 2_10 ud_files_map_2_10 = {} # ud_files_map_2_10["amh"]="UD_Amharic-ATT/am_att-ud-test.conllu" ##### # ud_files_map_2_10["ind"]="UD_Indonesian-GSD/id_gsd-ud-test.conllu" ####### # ud_files_map_2_10["pes"]="UD_Persian-Seraji/fa_seraji-ud-test.conllu" #### # ud_files_map_2_10["por"]="UD...
# # Copyright 2018 Red Hat | Ansible # # This file is part of Ansible # # Ansible 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 3 of the License, or # (at your option) any later version. # # ...
from functools import wraps from flask_caching import Cache import base64 import io import json import copy import collections from glom import glom from . import dash_layout as dl def unstringify(val): """ Used to change any str value created by DBC.Input once initialised due to not defining the compone...
import argparse import os import json import random import numpy as np from faiss import Kmeans, IndexFlatL2 from tqdm import tqdm import torch from scipy.stats import entropy from rudetox.util.io import read_jsonl, write_jsonl from rudetox.util.dl import gen_batch from rudetox.clf.train import train as train_clf d...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.transforms as transforms from sklearn.metrics import auc def confidence_ellipse(x, y, ax, n_std=3.0, facecolor='none', **kwargs): """ Create a plot of the covariance confidence ellipse of *x* and *y*. Parameters...
## PLOT STREAMFUNCTION from __future__ import print_function #path = '/home/mkloewer/python/swm/' path = '/network/aopp/cirrus/pred/kloewer/swm_bf_cntrl/data/' path2 = '/home/kloewer/git/swm/' outpath = '/network/home/aopp/kloewer/swm/paperplot/' import numpy as np from scipy import sparse import matplotlib.pyplot as ...
# -*- coding: utf-8 -*- import itertools import logging from apscheduler.schedulers import base import futurist import munch from padre import channel as c from padre import date_utils as du from padre import finishers from padre import message as m from padre import slack_utils as su from padre import utils from pa...
#!/usr/bin/env python3 import logging import os from pathlib import Path from typing import Any, Mapping, Optional import jinja2 import yaml __all__ = [ "create_jinja2_template_env", "template_rendered", "merge_dict", "StartServerTemplates", ] SERVER_HOME = os.environ.get("SERVER_HOME") SERVER_INSTA...
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
""" @author: <NAME> @email : <EMAIL> """ import re import itertools import operator import copy import igraph import heapq import nltk from igraph import * import numpy as np # requires nltk 3.2.1 from nltk import pos_tag nltk.download('maxent_treebank_pos_tagger') nltk.download('averaged_perceptron_tagger') def c...
"""Options are the ultimate mean of configuration inside a configuration value. They are always associated with a :attr:`~Option.key` (or the name of the configuration parameter) and a :attr:`~Option.value`. Options can also have multi-line values that are usually interpreted as a list of values. When editing config...
from __future__ import annotations import os import re import sys import warnings from typing import Any, cast from urllib.parse import urlparse import cv2 # type: ignore[import] import numpy as np import numpy.typing as npt import requests from .gap import HEIGHT_GAP, WIDTH_GAP HEADERS = { "User-Agent": ( ...
import tempfile import time import os import subprocess from Bio.Blast import NCBIXML import numpy as np from .sequence_operations import sequence_to_atgc def blast_sequence( sequence, blast_db=None, subject=None, word_size=4, perc_identity=80, num_alignments=1000, num_threads=3, use_m...
import interpriters import json import logging import subprocess from pprint import pprint import config as cfg import smartctl_util as smutil import modules.zabbix_parsed as zbx_parsed import modules.zabbix_smart as zbx_smart logger = logging.getLogger(__name__) # smartctl --scan を実行して結果を返す # def exec_smartctl_sc...
""" Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agr...
''' Created on 16/06/2015 @author: jramsay This module is a hack wrapping LXML because Py2.6 doesn't support namespaces declarations. This isn't necessary in a 2.7+ env ''' import re import sys import http from lxml import etree from six.moves.urllib.error import HTTPError from six.moves.urllib.request import urlo...
import getpass import random import readline import socket import string import sys from datetime import datetime from signal import SIG_DFL, SIGPIPE, signal from typing import Any, Dict, Union from ..api import Novem401, NovemAPI from ..utils import cl, colors, get_current_config from ..version import __version__ fro...
""" MIT License This example is based on https://github.com/eriklindernoren/Keras-GAN Copyright (c) 2017 <NAME> Copyright (c) 2019 <NAME> 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 r...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # File name : get_wordpress_paths.py # Author : Podalirius (@podalirius_) # Date created : 21 Nov 2021 import json import os import sys import requests import argparse from bs4 import BeautifulSoup def parseArgs(): parser = argparse.Argum...
import itertools import math import tensorflow as tf import numpy as np from collections import namedtuple def generate_default_boxes(config): """ Generate default boxes for all feature maps Args: config: information of feature maps scales: boxes' size relative to image's size f...
## FontUtil ## ## Utilities for dealing with FontSymbols, "XXX_CHAR" keys, and "[ICON_XXX]" tags in XML messages. ## "init.xml" adds most of the built-in and BUG-related symbol keys by using this module's functions. ## You can add your own using the <symbol> XML entity. ## ## Getting Symbols ## ## getSymbol(s...
# Copyright 2020 Forschungszentrum Jülich # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
##Kac Ring Model import random import math import time import tkinter as tk from tkinter import ttk # a subclass of Canvas for dealing with resizing of windows class ResizingCanvas(tk.Canvas): def __init__(self,parent,**kwargs): tk.Canvas.__init__(self,parent,**kwargs) self.bind("<Co...
# FIXME: # 若您为项目开发者 请不要在生产环境中启用进度条功能 <- 未知bug __all__ = ['vsu', 'lsu', 'PuppetCore'] import gevent from gevent.queue import Queue from BusinessCentralLayer.middleware.work_io import Middleware from config import logger class CoroutineEngine(object): """协程加速控件""" def __init__(self, core, power: int = None...
from argparse import ArgumentParser from collections import OrderedDict import inspect from io import StringIO import os import subprocess import tokenize from typing import Any, Dict, Generator, List, Union NO_CHANGES_STATUS = """nothing to commit, working tree clean""" def check_output(command: List[str]) -> str:...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch from torch.nn import functional as F from fcos_core.layers import smooth_l1_loss from fcos_core.modeling.box_coder import BoxCoder from fcos_core.modeling.matcher import Matcher from fcos_core.structures.boxlist_ops import boxl...
from torch import nn from backbone_block.shufflleV2 import ShuffleV2Block from utils_frequent.activation import act_layers def channel_shuffle(x, groups): # type: (torch.Tensor, int) -> torch.Tensor batchsize, num_channels, height, width = x.data.size() channels_per_group = num_channels // groups # re...
#!/usr/bin/env python3 # # This file is part of the MicroPython project, http://micropython.org/ # # The MIT License (MIT) # # Copyright (c) 2020 <NAME> # # 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 t...
""" Attribution: 1. Player rotation was adapted from this video tutorial by Web Dev Junkie: https: // www.youtube.com/watch?v = _WJSH7NxtRc. Made adjustments to it so that the player's gun pointed to the mouse. 2. Code to move a canvas element from its current position to a target position was borrowed from a...
""" sentry.management.commands.serve_normalize ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2018 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import, print_function import SocketServer import base64 import os impor...
#!/user/bin/env python '''swissModelDataset This module provides access to SWISS-MODEL datasets containing homology models. References ---------- - SWISS-MODEL API: https://swissmodel.expasy.org/docs/repository_help#smr_api - <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME> (2017). The SWISS-MODEL Repository ...
"""Example AWS Lambda function module for scheduling an exported Data Wrangler flow. """ import json import time import uuid import boto3 import sagemaker from sagemaker.dataset_definition.inputs import AthenaDatasetDefinition, DatasetDefinition from sagemaker.network import NetworkConfig from sagemaker.processing imp...
import argparse import json import os import time import numpy as np import torch from torch.autograd import Variable from torch.utils.data import DataLoader from AdaptiveConcreteGRU import AdaptiveGRU from OpportunityDataset import OpportunityDataset import multiprocessing multiprocessing.set_start_method("spawn",...
# Copyright 2013 Devsim LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
""" Script reads LENS data for SIT for the control run. Notes ----- Author : <NAME> Date : 20 October 2016 Usage ----- readLENS(directory,threshold) lats,lons,sit = readLENS(directory,threshold,version) meanThick(yearmin,yearmax,years,sit) """ def readLENS(directory,threshold): """ ...
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
import urllib.parse from argparse import ArgumentParser import torch from pytorch_lightning import LightningModule, Trainer from torch import nn from torch.nn import functional as F from pl_bolts import _HTTPS_AWS_HUB from pl_bolts.models.autoencoders.components import ( resnet18_decoder, resnet18_encoder, ...
# Copyright 2019 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
import copy def _default_cls_attr(name, type_, cls_value): # Proxy uses properties to forward the standard # class attributes __module__, __name__ and __doc__ to the real # object, but these needs to be a string when accessed from # the Proxy class directly. This is a hack to make that work. # --...
from django.db import models from django.contrib.auth.models import AbstractUser from django.utils import timezone import random class Info(models.Model): online_users = models.IntegerField(default=0) class Game(models.Model): code = models.IntegerField() timestamp = models.DateTimeField(auto_now_add=Tr...
# The MIT License (MIT) # # Copyright (c) 2007-2018 <NAME>, <NAME>, and contributors. # # 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...
# -*- coding: utf-8 -*- # File: logger.py """ The logger module itself has the common logging functions of Python's :class:`logging.Logger`. For example: .. code-block:: python from tensorpack.utils import logger logger.set_logger_dir('train_log/test') logger.info("Test") logger.error("Error happened...
''' Regular ResNet codes are based on @article{ zhang2018mixup, title={mixup: Beyond Empirical Risk Minimization}, author={<NAME>, <NAME>, <NAME>, <NAME>}, journal={International Conference on Learning Representations}, year={2018}, url={https://openreview.net/forum?id=r1Ddp1-Rb}, } ''' import torch import torch.nn ...
"""Convert the HA config to the dynalite config.""" from typing import Any, Dict from dynalite_devices_lib import const as dyn_const from homeassistant.const import ( CONF_DEFAULT, CONF_HOST, CONF_NAME, CONF_PORT, CONF_ROOM, CONF_TYPE, ) from .const import ( ACTIVE_INIT, ACTIVE_OFF, ...
import torch.nn as nn import torch from torch.autograd import Variable import torch.nn.functional as F class Conv(nn.Sequential): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, groups=1): super(Conv, self).__init__() self.add_module('norm', nn.Batch...
from __future__ import print_function, division from sympy.core import S, Symbol, Add, sympify, Expr, PoleError, Mul from sympy.core.compatibility import string_types from sympy.core.symbol import Dummy from sympy.functions.combinatorial.factorials import factorial from sympy.core.numbers import GoldenRatio from sympy...
"""Bluetooth LE Humidity/Temperature data classes.""" from typing import List, Optional, Union import statistics as sts import logging from .const import ( DEFAULT_TEMP_RANGE_MIN, DEFAULT_TEMP_RANGE_MAX, CONF_HMIN, CONF_HMAX, ) _LOGGER = logging.getLogger(__name__) class BLE_HT_packet: """Blueto...
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.c (the "License"); # you may not use this file except in compliance with the License. # """ Userbot module for executing code and terminal commands from Telegram. """ import asyncio import io import re impo...
"""Test HomeKit util module.""" import pytest import voluptuous as vol from homeassistant.components.homekit.const import ( CONF_FEATURE, CONF_FEATURE_LIST, HOMEKIT_NOTIFY_ID, FEATURE_ON_OFF, FEATURE_PLAY_PAUSE, TYPE_OUTLET) from homeassistant.components.homekit.util import ( convert_to_float, density_to_a...
import run from music import BeatTimestamp, FileOffsetRecording simple_json_body = {'startTime': '201:21:51:00:000', 'endTime': '201:21:51:06:000', 'recordingEntries': [ {'dateTime': '201:21:51:01:000', 'fileName': 'prototype_loop1', 'loopable': True}, ...
""" Copyright (c) 2019 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing,...
"""Convert straight quotation marks to typographic ones """ from __future__ import annotations import re from typing import Any from .state_core import StateCore from ..common.utils import charCodeAt from ..common.utils import isWhiteSpace, isPunctChar, isMdAsciiPunct from ..token import Token QUOTE_TEST_RE = re.co...
#!/usr/bin/env python3 import sys import struct import socket import time import hashlib import argparse #from Crypto.Cipher import AES import rsa_sign # How many firmware data bytes are included in each packet. # Set a conservative default. There were issues reported that # UDP packet larger than 548 bytes don't ge...
import dash import dash_core_components as dcc import dash_html_components as html import dash_bootstrap_components as dbc from dash.dependencies import Input, Output, State import pandas as pd import json from functools import lru_cache import app.config.env as env from app.data.DataManager import DataManager from app...
# Copyright 2018 <NAME> # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software...
# Copyright 2017-2020 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, soft...
import os import sys import json import pytest from symbolic import ( ObjectLookup, Archive, SourceMapView, SourceView, find_best_instruction, parse_addr, ) diff_report = None def get_symcache(path, object_lookup): dsym_path = os.path.join(path, "Contents/Resources/DWARF") if not os....
""" Models for the Permission submodule """ from typing import List from django.db import models from base.models.character import Character from permissions.utils import AbstractPermissionSystem class PermissionManager(models.Model): """ Manages the permissions. All permissions are bound to specific manage...
#!/usr/bin/env python import csv import datetime import itertools import agate import six from csvkit import typeinference from csvkit.cli import parse_column_identifiers, make_default_headers POSSIBLE_DELIMITERS = [',', '\t', ';', ' ', ':', '|'] def sniff_dialect(sample): """ A functional version of ``cs...
# Copyright (c) 2015-2018, 2020 <NAME> <<EMAIL>> # Copyright (c) 2015 <NAME> <<EMAIL>> # Copyright (c) 2016 <NAME> <<EMAIL>> # Copyright (c) 2018 ssolanki <<EMAIL>> # Copyright (c) 2019, 2021 <NAME> <<EMAIL>> # Copyright (c) 2019 <NAME> <<EMAIL>> # Copyright (c) 2020 hippo91 <<EMAIL>> # Copyright (c) 2020 <NAME> <<EMAI...
import pytest from src.clients.IClient import ClientError from src.ApplicationExceptions import ErrorDispatch from src.clients.TcpClientR3 import validate_ip, validate_port, TcpClientR3 from src.clients.TcpEchoServer import ConfigurableEchoServer VALID_HOST, VALID_PORT = 'localhost', 10002 INVALID_HOST, INVALID_PORT ...
# -*- coding: utf-8 -*- """ Created on Fri Mar 27 14:38:31 2020 radar grid map for zhihu @author: wenzt """ import numpy as np import math import matplotlib.pyplot as plt #parameters ##environment worldsize = [50, 50]#rectangle gridsize = 0.08 #resolution of grid map #sensor MAX_dect_range = 20 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- #============================================================================== # # vu_meter.py - Listen to microphone left/right and generate vu level # #============================================================================== """ FROM: https://github.com/kme...
#!/usr/bin/env python # -*- coding: utf-8 -*- """quantulum regex functions.""" # Standard library import re # Quantulum from . import load as l UNITS = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'si...
# Copyright 2013 Nebula 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...
from sqlalchemy.test.testing import assert_raises, assert_raises_message from sqlalchemy.orm import interfaces, util from sqlalchemy import Column from sqlalchemy import Integer from sqlalchemy import MetaData from sqlalchemy import Table from sqlalchemy.orm import aliased from sqlalchemy.orm import mapper, create_sess...
import json import binascii import base64 import websocket import requests import syft as sy from syft.serde import protobuf from syft.execution.state import State from syft_proto.execution.v1.plan_pb2 import Plan as PlanPB from syft_proto.execution.v1.state_pb2 import State as StatePB from syft_proto.execution.v1.p...
import torch from cudaHelperFunctions import * import torch.nn as nn from torch import autograd from torch import optim import torch.nn.functional as F torch.set_default_tensor_type('torch.cuda.FloatTensor') def TrainAcc(start = 0, l = 1000): print("The training accuracy is:", ) print(checkAcc(model,data,labels, st...
# coding=utf-8 # Copyright 2018 The TF-Agents 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...
# this builtin is needed so we can overwrite in test import asyncio import json import logging import os import aiohttp import questionary from aiohttp import ClientTimeout from prompt_toolkit.styles import Style from typing import Any, Generator from typing import Text, Optional, Dict, List import rasa.shared.utils....
# pylint: disable=missing-function-docstring import threading import time import typing from unittest import mock from psycopg2.pool import ThreadedConnectionPool from common.db.bounded_threaded_connection_pool import BoundedThreadedConnectionPool class ThreadedConnectionPoolForTest(ThreadedConnectionPool): ""...
import numpy as np eps = 1.0e-8 def total_prioritization(coverage, unit_prob): total_weighted_coverage = np.matmul(coverage, unit_prob) return np.flip(np.argsort(total_weighted_coverage)) def add_all_remaining_tests(tcp_ordering, test_num, test_used): for test_ind in range(0, test_num): ...
#!/usr/bin/env python3 # SPDX-License-Identifier: BSD-3-Clause """ Check that there is a playbook to run all role tests with both providers """ # vim: fileencoding=utf8 import glob import os import sys GET_NM_VERSION = """ - block: - name: Install NetworkManager package: name: Netwo...
# Copyright 2018 University of Groningen # # 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 i...
# -*- coding: utf-8 -*- '''This script contains the functions for FITS file and raw image manipulations''' import numpy as np from glob import glob import astropy.io.fits as pyfits import re, os # from matplotlib import pyplot as plt # from matplotlib.ticker import MultipleLocator import pickle as pickle from medis.D...
# -*- coding: utf-8 -*- # python-holidays # --------------- # A fast, efficient Python library for generating country, province and state # specific sets of holidays on the fly. It aims to make determining whether a # specific date is a holiday as fast and flexible as possible. # # Authors: dr-prodigy <<EMAIL>> ...
#!/usr/bin/env python3 """Test the program psa_constant_names. Gather constant names from header files and test cases. Compile a C program to print out their numerical values, feed these numerical values to psa_constant_names, and check that the output is the original name. Return 0 if all test cases pass, 1 if the out...
import cv2 import numpy as np import matplotlib.pyplot as plt from art.estimators.object_detection import PyTorchFasterRCNN from art.attacks.evasion import FastGradientMethod COCO_INSTANCE_CATEGORY_NAMES = [ "__background__", "person", "bicycle", "car", "motorcycle", "airplane", "bus", ...
#!/usr/bin/env python3 """ Copyright (c) 2019, <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions a...
import pytest import time from rancher import ApiError from .common import wait_for_template_to_be_created, \ wait_for_template_to_be_deleted, random_str from .conftest import set_server_version def test_catalog(admin_mc): client = admin_mc.client name1 = random_str() name2 = random_str() url = "h...
#!/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 __future__ import annotations import abc import importlib import pkgutil from typing import Optional, Iterable, T...
from __future__ import absolute_import import six from string import Formatter class dontexplodedict(object): """ A dictionary that won't throw a KeyError and will return back a sensible default value to be used in string formatting. """ def __init__(self, d=None): self.data = d or {...
import numpy as np from knngraph import * from loadData import * from measure import * def getAffinityMaxtrix(Vc, W): nc = len(Vc) print(nc) affinity = np.zeros([nc, nc]) for i in range(nc): for j in range(i + 1, nc): ij = np.ix_(Vc[i], Vc[j]) ji = np.ix_(Vc[j], Vc[i...