text
stringlengths
3.07k
12.6k
from .asset_types import detect_asset_type, render_asset_html_tags, list_asset_types from webassets import Bundle, six from webassets.filter import get_filter __all__ = ('Package', 'PackageError') auto_filters = { "less": ("less", "css"), "coffee": ("coffeescript", "js"), "sass": ("sass", "css"), "s...
from typing import List, Tuple, Dict, Set from adventofcode.util.exceptions import SolutionNotFoundException from adventofcode.util.helpers import solution_timer from adventofcode.util.input_helpers import get_input_for_day class Decoder: def __init__(self, digits: List[str], results: List[str]): self.d...
from mapgen.maths import normalize, gauss_like from matplotlib import pyplot as plt import numpy as np N = (0, -1) E = (1, 0) S = (0, 1) W = (-1, 0) C = (0, 0) vnn_base = np.array([N, E, C, S, W])[:, ::-1] #(n, (x,y)) -> (n, (y,x)) class Base(dict): def __getattr__(self, item): return self[item] d...
from allauth.account.models import EmailAddress from django.contrib.auth import get_user_model, password_validation from django.utils.translation import gettext_lazy as _ from rest_auth.models import TokenModel from rest_auth.registration.serializers import RegisterSerializer from rest_framework import serializers f...
# -*- coding: utf-8 -*- import dash import dash_core_components as dcc import dash_html_components as html from matplotlib import pyplot as plt import pandas as pd import numpy as np import plotly.graph_objs as go from sklearn.neighbors import KNeighborsClassifier from sklearn.preprocessing import StandardScaler from s...
"""Various argparse-related support.""" import argparse from itertools import chain from snakeoil.cli import arghparse from snakeoil.strings import pluralism from .caches import CachedAddon from .checks import NetworkCheck from . import base, objects, results class ConfigArg(argparse._StoreAction): """Store co...
# coding: utf-8 # In[ ]: import numpy as np import matplotlib.pyplot as plt from skimage.color import rgb2gray from skimage.filters import gaussian import scipy import cv2 from scipy import ndimage import Image_preperation as prep import FitFunction as fit import FileManager as fm import Image_preperation as prep ...
import datetime import logging from django_pandas.managers import DataFrameManager from django.db import models from django.db.models import Manager from django.utils import timezone from django.utils.translation import gettext_lazy as _ from apps.datablock.models import DataBlock from apps.org.models import Org, Or...
# -*- coding: UTF-8-*- import sys from xml.etree.ElementTree import parse if sys.version_info.major > 2: from urllib.request import urlopen else: from urllib import urlopen import datetime class Base: def __init__(self, url): self.rss = '' self.fecha = '' self.__url = url self.__fecha_de_actualizacion = ...
# Copyright 2021 <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-2.0 # Unless required by applicable law or agreed to in writing, software...
import numpy as np def calculate_factorial(x: int) -> int: if x == 1: return 1 else: return x * calculate_factorial(x - 1) def p1(k: int) -> str: answer_string = "" for x in range(k, 0, -1): factorial = calculate_factorial(x) if x == k: answer_string = str...
import argparse import os import random import pandas as pd import numpy as np lang_families = {'arz': 'Afro-Asiatic', 'afb': 'Afro-Asiatic', 'ara': 'Afro-Asiatic', 'syc': 'Afro-Asiatic', 'heb': 'Afro-Asiatic', 'amh': 'Afro-Asiatic', 'gup': 'Arnhem', 'aym...
import numpy as np from collections import OrderedDict, deque import warnings import dm_env from dm_env import specs from dm_control import suite with warnings.catch_warnings(): warnings.filterwarnings('ignore', category=DeprecationWarning) from dm_control import manipulation from dm_control.suite.wrappers imp...
#831162.py from graphics import * def makeWindow(size): return GraphWin("Collection of patches", size*100, size*100) def main(): size, myColours = getInputs() win = makeWindow(size) displayAndMovePatches(win, size, myColours) # triangle function for penultimate patch def triangle(win ,p1, p2, p3, co...
#!/usr/bin/env python3 import sys import logging import traceback from typing import Optional from time import sleep from datetime import datetime, timezone, timedelta import json from requests import ConnectionError import spotipy import spotipy.util as util from spotipy.oauth2 import SpotifyClientCredentials from ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import inspect import math import os import uuid from collections import * from collections import deque from copy import copy, deepcopy from functools import partial from itertools import repeat import numpy...
from aio2ch import ( Api, Board, Thread, Image, Video, Sticker ) import pytest @pytest.fixture async def client(): async with Api(timeout=10.0) as api_client: yield api_client @pytest.fixture async def client_ujson(): from ujson import loads as ujson_loads async with Ap...
#!/usr/bin/python3 import PyQt5.QtWidgets as Qtw import PyQt5.QtGui as QtGui import PyQt5.QtCore as QtCore from PyQt5.QtCore import Qt from widgets.flow_layout import FlowLayout class LabelWidget(Qtw.QLabel): """ A widget displaying a single label, with it's color """ clicked = QtCore.pyqtSignal() ...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from...
''' Module containing the online game class called mayhem Written by <NAME> ''' import pygame as pg import numpy as np import pickle import time import itertools from multiprocessing import Pipe, Process from importlib import reload import user_settings as cng from states import state_config as state_c...
import face_recognition import cv2 from config import * import json import numpy as np import time import logging ''' This function will generate 2 face encodings for the person in front of the camera and will return it. If no face is found for 100 frames, then None is returned. ''' def generate_face_encodings(video_...
import itertools import os import click from InquirerPy import inquirer from rich.console import Console from ..directory import Directory from ..common import mlsorted, inspect_dir from ..config import _STYLE, CHECKBOX_STYLE, EXTS_IMAGE, EXTS_SIGNAL, EXTS_TEXT from ..misc import _linl from ..rich_print import rich_t...
""" Auteur : <NAME> Mise en forme de l'affichage d'une table de données en format CSV : Comma Separated values https://fr.wikipedia.org/wiki/Comma-separated_values utilisé pour échanger des données entre logiciels : carnet d'adresses sur gmail excel, libre office calc...
import dash import dash_table from dash.dependencies import Input, Output, State import dash_core_components as dcc import dash_html_components as html import pandas as pd import sqlite3 as sql from hero_scrape import fetch_hero_list #external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.D...
################################################################################# # # University of Nice Côte d’Azur (UCA) - # National Center of Scientific Research (CNRS) – # CHU of Nice (CHUN) - # Instituto Federal do Espirito Santo (IFES) # Copyri...
from functools import singledispatch from operator import attrgetter from typing import Collection, Union from antlr4 import FileStream, ParserRuleContext from knitscript.astnodes import Block, Call, Document, \ ExpandingStitchRepeat, FixedBlockRepeat, FixedStitchRepeat, Get, \ NaturalLit, Node, PatternDef, P...
""" Test for the core code of the method module """ import numpy as np import adafdr.method as md import adafdr.data_loader as dl def test_method_init(): """ test for md.method_init """ p, x, h, n_full, _ = dl.load_2d_bump_slope(n_sample=20000) a, mu, sigma, w = md.method_init(p, x, 2, alpha=0.1, n_ful...
from __future__ import (print_function, unicode_literals, division, absolute_import) import io import os import re import subprocess from common import vprint, exe, ff, wf, check, get_latest_driver_version ETC = "/etc/glance/glance-api.conf" PACKAGE_INSTALL = "/usr/lib/python2.7/dist-packages...
# -*-coding:utf-8-*- import os import time from datetime import date from ftplib import FTP import pandas as pd from sqlalchemy import create_engine # 服务器地址 FTP_SERVER = '172.16.17.32' USER = 'yxh' PWD = '<PASSWORD>' FTP_PATH = '/' local_root = 'E:\\projects\\python\\beestock\\data\\result' DATE = time.strftime('%Y%m...
import math from urllib.request import urlretrieve import torch from PIL import Image from tqdm import tqdm import numpy as np import random import torch.nn.functional as F '''gen_A: co-occur matrix generation''' def gen_A(num_classes, t, adj_file): import pickle result = pickle.load(open(adj_file, 'rb')) ...
#!/usr/bin/env python3 # import logging # from scipy.special import comb import gmpy2 logging.basicConfig(format="%(message)s", level=logging.INFO) logger = logging.getLogger() MODULUS = pow(2, 15) # MODULUS = 0 class IterationError(Exception): pass def r0_3_r1_n(n, r7): result = r7 * (r7 + n + 3) % MODUL...
import numpy as np def get_tree_slow(sorted_indices, adj): block = [] treeNumber = {} nTrees = 0 for coordinate in sorted_indices: neighbors = np.nonzero(adj[coordinate])[0] nn = np.intersect1d(neighbors, block) neighTrees = set() continueFlag = False for neigh in...
#!/usr/bin/env python3 import os import re import sys from os.path import expanduser import ipfshttpclient from broker import cfg from broker._utils._log import log from broker._utils.tools import get_ip, is_byte_str_zero, print_tb from broker._utils.web3_tools import get_tx_status from broker._utils.yaml import Yam...
from matplotlib import pyplot as plt import numpy as np import random class ImageStitcher(object): """Stitches together two single digit images into a double digit image with possible overlap""" def __init__(self, img_width, images, labels, ...
import unicodedata import argparse import re from typing import Any, Callable, List, Union, TypeVar from re import Pattern CATEGORIES = { "Cc": "Other, control", "Cf": "Other, format", "Cn": "Other, not assigned", "Co": "Other, private use", "Cs": "Other, surrogate", "Ll": "Letter, lowercase", ...
import os import h5py import shutil import numpy as np from copy import deepcopy from contextlib import contextmanager from gonzales.simulator.space import Space import gonzales.simulator.simulation as sim # --------------------------------------------------------- # Utility functions # -----------------------------...
from math import factorial, inf from random import randint from genetic_algorithm.crossover import apply_crossover from genetic_algorithm.mutation import apply_mutation class NonDominatedSorter: ''' Class for sorting the population by objective fitness scores Sorts by using a non-dominated sortin...
#!/usr/bin/env python ''' Diffraction functions require for fitting and analyzing data. mkak 2017.02.06 (originally written spring 2016) ''' ########################################################################## # IMPORT PYTHON PACKAGES import math import numpy as np from numpy import cos, sin, arcsin, degrees ...
from collections import Counter from functools import partial import numpy as np import pandas as pd from sklearn.metrics import roc_auc_score, roc_curve from sklearn.utils.multiclass import unique_labels from responsibly.fairness.metrics.utils import ( _assert_binary, _groupby_y_x_sens, ) def _proportion(data,...
#!/usr/bin/env python ############################################################################# ## # This file is part of Taurus ## # http://taurus-scada.org ## # Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain ## # Taurus is free software: you can redistribute it and/or modify # it under the terms of t...
"""Runs transformed lambda code.""" import functools import itertools import logging import os from pathlib import Path from typing import Callable, Dict, List, Optional from .async_call import AsyncCaller, AsyncCallsNotSupported from .chk_manager import CheckpointManager, NULL_CHK_ID from .consts import Continuations...
import sys import os import time import toolshed as ts files = [ dict(file="ESP6500SI.all.snps_indels.tidy.v2.vcf.gz", fields=["EA_AC", "AA_AC"], names=["esp_ea", "esp_aa"], ops=["first", "first"]), dict(file="ExAC.r0.3.sites.vep.tidy.vcf.gz", field...
#! /usr/bin/python3.4 # -*- coding: utf-8 -*- # # program.py # import os import sys from kivy.app import App from kivy.lang import Builder from kivy.core.window import Window from kivy.config import ConfigParser from kivy.properties import ObjectProperty from kivy.utils import get_hex_from_color from libs.uix import...
#!/usr/bin/env python3 # # Copyright 2021 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 o...
# -*- coding: utf-8 -*- # Copyright (c) 2015, helpdesk and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from helpdesk.utils import send_mail from frappe.model.document import Document from frappe.utils import nowtime, get_datetime class TicketEsc...
#!/usr/bin/env python # encoding: utf-8 """ @author: <NAME> 刘祥德 @license: (C) Copyright 2019-now, Node Supply Chain Manager Corporation Limited. @contact: <EMAIL> @software: @file: __init__.py.py @time: 2022/2/13 19:39 @version 1.0 @descwerkzeug: """ from tkinter.tix import Tree import requests import os import time ...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2013 <NAME> (<EMAIL>). # 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.apac...
import random import pandas as pd import io import json from dateutil import parser from collections import OrderedDict import time import csv import difflib import matplotlib import numpy as np import matplotlib.pyplot as plt import os import sys, traceback from matplotlib.legend_handler import HandlerLine2D import gr...
import numpy as np import pandas as pd import os import random from textblob import TextBlob from googleapiclient.discovery import build api_key = os.environ.get("API_KEY") def related_ids(url): api_key = os.environ.get("API_KEY") # get video ID vid = url.split('=')[-1] # build youtube object to ac...
from . import api import argparse import os.path import sys parsing_errors = False def is_valid_file(parser, arg): """Check if the file exists and return its path. Otherwise raise error.""" if not arg: return arg if not os.path.exists(arg): parser.error("The file %s does not exist!" % arg) els...
import logging import json import sys import csv from inspect import isclass from stdnet.utils import StringIO from .globals import get_model_from_hash __all__ = ['get_serializer', 'register_serializer', 'unregister_serializer', 'all_serializers', 'Serializer...
import curses from npyscreen import ( FormMultiPage, fmActionFormV2, ActionPopup, NPSAppManaged, MiniButtonPress, notify, ) class CustomNPSAppManaged(NPSAppManaged): def removeCurrentFromHistory(self): self._FORM_VISIT_LIST.pop() class CustomFormMultiPage(FormMultiPage): OK_B...
"""This module defines I/O ports that serve as interfaces between tasks.""" import six from girder_worker.core import io from girder_worker.plugins.types import convert, isvalid, format from .spec import Spec class ValidationError(Exception): """An exception type raised when encountering invalid data types.""" ...
""" Grab the followers info by the target user input: target user output: followers info """ import sys from time import sleep import pandas as pd from instapy import InstaPy from instapy import set_workspace from instapy import smart_run from selenium import webdriver from selenium.webdriver import DesiredCapabiliti...
""" Quaternion - defined as (x, y, z, w) to be compatible with ROS and RealSense ROS: http://wiki.ros.org/tf2/Tutorials/Quaternions ROS uses quaternions to track and apply rotations. A quaternion has 4 components (x,y,z,w). That's right, 'w' is last (but beware: some libraries like Eigen put w as the first nu...
"""Module for reprsenting scheduler jobs.""" from datetime import timedelta import re from typing import Any, Dict, Optional, Union multiple_map = { "K": 1024 ** 0, "M": 1024 ** 1, "G": 1024 ** 2, "T": 1024 ** 3, "E": 1024 ** 4, } state_colors = { "FAILED": "red", "TIMEOUT": "red", "O...
# This file has been modified from: # https://github.com/DEAP/deap/blob/master/examples/ga/xkcd.py # This file is part of DEAP. # # DEAP is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation, eith...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2018 EMBL - European Bioinformatics Institute # # 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/LICEN...
# Modified from code by <NAME> # https://github.com/newexo/cifar-ten/blob/master/code/NSGAII.py import sys def domination_count_and_set(population, element): # gives the domination count and dominating set of the element of the population domination_count = 0 dominated_set = [] for chromosome in...
__source__ = 'https://leetcode.com/problems/soup-servings/' # Time: O(N^2) # Space: O(N^2) # # Description: Leetcode # 808. Soup Servings # # There are two types of soup: type A and type B. # Initially we have N ml of each type of soup. There are four kinds of operations: # # Serve 100 ml of soup A and 0 ml of sou...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ **Project Name:** MakeHuman **Product Home Page:** http://www.makehumancommunity.org/ **Github Code Home Page:** https://github.com/makehumancommunity/ **Authors:** <NAME> **Copyright(c):** MakeHuman Team 2001-2019 **Licensing:** A...
# -*- coding: utf-8 -*- from pysignfe.xml_sped import * from pysignfe.nfe.manual_500 import ESQUEMA_ATUAL from .evento_base import DetEvento, InfEventoEnviado, Evento, EnvEvento, InfEventoRecebido, RetEvento, RetEnvEvento, ProcEventoNFe import os DIRNAME = os.path.dirname(__file__) CONDICAO_USO = u'A Carta de Corre...
############################################################################### '''''' ############################################################################### import os import itertools import pandas as pd import numpy as np from PIL import Image from thesiscode.utilities import hard_cache import aliases fro...
import numpy as np, re, pickle from random import shuffle def init_weight(size1, size2=0, mean = 0, sigma = .1): if size2 == 0: return np.random.normal(mean, sigma, (size1, 1)) return np.random.normal(mean, sigma, (size1, size2)) def get_n_feature(line1, line2): nfeat = [0,0,0] p = re.compile...
# -*- coding: utf-8 -*- """ @author: <NAME> This is a unit test. If you would like to further develop pahmc_ode_gpu, you should visit here frequently. """ import os from pathlib import Path from numba import cuda, jit import numpy as np os.chdir(Path.cwd().parent) from pahmc_ode_gpu import cuda_li...
from json import loads, dumps from uuid import uuid4 from datetime import datetime, timedelta from flask.sessions import SessionInterface, SessionMixin from flask_login import _create_identifier from dataactcore.interfaces.db import GlobalDB from dataactcore.models.userModel import SessionMap class LoginSession: ...
from robustbench.data import load_cifar10 from robustbench.utils import load_model, clean_accuracy #from utils import l2_distance import math import torch import torchvision.transforms as transforms import numpy as np import faiss device = "cpu" import sys sys.path.insert(1, './core') from patchutils import symdnn_pu...
from django.shortcuts import render, redirect from django.views.generic import FormView, TemplateView from django.urls import reverse, reverse_lazy from django.db import transaction from django.utils.translation import ugettext_lazy as _ from django.contrib.auth import get_user_model, login from django.contrib.auth.tok...
"""Make histograms of posterior parameter distributions""" from dataclasses import dataclass import numpy as np import matplotlib.pyplot as plt import math import seaborn as sns from tarpan.shared.info_path import InfoPath, get_info_path from tarpan.shared.summary import SummaryParams, sample_summary from tarpan.share...
import numpy as np from .classes.block import Block from .classes.mesh import Mesh def generate_block(origin, size, n_cells): origin_x = origin[0] origin_y = origin[1] origin_z = origin[2] size_x = size[0] size_y = size[1] size_z = size[2] block_points = [ [origin_x, origin_y,...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' FISCO BCOS/Python-SDK is a python client for FISCO BCOS2.0 (https://github.com/FISCO-BCOS/) FISCO BCOS/Python-SDK is free software: you can redistribute it and/or modify it under the terms of the MIT License as published by the Free Software Foundation. This proje...
"""TODO(rpeloff) Author: <NAME> Contact: <EMAIL> Date: September 2019 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from absl import logging import tensorflow as tf from moonshot.utils import file_io def save_model(model, output_d...
# Advent of code Year 2021 Day 18 solution # Author = <NAME> # Date = December 2021 import functools import math def load_input_file(file_name: str): with open(file_name) as file: yield from (line.strip() for line in file) def parse(task_input): for line in task_input: yield eval(line) de...
# -*- coding: utf-8 -*- """ Created on Wed Jan 30 12:46:00 2019 @author: polsterc16 ============================================================================== LICENCE INFORMATION ============================================================================== This Software uses Code (spg4) provided by "<NAME>" und...
import paddle.fluid as fluid from paddle.fluid.executor import Executor import argparse from reader import construct_sample, train_reader, val_reader, Y_seq class RetDict(object): """doc""" pass class SeqModel(object): def __init__(self, seq_num, batch_size, hidden_size): self.name = "seq2seq" ...
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import hashlib import os import pytest from pex import dist_metadata, resolver, targets from pex.fetcher import URLFetcher from pex.pip.tool import PackageIndexConfiguration from pex.res...
from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, redirect, render from django.contrib.auth.models import User from django.views import View from .models import BankAccount, Transaction from .forms import BankAccountForm, RegistrationForm, TransactionForm from django.core.pagi...
import numpy as np import cv2 #MEAN_STD = [[0.29010095242892997, 0.32808144844279574, 0.28696394422942517], [0.1829540508368939, 0.18656561047509476, 0.18447508988480435]] MEAN_STD = np.array([[0.5, 0.5, 0.5], [1, 1, 1]], dtype=np.float32) MAX_DEPTH = 10 ## Global color mapping class ColorPalette: def __init__(se...
import inspect import json import os import time import datetime from PIL import Image from django.http import JsonResponse from baoming.settings import MEDIA_URL, MEDIA_ROOT from webapp.controller.common import * from webapp.controller.renderUtil import render_result from webapp.forms.PictureForm import PictureForm f...
import torch import os import sys import torch.nn as nn from MWCNN import WCNN,IWCNN import torch.nn.functional as F def init_weights(m): if type(m) == nn.Conv2d: nn.init.xavier_uniform_(m.weight) m.bias.data.fill_(0.01) class SimpleCNN(torch.nn.Module): #Our batch shape for input x is (...
""" prepare and save dataframe for eda, model training and evaluation : Data Source : deepdr : https://isbi.deepdr.org kaggle : https://www.kaggle.com/c/aptos2019-blindness-detection/ merge two datasets : - deepdr dataset have : train, valid, test dataset with image quality and diagnosis label - kaggle dataset have :...
from . import db from flask_login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash from datetime import datetime from . import login_manager @login_manager.user_loader def load_user(user_id): """ @login_manager.user_loader Passes in a user_id to this function and in r...
import sys if(len(sys.argv)!=2): print("usage: python "+sys.argv[0]+" <integer greater than 0 and less than 10^52>") sys.exit() num=int(sys.argv[1]) if(num<=0 or num>=(10**52)): print("usage: python "+sys.argv[0]+" <integer greater than 0 and less than 10^52>") sys.exit() out="" def il(numb...
import io import pytest import sys import sudoku.grid as grid class TestGrid: def test_grid(self): g = grid.Grid() assert g.grid_type == "grid" def test_grid_add_row(self): g = grid.Grid() row = [7, 0, 9, 4, 0, 2, 3, 8, 0] g.add_row(row) g.add_row(row) ...
"""Python SDK for Renren API using OAuth 2 authentication.""" __author__ = "<NAME> (<EMAIL>)" import json import time import urllib import urllib2 #HTTP Method code GET = 0 POST = 1 UPLOAD = 2 #Keyword for GET method GET_KEYWORDS = ["get", "list", "batch"] class APIError(StandardError): """API exception clas...
#!/usr/bin/python # -*- coding: utf-8 -*- # cython: language_level=3 """ MIT License Copyright (c) 2021-present, Pelfox. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, inclu...
from enum import Enum from typing import Dict, List from robot.board import Board class PinMode(Enum): """A pin-mode for a pin on the servo board.""" INPUT = 'Z' INPUT_PULLUP = 'P' OUTPUT_HIGH = 'H' OUTPUT_LOW = 'L' class PinValue(Enum): """A value state for a pin on the servo board.""" ...
# Stock data visualization dashboard # Awesome-quent list of packages for fin data: https://github.com/wilsonfreitas/awesome-quant#data-sources import os import pandas as pd import matplotlib.pyplot as plt import pandas_datareader as web import finnhub from dateutil import parser import datetime as dt # Dash imports ...
import pandas as pd import numpy as np from .extractors import TfIdfExtractor from .encoders import GenericLabelBinarizer from typing import List, Tuple from .extractors import BaseExtractor from .encoders import BaseEncoder def check_data_alignment(labeled_df, unlabeled_df): if labeled_df is None and unlabeled_d...
# MIT License # # Copyright (c) 2019 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge,...
import numpy as np import matplotlib.pyplot as plt import unittest import copy from scipy.signal import convolve2d def life_step(X): nbrs_count = convolve2d(X, np.ones((3, 3)), mode='same', boundary='wrap') - X ans = (nbrs_count == 3) | (X & (nbrs_count == 2)) return ans def life_step_RGB(X): """Game ...
""" Scaling up Gaussian convolutions on 3D point clouds =========================================================== Let's compare the performances of PyTorch and KeOps on simple Gaussian RBF kernel products, as the number of samples grows from 100 to 1,000,000. .. note:: In this demo, we use exact **bruteforce**...
from math import log10, log def fsPathLoss(dist,freq): """ dist : Kilometros freq : Megahertz """ return 32.44 + 20*log10(dist) + 20*log10(freq) def okumuraHataPL(dist, freq, cityKind, areaKind, hb, hm): """OKUMURA-HATA URBAN model freq: signal frequency(500Mhz e 1500Mhz); ...
import datetime as dt import json from typing import Dict, List, Optional from _autoclimate.state import State from _autoclimate.utils import climate_name from adplus import Hass """ Laston - create new sensors that track the last time the climate was "on" as defined by autoclimate entity_rules. sensor.autoclimate_...
#!/usr/bin/env python import argparse import random import numpy as np import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim import torch.utils.data import torch.utils.data.distributed from torch.utils.data import DataLoader from models.fewshot_anom import FewShotSeg ...
# -*- coding: utf-8 -*- # vim:set et tabstop=4 shiftwidth=4 nu nowrap fileencoding=utf-8: from zope.interface import implements from twisted.python import log from twisted.web.client import HTTP11ClientProtocol from twisted.internet import reactor from twisted.internet.defer import Deferred from twisted.internet.proto...
import os import re import logging import traceback from subprocess import call from time import time from pyramid.view import view_config from pyramid.response import Response from mist.monitor import config from mist.monitor import methods from mist.monitor import graphite from mist.monitor.model import get_all_ma...
import numpy as np import tensorflow as tf from tensorflow.contrib.framework.python.ops import arg_scope import net.nn as nn def vq_encoder_spec(x, ema=None, nr_channel=128, nr_res_block=2, nr_res_channel=64, embedding_dim=64, num_embeddings=512, commitment_cost=0.25, decay=0.99, is_training=False...
""" Forum views =========== This module overrides views provided by the ``forum`` application. """ from django.http import Http404 from django.urls import reverse from django.utils.http import urlencode from django.views.generic import UpdateView from machina.apps.forum.views import ForumView as BaseForum...
#!/usr/bin/env python import sys import os import argparse import importlib import getpass from datetime import datetime import logging import subprocess import socket import boto3 from click import echo from drift.management.gittools import get_branch, get_commit, get_repo_url, get_git_version from drift.utils impor...