text
stringlengths
3.07k
12.6k
import numpy as np from typing import Tuple from IMLearn.metalearners.adaboost import AdaBoost from IMLearn.learners.classifiers import DecisionStump from utils import * import plotly.graph_objects as go from plotly.subplots import make_subplots def generate_data(n: int, noise_ratio: float) -> Tuple[np.ndarray, np.nda...
from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.core.validators import MinValueValidator, MaxValueValidator from django.conf import settings from django.shortcuts import get_object_or_404 from rest_framework.exceptions import Validation...
#!/bin/python # flake8: noqa: E501 '''Script to generate documentation for this project.''' import argparse import glob import json import os import shutil import sys from functools import cache from pathlib import Path import pdoc from jsmin import jsmin as minify_js from packaging import version from pdoc.render_hel...
"""This file contains function which help in parsing GPML file.""" #oggpnosn #hkhr import networkx as nx from bs4 import BeautifulSoup from itertools import permutations def get_node_information(data_node): """ It parses nodes in GPML xml file. :param data_node: XML node of the type "data" :return: no...
from pylightnix import (Registry, RConfig, datahash, PYLIGHTNIX_NAMEPAT, mkdref, mkrref, trimhash, encode, dagroots, List, DRef, Callable) from tests.imports import (given, assume, example, note, settings, text, decimals, integers, rmtree, char...
from flask import Flask, request, jsonify from flask_cors import CORS from circuit import Circuit from results import Results from features import Features from booleanExpression import BooleanFunction from qiskit.quantum_info.operators.predicates import is_unitary_matrix from math import log2 # configu...
# imports # base import operator import json from collections import Counter # third party import pandas as pd import dash import plotly.figure_factory as ff # project from .layout import retrieve_layout # NON-CALLBACK FUNCTIONS REQUIRED FOR THE APP # ----------------------------------------------------------------...
from sqlalchemy import ( create_engine as ce, Column, Integer, String, Float, ForeignKey, Table ) from sqlalchemy.ext.declarative import declarative_base, declared_attr from sqlalchemy.orm import sessionmaker, relationship # DEFINE DATABASE ENGINE engine = ce('sqlite:///dat') Base = declarative_base() Session =...
import subprocess import argparse import json import shutil import os import glob import signal import sys ops_cfg_path = "config/operators.json" def signal_handler(sig, frame): print('Aborted') os.chdir(owd) sys.exit(0) def dump_func_name(func): def echo_func(*func_args, **func_kwargs): pr...
""" preprocessing twitter dataset """ import time import os from os import path from os.path import join, expanduser as expand import json import re import csv from collections import defaultdict import argparse import nltk from preprocessing import twitter_airlines all_companies = 'AppleSupport,Amazon,Uber_Support...
from django.db import models from django.utils import timezone from django.db.models.signals import post_save from django.dispatch import receiver from datetime import datetime, timedelta from django.db.models import Count, Sum from django.db.models.functions import TruncDate from django.template.defaultfilters import ...
# MIT License # # Copyright (c) 2021 <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, publi...
import yaml try: yaml.warnings({'YAMLLoadWarning': False}) # not all versions of YAML support this except AttributeError: pass from .builders.jupyter import JupyterBuilder from .builders.jupyterpdf import JupyterPDFBuilder from .directive.jupyter import jupyter_node from .directive.jupyter import Jupyter as ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2014-2015 clowwindy # # 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 r...
from splinter import Browser from bs4 import BeautifulSoup import pandas as pd import time def init_browser(): executable_path = {'executable_path': '/usr/local/bin/chromedriver'} return Browser('chrome', **executable_path, headless=False) def scrape(): browser = init_browser() # Visit NASA url = 'https://mar...
'''Train CIFAR10 with PyTorch.''' import torch, os import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import torch.backends.cudnn as cudnn from torchvision import datasets import torchvision import torchvision.transforms as transforms import os, glob, sys import argparse from models i...
#!/usr/bin/env python # -*- coding: UTF-8 -*- # ViewSets define the view behavior. import logging import os import stat import traceback import tempfile from collections import OrderedDict from django.conf import settings from django.contrib.sites.models import Site from django.shortcuts import redirect from django....
# This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load in import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O...
import pandas as pd import numpy as np from numpy import mean from numpy import std from numpy import NaN from sklearn.datasets import make_regression from sklearn.model_selection import cross_val_score from sklearn.model_selection import RepeatedKFold from sklearn.model_selection import train_test_split from sklearn...
import re import librosa import numpy as np import torch from scipy.interpolate import interp1d from sklearn.preprocessing import normalize device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") skeleton_line_pairs = [(0, 1, 'b'), (1, 2, 'darkred'), (2, 3, 'r'), (3, 4, 'orange'), (1, 5, 'darkgreen'...
import cv2 def compare_ratio(src_img, template, ratio_list): optimal_maxVal = 0 optimal_ratio = 0 optimal_x = 0 optimal_y = 0 optimal_w = 0 optimal_h = 0 temp_h, temp_w = template.shape[:2] for ratio in ratio_list: resize_w = int(temp_w*ratio) resize_h = int(temp_h*rati...
import onnxruntime import numpy as np import scipy.stats as stat def onnx_to_model(net_file): sess = onnxruntime.InferenceSession(net_file) input_name = sess.get_inputs()[0].name label_name = sess.get_outputs()[0].name def out_model(X): if len(X.shape)<=1: logits= sess.run([label_n...
# -*- coding: utf-8 -*- import logging import datetime from mutagenerate.core import AmazonSource import os import random import requests_cache from optparse import OptionParser from collections import Counter from scrapers import NovaScraper, FipScraper, OuiScraper, NostalgieScraper, RadioparadiseScraper from core....
# Core Packages import streamlit as st # Load EDA Packages import pandas as pd import numpy as np # Load Data Viz packages import matplotlib.pyplot as plt import seaborn as sns import plotly.express as px # Load Data data = pd.read_csv("data/diabetes_data_upload.csv") age_dist = pd.read_csv("data/freqdist_of_age_da...
import discord from discord.ext import commands, menus from utils import config_var, MenuPages import os import inspect import datetime class LyricPageSource(menus.ListPageSource): def __init__(self, title, url, thumbnail, data): self.title = title self.url = url self.thumbnail = thumbnail...
from lxml import etree import requests from prettytable import PrettyTable import datetime # 使用BeautifulSoup解析网页 from bs4 import BeautifulSoup import json import db_executor as executor # 基金变动信息 # http://fundgz.1234567.com.cn/js/005585.js # 基金基变动信息 # http://fund.eastmoney.com/005585.html # 阶段涨幅 http://fundf10.eastmo...
import types import inspect import functools import random import aot import tvm from tvm import relay from tvm.relay.testing import mlp from tvm.relay.testing import check_grad from tvm.relay import transform from tvm.relay.backend import interpreter import numpy as np def str_to_np_type(ty): if ty == 'float32'...
from __future__ import annotations from typing import Any, Callable, Dict, List, Optional, Tuple, Union from warnings import warn import jax import jax.numpy as jnp import matplotlib.pylab as plt from jax import hessian, jacfwd, jit from jax._src.scipy.optimize.minimize import OptimizeResults as OptimizeResultsJax fr...
# coding: utf-8 """ Создание исходного корпуса Sociation.org Выполняется в консоли. Код для ознакомления """ import os from collections import Counter from operator import itemgetter from random import randint import numpy as np from gensim import corpora, models, similarities class DictEncoder(object): """ В...
from pathlib import Path import matplotlib.pyplot as plt import numpy as np import pandas as pd # plt.close("all") CURRENT_DIRECTORY = Path(__file__).parent def plot_01(): ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)) ts = ts.cumsum() ts.plot() # Display plo...
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% [markdown] # # Postgresql Tests With Python # In this jupyter notebook, I will be testing bulk insert, execute some queries on about 2 million rows of data, and save their execution times. # %% [markdown] # ## Import libraries #...
import numpy as np from sklearn.base import BaseEstimator from sklearn.base import RegressorMixin from sklearn.metrics import mean_squared_error from sklearn.utils.validation import check_array from sklearn.utils.validation import check_random_state from .algorithm import oneplus from .algorithm import optimize from ....
# -*- coding:utf-8 -*- #!/usr/bin/env python2 # # Example to compare the faces in two images. # <NAME> # 2015/09/29 # # Copyright 2015-2016 Carnegie Mellon University # # 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...
# Copyright (c) 2021 Graphcore 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 applicable law...
# flake8: noqa from __future__ import annotations # %% # Écrire une fonction qui pour un entier entre 1 et 3999 retourne sa # représentation sous forme de nombre romain. # Rappel: I (1), V (5), X (10), L (50), C (100), D (500), M (1000) def romain(n: int) -> str: assert 1 <= n <= 3999 cumul = "" whil...
import os from collections import OrderedDict from datetime import datetime import json import re import glob import sys import datetime import logging ''' # -------------------------------------------- # https://github.com/cszn # https://github.com/xinntao/BasicSR # -------------------------------------------- ''' ...
# # Description: # Utilities and rules concerning the actual fetch of artifacts and sub-artifacts and metadata. # load(":artifacts.bzl", "artifacts") load(":globals.bzl", "DOWNLOAD_PREFIX", "PACKAGING_TYPE_FILE", "fetch_repo") load(":packaging_type.bzl", "packaging_type") load(":poms.bzl", "poms") load(":utils.bzl", ...
from flask import request, url_for from flask_api import FlaskAPI, status, exceptions from base64 import b64decode from utils import constants import tensorflow as tf # build an array of labels from the labels file so we can translate the result of the network to a human readable label with open(constants.root_dir +...
#!/usr/bin/env python3 # coding=utf-8 import argparse import datetime import logging import nagiosplugin import pypuppetdb import re _log = logging.getLogger('nagiosplugin') class ListContext(nagiosplugin.Context): def __init__(self, name, text, state=nagiosplugin.state.Critical, result_cls=nagiosplugin.result.Res...
import Adafruit_BBIO.GPIO as GPIO import time import cp437 #==============================================================================# # Beaglebone Black script to interface with Noritake 8-bit Protocol display #==============================================================================# # # Author: <NAME>...
import matplotlib.pyplot as plt import pandas as pd import numpy as np def rearrange(sample_volumes): """Rearranges sample information to group samples based on position in sublist. [[a1,b1,c1],[a2,b2,c2]] => [[a1,a2],[b1,b2],[c1,c2]]""" component_volumes_rearranged = [] for i in range(len(sample_volumes[0...
import numpy as np import cv2 from matplotlib import pyplot as plt from os import walk import os import random import pdb import pickle from sklearn.mixture import GaussianMixture as GMM from sklearn import preprocessing from sklearn.ensemble import AdaBoostClassifier from sklearn.pipeline import make_pipeline from sk...
import filecmp import os import socket import sys import tempfile import time from unittest import mock import docker import pytest import schema from docker_cp import cli def docker_responsive(): client = docker.from_env() try: return client.ping() except Exception: return False def i...
import cv2 import plotly.express as px import os from tqdm import tqdm import tensorflow_hub as hub import tensorflow as tf from PIL import Image # For drawing onto the image. import numpy as np from PIL import Image from PIL import ImageColor from PIL import ImageDraw from PIL import ImageFont from PIL import ImageOp...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ SnapSearch.tests.test_client ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Tests SnapSearch.client :author: `<NAME> <<EMAIL>>`_ :date: 2014/03/08 """ __all__ = ['TestClientInit', 'TestClientMethods', ] import os import sys try: from . import _con...
from __future__ import absolute_import import re import datetime import ipaddress from yamale.util import to_unicode from .base import Validator from .. import util class Constraint(object): keywords = {} # Keywords and types accepted by this constraint is_active = False def __init__(self, value_type, ...
from graphics import * import time import random chars='<KEY>' i = 0 j = 0 k = 0 l=0 m=0 ix=250 jx=ix+150 kx=jx+150 lx=kx+150 mx=lx+150 points=0 def move(b,w): time.sleep(0.05) b.move(0, 10) w.move(0, 10) def destroy(i,x): bow=Image(Point(30,10*i),'arrows.gif') bow.draw(win) ...
from mpi4py import MPI import mpiunittest as unittest import arrayimpl def mkzeros(n): import sys if not hasattr(sys, 'pypy_version_info'): return bytearray(n) return b'\0' * n def memzero(m): try: m[:] = 0 except IndexError: # cffi buffer m[0:len(m)] = b'\0'*len(m) class ...
from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval from transform.convert_bbox_format import BboxFormatConvert from util.progress import interactive def create_coco_annotations(image_id, boxes, labels, scores, gt=False): if not hasattr(create_coco_annotations, "ann_id"): create_coco_anno...
from textblob import TextBlob import tweepy def filter(s): a=s.split('@') b=a[1].split(" ") b.pop(0) s1=" ".join(b) a.pop(1) s=" ".join(a)+" " +s1 return s #Classificaation system key : daa64450905b79ff28e52174d39880d5f4216cab #ml = mkl('daa64450905b79ff28e52174d39880d5f4216cab') ...
# Copyright (c) <NAME> and Unlock contributors. # All rights reserved. # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of ...
# CV = Curriculum Vitae from django.db import models from django.utils.translation import ugettext_lazy as _ from django.core.validators import RegexValidator from datetime import date, timedelta, datetime from phonenumber_field.modelfields import PhoneNumberField from utils.utils import capitalize from utils.constant...
# -*- coding: utf-8 -*- # Copyright (c) 2018, <EMAIL> and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document import json from frappe import _ class MaterialRequestsToPurchaseInvoicesManager(Document): pass ...
from .energy import get_events_energy from .time import deadtime_correction, make_ingti_times, tarange, get_gti, gti_intersection, GTI from .caldb import get_energycal, urdbkgsc from scipy.interpolate import interp1d import numpy as np from functools import reduce #import matplotlib.pyplot as plt def stepsize(arr): ...
# credits: # https://github.com/pfnet-research/sngan_projection/blob/master/source/inception/inception_score_tf.py # https://github.com/bioinf-jku/TTUR/blob/master/fid.py # https://github.com/openai/improved-gan/pull/40/commits/0a09faccb45088695228bbf50435ee71e94eb2ce (bug fixing) import os.path import sys import...
#!/usr/bin/env python # # This code is part of the binding affinity prediction tools distribution # and governed by its license. Please see the LICENSE file that should # have been included as part of this package. # """ Functions to execute freesasa and parse its output. """ from __future__ import print_function, d...
import os import numpy as np import random import keras from keras.datasets import cifar10 from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential, Model, model_from_json from keras.layers import Dense, Dropout, Activation, Flatten, Input, Lambda, Conv2D, MaxPooling2D from keras im...
import numpy as np import sklearn from scipy.interpolate import interp1d from scipy.stats import rankdata import warnings class AbsDiffTransformer(sklearn.base.TransformerMixin): """ Takes an array of sample pairs and returns the element-wise absolute difference. Expects: - X is of shape (n,f,2) ...
#! /usr/bin/env python3 from typing import Type from aiohttp import web from maubot import Plugin, MessageEvent from maubot.handlers import command, event, web as web_handler from mautrix.types import EventType, TextMessageEventContent, MessageType, Format from mautrix.util.config import BaseProxyConfig, ConfigUpdat...
# -*- coding: utf-8 -*- import graphene from django.db import IntegrityError from django.db.models import ProtectedError from django.http import Http404 from rest_framework import serializers from graphene import relay from app.authorization.mixins import AuthMutation from utils.graphql.types import ErrorType from...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # vajra-apis documentation build configuration file, created by # sphinx-quickstart on Wed Apr 26 11:45:22 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this #...
# This file contains the following function(s): find_duplicates, getnoneditable, countsCDSedits import pandas as pd pd.set_option('display.max_rows', 500) pd.set_option('display.max_columns', 500) pd.set_option('display.width', 1000) from check_CDS import remove_dup def find_duplicates(df_all): """finds the count...
import os import sys import time import errno import shutil import zipfile import argparse import tempfile import subprocess try: from urllib.request import urlretrieve except ImportError: # Support for Python 2.7 from urllib import urlretrieve parser = argparse.ArgumentParser() parser.add_argument("versi...
# -*- coding: utf-8 -*- import os import telebot import time import random import threading from emoji import emojize from telebot import types from pymongo import MongoClient import traceback token = os.environ['TELEGRAM_TOKEN'] bot = telebot.TeleBot(token) client=MongoClient(os.environ['database']) db=client.dataw...
import os from os.path import isfile, join from os import listdir from pathlib import Path class Util(): def toClassName(self, fileName): #parts = fileName.split('.') fileName = fileName.replace('-', '.') parts = [p.capitalize() for p in fileName.split('.')] return ''.join(parts) ...
""" This module has functions for liquid layer detection. """ import numpy as np import numpy.ma as ma import scipy.signal from cloudnetpy import utils from cloudnetpy.constants import T0 def ind_base(dprof, p, dist, lim): """Finds base index of a peak in profile. Return the lowermost index of profile where ...
import torch import torch.nn as nn import torch.nn.functional as F import functools def get_norm_layer(norm_type='group'): """Return a normalization layer Parameters: norm_type (str) -- the name of the normalization layer: batch | instance | none For BatchNorm, we use learnable affine parameters a...
import copy import math from threading import Thread, Condition, Lock import time from engine.geometry import calcs from gui import draw import gui from gui.core import Drawable import numpy as np class SimManager: def __init__(self): self._lock = Condition(Lock()) self._simulator = None ...
''' Created on November 06, 2019 Function to determine which files have been modified after a given date Returns a pandas DataFrame object @author: pauladjata ''' # import site-packages and modules import glob import os.path, time import pandas as pd import os import datetime import time import r...
#!/usr/bin/env python # coding: utf-8 from __future__ import print_function, division, unicode_literals import ctypes import platform import sys import os if platform.system() == "Windows": DLL_PATH = "./Release/Lakaseg_lib.dll" else: DLL_PATH = "./liblakaseg.so" directory_of_this_file = os.path.dirname(os....
import argparse from datetime import datetime, timedelta import json import traceback from uuid import UUID, uuid4 from bson import ObjectId from motor import motor_tornado from tornado import escape, gen, ioloop, web class _JSONEncoder(json.JSONEncoder): """Custom JSON encoder.""" def default(self, obj): ...
# -*- coding: utf-8 -*- ########################################################################## # NSAp - Copyright (C) CEA, 2021 # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html #...
from __future__ import absolute_import, division, print_function, unicode_literals __metaclass__ = type import base64 import cv2 import numpy as np import pickle from tornado.ioloop import IOLoop, PeriodicCallback from tornado import gen from tornado.websocket import websocket_connect from .data import squashCoords ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import cv2 import numpy as np pix_width = 0.05 map_x_min = 0.0 map_x_max = 20.0 map_y_min = -20.0 map_y_max = 20.0 lim_z = -1.95 width = int((map_x_max-map_x_min)/pix_width) height = int((map_y_max-map_y_min)/pix_width) u_bias = int(np.abs(map_y_max)/(map_y_max-map_...
#!/usr/bin/env pypy from __future__ import print_function import json import os import re import sys stdout = sys.stdout sys.stdout = sys.stderr # We use pypy so that dictionary order is preserved. # pypy2 preserves dictionary order everywhere! Even for kwargs! # A convenient docker container is provided if you just...
# Based on github.com/lambci/docker-lambda/python2.7/run/runtime-mock.py version cf93693 from __future__ import print_function import sys import os import random import uuid import time import resource import datetime import json # hijack stdout so it won't be taken by mistake orig_stdout = os.fdopen(os.dup(1),"w") os...
import numpy as np from scipy import integrate from rastlib import proximity_rast_ds, create_mem_raster_on_ref, read_nanarray, pixel_size def neff_sum_circular(area,crange1,psill1,crange2,psill2): #short range variogram c1 = psill1 # partial sill a1 = crange1 # short correlation range #long range va...
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import pandas as pd import os import zipfile import requests import io import re import json import math as mt url = 'https://s3.amazonaws.com/weruns/forfun/Kickstarter/Kickstarter_2019-02-14T03_20_04_734Z.zip' f = 'Kickstarter_2019-02-1...
import dataclasses import datetime import json import pprint import typing import pytz import requests SWITCH_STATUS_URL = "https://status.nic.ch/availability/service/json" STATUSPAGE_BASE_URL = "https://api.statuspage.io/v1" STATUSPAGE_API_KEY = "" STATUSPAGE_PAGE_ID = "" STATUSPAGE_COMPONENT_ID = "" @dataclasses....
import os import numpy as np import matplotlib.pyplot as plt from skimage.exposure import equalize_adapthist from PIL import Image from util import load_filters, get_boxes, draw_boxes, binary_dilation, gray2rgb, correlate, gray_dilation, min_box_size # Thresholds # heat_thresh = 0.695 # heat_thresh = 0.655 # heat_t...
from django.shortcuts import render,reverse, get_object_or_404 from django.urls import reverse_lazy from django.http import HttpResponse, JsonResponse from django.views import generic from rest_framework.views import APIView from rest_framework.response import Response from . import forms from . import models ...
import sqlite3 from com.nico.webapp.security_flask.password_hashing import password_security forhobbies = [] def get_connection(): return sqlite3.connect('register.db') def initdb(): conn = get_connection() cur = conn.cursor() create_register_sql = "CREATE TABLE IF NOT EXISTS register (name varchar ...
''' This module contains methods for training models with different loss functions. ''' import torch from torch.nn import functional as F from torch import nn from Losses.loss import cross_entropy, focal_loss, focal_loss_adaptive from Losses.loss import mmce, mmce_weighted from Losses.loss import brier_score loss_fu...
import asyncio import multiprocessing import os import socket import ujson as json from email.utils import formatdate from functools import partial from http import HTTPStatus import httptools from jsonschema import Draft4Validator, ErrorTree __version__ = '3.0.1' class HTTPException(Exception): def __init__(se...
import argparse import time from os import path as osp import numpy as np import torch import torch.nn.functional as F import torch_geometric import yaml from tqdm import tqdm, trange from hetsage.data import DataManager from hetsage.model import Model from hetsage.utils import (TB, flatten, init_random, print_metric...
import numpy as np from medpy.metric.binary import hd, dc, asd def dice_coef(y_true, y_pred): """ :param y_true: :param y_pred: :return: """ y_true = y_true.flatten() y_pred = y_pred.flatten() intersection = np.sum(y_true * y_pred) return (2. * intersection + 1.0) / (np.sum(y_true)...
import asyncio import logging import functools import time import threading from collections import OrderedDict import numpy as np from matplotlib.backends.qt_compat import QtCore from bluesky.callbacks.mpl_plotting import QtAwareCallback logger = logging.getLogger(__name__) def catch_exceptions(fcn): @functoo...
from argparse import ArgumentParser import tempfile from better_exchook import * import sys PY2 = sys.version_info[0] == 2 if PY2: from io import BytesIO as StringIO else: from io import StringIO _IsGithubEnv = os.environ.get("GITHUB_ACTIONS") == "true" def _fold_open(txt): if _IsGithubEnv: pri...
import torch from torch import nn from torch.autograd import Function # Inherit from Function class LinearFunctionCustom(Function): @staticmethod def forward(ctx, input, weight, b_weights, bias=None): ctx.save_for_backward(input, weight, b_weights, bias) output = input.mm(weight.t()) i...
import math from typing import Callable import geopandas as gpd import pandas as pd import shapely from shapely.geometry import Polygon from eolearn.core import EOPatch, EOTask, FeatureType, MapFeatureTask from eolearn.io import VectorImportTask from ..utils.geometry import merge_bboxes class PrepareMRRTask(EOTask...
""" Accuracy measures ----------------- .. autosummary:: :toctree: toctree/monitor AccuracyArgmax AccuracyEmbedding """ from abc import ABC import torch import torch.utils.data from mighty.utils.var_online import MeanOnlineLabels from mighty.utils.signal import compute_distance def calc_accuracy(lab...
from kubernetes import client, config from os import listdir, path import yaml import re import inflect import urllib3 def initialize(params): if "mode" not in params: raise Exception("The Kubernetes plugin requires 'mode' to be set in the params.") load_config(params) def process(context, params): ...
import numpy as np import matplotlib.pyplot as plt from typing import Tuple from IMLearn.metalearners.adaboost import AdaBoost # from IMLearn.learners.metalearners.adaboost import AdaBoost from IMLearn.learners.classifiers import DecisionStump from IMLearn.metrics import misclassification_error from utils import * impo...
import math from collections import namedtuple import pandas as pd from gensim.models import FastText df = pd.read_csv('../data/hospital.csv') def remove_nan(embed_vec:list): # return the nan idx, and remove it jointly from two vectors nan_list = [] for i,e in enumerate(embed_vec): for j in e: ...
""" Checks for Adobe Fonts (formerly known as Typekit). """ import unicodedata from fontbakery.callable import check from fontbakery.fonts_profile import profile_factory from fontbakery.message import Message, KEEP_ORIGINAL_MESSAGE from fontbakery.profiles.universal import UNIVERSAL_PROFILE_CHECKS from fontbakery.sect...
# Module for evaluating performance of vad models, # may also be run directly as a script # Author: <NAME> 2021 import argparse import numpy as np import pandas as pd from scipy.io import wavfile from typing import Dict from voxseg import utils def print_confusion_matrix(scores: Dict[str,Dict[str,int]]) -> None: ...
import datetime import ipaddress import re from enum import Enum from io import TextIOWrapper from ipaddress import IPv4Network, IPv6Network from typing import Union class PolicyAction(Enum): NXDOMAIN = "." NODATA = "*." PASSTHRU = "rpz-passthru." TCP_ONLY = "rpz-tcp-only." DROP = "rpz-drop." ...
# -*- coding: utf-8 -*- from decimal import Decimal from datetime import date from django.db.models import Q from django.db import models from django.utils.translation import ugettext_lazy from dateutil.relativedelta import relativedelta from dateutil.rrule import MONTHLY, YEARLY, DAILY from ..constants import COST_T...
#-*- coding: utf-8 -*- ''' Created on 2016. 11. 19 Updated on 2016. 01. 09 ''' from __future__ import print_function import os import re from utils import PrettyStringBuilder from utils import Progress import javalang class Resource(object): Stopwords = None EngDictionary = None @staticmethod d...
from typing import Dict, Any from django.shortcuts import render, redirect from django.http import HttpRequest from ..middleware import authenticated from datetime import datetime, timedelta from ..utils import datetime_now_tz as now from ..forms.lessons import ( LessonsByClassRoomForm, AddLessonsForm, Lessons...