content
stringlengths
5
1.05M
# AoC 2019. Day 12. The N-Body Problem import util class Moon(): def __init__(self, pos): self.pos = pos.copy() self.vel = [0,0,0] def apply_velocity(self): for dim in range(3): self.pos[dim] += self.vel[dim] def potential(self): return sum([abs(x) for x in...
import re import bpy import bmesh import logging from mathutils import Vector """ split mesh into different objects """ def split(regex, split_z, **kwargs): for obj in bpy.data.objects: m = re.match(regex, obj.name) if not m: continue for ob in bpy.data.objects: ob.s...
import numpy as np import torch from torch.distributions import Distribution def gaussian_processes(data=10): return NotImplementedError
import xarray import numpy as np BA_THRESH = 7.7 * 1e6 # Threshold for burned area AGB_THRESH = 0 # Threshold for AGB dataset def fuelload(path_agb: str, path_ba: str, path_fl: str = None) -> xarray.Dataset: """This function generates Fuel Load xarray dataset Parameters ----------- path_agb : str ...
#!/usr/bin/env python3 from datetime import datetime, timedelta import subprocess import time imagelist = [ {"filename": "test_images/nzflag.svg", "fuzz": None}, {"filename":"test_images/redpainting.jpg", "fuzz": None}, {"filename":"test_images/redwhiteblack-art.jpg", "fuzz": None}, {"filename":"test_...
''' python manage.py --dest backup ''' from django.apps import apps as django_apps from django.db import connections, transaction from django.db.utils import ConnectionDoesNotExist, OperationalError from django.core.management.base import BaseCommand, CommandError from django.core.management import call_command clas...
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-09-14 16:03 from __future__ import unicode_literals from django.db import migrations import django.db.models.manager class Migration(migrations.Migration): dependencies = [ ('courses', '0002_auto_20170913_1307'), ] operations = [ ...
import argparse from overrides import overrides from typing import Any from typing import Dict from allennlp.commands.subcommand import Subcommand import optuna def fetch_best_params(storage: str, study_name: str) -> Dict[str, Any]: study = optuna.load_study(study_name=study_name, storage=storage) return stu...
''' 65-Crie um programa que leia vários números inteiros pelo teclado.No final da execução,mostre a média entre todos,e qual foi o maior e o menor valores lidos.O programa deve perguntar se o usuário quer continuar ou não. ''' total=0 soma=0 maior=0 menor=0 resp=False while not resp: num=int(input('Digite um valor:...
import fixtures import os import uuid from vnc_api.vnc_api import * from cfgm_common.exceptions import NoIdError from tcutils.util import get_dashed_uuid from openstack import OpenstackAuth, OpenstackOrchestrator from vcenter import VcenterAuth from common import log_orig as contrail_logging from contrailapi import C...
#Automatic Hyperparameter Tuning Method for Local Outlier Factor, with Applications to Anomaly Detection #https://arxiv.org/pdf/1902.00567v1.pdf import numpy as np import tqdm import matplotlib import matplotlib.pyplot as plt from celluloid import Camera from collections import defaultdict from sklearn.neighbors impo...
from . import packet class Packet68(packet.Packet): def __init__(self, player): super().__init__(68) self.add_data(player.uuid, pascal_string=True)
import requests import re from typing import List, Optional, Iterator from .codingamer import CodinGamer from .clash_of_code import ClashOfCode from .notification import Notification from .endpoints import Endpoints from .exceptions import CodinGamerNotFound, ClashOfCodeNotFound, LoginRequired from .utils import val...
import pytest from kopf.reactor.registries import Resource def test_no_args(): with pytest.raises(TypeError): Resource() def test_all_args(mocker): group = mocker.Mock() version = mocker.Mock() plural = mocker.Mock() resource = Resource( group=group, version=version, ...
from PyObjCTools.TestSupport import * from AppKit import * try: unicode except NameError: unicode = str class TestNSErrors (TestCase): def testConstants(self): self.assertIsInstance(NSTextLineTooLongException, unicode) self.assertIsInstance(NSTextNoSelectionException, unicode) sel...
# -*- coding: utf-8 -*- # visigoth: A lightweight Python3 library for rendering data visualizations in SVG # Copyright (C) 2020-2021 Visigoth Developers # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software # and associated documentation files (the "Software"), to...
import cv2 import numpy as np # imgpath = os.path.join(os.getcwd(), # "images", "4.2.06.tiff") # img = cv2.imread(imgpath, 0) original = np.zeros((200, 200), dtype=np.uint8) original[50:150, 50:150] = 255 original[90:110, 90:110] = 128 # ret, thresh = cv2.threshold(original, 127, 255, cv2.THR...
"""Implements learning rate schedulers used in training loops.""" import numpy as np # %% class LRCosineAnnealingScheduler(): """Implements an LRCosineAnnealingScheduler for lr adjustment.""" def __init__(self, eta_max, eta_min, Ti, Tmultiplier, num_batches_per_epoch): """Initialize LRCosineAnnea...
import json import numpy as np class NumpyEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, np.void): return None if isinstance(o, (np.generic, np.bool_)): return o.item() if isinstance(o, np.ndarray): return o.tolist() return o
from unittest import TestCase import pytest from zanna._binding_spec import InstanceBindingSpec class DummyClass(object): def __init__(self, value): self.value = value def TEST_CALLABLE(x): return x + 500 class TestInstanceBindingSpec(TestCase): TEST_STRING = "testtest" TEST_INT = 9999 ...
import numpy as np def linear(x): return x def sigmoid(x): return np.divide(1, np.add(1, np.exp(np.multiply(-1, x)))) def tanh(x): return np.tanh(x) def relu(x): return np.maximum(x, 0) def lrelu(x): if x >= 0: return x else: return np.multiply(0.01, x) def prelu(x, a...
import time import matplotlib.pyplot as plt import numpy as np from core import get_model, global_opt, LOOCV, normalize, plot_2d from scipy.special import erfc def sbostep(X_, Y, bnds, acq='EI', model_type='GP', output=False, plotting=False, loocv=False): acqd = {'EI': EI, 'Bayesian optim...
import os import uuid import shutil import subprocess from avel.shared_lib import call_ffmpeg, get_duration def _pad_integer(i): return str(i).zfill(2) def combine_audio(audio_list, output_path, transition_time=13, debugging=False): """Creates a single audio file from a list""" temp0 = os.path.join(os.pat...
#!/usr/bin/python # ex:set fileencoding=utf-8: from __future__ import unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from djangobmf.categories import SETTINGS from djangobmf.contrib.accounting.models ...
from Module import AbstractModule class Module(AbstractModule): def __init__(self): AbstractModule.__init__(self) def run( self, network, in_data, out_attributes, user_options, num_cores, outfile): import shutil shutil.copyfile(in_data.identifier, outfile) def nam...
import numpy as np class Dynamics: """docstring for Dynamics""" def __init__(self, dt): self.dt = dt def create_motion_model_params(motion_model_cov): raise NotImplementedError def create_meas_model_params(meas_cov): raise NotImplementedError if __name__ == '__main__': main()
from java.lang import String # a demo of using speech recognition to # turn an Arduino's pin 13 off or on # the commands are 2 stage - with the command, the the system # asking if that command was said, then a affirmation or negation # e.g. - you say "on", the system asks if you said "on", you say "yes" # the syst...
import sys from pprint import pprint from collections import deque import urllib import urlparse import json import random from lxml import html def create_node(name, children): return { "name": name, "children": children } def crawl(addr): current = create_node(addr, []) root = current depth = random...
#I officially GIVE UP ON THIS FUNCTION. # In order to remove silence I have to split into mono, then resample and then clean # and EVEN AFTER I managed to do all that, the script I use to remove silence doesn't like # libosa resambling, however when I manually resamble with audacity it works just fine. # THIS MAKES NO ...
from functools import partial import torch from glasses.models.classification.resnest import * def test_resnest(): x = torch.rand(1, 3, 224, 224) with torch.no_grad(): model = ResNeSt.resnest14d().eval() pred = model(x) assert pred.shape[-1] == 1000 n_classes = 10 mode...
# Standard Imports import time import paho.mqtt.client as mqtt from db.connection import add_weatherData def on_message(client, userdata, message): dataArray = str(message.payload.decode("utf-8")).split(",") add_weatherData(dataArray[0], dataArray[1], dataArray[2], dataArray[3], dataArray[4], dataArray[5], dat...
import json from django.contrib import admin, auth from django.core import serializers from .models import LandZone class LandZoneAdmin(admin.ModelAdmin): """ Creates the land zone dashboard section :author Munir Safi :since 2020-11-22 """ model = LandZone list_display = ('geo_js...
import cv2 cv2.ocl.setUseOpenCL(False) import numpy as np from copy import deepcopy from utils.sth import sth from utils.sampler import create_sampler_manager from mlagents.mlagents_envs.environment import UnityEnvironment from mlagents.mlagents_envs.side_channel.engine_configuration_channel import EngineConfiguration...
# # PySNMP MIB module SAMSUNG-DIAGNOSTICS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SAMSUNG-DIAGNOSTICS-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:52:28 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 ...
import numpy as np from mpi4py import MPI from time import time import sys sys.path.append("/Users/bl/Dropbox/repos/Delight/") from delight.utils_cy import * comm = MPI.COMM_WORLD threadNum = comm.Get_rank() numThreads = comm.Get_size() # -------------------------------------- numsamples = int(sys.argv[1]) prefix ...
name0_1_1_1_0_3_0 = None name0_1_1_1_0_3_1 = None name0_1_1_1_0_3_2 = None name0_1_1_1_0_3_3 = None name0_1_1_1_0_3_4 = None
import datetime import numpy as np import matplotlib as plt from floodsystem.datafetcher import fetch_measure_levels from floodsystem.analysis import polyfit from floodsystem.flood import stations_level_over_threshold from floodsystem.stationdata import build_station_list, update_water_levels """Explanation If the de...
from .models import Campaign def connect_campaign(sender, **kwargs): reference = kwargs.get('reference') if not reference: return parts = reference.split(':', 1) if len(parts) != 2: return namespace = parts[0] try: campaign = Campaign.objects.get(ident=namespace) ex...
import discord import logging import asyncio import aiosqlite import contextlib from bot import Main # source: rdanny because I'm lazy to do my own launcher @contextlib.contextmanager def setlogging(): try: logging.getLogger('discord').setLevel(logging.INFO) logging.getLogger('discord.http').setLe...
#!/usr/bin/env python3 """The Museum of Incredibly Dull Things. A museum wants to get rid of some exhibitions. Vanya, the interior architect, comes up with a plan to remove the most boring exhibitions. She gives them a rating, and removes the one with the lowest rating. Just as she finishes rating the exhibitions, sh...
import os, sys import cgi import webapp2 from google.appengine.ext import ndb from datetime import datetime import json from Cube.models import Cube, Content import logging #Get Functionality. class CubeHandler(webapp2.RequestHandler): def post(self): # try: cube_fields = json.loads(self.re...
#!/usr/bin/env pybricks-micropython from pybricks.hubs import EV3Brick from pybricks.ev3devices import Motor, TouchSensor, ColorSensor, GyroSensor from pybricks.parameters import Port, Direction, Button, Stop from pybricks.tools import wait, StopWatch from pybricks.robotics import DriveBase from pybricks.media.ev3dev i...
# Copyright 2019-2022 Cambridge Quantum Computing # # 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 -*- """ @date: 2020/11/4 下午1:49 @file: build.py @author: zj @description: """ import torch.nn as nn from .. import registry from .sgd import build_sgd from .adam import build_adam def build_optimizer(cfg, model): assert isinstance(model, nn.Module) return registry.OPTIMIZERS[cfg.OPTIMI...
# -*- coding: utf-8 -*- # Generated by Django 1.9.9 on 2016-10-22 19:45 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('access', '0013_auto_20160608_0018'), ] operations = [ migrations.AddField( model_name='emailaliastype',...
# Author : ThammeGowda Narayanaswamy # Email : [email protected] # Student ID : 2074669439 # Subject : CSCI 567 Fall 16 Homework 2 # Date : Oct 2, 2016 from __future__ import print_function import numpy as np import pandas as pd import matplotlib.pyplot as plt quiet = True # to disable unwanted outpu...
# coding=utf-8 # Copyright 2018 The TF-Agents 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 applicable law...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # Copyright (c) Megvii, Inc. and its affiliates. import itertools from typing import Optional import torch import torch.distributed as dist from torch.utils.data.sampler import Sampler class InfiniteSampler(Sampler): """ In training, we only care about the "infi...
for i in range(10): print("i", i) if(i % 2 == 0): continue for j in range(10): print("j", j)
import bz2 from collections import Counter from contextlib import contextmanager from datetime import datetime from functools import wraps import gzip import operator import os import re import string from typing import ( Any, Callable, ContextManager, List, Optional, Sequence, Tuple, Ty...
import os import matplotlib.pyplot as plt import sys import re def parse_logs_to_lists(logs_path): with open(logs_path, 'r') as f: lines = f.readlines() loss_list = [] psnr_noise_list = [] psnr_gt_list = [] iter_list = [] for line in lines: if 'Iteration' not in line: ...
from io import BytesIO from typing import TYPE_CHECKING from xml import sax if TYPE_CHECKING: from ..environment import Environment class XmlParser(sax.ContentHandler): def __init__(self, environment: 'Environment'): self.environment = environment self.template = None self.act_parent...
#!/usr/bin/env python import os import sys, time, math, cmath from std_msgs.msg import String import numpy as np import roslib import rospy from hlpr_object_labeling.msg import LabeledObjects from hlpr_knowledge_retrieval.msg import ObjectKnowledge, ObjectKnowledgeArray def get_param(name, value=None): private =...
{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "d27457c3", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import numpy as np\n", "import math\n", "class Node:\n", " def __init__(self, l):\n", " self.label = l\n", " ...
from rest_framework.status import HTTP_400_BAD_REQUEST ERROR_ADMIN_LISTING_INVALID_SORT_DIRECTION = ( "ERROR_ADMIN_LISTING_INVALID_SORT_DIRECTION", HTTP_400_BAD_REQUEST, "Attributes to sort by must be prefixed with one of '-' or '+'.", ) ERROR_ADMIN_LISTING_INVALID_SORT_ATTRIBUTE = ( "ERROR_ADMIN_LIST...
from unittest.mock import MagicMock from coworks.fixture import * from tests.mockup import email_mock, smtp_mock @pytest.fixture def example_dir(): return os.getenv('EXAMPLE_DIR') @pytest.fixture def samples_docs_dir(): return os.getenv('SAMPLES_DOCS_DIR') @pytest.fixture def email_mock_fixture(): yi...
# Correlations from Churchill1974 paper # see section "Functions Which Cross One Limiting Solution", pg. 41 # plot should be same as plot in Fig. 9, pg. 41 # use Python 3 print function from __future__ import print_function from __future__ import division import numpy as np import matplotlib.pyplot as py py.close('a...
import tensorflow as tf from data_loader.data_generator import DataGenerator from scripts.gan import GAN from scripts.gan_trainer import GANTrainer from utils.summarizer import Summarizer from utils.dirs import create_dirs def main(config): # capture the config path from the run arguments # then process the ...
import os from app import create_app app = create_app() app.run( host=os.environ.get("BIND_HOST", '0.0.0.0'), port=os.environ.get("BIND_PORT", 80), )
#!/usr/bin/env python # -*- coding: utf-8 -*- #MIT License (MIT) #Copyright (c) <2014> <Rapp Project EU> #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...
import re, os, datetime file_shell_rex = "data_orig/200[0-9]_[0-9][0-9]_[a-z]*/*.2[0-9][0-9]" site_rex = re.compile("^\*SITE NUMB\s*ER: ([0-9\s]+)$") channel_rex = re.compile("^\*CHANNEL\s*:\s+([0-9]+)\s+OF") date_rex = re.compile("^DATE\s+([0-9]?[0-9])\s*/([0-1]?[0-9])/([0-3]?[0-9])\s[0-9\s]+AVERAGE$") count_rex = re...
#!/usr/bin/env python3 import rogue.hardware.rce import pyrogue.mesh import surf import rceg3 class rce(object): def __init__(self): # Set base self.dpmTest = pyrogue.Root('dpmTest','DPM Test Image') # Create the AXI interfaces self.rceMap = rogue.hardware.rce.MapMemory(); ...
S = input() if S[0] == 'A' and S[2:-1].count('C') == 1: index_c = S[2:-1].index('C') S = S[1:2 + index_c] + S[3 + index_c:] if S.islower(): print('AC') exit() print('WA')
from keras.layers import Embedding, TimeDistributed, RepeatVector, LSTM class AttentionLSTM(LSTM): """LSTM with attention mechanism This is an LSTM incorporating an attention mechanism into its hidden states. Currently, the context vector calculated from the attended vector is fed into the model's inte...
import os if not os.environ.get("AZURE_TESTING") and not is_re_worker_active(): new_user() show_global_para() run_pdf() read_calib_file_new() # read file from: /nsls2/data/fxi-new/legacy/log/calib_new.csv # check_latest_scan_id(init_guess=60000, search_size=100)
"""Hello World Class.""" class HelloWorld: """Class Hello World!""" def __init__(self, my_name="Hello World!"): """Initializer for the HelloWorld class""" self.my_name = my_name def print_name(self): """Prints the value of my_name""" print(str(self.my_name))
__version__ = "0.1.0" from .config import Config from .database import Database __all__ = ["Database", "Config"]
from dcache_nagios_plugins.urlopen import urlopen try: from xml.etree import cElementTree as etree except ImportError: from xml.etree import ElementTree as etree # The full XML data is available from /info. The document is wrappend in # dCache. Subelements can also be fetched independently under a sub-URL # comp...
import os from cs50 import SQL from flask import Flask, flash, redirect, render_template, request, session from flask_session import Session from tempfile import mkdtemp from werkzeug.exceptions import default_exceptions from werkzeug.security import check_password_hash, generate_password_hash from time import sleep ...
#!/usr/bin/env python # -*- coding: utf-8 -*-\ import os import unittest os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import tensorlayerx import tensorlayerx as tlx import numpy as np from tests.utils import CustomTestCase class Layer_nested(CustomTestCase): @classmethod def setUpClass(cls): print("###...
""" lokalise.models.translation ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Module containing translation model. """ from .base_model import BaseModel class TranslationModel(BaseModel): """Describes translation model. """ DATA_KEY = 'translation' ATTRS = [ 'translation_id', 'key_id', 'langua...
from django.contrib.auth.models import User from django.forms import model_to_dict from django.urls import include, path, reverse from rest_framework import status from rest_framework.test import APITestCase, URLPatternsTestCase, APIClient from oldp.apps.annotations.models import AnnotationLabel, CaseAnnotation clas...
from . import expedia from . import scraper import datetime import requests import json def timeScorer(s): if "pm" in s: if len(s) == 7: hours = int(s[0:2]) minutes = int(s[3:5]) else : hours = int(s[0:1]) minutes = int(s[2:4]) score = hours * 60 + minutes + 720 else : if len(s) == 7: hours = ...
import numpy as np import argparse parser = argparse.ArgumentParser() parser.add_argument('-n', type=int, help='number of iterations') parser.add_argument('-x', type=float, help='X0') parser.add_argument('-s', type=float, help='step') parser.add_argument('-a', type=str, help='calculate automaticaly') parser.add_arg...
#!/usr/bin/env python # -*- coding: utf-8 -*- import vtk def main(): colors = vtk.vtkNamedColors() # Set the background color. colors.SetColor("BkgColor", [26, 51, 102, 255]) surface = vtk.vtkParametricSuperEllipsoid() source = vtk.vtkParametricFunctionSource() renderer = vtk.vtkRenderer()...
from flask import Flask from flask_limiter import Limiter from flask_limiter.util import get_ipaddr as get_remote_address from core import config limiter = Limiter(key_func=get_remote_address) def init_limiter(app: Flask): app.config["RATELIMIT_DEFAULT"] = config.RATELIMIT_DEFAULT app.config["RATELIMIT_STO...
class Silly: def __setattr__(self, attr, value): if attr == "silly" and value == 7: raise AttributeError("you shall not set 7 for silly") super().__setattr__(attr, value) def __getattribute__(self, attr): if attr == "silly": return "Just Try and Change Me!" ...
#!/usr/bin/python # ex:ts=4:sw=4:sts=4:et # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- # The unittest framwork doesn't play nice with pylint: # pylint: disable-msg=C0103 from __future__ import absolute_import import unittest from svtplay_dl.service.tests import HandlesURLsTestMixin from svtplay_...
# kdtree的具体实现,包括构建和查找 import random import math import numpy as np from result_set import KNNResultSet, RadiusNNResultSet # Node类,Node是tree的基本组成元素 class Node: def __init__(self, axis, value, left, right, point_indices): self.axis = axis self.value = value self.left = left self.rig...
students = [] references = [] benefits = [] MODE_SPECIFIC = '1. SPECIFIC' MODE_HOSTEL = '2. HOSTEL' MODE_MCDM = '3. MCDM' MODE_REMAIN = '4. REMAIN'
from discord.ext import commands import cogs.inactive.lists.listconf as lc class Lists(commands.Cog): def __init__(self, bot): self.bot = bot self.lists = {} @commands.Cog.listener("on_ready") async def on_ready(self): """Load JSON lists when ready""" lc.backup_data() ...
import uuid from src.model.SqliteObject import SqliteObject from src.server import databaseHandler class Session(SqliteObject): properties = [ "id", "name", "description" ] table = "session" def __init__(self, name=None, description=None, ...
"""Created by sgoswami on 3/23/17 as part of leetcode""" """The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility). P A H N A P L S I I G Y I R And then read line by line: 'PAHNAPLSIIGYIR' Wri...
from __future__ import print_function, absolute_import, unicode_literals, division import six from six.moves import (zip, filter, map, reduce, input, range) from IPython.core.display import Image as display_image from .dot import ( render_nx_as_dot, clear_formatting, format_graph_for_lifespan, format_grap...
import sys import json import argparse from clickandcollectnz.countdown import Countdown from clickandcollectnz.foodstuffs import NewWorld, PakNSave classes = ['Countdown', 'NewWorld', 'PakNSave'] def print_usage(): print("Usage: python -m clickandcollectnz [chain] [store_id]") print() print(" chain: Count...
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import usuario_acesso, recursos #admin.site.register(Usuario, UserAdmin) class usuario_acesso_adm (admin.ModelAdmin): list_display = ['user','escrita']#lista de campos mostrados na tela do admin admin.site.register(usuari...
import re import torch from torch import nn import logging from typing import Dict logger = logging.getLogger(__name__) class DefaultModelVocabResizer: @classmethod def set_embeddings(cls, model, token_ids): # self.model.get_input_embeddings() old_word_embeddings = model.embeddings.word_embeddi...
import sys import os import logging import time import json # os.environ['PYTHON_EGG_CACHE'] = '/tmp' sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'vendored/')) logger = logging.getLogger() logger.setLevel(logging.INFO) import Adafruit_DHT import RPi.GPIO as GPIO import greengrasssdk l...
from flask import Flask, url_for, redirect, Blueprint,render_template,session from werkzeug.security import generate_password_hash from prol import db from prol.user.forms import RegisterForm, LoginForm from prol.user.models import User user_app = Blueprint('User',__name__) @user_app.route('/register', methods=('GE...
import json import requests from webContent.constants import URL_AUTH_V2, TIMEOUT from exception import Unauthorized def keystone_auth(username, password, tenant='admin'): # Authentication json tenant = username datajs = {"auth": {"tenantName": tenant, "passwordCredentials": {"username": username, "password": pas...
import numpy as np import cv2 def calibrate_images(images, nx, ny): objpoints = [] # 3d points from real world imgpoints = [] # 2d points on image #prepare object points - points of cheessboard in undistoretd space objp = np.zeros((6 * 9, 3), np.float32) objp[:, :2] = np.mgrid[0:9, 0:6].T.resh...
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-06-25 16:47 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Blackl...
import pytest from l5kit.configs import load_config_data from l5kit.data import ChunkedDataset, LocalDataManager @pytest.fixture(scope="session") def dmg() -> LocalDataManager: """ Get a data manager for the artefacts folder. Note: the scope of this fixture is "session"-> only one is created regardless t...
def romberg(n0,steps,order,quadrature,f): res = np.zeros((steps,steps)) for i in range(0,steps): n = n0 * 1<<i res[i,0] = quadrature(n,f) for j in range(1,i+1): res[i,j] = res[i,j-1] + \ (res[i,j-1]-res[i-1,j-1])/(2**(order*j)-1.) return res
import time from machine import Pin pin0 = Pin(0, Pin.IN, Pin.PULL_UP) def callback(pin): # disable callback pin.irq(trigger=False) print("PUSH") time.sleep_ms(200) #re-enable callback irq(pin) def irq(pin): pin.irq(trigger=Pin.IRQ_FALLING, handler=callback) # Initial irq setup irq(pin0...
# AUTOGENERATED! DO NOT EDIT! File to edit: 10_matrix_multiply.ipynb (unless otherwise specified). __all__ = ['dotp', 'mmult'] # Cell def dotp(v1, v2): "Get dot product of 2 vectors" sum = 0 for i in range(0, len(v1)): sum += v1[i] * v2[i] return sum # Cell def mmult(m1, m2): "Get product...
# Copyright 2020 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...
import math import os import random import re import sys def factorial(x): if x == 1 or x == 0: return 1 else: return x * factorial(x-1) def bino(n, x, p): comb = factorial(n) / (factorial(n-x) * factorial(x)) return comb * pow(p, x) * pow((1-p), n-x) def bd(prob, n): ans = 0 ...
#!/usr/bin/env python3 """ Created on Sat May 8 19:17:36 2021 @author: Gruppo Carboni - Ongaro """ from socket import AF_INET, socket, SOCK_STREAM from threading import Thread import threading from Game.game import Game from Game.gameStatus import GameStatus import time as tm """ La funzione che segue accetta le c...
# -*- coding: utf-8 -*- # # Copyright (c) nexB Inc. and others. All rights reserved. # http://nexb.com and https://github.com/nexB/scancode-toolkit/ # The ScanCode software is licensed under the Apache License version 2.0. # Data generated with ScanCode require an acknowledgment. # ScanCode is a trademark of nexB Inc. ...