text
stringlengths
3.07k
12.6k
import json import dateutil.parser import datetime import os.path import time import shared import fetch_data fetch_data.handle_fetch() def dates_to_days(XDates): XDays = [] for date in XDates: XDays.append((date - min(XDates)).days) XDays.sort() return XDays with open(shar...
""" This file gather some graphical utilities that could be used inside other apps of the projet PLaTon. <NAME>(poor graphical programmer) : original version 10. jan 2021. Feel free to modify, throw away or use better technology. TESTS: >>> all([graph_percent(i) for i in range(101)]) True """ def color_percent(p):...
import asyncio import time from inspect import isgenerator from molotov.listeners import EventSender from molotov.session import get_session, get_context from molotov.api import get_fixture, pick_scenario, get_scenario, next_scenario from molotov.util import cancellable_sleep, is_stopped, set_timer, get_timer, stop ...
import logging import copy import tempfile import numpy as np import galsim from pizza_cutter_sims.mdet import run_metadetect, make_mbobs_from_coadd_data from pizza_cutter_sims.pizza_cutter import run_des_pizza_cutter_coadding_on_sim from pizza_cutter_sims.sim import generate_sim from pizza_cutter_sims.stars import ma...
# Copyright 2016 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 # # Unless required by appl...
# --------------------------------------------------- # Parse Tree node classes # stdlib import re from typing import Dict, List class SemanticActionResults(list): """ Used in visitor methods call to supply results of semantic analysis of children parse tree nodes. Enables dot access by the name of t...
import click import yaml from pathlib import Path def add_type(node, prop): if "domains" not in node: return if "DoubleValue" in node["domains"]: prop["type"] = "float32" return if "IntValue" in node["domains"]: prop["type"] = "int8" return prop["type"] = "strin...
import numpy as np from keras import backend as K import cv2 import os import shutil from keras.applications.vgg16 import VGG16, preprocess_input from keras.preprocessing.image import img_to_array from keras.optimizers import SGD def hard_sigmoid(x): i = 0 y = np.zeros((1, len(x[0,:]))) for x_i in x[0,:]: ...
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from natsort import natsorted from typing import Tuple, List from pegasusio import UnimodalData def plot_hto_hist(hashing_data: UnimodalData, attr: str, out_file: str, alpha: float = 0.5, dpi: int = 500, figsize: Tuple[floa...
import numpy as np import pandas as pd import re, os """ This module converts chemical formula information into numerical values. """ class ChemFormula: def __init__(self, path=None, index="Element"): """ Args: path(str) : Path of the csv file containing the name of the target element ...
# -------------------------------------------------------------------------- # Source file provided under Apache License, Version 2.0, January 2004, # http://www.apache.org/licenses/ # (c) Copyright IBM Corp. 2015, 2016 # -------------------------------------------------------------------------- """ Problem Descriptio...
import numpy as np from pyquaternion import Quaternion H = 360 W = 720 topic_info_dict = {'paris': ['paris.mp4', 244.06047, 3840, 2048], \ 'timelapse': ['newyork.webm', 91.03333, 3840, 2048], \ '3': ['conan2.mp4', 172.5724, 2560, 1440], \ '1': ['skiing.mp4', 201...
## ------------------------------------------------------------------------------------------------------------------ ## ## ------------------------------------------------------------------------------------------------------------------ ## ## ___ ___ ________ ________ ______ _...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: avpreetsingh """ import numpy as N import pylab as p import matplotlib as plt from pymodelica import compile_fmu from pyfmi import load_fmu import fftUtils class ModelicaModel: # retrieve parameters """ Modelica HPF class for accessing model pa...
import re from string import punctuation from string import digits import pandas as pd import numpy as np import os, sys import bias_rv curPath = os.path.abspath(os.path.dirname(__file__)) rootPath = curPath[:curPath.find("workspace/")+len("workspace/")] import neuralcoref import en_core_web_sm nlp = en_core_web_sm.lo...
import argparse import gzip import json import os import sys import time from pathlib import Path from requests.exceptions import Timeout from requests_oauthlib import OAuth1Session from backend.stream.common.file_util import get_dir_paths, get_file_paths CONSUMER_KEY = os.environ.get('TWITTER_CONSUMER_KEY', None) C...
import json import os import sys import traceback import warnings from contextlib import contextmanager from datetime import datetime from typing import Optional, Tuple, Union, List import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from sklearn.model_selection import BaseCros...
import logging from thespian.actors import * from thespian.test import * class ThereCanBeOnlyOne(Actor): def receiveMessage(self, msg, sender): if not isinstance(msg, ActorSystemMessage): self.send(sender, "ONE: %s"%msg) class GlobalNameReporter(Actor): def receiveMessage(self, msg, sende...
"""Collection of pre-defined Metric classes.""" from abc import ABCMeta, abstractmethod import numpy as np from multiml import logger class Metric(metaclass=ABCMeta): """Abstraction class of metric calculation.""" @abstractmethod def calculate(self): """Return calculated metric.""" class Base...
""" MySQL concurrent command sequences visualizer. This tool visually graphs connections and their sequence of commands. This in intended to help you inspect and debug interacting connections' behaviors. I recommend adding `session.execute(text("/* MY DEBUG MESSAGE */ SELECT 1;"))` lines to annotate complex transacti...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Importing couple of packages here import numpy as np import sys, os, glob import matplotlib.pyplot as plt import h5py from skimage.transform import iradon from scipy.ndimage import shift from scipy.ndimage import label from scipy.ndimage.measurements import center_of_m...
# Copyright (c) OpenMMLab. All rights reserved. import mmcv import numpy as np from ..builder import PIPELINES @PIPELINES.register_module() class LoadImageFromFile: """Loading image(s) from file. Required key: "image_file". Added key: "img". Args: to_float32 (bool): Whether to convert the ...
import json import yaml import os import math import requests from datetime import datetime # from config import ise_node, file_path, page_limit from progress.bar import Bar import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) # Making sure Yaml understand how to represent a defaultdict f...
import numpy as np import numpy.ma as ma import pytest import numpy.testing as testing from datetime import datetime, timedelta from model_evaluation.products.model_products import ModelManager MODEL = 'ecmwf' OUTPUT_FILE = '/' PRODUCT = 'iwc' def test_model_file_list(): from model_evaluation.products.tools impo...
#!/usr/bin/env python # coding=utf-8 import json import logging import requests from requests.compat import urljoin from .utils.version import get_version requests.packages.urllib3.disable_warnings() class Config(object): DEFAULT_API_URL = 'https://api.mailjet.com/' API_REF = 'http://dev.mailjet.com/email-...
''' MIT License Copyright (c) 2017 <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 restriction, including without limitation the rights to use, copy, modify, merge, publish, distri...
import threading from enum import Enum import RPi.GPIO as GPIO import pigpio as pigpio START_PIN_INDEX = 2 END_PIN_INDEX = 27 class PinType(Enum): """ Enum class to describe the type of each pin used by a hardware component. """ EN = 1, IN = 2, PWM = 3 class InPinState(Enum): """ P...
#!/usr/bin/env python3 #-*-coding:utf-8-*- import random import time try: import thread except ImportError: import _thread as thread import board import neopixel from gpiozero import Button import json import requests import websocket pixels = neopixel.NeoPixel(board.D18, 60+13, auto_write=False) #0-60:tape, 6...
# -*- coding: utf-8 -*- """ Created on Wed Feb 19 12:39:49 2014 Author: <NAME> """ import numpy as np from scipy import stats from statsmodels.sandbox.distributions.extras import (SkewNorm_gen, skewnorm, ACSkewT_gen, NormExpan_gen, pdf_moments, ...
# -*- coding: utf-8 -*- from django.conf import settings from django.template import Library, TemplateDoesNotExist, loader from django.template.base import Node from core.models import Section, Publication, Category, get_current_edition register = Library() last_old_day = getattr(settings, 'LAST_OLD_DAY') @regist...
from nertoolkit.geneontology.GeneOntology import GeneOntology from utils.parallel import MapReduce import glob import sys import os sys.path.insert(0, str(os.path.dirname(os.path.realpath(__file__))) + "/../") from collections import Counter, defaultdict import nltk from porestat.utils.DataFrame import DataFrame ...
import numpy as np import math import sys ''' Retorna la entropia de un conjunto de datos para un determinado atributo objetivo. ''' def entropy(attributes, data, targetAttr): i = attributes.index(targetAttr) targetValues = data[:,i] #Frecuencia de cada valor del atributo objetivo dentro del conjunto...
import requests import localdata import logging import enum import string import collections import pickle import numpy as np TC_HEADER = {'Content-type': 'application/json', 'Accept': 'application/json'} TC_AUTH = (localdata.USER, localdata.PW) TC_ENDPOINT_API = '/app/rest/latest' TC_ENDPOINT = localdata.TC FNAME_DB...
import cv2 import numpy as np import time import pandas as pd import math xa=0 ca=0 xb=0 ya=550 yb=750 ua=170 uacon=170 ub = 1180 ubcon = 1180 solort = 363 sagort = 968 thres = 0.45 def region_of_interest(img, vertices): mask = np.zeros_like(img) #channel_count = img.shape[2] m...
# python3 # Copyright 2021 InstaDeep Ltd. 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 applic...
from django.shortcuts import render from rest_framework import generics, status, views, permissions from .serializers import RegisterSerializer, SetNewPasswordSerializer, ResetPasswordEmailRequestSerializer, EmailVerificationSerializer, LoginSerializer, LogoutSerializer from rest_framework.response import Response from...
# coding=utf-8 """ Al the sieves that are relatid with the same head coreference. """ __author__ = '<NAME> <<EMAIL>>' from ...multisieve.sieves.base import Sieve from ...resources.dictionaries import stopwords from ...resources.tagset import pos_tags class StrictHeadMatching(Sieve): """ A relative pronoun is ...
# <pep8-80 compliant> # ##### BEGIN GPL LICENSE BLOCK ##### # # 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, or (at your option) any later version. # # ...
import tensorflow as tf import numpy as np from . import pixel_dcn """ This module provides some short functions to reduce code volume """ def pixel_dcl(inputs, out_num, kernel_size, scope, data_type='2D', action='add'): if data_type == '2D': outs = pixel_dcn.pixel_dcl(inputs, out_num, kernel_size, scop...
from pathlib import Path import argparse from random import random import celery from lxml.etree import XPath from .tasks import examples_from_file_task, save_task from .utils import progress from .config import config class ExtractorXML: """Extract multiple text examples from xml documents based on an XPath sele...
#!/usr/bin/env python3 # # Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates # # 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 # ...
# Copyright 2018 <NAME> 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 agreed...
from __future__ import print_function, absolute_import, division import numpy as np np.random.seed(1) from tensorflow import set_random_seed set_random_seed(1) from datetime import datetime import argparse import os from keras.utils import to_categorical, plot_model from keras.layers import Flatten, Dense from keras.mo...
import tensorflow as tf import numpy as np import utils import vgg19 import style_transfer_trainer import os import argparse """parsing and configuration""" def parse_args(): desc = "Tensorflow implementation of 'Image Style Transfer Using Convolutional Neural Networks" parser = argparse.ArgumentParser(descri...
# -*- coding: utf-8 -*- """ Custom widget for wxPython: file list control """ import wx import os import time import platform from math import log unit_list = zip(['bytes', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb'], [0, 0, 1, 2, 2, 2]) def convertSize(num): """ Converting file size in bytes to Kb/Mb /etc. ""...
"""Training with long time series. Supplementary code for: <NAME> and <NAME>. "Signal Processing with Recurrent Neural Networks in TensorFlow" """ import numpy as np import tensorflow as tf import matplotlib.pyplot as plt nest = tf.contrib.framework.nest def lstm_func(d, m, n, lr): # Placeholders ...
# Copyright (c) 2020 Huawei Technologies Co., Ltd. # Licensed under CC BY-NC-SA 4.0 (Attribution-NonCommercial-ShareAlike 4.0 International) (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://creativecommons.org/licenses/by-nc-sa...
import sys import os from configparser import ConfigParser from abc import ABC, abstractmethod import typing import asyncio import boto3 import openai import numpy import sounddevice from amazon_transcribe.client import TranscribeStreamingClient from amazon_transcribe.handlers import TranscriptResultStreamHandler from ...
import tensorflow as tf import random AUTO = tf.data.experimental.AUTOTUNE # Reference: https://github.com/google-research/simclr/blob/master/data_util.py @tf.function def gaussian_blur(image, kernel_size=23, padding='SAME'): sigma = tf.random.uniform((1,))* 1.9 + 0.1 radius = tf.cast(kernel_size / 2, tf.int32) ...
import time from pddlstream.language.conversion import substitute_expression, list_from_conjunction, str_from_head from pddlstream.language.constants import Not, Equal, get_prefix, get_args, is_head from pddlstream.language.external import ExternalInfo, Result, Instance, External, DEBUG, get_procedure_fn from pddlstre...
#!/usr/bin/env python2 # encoding: utf-8 ''' fig4.py Written by: <NAME>, Computational Science Lab, University of Amsterdam <EMAIL> Last updated on 25 September 2015 Description: Figure 4 in Ref.[1] References: [1] <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, Non-parametric estimation of Fish...
from typing import Dict, Text, Any, NoReturn import jmespath import requests from loguru import logger from httprunner.exceptions import ValidationFailure, ParamsError from httprunner.parser import parse_data, parse_string_value, get_mapping_function from httprunner.schema import VariablesMapping, Validators, Functio...
""" newton.py - Implement fractals using newton-raphson approximation method of solving functions. """ import matplotlib.pyplot as plt import numpy as np import math import functools import multiprocessing as mp def rgb2int(rgb): red = rgb[0] green = rgb[1] blue = rgb[2] RGBint = (red << 16) + (green...
#!/usr/bin/env python # -*- coding:utf-8 -*- # # make_raw_data.py # # Copyright (c) 2018 <NAME> <<EMAIL>> # from collections import Counter from dotenv import find_dotenv, load_dotenv from pathlib2 import Path from subprocess import check_output import click import logging import nflgame import warnings with warnings....
from __future__ import absolute_import import torch import torch.nn.functional as F from torch import nn, autograd from ..utils.distributed import tensor_gather class OIM2CQ(autograd.Function): @staticmethod def forward(ctx, inputs, targets, lut, cq, cqb, cq_omega, cqb_omega, ...
import math import random import gym import highway_env import numpy as np import torch import torch.nn as nn import torch.optim as optim import torch.autograd as autograd import torch.nn.functional as F from IPython.display import clear_output import matplotlib.pyplot as plt from collections import deque class Repla...
import numpy as np import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func import datetime as dt from flask import Flask, jsonify # Database Setup engine = create_engine("sqlite:///resources/hawaii.sqlite") # reflect an existing ...
from __future__ import unicode_literals # from django.utils.encoding import python_2_unicode_compatible from django.conf import settings from django.utils.translation import gettext_lazy as _ from django.db import models from django.utils.html import format_html from django.contrib import admin from django.contrib.con...
import os import re from functools import reduce import urllib.request import tarfile # helper function to download data from web and # extract it to ./data; # if use_complete_group is True, then 20_newsgroups is downloaded; # else, mini_newsgroups is downloaded. def FetchData(use_complete_group = True): data_di...
#!/usr/bin/env python3 import sys import argparse import time from sh import barman as barman_cli from datetime import datetime import prometheus_client from prometheus_client import core class Barman: def servers(self): return barman_cli('list-server', '--minimal').split() def server_status(self, s...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import numpy as np import torch import torchaudio import augment import argparse from dataclasses import dataclass class RandomPitchShift: ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals # import tensorflow as tf import numpy as np import os import pickle # from misc.utils import get_image import scipy.misc import pandas as pd def imread(path): img =...
import pytest import copy import numpy as np import numpy.testing as npt from sklearn.datasets import make_classification from sklearn.cross_validation import train_test_split from ..rotation_forest import random_feature_subsets from ..rotation_forest import RotationTreeClassifier, RotationForestClassifier def class...
''' This module implements the Locality Sensitive Hashing index with MinHash (MinHash LSH) and Weighted MinHash (Weighted MinHash LSH) Both indexes supports query with Jaccard similarity threshold. Reference: Chapter 3, Mining of Massive Datasets (http://www.mmds.org/) ''' _integration_precision = 0.001 def _integ...
from __future__ import print_function import numpy as np try: import QENSmodels except ImportError: print('Module QENSmodels not found') def hwhmGaussianModel3D(q, D=1., variance_ux=1.): """ Returns some characteristics of `GaussianModel3D` as functions of the momentum transfer `q`: the half-widt...
#!/usr/bin/env python3 import atexit import glob import logging import os import random import subprocess import sys import tempfile import time logger = logging.getLogger(__name__) defaultTimeout = 30 # seconds def ensureTestData(e2edata): blocktars = glob.glob(os.path.join(e2edata, 'blocktars', '*.tar.bz2')) ...
# ****************************************************************************** # 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...
"""Wrapper module for a database.""" from __future__ import print_function from datetime import datetime import json import peewee from beerlog import errors from beerlog import constants database_proxy = peewee.Proxy() # pylint: disable=no-init class BeerModel(peewee.Model): """Model for the database.""" cla...
import os if (os.getcwd().endswith('scripts')): os.chdir('..') from classes.tosec_dat import * from classes.game import * from classes.scraper import * def createDATFromCSV(): with open('tosec\\unsorted files\\ROMs\\roms.csv') as f: lines = f.readlines() dat = TOSECDat('Sinclair ZX Spectrum - Firmw...
# pylint: disable-msg=W0621 # pylint: disable-msg=W0613 import os import warnings import pytest import sqlalchemy from sqlalchemy import ( Column, String, ForeignKey, Integer, func, DateTime, bindparam) from sqlalchemy.orm import relationship, column_property from painless_sqlalchemy import Painless from painless_s...
from typing import Type, Union import sqlalchemy as sa from airflow import DAG from airflow.operators.python_operator import PythonOperator from dataflow import config from dataflow.dags import _PipelineDAG from dataflow.dags.activity_stream_pipelines import ( GreatGOVUKExportOpportunityEnquiriesPipeline, ) from ...
#!/usr/bin/env python """ Generate a PDF of all small molecules in the JSON dataset. """ import gzip import json import cmiles from openeye import oechem from openforcefield.typing.engines.smirnoff import ForceField forcefield = ForceField('param_valence.offxml', allow_cosmetic_attributes=True) ff_torsion_param_list...
import multiprocessing as mp from unittest.mock import patch import matplotlib.pyplot as plt import numpy as np import btk.plot_utils from btk.survey import get_surveys TEST_SEED = 0 def get_draw_generator( batch_size=8, cpus=1, add_noise="all", fixed_parameters=False, sampling_function=None, )...
import setup_path import airsim import numpy as np import pprint import cv2 import math import random from scipy.optimize import curve_fit import matplotlib.pyplot as plt #RESULTS: 8.89922094 0.0304452 13.7360959 0.02951979 0.10829337 def func(X, a1, b1, a2, b2, c): x,y = X return a1 * np.exp(-b1 * x...
import configparser from datetime import datetime import os from pyspark.sql import SparkSession from pyspark.sql.functions import udf, col from pyspark.sql import functions as F config = configparser.ConfigParser() config.read('dl.cfg', encoding='utf-8-sig') os.environ['AWS_ACCESS_KEY_ID']=config['AWS'][...
"""Utilities related to handling / interacting with wheel files.""" import contextlib import hashlib import io import os import re import sys from collections import namedtuple from configparser import ConfigParser from email.message import Message from email.parser import FeedParser from typing import ( TYPE_CHEC...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Oct 25 08:48:00 2019 Recreated from <NAME> @author: nikkicreange """ #!/usr/bin/python # See http://maggotroot.blogspot.ch/2013/11/constrained-linear-least-squares-in.html for more info ''' A simple library to solve constrained linear least square...
from abc import ABC, abstractmethod import sys class NmeaSentence(ABC): """ Interface for interpretting all transmitted NMEA 0183 Sentences Refer to 300 WX User Technical Manual_0183 for descriptions of fields """ @abstractmethod def update_data(nmea_map, fields): """ Adds/updates thi...
from typing import Optional, Tuple, Type from fastapi import APIRouter, Depends from pydantic.main import BaseModel from starlette import status from tortoise import Model from tortoise.query_utils import Q from fast_tmp.depends.auth import get_user_has_perms from fast_tmp.utils.crud_tools import add_filter from fast...
#----------------------------------------------------------------------------# # Imports #----------------------------------------------------------------------------# from flask import Flask, render_template, request, redirect # from flask_sqlalchemy import SQLAlchemy import logging from logging import Formatter, Fil...
#!/usr/bin/env python # -*- coding: utf-8 -*- """A module to load the German Traffic Sign Recognition Benchmark (GTSRB) The dataset contains more than 50,000 images of traffic signs belonging to more than 40 classes. The dataset can be freely obtained from: http://benchmark.ini.rub.de/?section=gtsrb&subse...
#!/usr/bin/env python3 import argparse import fnmatch import re import os import subprocess import sys DFHACK_ROOT = os.path.normpath(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) def load_pattern_files(paths): patterns = [] for p in paths: with open(p) as f: for line in f.r...
__all__ = ['standardize_agent_name', 'standardize_db_refs', 'get_standard_name', 'standardize_name_db_refs'] import logging from copy import deepcopy from collections import defaultdict from indra.statements.agent import default_ns_order, get_grounding logger = logging.getLogger(__name__) default_ns_prio...
""" Tests """ import numpy as np import pytest parametrize = pytest.mark.parametrize def test_ceil(): from dmt.binning import ceil filtration = np.array([5, 3, 7, 2, 43, 7, 3, 1, 5, -2]) bins = np.array([0, 2, 5, 10]) assert np.all(ceil(filtration, bins) == [5., 5., 10., 2., np.inf, 10., 5., 2., 5.,...
"""celery.backends.amqp""" import socket import time from datetime import timedelta from carrot.messaging import Consumer, Publisher from celery import conf from celery import states from celery.backends.base import BaseDictBackend from celery.exceptions import TimeoutError from celery.messaging import establish_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 __...
import random import torch from torch.nn.utils import rnn from torch.utils.data import Dataset class Dictionary: def __init__(self): self.word2idx = {} self.idx2word = [] def add_word(self, word): if word not in self.word2idx: self.idx2word.append(word) self.wo...
import logging try: import keras as keras_keras except ImportError: keras_keras = None try: from tensorflow import keras as tf_keras except ImportError: tf_keras = None from dlhub_sdk.models.servables.python import BasePythonServableModel from dlhub_sdk.models.servables import ArgumentTypeMetadata fro...
import numpy as np from objs import * from sim_utils import * num_cluster = 20 forward_rate, backward_rate = 0.8, 1 # 1, 1 # 0.6, 1 # state_state_rate_m = { # 1 : {1 : backward_rate, 2 : forward_rate}, # 2 : {1 : backward_rate, 3 : forward_rate}, # 3 : {2 : backward_rate, 3 : forward_rate} # } # state_state_rate_m...
""" Generates a Swagger definition for registered endpoints. Note that: - Swagger operations and type names use different conventions from the internal definitions because we want to make usage friendly for code generation (e.g. bravado) - Marshmallow to JSON Schema conversion is somewhat simplistic. There ar...
from django.core.management.base import BaseCommand from django.conf import settings from django.utils.timezone import now from cpes.models import Item from cpes.management.commands.utils import get_remote_dict, fast_iter from cves.models import ( VulnerabilityDictionary as Dictionary, Vulnerability, Alert ...
from typing import Coroutine, Generic, List, Optional, TypeVar, Union from . import Parser from ..context import Context, Result T = TypeVar('T', covariant=True) U = TypeVar('U', covariant=True) class DelegateParser(Parser[T], Generic[T]): __slots__ = '_delegate', def __init__(self, delegate: Parser[T]): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import argparse import ConfigParser import logging from utf8_utils import UnicodeReader from api_utils import ModelAPI class ImportStmt( object ): """ Copies STMT file formats into Termite internal format. """ # Files generated by STMT TERM_INDEX = 't...
from pydub import AudioSegment import webrtcvad import numpy as np import speechpy import torch import torch.autograd as grad import torch.nn.functional as F from model.hparam import hp import os from model.frame import Frame def get_logmel_fb(segment, len_window=25, stride=10, filters=40): ''' Gives the ...
import random as rd import time import pandas as pd import pyautogui import pyperclip import PySimpleGUI as sg import requests from bs4 import BeautifulSoup suppliers_list = [] list_themes = sg.theme_list() sg.theme(rd.choice(list_themes)) layout = [ [sg.Text("Enter the product name and descript...
""" Script for policy-based sampling using uncertainty estimate. Uncertainty is measured by computing the variance in the predicted controls of 100 runs of model with test time dropout Requires: var_file: computed variance in the controls with test time dropout preload: npy preload file for the entire on-policy data...
#!/usr/bin/env python3 # SPDX-License-Identifier: Apache-2.0 # Copyright (c) 2022 Intel Corporation "Convenience script to display and modify some BIOS settings via Redfish API" import os import sys import logging import argparse import time import redfish_api # pylint: disable=import-error # create root logger fo...
#!/usr/bin/env python3 from datacube_ows.product_ranges import update_all_ranges, get_sqlconn, add_product_range, add_multiproduct_range, add_all, update_range from datacube import Datacube from psycopg2.sql import SQL, Identifier import os import click @click.command() @click.option("--schema", is_flag=True, default...
# LICENSED UNDER BSD-3-CLAUSE-CLEAR LICENSE # SEE PROVIDED LICENSE FILE IN ROOT DIRECTORY # Import Third Party Modules import logging import click from requests import request # Import Throne Modules from src.parsers import json_request from src.parsers import rdap_ip_parser as ip_parser from src.bgp import asn as get...
#!/usr/bin/env python """ Analyze the tree level structure of a tree. At the moment, BFS is computed using numpy.ndarray.argsort. However, it should be possible to compute it in linear time if you know the tree (as a linked list, e.g.). """ import argparse import sys import numpy as np import matplotlib.pyplot as plt ...