text
stringlengths
3.07k
12.6k
import io import os import re import shutil import sys import typing import webbrowser from time import sleep import click import pandas as pd from whylogs.app import SessionConfig, WriterConfig from whylogs.app.session import session_from_config from whylogs.cli import ( OBSERVATORY_EXPLANATION, PIPELINE_DES...
from .helper import parse_rule_list, inherit_json from .exceptions import VersionNotFound from .utils import get_library_version from typing import Dict, List, Any from .natives import get_natives import platform import json import copy import os __all__ = ["get_minecraft_command"] def get_libraries(data: Dict[str,A...
import binascii import os from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import ugettext_lazy as _ from project.apps.user.managers import UserManager, ActionTokenManager from rest_framework.authtoken.models import Token from django.utils import timezone...
import os import sys import numpy as np import cv2 from PIL import Image import time BASE_DIR = os.path.dirname(os.path.abspath(__file__)) ROOT_DIR = os.path.dirname(BASE_DIR) sys.path.append(BASE_DIR) sys.path.append(os.path.join(ROOT_DIR, 'mayavi')) sys.path.append(os.path.join(BASE_DIR, '../kitti')) import kitti_uti...
############################################################################### # Version: 1.1 # Last modified on: 3 April, 2016 # Developers: <NAME> # email: m_(DOT)_epitropakis_(AT)_lancaster_(DOT)_ac_(DOT)_uk ############################################################################### from builtins import o...
""" @AmineHorseman Sep, 12th, 2016 """ import tensorflow as tf from tflearn import DNN import time import numpy as np import argparse import dlib import cv2 import os from skimage.feature import hog from parameters import DATASET, TRAINING, NETWORK, VIDEO_PREDICTOR from model import build_model window_size = 24 windo...
import flask from flask import request from flask import render_template from .web_support import * from .cli import cli ##################################################################### # STARING NEW FLASK SKELETON (Task 2 - flask) #check the config class LabelordWeb(flask.Flask): """ The class represent...
import argparse, sys, json, yaml import pandas as pd import asyncio from iotsim.utils import to_iterable from iotsim.runtime.destinations import known_destinations from iotsim.assembler import from_config if __name__ != '__main__': sys.exit("This program must be run as a standalone script") parser = argparse.A...
from django.db import models from django.contrib.humanize.templatetags.humanize import naturaltime from django.utils.html import escape, format_html from config import models as config_models from cached_property import cached_property from utils import notify_slack from django.dispatch import receiver from django.db...
import numpy as np import matplotlib import matplotlib.pyplot as plt from matplotlib.colors import LogNorm, PowerNorm, Normalize from scipy import fftpack def pix_intensity_hist(vals, generator, noise_vector_length, inv_transf, channel_axis, fname=None, Xterm=True, window=None, multichannel=False): """Plots a hist...
# sales / pickups / tries # ['date' => Carbon::parse('2017-03-03 00:00:00'),'barcode' => 123], # met de funcie get_random_entry krijg je random entry tussen de data: 2016-1-1 01:00:00' en '2017-12-31 01:00:00' # in combinatie met de barcodes uit de set barcodes import random import time barcodes = ['\'1234567891234\...
import fastscapelib_fortran as fs import numpy as np import xsimlab as xs from .grid import UniformRectilinearGrid2D @xs.process class TotalVerticalMotion: """Sum up all vertical motions of bedrock and topographic surface, respectively. Vertical motions may result from external forcing, erosion and/or ...
# -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright (C) 2020 Freie Universität Berlin # # This file is subject to the terms and conditions of the GNU Lesser # General Public License v2.1. See the file LICENSE in the top level # directory for more details. import atexit import os import shutil import subprocess imp...
import time from collections import ChainMap from typing import Any, Callable, Literal, Optional, Sequence, TypedDict from .dbapi import Cursor RowType = dict[str, Any] MessageTableType = TypedDict("Table", {"modified": list[RowType], "deleted": list[RowType]}) MessageType = TypedDict("Message", {"timestamp": int, "t...
import collections import gzip import itertools import os import torch import torchtext import onmt.inputters class SortedCounter(collections.Counter): """A Counter, with most_common replaced with a version that sorts results by count and key, rather than just count. The keys (counted elements) must be so...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division import yaml import json import urllib2 import csv import re with open('./config', 'r') as config_yaml: config = yaml.load(config_yaml) def update_output(docid, sentid, minerals, ages, locations, lemma): output.append({ "doc...
import pytest from mock import patch from backend.query_server import QueryServer @pytest.fixture def query_server(fake_queue_name, mock_pokedex): yield QueryServer(fake_queue_name, mock_pokedex) @pytest.fixture def mock_query_server_publish(): with patch( "backend.query_server.QueryServer._publish"...
from __future__ import unicode_literals import os import appdirs from reviewbot.config import config from reviewbot.utils.api import get_api_root from reviewbot.utils.filesystem import make_tempdir from reviewbot.utils.log import get_logger from reviewbot.utils.process import execute logger = get_logger(__name__) ...
import operator from typing import List import torch from torch.fx import GraphModule import mqbench.nn.qat as qnnqat from mqbench.utils.logger import logger from mqbench.utils.registry import register_model_quantizer from mqbench.prepare_by_platform import BackendType from mqbench.custom_quantizer import ModelQuanti...
from __future__ import print_function import os import time import json import numpy as np from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Lambda from keras.optimizers import Nadam as Trainer #from keras.optimizers import Adam as Trainer from keras.regularizers import WeightRe...
# # Copyright 2021 Splunk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, so...
import json import os from django.shortcuts import render, get_object_or_404, get_list_or_404 from django.http import HttpResponse, JsonResponse from django.core import serializers from django.core.exceptions import ObjectDoesNotExist from .models import ( MediaFile, ImagePrediction, AudioPrediction, Vi...
import torch import torchvision import torchvision.transforms as transforms import torch.nn.functional as F from torch import nn import os import matplotlib.pyplot as plt import sys import numpy as np sys.path.append('./') from args import opt sys.path.append('./lib/') from dataset import FruitFlyNeuronDataset from cv2...
import numpy import random from solution import solution def elitism(population, scores, bestIndividual, bestScore): """ This melitism operator of the population """ # get the worst individual worstFitnessId = selectWorstIndividual(scores) # replace worst cromosome with best one from previous...
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import formatter # m: number of machines # n: number of jobs # T: number of time indices # S: schedule # p: integer processing times # s: inclusive integer earlest starting times # f: exclusive itneger latest finishing times def new_schedule(...
#!/usr/bin/env python3 """ Copyright 2017, <NAME>, HKUST. Training script for local features. """ import os import time import yaml import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from model import training from preprocess import prepare_match_sets from utils.npy_utils import EndPoints fr...
import numpy as np import scipy.constants as c import math, cmath from sympy import * from math import e import numba from numba import jit import sympy as sp r, x, a, theta = symbols('r x a theta') init_printing(use_unicode=True) @jit(nopython=True, cache=True, parallel=True) def spherical_to_cartesian(r, theta, phi)...
from threading import Thread, Timer, Condition import time import random import traceback import animations DITHER_CEIL=173 class ImageManager: def __init__(self): self.gamma = bytearray(256) for i in range(256): if i>0 and i<28: self.gamma[i] = 0x81 else: ...
import discord from discord.ext import commands, tasks from discord.ext.commands import has_permissions, CheckFailure from typing import Union import random import json import utils.embed as embed from utils.colors import * import utils.converters as converters import os # ENV from dotenv import do...
import torch.nn as nn import torch import numpy as np class VNet(nn.Module): def __init__(self, nb_classes, in_channels=1, depth=5, start_filters=16, batchnorm=True, mode="AE", input_size=None): assert mode in ['AE', 'classifier'], "Unknown mode selected, currently supported are: 'AE' an...
################################################## ## M5Hamote - A HomeAssistant remote on M5Paper ################################################## ## Author: @paeber ## Github: https://github.com/paeber/m5paper-homeassistant-remote ## Copyright: Copyright 2021, PaEber Electronics ## Version: 0.0.1 ## Status: alpha #...
#!/usr/bin/python # -*- coding: utf-8 -*- """ Copyright 2020 THG / The Hut Group 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 Unles...
''' Author <NAME> Date 5/21/2021 utility functions for train and predict data generators ''' import cv2 import numpy as np import re from joblib import Parallel, delayed def sort_frame_crop_filenames(filenames): def find_frame_crop_number(filename): filename = filename.split('/')[-1] ...
''' 间接平差 main.py ''' import pandas as pd import numpy as np import sys np.set_printoptions(threshold=sys.maxsize) #print显示完整array from gnssnet import * import math def Save2Excel(mats,name): data = pd.DataFrame(mats) writer = pd.ExcelWriter("C:\\Users\\sheld\\Desktop\\111\\"+ "间接平差的" +name + ".xlsx")...
# -*- coding: utf-8 -*- """ """ import os import shutil from binascii import hexlify from pathlib import Path from unittest.mock import MagicMock import pytest from lxml import etree as et from werkzeug.datastructures import FileStorage from pynuget import create_app from pynuget import core DATA_DIR = os.path.join(...
''' Author: <NAME> Description: Module to test the ODA algorithm and targeted landing. ''' from Camera import camera from Algorithms import create_samples as cs from Algorithms import discretize as disc from Algorithms import voronoi as voronoi from Algorithms import gap_detection as gd from process_frames import plot...
# the python script for finding the best kali linux mirror # according to your country, (having the lowest latency) # designed by Mrsingh2002 (https://github.com/mrsinghh2002) import re import sys import subprocess import urllib import xmltodict from threading import Thread import os # values hostlist = dict() resul...
import csv import logging from pathlib import Path from typing import Union import click import numpy as np from blender import Blender, Blend from blender.catalog import blend2cat, CATALOG_HEADER def save_img(blend: Blend, idx: int, prefix: str, outdir: Union[Path, str] = ".") -> None: np.save(f"{outdir}/{pref...
import math from time import time as _time from typing import Iterator, Tuple _YEAR = 33177600 _MOON = 2764800 _DAY = 86400 _HOUR = 3600 _MINUTE = 60 _SECOND = 1 _EORZEA_MINUTE = 60 _EORZEA_BELL = 60 _EORZEA_SUN = 24 _EORZEA_MOON = 32 _EORZEA_YEAR = 12 _EORZEA_TIME_CONST = 3600.0 / 175.0 _MILLISECOND_EORZEA_PER_MINUTE...
# Copyright 2015 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. from collections import defaultdict import datetime import json from apiclient import discovery from apiclient.errors import HttpError import httplib2 from ...
""" Example file showing a demo with 100 agents split in four groups initially positioned in four corners of the environment. Each agent attempts to move to other side of the environment through a narrow passage generated by four obstacles. There is no roadmap to guide the agents around the obstacles. """ import math i...
from __future__ import print_function from urllib import request import datetime import hashlib import json import os import re from io import BytesIO import gzip HEADERS = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', # noqa 'Accept-Charset': 'UTF-8,*;q=0.5', 'Accept-Enc...
# -*- coding: utf-8 -*- import json import os import click import logging from pathlib import Path from dotenv import find_dotenv, load_dotenv import pandas as pd from sklearn.model_selection import train_test_split import csv import pickle import src.data.unify_datasets as unify @click.command() @click.option('--d...
from email.mime.image import MIMEImage from email.utils import unquote from pathlib import Path from django.core.mail import EmailMessage, EmailMultiAlternatives, make_msgid from .utils import UNSET class AnymailMessageMixin(EmailMessage): """Mixin for EmailMessage that exposes Anymail features. Use of thi...
# -*- coding: utf-8 -*- from __future__ import division from ..exceptions import ValidationError, ConversionError, ModelValidationError, StopValidation from ..transforms import export_loop, EMPTY_LIST, EMPTY_DICT from .base import BaseType class MultiType(BaseType): def validate(self, value): """Report ...
import fiona import numpy as np import pandas as pd import geopandas as gpd import geojson from shapely.geometry import Point, LineString from six import iteritems from six.moves import reduce from itertools import chain, count, permutations import os, sys type_map = dict(MultiLineString="LineString", ...
# -*- coding: utf-8 -*- __author__ = 'raek' __updated__ = 'kmu' import requests # import datetime # import getdangers as gd # import makelogs as md # import types def get_warnings_as_json(region_ids, start_date, end_date, lang_key=1, simple=False, recursive_count=5): """Selects warnings and returns the json stru...
import numpy as np import matplotlib.pyplot as plt import time, psutil, sys, gc useColab = False if useColab: #!pip3 install hdf5storage from google.colab import drive drive.mount('/content/gdrive') import hdf5storage as hdf def loadData(filename): #Get data return hdf.loadmat(filename) def...
#!/usr/bin/env python3 import argparse import subprocess import re import sys import os from itertools import chain # Commands that will require a load db LOAD_DB_COMMANDS = ["load-db", "load-db-france"] def exec_command(command, debug=False): if debug: print("===>", " ".join(command), file=sys.stderr, ...
import os import json from numbers import Number from collections import Iterable, Mapping from operator import itemgetter from .config import set_class_path, JavaSettingsConstructorParams set_class_path() from jnius import autoclass, MetaJavaClass # Java DataTypes jMap = autoclass('java.util.HashMap') jArrayList = ...
import json import os import numpy as np from app import app from app import r from app.models import Student, Grade, Course from bson import json_util from flask import render_template, request, jsonify, Response, send_from_directory from flask.json import JSONEncoder from mongoengine.base import BaseDocument from mo...
# standart modules import os # blender modules import bpy import bpy_extras # addon modules from . import imp from . import exp from .. import icons from .. import log from .. import contexts from .. import version_utils from .. import ie_props from .. import utils def menu_func_import(self, context): icon = ic...
# -*- coding: utf-8 -*- from __future__ import (absolute_import, print_function, unicode_literals) import humanize from colorclass import Color, Windows from acli.output import (output_ascii_table, output_ascii_table_list, dash_if_none) from external.six import iteritems Windows.enable(auto_colors=True, reset_atexit...
import six import graphene from graphene_django.filter.filterset import setup_filterset, GrapheneFilterSetMixin from graphene_django.registry import get_global_registry from graphql_relay.connection.connectiontypes import Connection, PageInfo, Edge from graphql_relay.connection.arrayconnection import get_offset_...
import os from shlex import quote from fast_align.utils import run_bash_command def read_err(err): T, m = "", "" for line in open(err): if "expected target length" in line: m = line.split()[-1] elif "final tension" in line: T = line.split()[-1] return T, m def ali...
# -*- coding: utf-8 -*- # # Dao-Ke-Dao: Universal Message Module # # Written in 2019 by Moky <<EMAIL>> # # ============================================================================== # MIT License # # Copyright (c) 2019 <NAME> # # Permission is hereby granted, free of charge, to any ...
from flow.envs.base_env import SumoEnvironment from flow.core import rewards from flow.controllers.car_following_models import * from gym.spaces.box import Box from gym.spaces.discrete import Discrete from gym.spaces.tuple_space import Tuple import numpy as np class SimpleLaneChangingAccelerationEnvironment(SumoEnvi...
from typing import TYPE_CHECKING, Dict, Optional, Tuple, Union from pathlib import Path import cloup import click from cloup import ( command, option, help_option, Path as PathType, option_group, ) if TYPE_CHECKING: import pandas as pd def measure_tubes_polylines( ann_file: str, scales: U...
import os from django.db import models from django.db.models.signals import post_delete from django.dispatch import receiver from django.utils.crypto import get_random_string def upload_obfuscated_filename(instance, orig_filename): _filename, _ext = os.path.splitext(orig_filename) _fn = get_random_string(len...
#!/usr/bin/env python # -*- coding: utf-8 -*- # pylint: disable-msg=C0103 ################################################################################ # Copyright (c) 2006-2017 <NAME>. # All rights reserved. This program and the accompanying materials are # made available under the terms of the MIT License whic...
import numpy as np import time nodes = [] class node: def __init__(self, symbol): self.symbol = symbol self.edges = [] self.shortest_distance = float('inf') self.shortest_path_via = None nodes.append(self) def add_edge(self, node, distance): edge = [node, dist...
################################################################## # # Trap calibration with stage oscillation (by <NAME>) # Ref: Tolic-Norrelykke et al. (2006) # ################################################################## from __future__ import division, print_function, absolute_import import numpy as ...
# Standard Library import copy import gzip import json from typing import List # Third Party from loguru import logger # Local import bel.core.mail import bel.core.settings as settings import bel.core.utils import bel.db.arangodb as arangodb import bel.db.elasticsearch as elasticsearch import bel.resources.namespace ...
import json import collections import re import attr from clldutils.source import Source from clldutils.licenses import find from ldh.util import REPOS @attr.s class Rights(object): name = attr.ib() url = attr.ib() @attr.s class Creator(object): type = attr.ib(default='PERSON') role = attr.ib(defa...
# Copyright (C) 2022 <NAME> <<EMAIL>> # SPDX-License-Identifier: MIT # # pylint: disable=invalid-name """Generates argument_specs.yml from variables parsed in role. Usage: vars2specs.py [-c] [-r DIR] Options: -c Parse all roles in a collection [default: no] -r DIR --role_dir=DIR Input r...
from enum import Enum from trader.combat import Combat, CombatEventCode from trader.search import Search, SearchAction, SearchEventCode from trader.trade import Trade class EncounterState: """A base class for all encounter state objects.""" def doTurn(self, encounter): """ Do the n...
import random from discord.ext import commands import discord from cogs.menus import Menus def get_role(guild): return discord.utils.get(guild.roles, name='Giveaway') async def get_entrants(guild, remove=True): role = get_role(guild) entrants = [] for m in guild.members: if role in m.roles...
# A simple simulator for SHA+XRAM from mmio import mmiodev, NOP, RD, WR import sha as SHAFunc def as_chars(s, n): b = [] for i in xrange(n): byte = s & 0xff s >>= 8 b.append(byte) return [chr(i) for i in b] def to_num(s, n): num = 0 for i in xrange(n): num |= (ord(s...
import os import shutil import subprocess import sys import time MMT_HOME = os.path.abspath(os.path.join(__file__, os.pardir, os.pardir, os.pardir, os.pardir, os.pardir)) sys.path.insert(0, MMT_HOME) os.environ['LD_LIBRARY_PATH'] = os.path.join(MMT_HOME, 'build', 'lib') os.environ['LC_ALL'] = 'en_US.UTF-8' os.envir...
# -*- coding: utf-8 -*- """ Created on Thu May 16 13:06:17 2019 @author: Ayush """ import random, math random.seed(0) def r_matrix(m, n, a = -0.5, b = 0.5): return [[random.uniform(a,b) for j in range(n)] for i in range(m)] def sigmoid(x): return 1.0/ (1.0 + math.exp(-x)) def d_sigmoid(y)...
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function import json import logging.handlers import os import ansible import firebase_admin import hashids from ansible.cli import CLI from ansible.inventory.host import Host from ansible.inventory.manager import InventoryManager from ansible.parsi...
import csv import json import os import random from genericpath import exists from .base import ErConnector from .address import add_address, get_address_type_id_by_name from .communication import list_communication_methods, add_communication_method from .owner import add_owner class Seed(object): def __init__(...
""" Enable construction of containers with uniform item type(s) """ # std libs import warnings as wrn from abc import ABCMeta from collections import abc # local libs from recipes.iter import first_true_index from recipes.functionals import echo0, raises as bork class OfTypes(ABCMeta): """ Factory that cre...
import pytest from tweet_nlp_toolkit.prep.token import Token, WeiboToken from tweet_nlp_toolkit.prep.tokenizer import white_space_tokenize, tweet_tokenize, Detokenizer, chinese_tokenize, japanese_tokenize, \ _is_chinese, _is_japanese, thai_tokenize, _is_thai, weibo_tokenize @pytest.mark.parametrize(("text", "exp...
from datetime import timedelta from unittest import mock import pytest from django.utils import timezone from rest_framework import status from rest_framework.test import APIClient from apps.accounts.factories import UserFactory from apps.costcontrol.factories import ( BalanceRecordFactory, ProceedCategoryFac...
# coding=utf-8 import json import re from typing import List import pandas as pd from collections import defaultdict from dataclasses import dataclass import numpy as np from backend.integrations import database def normalize_test_name(tests: np.ndarray): """ Normalize test names to match database. - ...
# Copyright 2018 The TensorFlow Authors All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # J.V.Ojala 17.11.2021 # coinstar import json import datetime import sys, getopt import status import gui def time_to_posix(year, mon, day, hour=0, min=0, sec=0): """Takes date and time and returns POSIX timestamp in seconds""" try: time_object = datetim...
#!/usr/bin/env python3 # SPDX-License-Identifier: MIT import sys, pathlib import time sys.path.append(str(pathlib.Path(__file__).resolve().parents[1])) from m1n1.setup import * from m1n1.loadobjs import * import argparse import numpy as np argparser = argparse.ArgumentParser() argparser.add_argument("-d", "--domain",...
from time import time import torch import argparse from flask import Flask, request, render_template, Response import shutil from iterativeutil import * import os os.sys.path.append("..") from model_backup import G,D from util import load_image, save_image app = Flask(__name__) prev_G_path = 'default.pt...
import pickle import json import argparse import cv2 import os import numpy as np import torch import matplotlib.pyplot as plt import matplotlib.image as mpimg import matplotlib.patches as patches import matplotlib.lines as lines from tqdm import tqdm import _init_paths from core.config import cfg from datasets_rel.p...
# Keypirinha launcher (keypirinha.<EMAIL>) # Copyright 2013-2018 <NAME> <<EMAIL>> import os import stat from . import _glob __all__ = ["FsEntry", "globscan", "iglobscan"] _IS_WINDOWS = os.name.lower() == "nt" class FsEntry: """A :py:class:`os.DirEntry` compatible class.""" def is_hidden(self, f...
# Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
# To download ERA Interim data from the ECMWF data server # Download all the files for a year or selected months # Timestep is 6hrs # Resolution is 0.75X0.75 degree, area is global # to change them change the relative fields # Use: change year and adjust mntlist if necessary # python erai_download_full.py # depend...
import cv2 import numpy as np import os import glob from random import shuffle #from tqdm import tqdm import os, fnmatch import torch from torch import autograd, nn, optim import torch.nn.functional as F from time import time #input = autograd.Variable(torch.rand(batch_size, input_size))-0.5 #target = autograd.Variab...
import numpy as np import pandas as pd import matplotlib.pyplot as plt aux = { 'get_server': 'Get server delay', 'start_session': 'Start session delay', 'stop_session': 'Stop session delay', 'srv_request': 'Service request delay', } def plot_ue_service_delay(time, delay, ue_id=None, service_id=None,...
# -*- coding: utf-8 -*- """ triangulate =========== Script : triangulate.py Author : <EMAIL> Modified : 2018-08-24 Purpose: triangulate poly* features Useage : References ---------- `<http://pro.arcgis.com/en/pro-app/arcpy/data-access/numpyarraytotable.htm>`_. `<http://pro.arcgis.com/en/pro...
import serial import time from squid import * import os.path import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) import Adafruit_GPIO.SPI as SPI import Adafruit_SSD1306 from PIL import Image from PIL import ImageDraw from PIL import ImageFont RST = None disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST) disp.begin() # Clear ...
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
import datetime import re from pyasn1.codec.der import decoder from ldap_shell.krb5 import constants, asn1 class KerberosException(Exception): pass def _asn1_decode(data, asn1Spec): if isinstance(data, str) or isinstance(data, bytes): data, substrate = decoder.decode(data, asn1Spec=asn1Spec) ...
from __future__ import annotations from collections import namedtuple from copy import deepcopy from typing import Dict, List, Optional, Tuple, Union import numpy as np from numpy.typing import ArrayLike, NDArray from simweights.powerlaw import PowerLaw from simweights.spatial import SpatialDist from .pdgcode impor...
import csv import os from datetime import datetime import time import locale import re from src.Entities import Restaurant, Product, Address, Customer, Order, Coupon from src.database import Database from src.logger import Logger class OrderData: SKIP_ROWS = 4 def __init__(self, fileName): self.fileN...
from typing import List import torch from deepclustering.method import _Method from deepclustering.model import Model from torch import Tensor class SubSpaceClusteringMethod(_Method): def __init__( self, model: Model, lamda: float = 0.1, lr: float = 0.0001, num_samples: in...
import torch import numpy as np from hparams import create_hparams as hps def mode(obj, model = False): if model and hps.is_cuda: obj = obj.cuda() elif hps.is_cuda: obj = obj.cuda(non_blocking = hps.pin_mem) return obj def to_arr(var): return var.cpu().detach().numpy().astype(np.float32) def get_mask_from_le...
import pandas as pd import matplotlib.pyplot as plt import requests import numpy as np from math import floor from termcolor import colored as cl plt.style.use('fivethirtyeight') plt.rcParams['figure.figsize'] = (20, 10) # EXTRACTING STOCK DATA def get_historical_data(symbol, start_date): api_key = 'YOUR API K...
""" Created on Tuesday 20 February 2018 Last update: Sunday 11 March 2018 @author: <NAME> <EMAIL> Solution for the lecture optimal transport """ from itertools import permutations import numpy as np from sklearn.metrics.pairwise import pairwise_distances from random import shuffle blue = '#264653' green = '#2a9d8f'...
from Config import Config from Classes import UploadEvent, PurchaseSessionEvent, Artwork def get_upload_events(df): events = [ UploadEvent(upload_date, artwork_id) for artwork_id, upload_date\ in zip(df.artwork_id_hash, df.upload_timestamp) ] events.sort(key=lambda e: e.timestamp) retur...
#`!/usr/bin/env python3 # -*- coding: utf-8 -*- """This file contains a class for a house listing The listing class contains functionality to get all info for a listing""" import re from enum import Enum from .google_maps import GMaps __author__ = "<NAME>" __credits__ = ["<NAME>"] __Lisence__ = "MIT" __maintainer__...
# ex:ts=4:sw=4:sts=4:et # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- from __future__ import absolute_import import sys import time import re import os import io import platform from datetime import timedelta from svtplay_dl.utils import is_py2, filenamify, decode_html_entities, ensure_unicode from ...
# -*- coding:utf-8 -*- __author__ = 'eric' from . import api from ..models import * from flask import jsonify, g, abort from .decorators import permission_required from .authentication import auth from .errors import ValidationError @api.route('/assets/') @auth.login_required @permission_requi...