text
stringlengths
3.07k
12.6k
import math import numpy as np from scipy.optimize import root def lambda_predmix_eb( x, truncation=math.inf, alpha=0.05, fixed_n=None, prior_mean=1 / 2, prior_variance=1 / 4, fake_obs=1, scale=1, ): """ Predictable mixture lambda values or "bets" Parameters ----------...
from aiogram import types from aiogram.dispatcher.filters.builtin import CommandHelp, CommandStart from database.database import session, Customer, Product, Organization from loader import dp, bot from aiogram.dispatcher import FSMContext from aiogram.types import ReplyKeyboardMarkup, KeyboardButton from aiogram.dispat...
from datetime import timedelta, datetime from typing import Dict from django.contrib.messages.views import SuccessMessageMixin from django.core.files import File from django.db.models import Q from django.utils import timezone from django.views.generic import CreateView, ListView, DetailView, UpdateView from grandcha...
# Name: TruncateDateTime.py # Purpose: Will take a selected datetime field and will truncate it to chosen values for each of the chosen sub dates. # Author: <NAME> # Last Modified: 2/7/2018 # Copyright: <NAME> # Python Version: 2.7-3.1 # ArcGIS Version: 10.4 (Pro) # -------------------------------- # Copyright 2016 <...
import numpy as np import os import cv2 import torch import fastai from fastai.vision import * from Util.Timer import Timer from Util.FeatureStats import preds2features, getStatFeatNames from RecurrentModel.RecurrentCNN import MixedVideoSequenceModel, VideoSequenceModel from RecurrentModel.RecurrentModelConfig import ...
import csv import math import numpy as np import tensorflow as tf from PIL import Image from tensorflow.keras import Model from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2, preprocess_input from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau, Callback from tensorf...
import logging import random import sqlite3 from abc import ABCMeta, abstractmethod from urllib.parse import urlparse, urljoin import genanki import nltk import requests from bs4 import BeautifulSoup from nltk import word_tokenize from nltk.corpus import stopwords from nltk.corpus import words class Crawler(metaclas...
import json import os import requests from .geo import distance def get_aqi(lat, lon, results_to_return=10): aqi_token = os.environ.get('AQI_TOKEN', '').strip() url = "https://api.waqi.info/map/bounds/?token={}&latlng=26.3978980576,80.0884245137,30.4227169866,88.1748043151".format( aqi_token) re...
# # Copyright (c) 2009, 2010 Testrepository Contributors # # Licensed under either the Apache License, Version 2.0 or the BSD 3-clause # license at the users choice. A copy of both licenses are available in the # project source as Apache-2.0 and BSD. You may not use this file except in # compliance with one of these t...
import torch import torch.nn as nn import torch.nn.functional as F from torchvision import datasets from torch.autograd import Variable from torch.utils.data import DataLoader from itertools import cycle from collections import OrderedDict from utils import reparameterize, transform_config CONV_OUTPUT_SIZE = 14400 ...
#from pandas import Timedelta from flask import Flask, session, redirect, url_for, request, render_template, jsonify from sqlalchemy import create_engine from sqlalchemy.engine import Connection from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column...
#!/usr/bin/env python # -*- coding: utf-8 -*- """This module measures the performance of various programming languages.""" import os import math import csv import logging import statistics import delegator from lauda import StopWatch from termcolor import colored class Measure: """Initializes the Measurement ...
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import init from pynif3d.common import init_Conv2d, init_ConvTranspose2d from pynif3d.common.verification import check_in_options from pynif3d.log.log_funcs import func_logger class UNet(nn.Module): """ UNet class for Convolutio...
#!/usr/bin/python # This generates SQL script for go structs with # the comment 'sql generate' after struct name. # Some additional instructions for this generator # may be provided in struct tags (see this file # or project go source files for examples). # Run go generate in project folder. import sys import os impo...
# -*- coding: utf-8 -*- from .component import ColumnList from . import debug BG_GEN = "#E6FFEE" BG_KICAD = "#FFE6B3" BG_USER = "#E6F9FF" BG_EMPTY = "#FF8080" def bgColor(col): """ Return a background color for a given column title """ # Auto-generated columns if col in ColumnList._COLUMNS_GEN: ...
from binascii import a2b_base64, b2a_base64, hexlify from hashlib import sha256 import hmac from os import urandom from struct import pack def int_to_bytes(i, outlen=None): bs = b'' while i != 0: bs = pack('=B', i & 0xff) + bs i >>= 8 if outlen and len(bs) < outlen: bs = b'\x00' *...
# coding=utf-8 """Circles, collisions and gravity""" import glfw from OpenGL.GL import * import OpenGL.GL.shaders import numpy as np import random import sys import os.path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import grafica.basic_shapes as bs import grafica.easy_shaders as es i...
# -*- coding: utf-8 -*- """Test the supply curve SupplyCurveAggregation with friction surface. Created on Wed Jun 19 15:37:05 2019 @author: gbuster """ import h5py import numpy as np import pytest import os import warnings from reV.supply_curve.points import SupplyCurveExtent from reV.supply_curve.exclusions import ...
#!/usr/bin/env python # coding: utf-8 # In this Kernel, I'd like to show you a very basic segmentation technique whihc only applies pure computer vision techniques. Nothing fancy. # # At first, I'll show the step-by-step processing and after that I will create the submission for the competition. # # With this kernel, ...
#!/usr/bin/env python """ Simple multiprocessing (and multithreaded) epoll HTTP server example Use multiprocessed_loop() or threaded_loop() in main() function for multiprocessing and multithreaded version correspondingly """ import errno import fcntl import multiprocessing import os import select import socket import...
"""Module to support calculation of metrics of circadian rhythm from acc data""" import numpy as np import scipy as sp from scipy import fftpack from datetime import timedelta def calculatePSD(e, epochPeriod, fourierWithAcc, labels, summary): """Calculate the power spectral density from fourier analysis of a 1 d...
# agent.py why?: solve environments with rl from tensorflow.keras.layers import Dense from tensorflow.keras import Model import matplotlib.pyplot as plt from resnet import make_resnet import tensorflow as tf from queue import Queue import numpy as np import threading from d import d import os class ActorCritic(Model)...
# CREATED: 5/5/17 14:36 by <NAME> <<EMAIL>> from scaper.audio import get_integrated_lufs, match_sample_length from scaper.audio import peak_normalize from scaper.util import _close_temp_files import numpy as np import scipy.signal as sg import os import pytest from scaper.scaper_exceptions import ScaperError from pkg_...
from collections import defaultdict, OrderedDict import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import pytest from smartva import cause_grapher from smartva.data.common_data import MALE, FEMALE from smartva.tariff_prep import TariffPrep, Record from smartva.data import adu...
#!/usr/bin/env python # coding=utf-8 import pprint import csv import click import requests import datetime as datetime # from splinter import Browser import time import re from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait f...
""" Utilities for FT costing calculations """ from typing import Tuple, Optional import sys import os import h5py import numpy as np from pyscf import gto, scf, mcscf, ao2mo, cc def QR(L : int, M1 : int) -> Tuple[int, int]: """ This gives the optimal k and minimum cost for a QROM over L values of size M. Arg...
# run_example = false import numpy as np import pygfx as gfx from PySide6 import QtWidgets, QtCore, QtGui from wgpu.gui.qt import WgpuCanvas # %% Qt logic class CanvasWithOverlay(WgpuCanvas): """A Qt canvas with support for 2D overlay.""" overlay = None def __init__(self, *args, **kwargs): s...
import time from flask import * from libs import admin_authentication from libs.admin_authentication import authenticate_admin_login,\ authenticate_admin_study_access, get_admins_allowed_studies, get_admins_allowed_studies_as_query_set,\ admin_is_system_admin from libs.security import check_password_requirement...
# -*- coding: utf-8 -*- """ Created on Sun Feb 21 13:55:04 2021 @author: lowes """ import numpy as np import vtk from vtk.numpy_interface import dataset_adapter as dsa from models.layers.mesh_prepare import (remove_non_manifolds,augmentation, build_gemm,post_augmentation,extract_features) from matplotlib.cbook import...
"""Tests for all number generators.""" import sys from collections import namedtuple from functools import partial import pytest from fauxfactory.helpers import base_repr, VALID_DIGITS from fauxfactory import ( gen_hexadecimal, gen_integer, gen_number, gen_octagonal, gen_negative_integer, gen...
import torch import torch.nn as nn import numpy as np import sklearn.decomposition from utils.distributed import get_world_size, all_gather, rank0_to_all class PCA: def __init__(self, n_components, w_batch): pca = sklearn.decomposition.IncrementalPCA(n_components) print('Fitting PCA...') ...
"""Collection of utilities to detect properties of the underlying architecture.""" from subprocess import PIPE, Popen import numpy as np import cpuinfo import psutil from devito.logger import warning from devito.tools.memoization import memoized_func __all__ = ['platform_registry', 'INTEL64', 'SNB', 'IVB...
""" logan.runner ~~~~~~~~~~~~ :copyright: (c) 2012 <NAME>. :license: Apache License 2.0, see NOTICE for more details. """ import argparse import os import re import sys from django.core import management from nautobot import __version__ from . import importer from .settings import create_default_settings __config...
# Create your views here. from rest_framework.views import APIView from .serializers import UserSerializer, LoginSerializer from ..utils.helpers.json_helpers import generate_response, raise_error, add_token_to_response, validate_url, validate_confirmation_request from ..utils import success_messages from ..utils.error...
"""Thermistor calculation methods, Semitec 103AT-2 thermistor using ADS1x15 ADC I2C Driver for Raspberry PI & MicroPython""" from math import log def steinhart_hart(r, a, b, c, degrees='celcius'): """Calculate temperature from a resistance based on the Steinhart-Hart equation. Defaults to degres in Celcius ...
''' Reference: https://github.com/akamaster/pytorch_resnet_cifar10 Properly implemented ResNet-s for CIFAR10 as described in paper [1]. The implementation and structure of this file is hugely influenced by [2] which is implemented for ImageNet and doesn't have option A for identity. Moreover, most of the implement...
from __future__ import print_function from __future__ import absolute_import from __future__ import division from math import sqrt __all__ = ['Polyhedron'] class Polyhedron(object): """Compute the vertices and faces of one of the Platonic solids. Notes ----- A Platonic solid is a regular, convex p...
from abc import ABC import torch import torch.nn as nn import time from torch.utils.data import DataLoader from torchvision import datasets, transforms, models import multiprocessing import torch.utils.model_zoo as model_zoo device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") max_workers = multipr...
from __future__ import print_function import os import sys import json import shutil import subprocess class PybythecError(Exception): def __init__(self, msg, *args): super(PybythecError, self).__init__(msg.format(*args)) def f(s, *args): try: return s.format(*args) except Exception: # so far the only...
"""Endpoints to allow for user creation, image upload & filtering.""" from custom_storage import AmazonStorage as store from django.contrib.auth.models import User from django.core.files.storage import default_storage as storage from models import Image, ThumbnailImage, ThumbnailFilter, Folder from random import randin...
'''predefined patches.''' from matplotlib import patches, transforms from matplotlib.path import Path import matplotlib.pyplot as plt from functools import reduce import numpy as np import pdb from numpy.linalg import norm from .utils import rotate from .setting import node_setting _basic_prop_list = ['ls', 'faceco...
""" SC101 Baby Names Project Adapted from <NAME>'s Baby Names assignment by <NAME>. To search the name in the database and print out all ranks of the name. """ import tkinter import babynames import babygraphicsgui as gui FILENAMES = [ 'data/full/baby-1900.txt', 'data/full/baby-1910.txt', 'data/full/baby-192...
from __future__ import print_function import re import time import azure.mgmt.batchai.models as models import requests from azure.mgmt.storage import StorageManagementClient from msrestazure.tools import parse_resource_id from utilities.cluster import print_cluster_status POLLING_INTERVAL_SEC = 5 class OutputStre...
import builtins import sys import math import random import time __all__ = ['enumerate', 'nonRepeatingRandomList', 'describeException', 'pdir', 'choice', 'cmp', 'lerp', 'triglerp'] if not hasattr(builtins, 'enumerate'): def enumerate(L): """Returns (0, L[0]), (1, L[1]), etc., allowing this syntax: ...
"""Test the SimplePooledDB module. Note: We don't test performance here, so the test does not predicate whether SimplePooledDB actually will help in improving performance or not. We also do not test any real world DB-API 2 module, we just mock the basic connection functionality of an arbitrary module. Copyright and c...
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT license. See LICENSE file in the project root for full license information. import datetime import os import re from os.path import join, dirname from watercooler_utils import ad_ops, blob_ops from watercooler_utils import arm_ops ...
import os import torch from AGBDataReader import AGBDataReader from ReformerSiamese import ReformerSiamese from datetime import datetime import logging from torch.utils.data import DataLoader from sklearn.metrics import precision_recall_fscore_support import json from tqdm import tqdm from tqdm import trange import num...
""" Pymodbus Interfaces --------------------- A collection of base classes that are used throughout the pymodbus library. """ from pymodbus.exceptions import (NotImplementedException, MessageRegisterException) # ------------------------------------------------------------------------...
from model.Accounts import Account from model.Transactions import Transaction import mongoengine as mongoengine import logging ## ACCOUNT Business operations: # Register client # Deposit # Withdraw # TBD: Transfer # Supporting functions: does account exist? #### changes # included logging in does account exi...
import argparse # Some basic setup: # Setup detectron2 logger import detectron2 from detectron2.utils.logger import setup_logger # import some common libraries import numpy as np import os, json, cv2, random from glob import glob from pathlib import Path # import some common detectron2 utilities from detectron2 impo...
#!/usr/bin/env python3 #-*- coding: UTF-8 -*- import os.path import re from Bitmap import Bitmap def save_bitmap(bmp, path): ext = os.path.splitext(path)[1].lower() if ext == '.bmp': bmp.save(path) else: img = bmp.toImage() img.save(path) def dump_bitmap(path): print('dump bitmap:', path) bmp = Bitmap.from...
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals from eight import * from future.utils import python_2_unicode_compatible from . import databases from .errors import InvalidExchange from .utils import get_activity from numbers import Number from stats_arrays import uncertainty_choices tr...
import unittest from pynwb.ophys import TwoPhotonSeries, RoiResponseSeries, DfOverF, Fluorescence, PlaneSegmentation, \ ImageSegmentation, OpticalChannel, ImagingPlane from pynwb.image import ImageSeries import numpy as np def CreatePlaneSegmentation(): w, h = 5, 5 img_mask = [[[1.0 for x in range(w)] f...
# ---------------------------------------------------------------------- # | # | RegularExpression.py # | # | <NAME> <<EMAIL>> # | 2018-04-25 14:23:12 # | # ---------------------------------------------------------------------- # | # | Copyright <NAME> 2018-22. # | Distributed under the Boost Softwar...
import math import numpy as np import sys sys.path.append('../backbone') sys.path.append('../vae-dpc') from select_backbone import select_resnet from convrnn import ConvGRU from vrnn_model import * import torch import torch.nn as nn import torch.nn.functional as F class LC_present(nn.Module): def __init__(self,...
from django.core.exceptions import ObjectDoesNotExist from .models import Transaction from systori.lib.accounting.tools import Amount def _transaction_sort_key(txn): """ If there are payments and invoices created on the same day we want to make sure to process the payments first and then the invoices....
import numpy as np def luminance(colours): """ Compute luminance of an array of colours. """ return (np.max(colours[..., :3], axis=2) + np.min(colours[..., :3], axis=2)) / 2 def _float2int(f): return int(f * 255) def _int2float(i): return i / 255.0 class Colour: DTYPE = np.float32 ...
#coding:utf-8 """ @author : linkin @email : <EMAIL> @date : 2018-10-04 """ import os import re import time import random import requests import asyncio import datetime import tldextract from APIserver import apiserver from const.settings import IP_check_url from const.settings import IP_check_url...
from .embeddings import get_ddpg_embeddings, get_dqn_embeddings from torch import nn import torch as th def create_ddpg_reward_shaper(source_model, num_sampling_episodes): embeddings, q_vals = get_ddpg_embeddings(source_model, num_sampling_episodes) reward_shaper = DDPGRewardShaper(source_model, embeddin...
import tensorflow as tf class Embedding(tf.keras.layers.Layer): """ The embedding layer. """ def __init__(self, vocab_size, embedding_dim, pretrained_embedding=None): """ Inputs: pretrained_embedding -- a numpy array (embedding_dim, vocab_size) """ super(E...
from omero.gateway import BlitzGateway from omero.model import MapAnnotationI import argparse import logging import pandas import sys import os DESC = ''' Checks an IDR dataset to make sure each image/well has an annotation. If an annotation.csv is provided it will be checked that all images have a corresponding ent...
# -*- coding: utf-8 -*- # # Copyright (c) 2013 Clione Software # Copyright (c) 2010-2013 <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-...
import numpy as np import torch import torch.nn as nn import cv2 def centernet_nms(heat, kernel=3): pad = (kernel - 1) // 2 hmax = nn.functional.max_pool2d( heat, (kernel, kernel), stride=1, padding=pad) keep = (hmax == heat).float() return heat * keep def _topk(scores, K=40): batch, cat...
from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) import tensorflow as tf import matplotlib.pyplot as plt import random as ran # 시각화를 위한 변수 및 함수들 SHOW_TRAIN_EXAMPLE = 1 SHOW_PREDICTION = 20 def display_trainData(num, train_size): x_train = ...
import time, argparse, json, configparser, pprint from rapidfuzz import fuzz, process from pypresence import Presence # Functions def lower_if_exists(lie_argument): if lie_argument: lie_output = lie_argument.lower() else: lie_output = lie_argument return lie_output def fu...
#!/usr/bin/env python ''' Created on Apr 3, 2015 @author: <NAME> <<EMAIL>> ''' from __future__ import division import sys import os.path # append base path to sys.path script_path = os.path.split(os.path.realpath(__file__))[0] sys.path.append(os.path.join(script_path, '..', '..')) import argparse import datetime im...
""" run mondrian with given parameters """ # !/usr/bin/env python # coding=utf-8 from mondrian import mondrian from utils.read_adult_data import read_data as read_adult from utils.read_informs_data import read_data as read_informs from utils.read_registration_data import read_data as read_registration import sys, copy...
import argparse import os from os.path import dirname import subprocess import time import json import datetime import random import shlex import requests from kafka import KafkaConsumer from analyze import analyze_kafka_dump class PopenWrapper: """ This class is a context manager that wraps subprocess.Pope...
"""livedoor dataset loader livedoor ニュースコーパスのデータセットを読み込む available: https://www.rondhuit.com/download.html livedoor ニュースコーパス - トピックニュース http://news.livedoor.com/category/vender/news/ - Sports Watch http://news.livedoor.com/category/vender/208/ - ITライフハック http://news.livedoor.com/...
# Copyright 2021-2022 NVIDIA 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 ...
# Purpose: dxf objects wrapper, dxf-objects are non-graphical entities # all dxf objects resides in the OBJECTS SECTION # Created: 22.03.2011 # Copyright (C) 2011, <NAME> # License: MIT-License from __future__ import unicode_literals __author__ = "mozman <<EMAIL>>" import warnings from contextlib import contextmanager...
""" Monitor servers through HAProxy A monitor can be configured to check a different set of conditions for each service Configuration happens through the final ctor parameter, which is a dictionary where the key is a regex used to match the service name and the value is a list of conditions where a condition ...
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = r''' --- module: digital_ocean_tag short_descripti...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @File : publish.py @Time : 2019-07-01 20:58 @Author : <NAME> @Contact : <EMAIL> @Description: @License : (C) Copyright 2016-2017, iFuture Corporation Limited. """ from mongo_db_util import get_wallpaper_data, find_news, recommendation_media ...
''' Goal1: an LSTM where the weight matrices have a block structure so that information flow is constrained Data is assumed to come in [block1, block2, ..., block_n]. Goal2: Dynamic parameter sharing between blocks (RIMs) ''' import torch import torch.nn as nn from .GroupLinearLayer import GroupLinearLayer ''' Giv...
import tensorflow as tf import argparse import os import time from model import Custom_Model from preprocess import load_data import requests requests.packages.urllib3.disable_warnings() import ssl try: _create_unverified_https_context = ssl._create_unverified_context except AttributeError: pass else: ssl....
import turtle import random import time delay = 0.3 # reading high score from file def reading(): with open("highScore.txt") as file: x = file.read() # if file is empty, it will return None and this will cause error while comparing with current score if not x: x = 0...
# coding=UTF-8 import operator from xml.sax.saxutils import escape # escape string to valid xml labels = { 'en': { 'cvheading': 'Consultant profile', 'profile': 'Profile', 'period': 'Period', 'client': 'Client', 'techs': 'Technologies/Methods', 'workplace2': 'Workplace', 'school': 'School', 'experien...
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 __copyright__ = ('Copyright Amazon.com, Inc. or its affiliates. ' 'All Rights Reserved.') __version__ = '2.6.0' __license__ = 'MIT-0' __author__ = '<NAME>' __url__ = 'https://github.com/aws-samples/sie...
#!/usr/bin/env python # -*- coding: utf-8 -*- # System libs import json import colorsys import numpy from pandas.io.json import json_normalize import plotly.graph_objs as go import plotly.offline as plotly colors = {'pref': 'rgb(85, 239, 196)', '1': 'rgb(255, 234, 167)', '2': 'rgb(250, 177, 160)', '3': 'rgb(255, 1...
from flask import Blueprint, render_template, request from randomchat.settings import settings # import socketio from flask_socketio import SocketIO import random import logging # Configuration # Event table # Default built-in SocketIO events are not in the table EVENTS = { 'PAIRFOUND' : 'pairfound', 'PAIRLOST' :...
import os import re import sys import platform import subprocess from setuptools import setup, Extension from setuptools.command.build_ext import build_ext from setuptools.command.sdist import sdist as orig_sdist from distutils.version import LooseVersion BASEDIR = os.path.split(os.path.abspath(__file__))[0] class P...
""" This module provides the interface for accessing tmdb """ import os import requests import json from typing import List, Dict, Optional from .movie import Movie import sys API_URL = "https://api.themoviedb.org/3" API_KEY = os.environ.get("TMDB_API_KEY") def make_api_url(path: str, params: Optional[Dict[str, st...
""" Script to generate segmented datasets of Imagenet12. """ # All imports import sys import os import random import numpy as np from PIL import Image import json import torch import torchvision import torchvision.transforms as transforms import torch.nn.functional as F import torch.nn as nn import torch.optim as opt...
import numpy as np ## Some vector calculus functions def unit_vector(a): """ Vector function: Given a vector a, return the unit vector """ return a / np.linalg.norm(a) def d_unit_vector(a, ndim=3): term1 = np.eye(ndim)/np.linalg.norm(a) term2 = np.outer(a, a)/(np.linalg.norm(a)**3) answer ...
import os import codecs import time import numpy as np import tensorflow as tf import process from model import Cell from settings import * embedding, word2idx = process.load_embedding("models/corpus.word2vec")#加载embeddings Q = [] #问题 T = [] #正确答案 F = [] #错误选项 stop_words = codecs.open("models/unused.txt", 'r', encodin...
#!/usr/bin/env python3 # Derived from https://marcobonzanini.com/2015/03/02/mining-twitter-data-with-python-part-1/ and following parts by <NAME> (http://marcobonzanini.com/) (licensed under a Creative Commons Attribution 4.0 International License (http://creativecommons.org/licenses/by/4.0/)) from nltk.tokenize import...
import functools import absl.flags as flags import tensorflow as tf import utils FLAGS = flags.FLAGS def __crop(image, is_training, crop_size): h, w, c = crop_size[0], crop_size[1], image.shape[-1] if is_training: return tf.random_crop(image, [h, w, c]) else: dy = (tf.sha...
# -*- coding: utf-8 -*- import sys import StringIO import json import logging import random import urllib import urllib2 import pickle import datetime #from pytz.gae import pytz # for sending images from PIL import Image import multipart # standard app engine imports from google.appengine.api import urlfetch from go...
from __future__ import annotations import os import struct from spacepackets.ecss.tm import CdsShortTimestamp, PusVersion, PusTelemetry from spacepackets.ecss.definitions import PusServices from tmtccmd.pus.obj_id import ObjectId from tmtccmd.tm.base import PusTmInfoBase, PusTmBase from tmtccmd.utility.logger import ...
# pylint: disable=wrong-import-order from ._version import __version__ import os from datetime import datetime from csh_ldap import CSHLDAP from flask import Flask, redirect, render_template, g from flask_migrate import Migrate from flask_pyoidc.flask_pyoidc import OIDCAuthentication from flask_sqlalchemy import SQLA...
import numpy as np from utils import get_features_fewshot_full_library import os, random import torch import torch.nn as nn import argparse import pickle model_names = ['resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152', 'densenet121', 'densenet161', 'densenet169', 'densenet201'] # model_names...
import utils as uts from thirdparty import log_mvnpdf, log_mvnpdf_diag import numpy as np from scipy.misc import logsumexp import online from gaussEM import GaussEM EPS = np.finfo(float).eps class Incremental(online.OnlineEM): def __init__(self, param): super().__init__(param) self.skip = int(para...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Functions for plotting streamer shadow. ''' # idea: Add averaging line to the shadow # idea: Add 3D shadow # idea: Add detailed shadow (details/scatter, existing+new) import numpy as np import logging from .. import plotterXYRZ logger = logging.getLogger(__name__)...
# # Copyright 2022 DMetaSoul # # 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, ...
import shutil import os.path import requests from cStringIO import StringIO from urlparse import urljoin from httmock import urlmatch, HTTMock from django.contrib.auth import authenticate from django.core.files.storage import get_storage_class from django.core.files.uploadedfile import UploadedFile from django.core.u...
from .gold_cat_gen_sketch import load_rnn_model, complete_drawing from .cat_train import create_mlp from .common import * import copy import sys import nnExplain.genExp as exp from nnExplain.utils import verbose from nnExplain.utils import Timeout def complete_until_satisfy(drawing, gen_model, gen_sess, dis_sess, pre...
import tensorflow as tf import keras import numpy as np import random import collect_data as cdata import epl print(tf.version.VERSION) def makeModel(input_len, output_len): model = keras.Sequential([ keras.layers.Dense(8, activation='sigmoid', input_shape=(input_len,)), keras.layers.Dense(output...
import logging import random import time import discord from .utils import find class Client(discord.Client): """Quartermaster client.""" def __init__(self, logger=logging.getLogger(), *args, **kwargs): self.log = logger super().__init__(*args, **kwargs) async def send_message(self, de...
import datetime as dt import ipaddress import json import pickle import typing as t import uuid import dill import rsa from sqlalchemy import types, DateTime, Enum as _Enum from sqlalchemy.dialects.postgresql import UUID as pUUID Kwargs = t.Union[t.MutableMapping['str', t.Any]] Id = t.TypeVar('Id', int, str, uuid.UUI...