text
stringlengths
3.07k
12.6k
import machine, time, logging import uasyncio as asyncio from esp32_adccal import ADCCal log = logging.getLogger(__name__) log.setLevel(logging.DEBUG) class Anemo: """ Anemo implements functions to determine average wind speed and gust speed as measured by an anemometer attached to a pulse counter input ...
from typing import List, Optional from .tokenize import TokenKind, Tokenizer, Token from .ast import * from . import LimeError def text_position_of_token(tok: Token) -> TextPosition: return TextPosition( tok.line, tok.col, tok.col + len(tok.value) ) class Parser: tk: Tokenizer ...
import pytest from django.urls import reverse from django.utils import timezone from rest_framework.status import ( HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN, HTTP_405_METHOD_NOT_ALLOWED) from ..utils import ALL_METHODS, check_method_status_codes list_url = reverse('monitoring:v1:valid_parking-list') def detail...
from django.template.loader import render_to_string from django.conf import settings from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger, Page, InvalidPage from rest_framework import pagination from collections import OrderedDict from rest_framework.response import Response from rest_framework.exce...
import numpy as np from ..cluster import cluster import time class Options(): def __init__(self): self.max_iter = 0 # maximum number of iterations self.max_error = -np.inf # maximum allowed error self.limit_space = True # optional coordinate bound control self.sp...
#!/usr/bin/env python3 import pandas as pd import json import sys track1_zoom_url = '' track2_zoom_url = '' remo_url_day_1 = '' remo_url_day_2 = '' remo_url_day_3 = '' remo_url_social_night = '' slack_url = '' remo_pre_url_1 = '' remo_pre_url_2 = '' remo_pre_url_3 = '' session_slacks = { 'Plant Genomics':'', 'Metagen...
""" Runs the trajectory solver on RMS JSON files. """ import os import sys import glob import json import argparse import numpy as np from wmpl.Formats.CAMS import MeteorObservation, prepareObservations from wmpl.Formats.GenericArgumentParser import addSolverOptions from wmpl.Trajectory.Trajectory import Trajectory...
''' Version: 0419 Utility Maximizing Learning Plan Simulations # Brute force, Greedy, ILP Solver # Support Additive cost function ''' import networkx as nx import numpy as np import random,copy, time, json, os, argparse, csv, datetime from gurobipy import * from UMLP_solver import * import utils # INPUT desc...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Copyright 2020 Huawei Technologies Co., Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless requir...
# Copyright 1999-2021 Alibaba Group Holding Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
# # -*- coding: utf-8 -*- # Copyright 2019 Red Hat # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # utils from __future__ import absolute_import, division, print_function __metaclass__ = type from ansible.module_utils.six import iteritems from ansible.module_utils.netw...
""" Scrub PII from your data """ # pylint: disable=invalid-name # pylint: disable=c-extension-no-member from typing import Dict, Union from numbers import Number import dateutil.parser import rapidjson REDACTED = "redacted" SCRUB_CSDS_PII_CHANNEL_INSTRUCTIONS = [ {"channel": "player_name"}, {"channel": "head...
import re import json import logging from .base import Filter from ..models import GroupVersionKind log = logging.getLogger(__name__) readonly_re = re.compile(r'read[ -]only', re.I) default_re = re.compile(r'defaults?\s+(?:to|\w+\s+is)\s+[\'"`]?([^"\'`\s\.\,\(]+)[\'"`]?[\,\.\s\(]', re.I) true_re = re.compile(r'true|y...
import os import datetime import redis import requests from flask import current_app from nomics import Nomics from rq import Queue, Worker, Connection from project.server.main.utils.formatter import strfdelta basedir = os.path.abspath(os.path.dirname(__file__)) def os_get(var): return os.environ.get(var) de...
import requests import sys from cmd import Cmd from time import sleep PIECE_NAME = { 3: 'bishop', 5: 'king', 7: 'knight', 9: 'pawn', 11: 'queen', 13: 'rook', } PROMPT = '> ' BRIGHT_GREEN = '\u001b[42;1m' RESET = '\u001b[0m' SELECTED_PIECE = f'{ BRIGHT_GREEN }{{}}{ RESET }' TOP_BOARD_OUTPUT_SHE...
from sklearn.metrics import coverage_error, accuracy_score from sklearn.metrics import label_ranking_loss from sklearn.metrics import label_ranking_average_precision_score from sklearn.metrics import hamming_loss from sklearn import metrics from collections import Counter import math import numpy as np def patk(predi...
import os import logging import json import io import time from collections import OrderedDict import jinja2 from homeassistant.util.yaml import loader from homeassistant.exceptions import HomeAssistantError _LOGGER = logging.getLogger(__name__) def fromjson(value): return json.loads(value) jinja = jinja2.Envi...
#!/usr/bin/env python3 from test_framework.test_framework import BitcoinTestFramework from test_framework.messages import ( COIN, COutPoint, CTransaction, CTxIn, CTxOut, ToHex, FromHex) from test_framework.script import ( CScript, hash160, OP_EQUAL, OP_HASH160, OP_TRUE, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of ObjectPath released under MIT license. # Copyright (C) 2008-2010 <NAME> import datetime import sys, os try: import pytz TIMEZONE_CACHE = {"UTC": pytz.utc} except ImportError: pass from objectpath.core import STR_TYPES HOURS_IN_DAY = 24 now ...
import matplotlib.pyplot as plt from abc import ABCMeta, abstractmethod, abstractproperty def plot_attributes(mrs, file_name): colors = ['red', 'blue', 'orange', 'green', 'yellow', 'black'] labels = ['mr_ref', 'mr_1', 'mr_2', 'mr_3', 'mr_4', 'mr_5'] markersizes = [8, 6, 4, 2, 1, 0.5] lc = len(colors) ...
#!/usr/bin/env python from builtins import str from builtins import range import os import unittest from io import StringIO import configparser from pyidr.screenio import ScreenWriter, ScreenReader, ScreenError class TestScreenIO(unittest.TestCase): def setUp(self, screen_name=None): self.name, self.ro...
# encoding: utf-8 from __future__ import absolute_import, unicode_literals import io from mopidy.m3u import translator from mopidy.models import Playlist, Ref, Track def loads(s, basedir=b'.'): return translator.load_items(io.StringIO(s), basedir=basedir) def dumps(items): fp = io.StringIO() translat...
# coding=utf-8 # Copyright 2021 The Mesh TensorFlow Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
"""This script generates REP-0132 CHANGELOG.rst files for git or hg repositories.""" from __future__ import print_function import argparse import logging import os import sys from catkin_pkg.changelog import CHANGELOG_FILENAME from catkin_pkg.changelog_generator import generate_changelog_file, generate_changelogs, g...
import random import operator import numpy as np from copy import deepcopy class point: def __init__(self,listLine): self.feature = listLine self.label = None class label: def __init__(self,listLine): self.feature = listLine self.cluster = [] # 載入data filenamme = '/...
import time import math import threading from collections import namedtuple import cv2 import numpy as np from scipy.stats import linregress from camera import Camera from detect_image import RFBNetDetector from uart import Uart class Memory(): def __init__(self, max_size=3): self.max_size = max_size ...
import torch from torch import nn import torch.nn.functional as F import numpy as np from collections import OrderedDict activations = { 'NON': lambda x: x, 'TANH': torch.tanh, 'SIGMOID': F.sigmoid, 'RELU': F.relu, 'ELU': F.elu, } class Linear(nn.Linear): def __init__(self, *args, **kwargs): ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch from torchtext import data from torchtext.datasets import SequenceTaggingDataset, CoNLL2000Chunking from torchtext.vocab import Vectors, GloVe, CharNGram import numpy as np import random import lo...
import ast def append(li, item): if item in li: return li.append(item) class CodeVisitor(ast.NodeVisitor): def __init__(self): self.methodName = [] self.nodeType = "" self.apiSequence = [] self.tokens = [] self.classInstance = {} self.classLevel =...
# -*- coding: UTF-8 -*- """ @author: hichenway @知乎: 海晨威 @contact: <EMAIL> @time: 2020/5/9 17:00 @license: Apache tensorflow 模型 """ import tensorflow as tf import numpy as np tf.logging.set_verbosity(tf.logging.ERROR) class Model: def __init__(self, config): self.config = config self.placeholders(...
# IMPORTS import pandas as pd import math import os.path import time from bitmex import bitmex import matplotlib.pyplot as plt import numpy as np import tulipy as ti # from binance.client import Client from datetime import timedelta, datetime from dateutil import parser from dateutil.tz import tzutc from finta import ...
# -*- coding: utf-8 -*- """Utilities for Bio2BEL.""" import hashlib import logging import os import pathlib import shutil import types from typing import Iterable, Mapping, Optional, Tuple from urllib.parse import urlparse from urllib.request import urlretrieve import requests from pkg_resources import UnknownExtra,...
from types import MemberDescriptorType from .._operators import OP_NAMES, UNARY, BINARY, COMPARISON from ..functions import call ZOMBIE_CLASSES = {} UNARY_METHODS = [OP_NAMES[op] for op in UNARY] UNARY_METHODS.extend(["iter"]) BINARY_METHODS = [OP_NAMES[op].rstrip("_") for op in COMPARISON + BINARY] RBINARY_METHODS =...
import click import logging import zmq import socket import urllib.parse import contextlib import time import attr import sys import os import psutil @contextlib.contextmanager def ioloop(context, *sockets): """Render a running IOLoop""" from zeeko.cyloop.loop import DebugIOLoop loop = DebugIOLoop(contex...
######################################################### # 2021-08-08 14:21:32 # AI # test programming ROM function # this test code are only suit for the simulator, # the real hardware has timing constraints. ######################################################### import random from .. import testutil as u from ....
import os, datetime from bs4.element import ResultSet basedir = os.path.dirname(__file__) category_urls = [ ] categories_filepath = os.path.join(basedir, 'categories.txt') with open(categories_filepath, 'r+') as f: category_urls = [ line.strip() for line in f.readlines() ] # Enter the products that could ...
import pandas as pd import matplotlib import matplotlib.pyplot as plt import mplhep as hep from matplotlib.ticker import AutoMinorLocator #====================================================================================================================== def start(): """ Define initial setup to be used in t...
import argparse import glob import os import shutil import PerformanceAnalyser as perfAnalyser import DatasetGenerator import Evaluator import pwd HADOOP_PROJECT_MAIN = "/user/" + pwd.getpwuid(os.getuid())[0] + "/project" HADOOP_PROJECT_PATH_OUTPUT_SUBFOLDER = "/ratio_vol_td" HADOOP_PROJECT_PATH_INPUT = HADOOP_PROJECT...
import sys import re import json import datetime class TaskFormatter: def __init__(self, indention='\t', time_format='{hours}:{minutes:02}'): self.indention = indention self.time_format = time_format def format_task_list(self, task_list, indention_level=0): list_string = '' f...
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import time from datetime import datetime, timedelta from os import path from typing import List, Dict import requests from jinja2 import Template def list_jobs(jenkins_url, jenkins_user, jenkins_token) -> List[Dict]: resp = requests.get(f'{jenkins_u...
from __future__ import annotations import os import traceback from pathlib import Path from subprocess import CalledProcessError from typing import Callable, Dict, List, Optional from colorama import Style from cache import make_cache_store from common.hash_utils import HashState from common.shell_utils import sh as...
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, absolute_import, division from six.moves import range, zip, map, reduce, filter from six import string_types import numpy as np try: from tifffile import imwrite as imsave except ImportError: from tifffile import imsave import war...
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import cv2 from PIL import Image import matplotlib.pyplot as plt def disp2distribute(disp_gt, max_disp, b=2): disp_gt = disp_gt.unsqueeze(1) disp_range = torch.arange(0, max_disp).view(1, -1, 1, 1).float().cuda() gt_dist...
#! /usr/bin/env python3 from html.parser import HTMLParser import re import itertools class html_parser(HTMLParser): """Returns a list of paragraphs options= get_meta, get_img_meta""" #parser options parser_options = {'get_meta':True, 'get_img_meta':False} get_meta = parser_options['get_meta'] ...
from optimism.JaxConfig import * import optimism.EquationSolver as EqSolver from optimism.NewtonSolver import globalized_newton_step from optimism.NewtonSolver import newton_step from optimism import WarmStart Settings = namedtuple('Settings', ['penalty_scaling', 'target_co...
import math import json import random import numpy as np import multiprocessing NUM_CENTROIDS = 256 def segregate(attributearray, value): outlist = [] for i in range(0, len(attributearray)): if(attributearray[i] == value): outlist.append(i) return outlist def select_labels(labels, ids...
import dolfin as df from ufl import grad as ufl_grad import pulse from perspect.porousproblem import PorousProblem from perspect.lagrangian_particles import LagrangianParticles, RandomSphere,\ RandomCircle, ParticlesFromPoint def get_mechanics_geometry(geometry): retu...
""" Module to compute truth catalog values for lensed hosts in DC2 Run3.0i. """ import os import sys import glob from collections import defaultdict import logging import sqlite3 from astropy.io import fits import pandas as pd from lsst.sims.photUtils import PhotometricParameters from .synthetic_photometry import find_...
import os import json import sys import io import fileinput import string import urllib #required to open html documents import urllib2 #required in python 2.7 import re #required to remove html tags vie regex import codecs #required to open html files import nltk #requires python 3.5 or python 2.7 to install...
""" CountModel class for dispatching different types of count models and different types of estimation technqiues. """ __author__ = "<NAME> <EMAIL>" import numpy as np from spglm.glm import GLM from spglm.family import Poisson, QuasiPoisson class CountModel(object): """ Base class for variety of count-based...
#! /usr/bin/env python3 import os import queue import argparse import json import sys import subprocess import avocadoslack import multiprocessing import graphs from shared import output_file_name, replace_type from threading import Thread, Event from typing import List, Dict, Tuple from string import Template genera...
#!/usr/bin/env python3 """Get BGP neighbours from network devices for PDB.""" import os import sys import pprint import json import ipaddress import click from napalm import get_network_driver pp = pprint.PrettyPrinter(indent=2, width=120) prog_args = {} def parse_neighbours(neighbours): """Parse the bgp neig...
import json import flask from flask_cors import ( cross_origin ) from flask import ( Flask, request ) import logging from http.client import responses from flask.logging import default_handler from .external_api.auth import ( get_auth_token, validate_service_token, validate_user_token, is_fe...
# Copyright (c) 2014-2021, <NAME> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the ...
# Generate the Cython wrapping file. # Imports # ------------------------------------------------------------------------------------------------- from functools import lru_cache import json from pathlib import Path import os from pprint import pprint import re import sys from textwrap import indent from tqdm import...
""" Bitcoin Abuse Integration for Cortex XSOAR - Unit Tests file """ import io import pytest from BitcoinAbuse import BitcoinAbuseClient, bitcoin_abuse_report_address_command, bitcoin_abuse_get_indicators_command, \ update_indicator_occurrences, READER_CONFIG from CommonServerPython import DemistoException, Dict...
# Copyright (C) 2020 GreenWaves Technologies, SAS # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # This program...
# # For licensing see accompanying LICENSE file. # Copyright (C) 2022 Apple Inc. All Rights Reserved. # import os import importlib import argparse from utils import logger from utils.common_utils import check_frozen_norm_layer from utils.ddp_utils import is_master, is_start_rank_node from utils.download_utils import ...
"""Macros for defining static website content.""" _WEB_DIR = "web" def erb_file(name, srcs, out, bootstrap=False, main_template='default'): """Renders a collection of eRuby templates to an output file. See the //webgen:erb tool for documentation on template syntax. Args: name: rule name. src...
import numpy as np from PIL import Image, ImageDraw from .colors import * def colorize_class_preds(class_maps, no_classes): # class maps are level-batch-class-H-W np_arrays = [] for lvl in class_maps: lvl = map_color_values(lvl, no_classes, True) np_arrays.append(lvl) return np_arrays...
import copy from unittest import mock import matplotlib from matplotlib import pyplot as plt from matplotlib._pylab_helpers import Gcf import pytest @pytest.fixture(autouse=True) def mpl_test_settings(qt5_module, mpl_test_settings): """ Ensure qt5_module fixture is *first* fixture. We override the `mpl...
import time import json import logging import logging.config import sys import os sys.path.append(os.path.dirname(__file__)) from dagflow.event_center.base_request_filter import RequestFilter, RequestFilterStatus, auto_load_filter from dagflow.flow_operation import start_flow, continue_flow, specify_step_to_run from d...
#!/usr/bin/env python import os import pickle import argparse import numpy as np import torch import torch.optim as optim from torch.utils.data import DataLoader import deepclean_prod as dc import deepclean_prod.config as config # Default tensor type torch.set_default_tensor_type(torch.FloatTensor) # Use GPU if a...
import json from transformers import * import torch from torch.utils.data import Dataset import numpy as np import copy SPECIAL_TOKENS = ['[BOS]', '[EOS]', '[speaker1]', '[speaker2]', '[IMG]', '[TAG]', '[PAD]'] SPECIAL_TOKENS_DICT = {'bos_token':'[BOS]', 'eos_token':'[EOS]', 'additional_special_tokens':['[spea...
import argparse import random import socket import time import typing from urllib.parse import urlparse import requests from pyfiglet import Figlet from termcolor import colored from errors import FetchedError # URL for fetching relays onion_url = ( "https://onionoo.torproject.org/details?type=relay" "&runni...
# Copyright (c) 2009-2022 The Regents of the University of Michigan. # Part of HOOMD-blue, released under the BSD 3-Clause License. """Apply external fields to HPMC simulations.""" from hoomd.data.parameterdicts import ParameterDict from hoomd.data.typeconverter import NDArrayValidator from hoomd.hpmc import _hpmc fr...
# imports from phue import Bridge from subprocess import call import speech_recognition as sr import serial import requests import json class LightOrchestrator: def __init__(self): self.bridge = Bridge('192.168.0.186') self.bridge.connect() self.light_objs = self.bri...
# Copyright 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Base models for a luci build. Data models are prefixed by 'Luci' to indicate that Findit is supporting Luci builds. And also to differentiate from the dat...
# -*- coding: utf-8 -*- # Time : 2022/1/16 0:27 # Author : QIN2DIM # Github : https://github.com/QIN2DIM # Description: import os.path import shutil import sys from datetime import datetime from typing import List, Union, Dict, Optional import colorama import yaml from loguru import logger from selenium....
#! /usr/bin/env python """ Script to go through all the VOA sites and get sitemaps and extract from them additional sitemaps. """ import gzip import os import re import shutil from argparse import ArgumentParser from os.path import basename from typing import List, Optional, Generator, Iterable, Dict from urllib import...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Project : MeUtils. # @File : common # @Time : 2020/11/12 11:42 上午 # @Author : yuanjie # @Email : <EMAIL> # @Software : PyCharm # @Description : 单向引用,避免循环引用 import os import gc import re import sys import time from abc import abstr...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: DI<EMAIL> @mail: <EMAIL> Created on Sun Jan 12 17:06:39 2020 """ import boxx from boxx import * from boxx import os, setTimeout, mapmt, timegap, sleep, pathjoin import random import glob from bs4 import BeautifulSoup import requests import urllib.parse as ur...
import curses import curses.textpad import time, random from curses import wrapper stdscr = curses.initscr() curses.noecho() curses.cbreak() stdscr.keypad(1) curses.curs_set(0) # colors: color_separator = '.' color_closed = curses.ACS_CKBOARD color_empty = ' ' color_bomb = 'X' color_flag = 'F' # states: state_playin...
import json class Stack: def __init__(self): self.stack_items = [] def append(self, stack_item): self.stack_items.append(stack_item) return self def __repr__(self): stack_dump = '' for item in self.stack_items: stack_dump += str(item) return st...
import math, torch from src.adversarial_base import AdversarialBase from src.optimizer.evolve import SingleGenOptimization from heapq import * sign = lambda x: 0.0 if x == 0.0 else math.copysign(1, x) class HeapItem: def __init__(self, score, eps): self.score = score self.eps = eps def __lt_...
# -*- mode: python; encoding: utf-8 -*- # # Copyright 2014 the Critic contributors, Opera Software ASA # # 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/LI...
# coding=utf-8 from __future__ import print_function import numpy as np import tensorrt as trt import pycuda.driver as cuda import pycuda.autoinit from PIL import ImageDraw import cv2 import math import sys, os import common def load_engine(trt_runtime, plan_path): with open(engine_path, 'rb') as f: engi...
#----------------------------------------------------------------------------# # Imports #----------------------------------------------------------------------------# from flask import Flask, render_template, request, flash, redirect, url_for from werkzeug.utils import secure_filename # from flask.ext.sqlalchemy impo...
import eel import os import uuid import sys memes = [] dir_path = os.path.dirname(os.path.realpath(__file__)) dir_path = dir_path + '\web' x = list(os.walk(dir_path)) for file in x[0][2]: if (file.endswith('.jpg') or file.endswith('.png') or file.endswith('.jpeg')) and (file != 'previousArrow.jpg' and file != 'nex...
# -*- coding: utf-8 -*- from irc3.plugins.command import command import irc3 import json __doc__ = ''' ============================================== :mod:`irc3.plugins.social` Social networking ============================================== Add ``tweet`` and ``retweet`` commands. Extend the bot with ``.get_social_co...
import settings import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable import numpy as np import torchvision from torchvision import datasets, models, transforms import matplotlib.pyplot as plt import time import copy import os import cv2 import random import argparse import...
#!/usr/bin/python import string import sys import tempfile class LevelData: def __init__(self, numblocks, assoc, write_policy): self.numblocks = numblocks self.assoc = assoc self.write_policy = write_policy def die(msg): print(msg, file=sys.stderr) sys.exit(1) def xml_header(): ...
__source__ = 'https://leetcode.com/problems/maximal-square/' # https://github.com/kamyu104/LeetCode/blob/master/Python/maximal-square.py # Time: O(n^2) # Space: O(n) # # Description: Leetcode # 221. Maximal Square # # Given a 2D binary matrix filled with 0's and 1's, # find the largest square containing all 1's and re...
""" Utility for running YARA within the context of a disassembly. This utility extends and overwrites the existing YARA API to work correctly within a dragodis context. usage:: from rugosa import yara # Compile a yara rule in the same way as the original yara library. rule = yara.compile(source=rule_text...
###################################################################################################################### # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # # ...
################################################################################################################ # Authors: # # <NAME> (<EMAIL>) ...
from abc import ABC from bs4 import BeautifulSoup import json import requests class BaseHelper(ABC): """ An abstract class that can be derived to define a helper, a piece of code that can grab arbitrary data from websites. """ target_url = None def __init__(self, target_url): self.t...
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/home/h4ckfu/Code/test/TheGANs/MNIST_data/", one_hot=True) ################### All your functions are belong... ########################## # http://...
"""toil_container containers tests.""" from multiprocessing import Process from os.path import join import getpass import os import docker import pytest from toil_container import __version__ from toil_container import exceptions from toil_container.containers import _TMP_PREFIX from toil_container.containers import...
from dataclasses import dataclass from decimal import Decimal from typing import List, Literal, Optional, TypedDict from exapi.typedefs.binance import OCOOrderStatus, OCOStatus, OrderContingencyType, OrderExecutionType, OrderSide, \ OrderStatus, \ OrderType, \ TimeInForce class BinanceSocketSpotExecution...
import numpy as np from scipy.optimize import least_squares from scipy.integrate import odeint def sol_u(t, u0, alpha, beta): return u0 * np.exp(-beta * t) + alpha / beta * (1 - np.exp(-beta * t)) def sol_s(t, s0, u0, alpha, beta, gamma): exp_gt = np.exp(-gamma * t) if beta == gamma: s = s0 * ex...
import unittest from btc_hd_wallet.wallet_utils import Bip, Version, Key, Bip32Path class TestVersion(unittest.TestCase): def test_parse(self): with self.assertRaises(ValueError): Version.parse(version_int="152110212") with self.assertRaises(ValueError): Version.parse(vers...
'''The SuperText class inherits from Tkinter's Text class and provides added functionality to a standard text widget: - Option to turn scrollbar on/off - Right-click pop-up menu - Two themes included (terminal and typewriter) Compliant with Python 2.5-2.7 Author: @ifthisthenbreak ''' from Tkinter import Tk, Frame, ...
import os import cv2 import pandas as pd import numpy as np import paddle import paddle.nn as nn import paddle.nn.functional as F import random from network.shrnet import SHR from dataset.CVSIdata import loaders_default import argparse def accuracy(dataloaders, net, num_classes, disp=False): net.ev...
"""BRACS Dataset loader.""" import os import h5py import torch.utils.data import numpy as np from dgl.data.utils import load_graphs from torch.utils.data import Dataset from glob import glob import dgl from histocartography.utils import set_graph_on_cuda IS_CUDA = torch.cuda.is_available() DEVICE = 'cuda:0' if IS_...
import os import csv import random import itertools import PySide2.QtWidgets as qtw from embr_survey.common_widgets import JustText from pip._vendor import pytoml as toml from pkg_resources import resource_filename from PySide2.QtCore import Qt from PySide2.QtGui import QPixmap from embr_survey.common_widgets import Ju...
""" network.py Provides different network models. """ import numpy as np np.random.seed(1337) from keras.callbacks import Callback from keras.models import Sequential, Model from keras.layers import Activation, Dense, Dropout, Merge, Reshape, Input, merge from keras.layers import Convolution2D, MaxPooling2D from kera...
import json import asyncio import posixpath from typing import Tuple, List, Any import logging import aiohttp import sentry_sdk # type: ignore from sentry_sdk.integrations.aiohttp import AioHttpIntegration # type: ignore from quart import ( Quart, jsonify, request, Response, Bluepri...
# -*- coding: utf-8 -*- from SuperGLU.Util.Serialization import SuperGlu_Serializable from SuperGLU.Core.MessagingGateway import BaseService from SuperGLU.Core.Messaging import Message from SuperGLU.Core.MessagingDB import DBLoggedMessage, KC_SCORE_VERB, USER_ID_CONTEXT_KEY, TASK_ID_CONTEXT_KEY, TASK_HINT_VERB, TAS...
# Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you under # the Apache License, Version 2.0 (the "License"); you may # not use ...