content
stringlengths
5
1.05M
import click import os from git.exc import CommandError as GitCommandError from .base import Vinnie @click.group(invoke_without_command=True) @click.option("--push/--no-push", envvar="VINNIE_PUSH", default=True) @click.option("--repo", envvar="VINNIE_REPO_PATH", default=".") @click.option("--repo-url", envvar="VINN...
# config variables LABELS = { 0:"AlegaPagamento", 1:"ClienteNaoDisponivel / Recado", 2:"ConfirmaSer", 3:"Desconfiança/Fraude", 4:"DuvidaSerasa", 5:"EnviarBoleto", 6:"Falecido", 7:"ForadeContexto", 8:"Irritado", 9:"Judicial cliente", 10:"Judicial não cliente", 11:"NaoConhece", 12:...
import torch RESGISTRIES = { 'LIGHTNING_REGISTRY': {}, 'BASE_MODEL_REGISTRY': {}, 'DATASET_REGISTRY': {}, 'MODEL_REGISTRY': {}, 'LOSS_REGISTRY': {}, 'METRIC_REGISTRY': {}, 'OPTIMIZER_REGISTRY': {}, 'SCHEDULER_REGISTRY': {}, 'CALLBACK_REGISTRY': {} } def get_object(object_name, obje...
from typing import Any class FakeRowProxy(dict): """ It's like a row proxy, but you don't have to provide a keymap etc... """ def __init__(self, seq=None, **kwargs): super().__init__(seq, **kwargs) def has_key(self, key: Any) -> bool: k = self.get(key) return True if k el...
#!/usr/bin/python import os import sys import slpsns import slpsXPath import elementtree.ElementTree as ET names = [] targets = {} results = {} def report(keys,key,note): print note, cx = 0 for x in keys: cx += results[key][x] if results[key][x]: print '{',results[key][x],'}' else: print '{---}', pr...
from django.contrib.gis.geos import Point from django.test import TestCase from mixer.backend.django import mixer import random from .models import Location, WeatherStation, WeatherObservation # TODO: obtain a list of 5-10 strings for each model, containing any minor # variations that might occur. TELVENT_DATA = [ ...
import os ATTRIBUTE = "organic_figure" def set_up(name): if name == 'wei': return set_up_wei() if name == 'zhewen': return set_up_zhewen() if name == 'xiuyuan': return set_up_xiuyuan() def set_up_wei(): os.environ['FONDUERHOME'] = '/Users/liwei/BoxSync/s2016/Dropbox/839_fonduer...
from _common import * from ..generators import toy as generator utils.set_processor('cpu') ''' some global definitions ''' NEPOCH = 50 VERSION = 0 MODELDIR = environ.get('MODELDIR', 'models/') + '/toys/' VARIATIONS = [0, 1, 2] _APOSTLE = None gen = None # must be called! def instantiate(name='SimpleSmear'): g...
import re s = 'hello 34 hello hi 566 meet 600' pat = input('Enter pattern ') result = re.findall(pat, s) sum = 0 for i in result : sum = sum + int(i) print(sum)
#!/usr/bin/python from Tkinter import * tipDelay = 1000 class TipButton(Button): def __init__(self,parent=None,tip='',**kw): Button.__init__(self,parent,kw) self.bind('<Enter>',self._delayedshow) self.bind('<Button-1>',self._leave) self.bind('<Leave>',self._leave) self.fr...
# 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 # distributed under th...
#The below is the combination of Week 1 & 2 Exc # Week 1 # Peter Thornton # College W1 Exc def fib(n): """This function returns the nth Fibonacci number.""" i = 0 j = 1 n = n - 1 while n >= 0: i, j = j, i + j n = n - 1 return i # Test the function with the following value. x = 34 ans = fib(x)...
import os from itertools import count from pathlib import Path import imageio from napari.utils.io import imsave from .easing import Easing from .frame_sequence import FrameSequence from .key_frame import KeyFrame, KeyFrameList class Animation: """Make animations using the napari viewer. Parameters ---...
num = int(input('Digite um numero:')) tot = 0 for c in range(1, num +1): if num % c == 0: print('\033[33m', end='') tot += 1 else: print('\033[31m', end='') print('{} '.format(c), end='') print('\n\033[mO numerio {} foi divisivel {} vezes '.format(num, tot)) if tot == 2: print('E...
import time import math import numpy as np from active_soccer_vision.envs import SoccerWorldEnv from stable_baselines3.common.env_checker import check_env env = SoccerWorldEnv("default.yaml") check_env(env) env.reset() done = False for i in range(9999999): obs = env.step(np.array([math.sin(i/4 -math.pi/2), math....
import os import sys import hydra import omegaconf import glob import random import torch import torchvision import PIL base = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../') sys.path.append(base) @hydra.main(config_path='../conf/show_sample.yaml') def main(cfg: omegaconf.DictConfig) -> None: if ...
class Config: DATABASE: str = 'database' KOAPY: str = 'koapy' LOGGER: str = 'logger' OPENDART: str = 'opendart' TISTORY: str = 'tistory' @classmethod def list(cls): return [ cls.DATABASE, cls.KOAPY, cls.LOGGER, cls.OPENDART, ...
from typing import List from pathlib import Path from adam.curriculum.phase1_curriculum import ( build_gaila_phase_1_curriculum as build_curriculum, ) from adam.language_specific.english.english_language_generator import ( GAILA_PHASE_1_LANGUAGE_GENERATOR, ) from vistautils.parameters_only_entrypoint import par...
from __future__ import absolute_import, print_function import sys import re import fnmatch try: from collections import OrderedDict except ImportError: # py 2.6 from ..extern.ordereddict import OrderedDict from .. import log; log = log[__name__] from .. import asrootpy, QROOT, ROOT from .. import stl from .....
# coding=utf-8 # *** WARNING: this file was generated by pulumigen. *** # *** 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 . import outp...
import itertools import matplotlib.pyplot as plt import pathlib import torch from torch.utils.data import DataLoader def _filename(directory, label=None, for_disc: bool=True): path = pathlib.Path(directory) assert path.is_dir() filename = "{}{}.pth".format( "discriminator" if for_disc else "generat...
from .names import EXEC, TAURUS_ARTIFACTS_DIR, SETTINGS from .engine import Engine from .dicts import Scenario, Configuration from .templates import HavingInstallableTools, Singletone from .modules import Provisioning, Reporter, Service, Aggregator, EngineModule, ScenarioExecutor
import pandas as pd import os def write_obs(obs=None, path="csv/obs_file.csv", env_name=None): df = pd.DataFrame(obs).T with open(path, 'a+') as f: if os.stat(path).st_size == 0: if env_name == "MARA-v0" or env_name == "MARACollision-v0": obs_headers = ['ob1', 'ob2', 'ob3', ...
import unittest import math import operator import platform import pygame from pygame.compat import long_ from pygame.colordict import THECOLORS IS_PYPY = "PyPy" == platform.python_implementation() ################################### CONSTANTS ################################## rgba_vals = [0, 1, 62, 63, 126, 127, ...
"""Setup module.""" import re from setuptools import setup RGX = re.compile(r'([\w-]+[<>=]{1}=[\d.]+)') def read_file(filename): """Read file correctly.""" with open(filename) as _file: return _file.read().strip() def requirements(filename): """Parse requirements from file.""" return re.f...
from collections import defaultdict from suffix import SuffixArray from edistance import * import numpy as np ''' Algorithm: stem_cluster(data [, mode, length_at_least] ) A clustering algorithm that bases from word frequency and stem trimming/lemmatizing. The goal of the algorithm is to reduce the data int...
# To use this code, make sure you # # import json # # and then, to convert JSON from a string, do # # result = admin_barriers_list_response_from_dict(json.loads(json_string)) from dataclasses import dataclass from typing import Optional, Any, List, TypeVar, Callable, Type, cast T = TypeVar("T") def from_st...
import numpy import keras from utils.preprocess import bag_of_words, load_data from fastapi import FastAPI words, labels, docs = load_data("intents.json") model = keras.models.load_model("model/model.h5") app = FastAPI() @app.get("/") def index(q:str): sentence = numpy.array([bag_of_words(q, words)]) results...
import os import fire import torch from fairseq.models.lightconv import LightConvModel def load_best_model(path, data_path): model = LightConvModel.from_pretrained( os.path.join(path, 'checkpoints'), checkpoint_file='checkpoint_best.pt', data_name_or_path=os.path.abspath(data_path)) print(model[0]) i...
from copy import copy import numpy as np from gym_chess import ChessEnvV1 from gym_chess.envs.chess_v1 import ( KING_ID, QUEEN_ID, ROOK_ID, BISHOP_ID, KNIGHT_ID, PAWN_ID, ) from gym_chess.test.utils import run_test_funcs # Blank board BASIC_BOARD = np.array([[0] * 8] * 8, dtype=np.int8) # Pa...
import pathlib from unittest import TestCase, expectedFailure from unittest.mock import ANY, patch from mit_d3m import ( BUCKET, download_dataset, extract_dataset, get_client, get_dataset_dir, get_dataset_s3_key, get_dataset_tarfile_path) class MitD3mTest(TestCase): def test_get_client(self): cl...
from sandbox import Scene from sandbox.hunter import Hunter scene = Scene() A = scene.free_point(label='A') B = scene.free_point(label='B') c0 = A.circle_through(B) c1 = B.circle_through(A) C = c0.intersection_point(c1, label='C') scene.centroid_point((A, B, C), label='D') A.segment(B).middle_point(label='E') hunter...
import os def getMeta(): moduleDir = os.path.realpath(os.path.join(os.path.dirname(__file__))) about = {} with open(os.path.join(moduleDir, "__about__.py")) as f: exec (f.read(), about) return about
#!/usr/bin/env python3 from flask import Flask, render_template, send_file, request import os from werkzeug.utils import secure_filename # instantiate WSGI application app = Flask(__name__) # to upload files (searchingCards) working with Flask uploadFolder = "/tmp/upload" app.config['UPLOAD_FOLDER'] = uploadFolder ...
from utilitiesmodule import * def displayDetails(title, value): banner(length=100, message=title) print(f"Length: {len(value)}") print(f"Value: {value}") title = "List Data Type Demo" displayDetails('List Demo', [1, 2, 3]) # Empty List listOne = [] displayDetails(title, listOne) integerList = [10, ...
def geometric_progression(a, q): k = 0 while True: result = a * q**k if result <= 100000: yield result else: return k += 1 for n in geometric_progression(2, 5): print(n)
from setuptools import setup, find_packages from os import path cwd = path.abspath(path.dirname(__file__)) with open(path.join(cwd, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup(name='noticeme', description=("Provides a framework for building file watchers." " In...
def checkPermutation(s): counts = {} for i in s: if i == " ": continue if i in counts.items(): counts[i] += 1 else: counts[i] = 1 hasOdd = False for key, value in counts: if value % 2 == 1: if hasOdd: # we ha...
import smtplib import datetime as dt import random import pandas my_email = "sami.smtptest@gmail.com" password = "0757230067" time_now = dt.datetime.now() weekday = time_now.weekday() # data = pandas.read_txt("quotess.txt") # print(data) q_list = [] if weekday == 1: with open("quotess.txt") as all_q...
# Please do not modify this file. # Instead have a look at `README.md` for how to start writing you AI. import argparse from joueur.run import run parser = argparse.ArgumentParser(description='Runs the python client with options. Must provide a game name to play on the server.') parser.add_argument('game', action='st...
# chapter 02-01 # 객체지향 프로그래밍(OOP) (<-> 절차지향) 장점 : 코드 재사용, 코드 중복 방지, 유지 보수 쉬움, 대형 프로젝트 관리 용이 # 규모가 큰 프로젝트 수행 시, 과거에는 함수 중심으로 코딩됨(함수에서 함수 호출하며 복잡해짐) -> 데이터가 방대해질 수록 개선 어려움 # 클래스 중심 -> 객체로 관리 class Car(): """ Car class Author : Kim Date : 2020.08.31 Description : Class, Static, Instance method """...
import json import numpy as np import torch from torch import nn from torch import optim import torch.nn.functional as F from torchvision import datasets, transforms, models import argparse from collections import OrderedDict from PIL import Image parser = argparse.ArgumentParser() parser.add_argument('path', help='D...
""" Exploration policy for permutation invariant environments """ from ..base_classes import Policy import itertools import random import copy import numpy as np class LongerExplorationPolicy(Policy): """Simple alternative to :math:`\epsilon`-greedy that can explore more efficiently for a broad class of real...
from .util import grid_search from tabulate import tabulate from ...dataset import load_annotated_corpus from ...config import config_context from .parameter_space import bm25_parameter_space, tfidf_parameter_space, lexrank_parameter_space, \ textrank_parameter_space from ..bm25 import BM25Summarizer from ..tf_idf...
from calendar import monthrange import datetime import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates import matplotlib.cbook as cbook import pandas as pd def parse_month(month) -> int: """ Parse string month to a number 1-12 """ map = { 'jan': 1, 'feb': 2, ...
from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from medilov.models import Gallery, GalleryTopic from django.contrib.staticfiles.testing import StaticLiveServerTestCase from django.urls import reverse from django.conf import settings import time import os c...
# Desenvolva um algoritmo em Python que receba duas notas e exiba a soma delas # Dados: # receber duas notas # Processamento: # somar notas # Informação: # exibir soma nota1 = input("Digite a nota 1: ") nota2 = input("Digite a nota 2: ") soma = float(nota1) + float(nota2) print(soma)
from gitz import config from pathlib import Path GITZ_ROOT = Path(__file__).parent.parent def commands(): print('SUMMARIES = {') for command in config.COMMANDS: summary = SUMMARIES.get(command) if not summary: file = GITZ_ROOT / command source = file.read_text() ...
from .api import Nuclino
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 5 17:26:31 2017 @author: farismismar """ import math from gym import spaces, logger from gym.utils import seeding import numpy as np # An attempt to follow # https://github.com/openai/gym/blob/master/gym/envs/classic_control/cartpol...
import operator as op from sweetpea.internal import get_all_external_level_names, intersperse from sweetpea.primitives import Factor, DerivedLevel, Transition color = Factor("color", ["red", "blue"]) text = Factor("text", ["red", "blue", "green"]) color_repeats_level = DerivedLevel("yes", Transition(lambda colo...
#!/usr/bin/env python3 """ A word-guessing game inspired by the game "Wordle" / "Quordle" / "Octordle", etc. Similar to the word-guessing hacking mini-game in the Fallout series, which is also similar to a word version of the game "Mastermind". By default, after you make a guess: * A yellow letter means "this charact...
import numpy as np import math from qiskit import IBMQ, Aer, execute, QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.providers.aer import noise from qiskit.aqua import QuantumInstance from qiskit.quantum_info import Pauli from qiskit.aqua.operators.weighted_pauli_operator import WeightedPauliOperator ...
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Scantailor(CMakePackage): """Scan Tailor is an interactive post-processing tool for scanne...
from .exceptions import * import sys BASE_URL = "https://blockchain.info/" TIMEOUT = 10 py_version = sys.version_info[0] if py_version >= 3: # Python 3.0 and later from urllib.request import urlopen from urllib.error import HTTPError from urllib.parse import urlencode else: # Python 2...
from entities.entity import Entity class Food(Entity): def __init__(self, foodId): tbl = Food.select_tuples('Food', ['foodId'], [foodId])[0] self.foodId = tbl[4] self.name = tbl[1] self.price = tbl[0] self.shopId = tbl[5] self.categoryId = tbl[6] self.discou...
import sqlite3 from typing import List import highscores from highscores.highscore import Highscore from pathmanager import PathManager class Btwinstreak(Highscore): def __init__(self): LAYOUT = ["Rank", "Username", "Win Streak", "Wins"] NAME = "btwinstreak" LINK = "https://pokemon-planet...
# Definition for a binary tree node. """ construct recusive function use height to be the index of the answer list when height is the len of List we need to append a [] into the List as its new listlist append curnode value and recusive traversal its left and right node. timecomplexity = O(n) spacecomplexity = O(n) f...
from django.db import models from django.conf import settings from django.db.models import Q from .validators import validate_category from django.db.models.signals import pre_save, post_save from django.core.urlresolvers import reverse from .utils import unique_slug_generator from tours.models import Tour # Create you...
from flask import Blueprint, jsonify, request, current_app from JumpScale import j cockpit_api = Blueprint('cockpit_api', __name__) @cockpit_api.route('/cockpit/update', methods=['POST']) def update(): ''' endpoint that update the cockpit to the last version It is handler for POST /cockpit/update ''...
import os import json import re from nltk import word_tokenize from nltk.translate.bleu_score import corpus_bleu from tqdm import tqdm from rouge import Rouge from sumy.parsers.plaintext import PlaintextParser from sumy.nlp.tokenizers import Tokenizer from sumy.summarizers.text_rank import TextRankSummarizer from sumy....
# _*_ encoding:utf8 _*_ import copy a = [1, 2, 3, 4, ['a', 'b', 'c']] b = copy.copy(a) c = copy.deepcopy(a) print(b) print(c)
#!/usr/bin/env python """Test suite for Stream XML Writer module""" # Copyright (c) 2009-2020 Filip Salomonsson # # 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, includi...
from flask import Blueprint from flask_restx import Api, Namespace from flask_jwt_extended.exceptions import (WrongTokenError, NoAuthorizationError, JWTDecodeError, InvalidHeaderError, ...
import math n, m, k = map(int, input().split()) a = [int(m) for m in input().split()] b = [int(m) for m in input().split()] """x = 0 y = 0 for i in range(n): x += math.log10(a[i] * (k ** (n - i - 1))) for i in range(m): y += math.log10(b[i] * (k ** (m - i - 1))) if x > y: print("Y") elif x < y: print("...
from __future__ import division, print_function from webthing import (Action, Event, Property, MultipleThings, Thing, Value, WebThingServer) from things.mock_DimmableLight import MockDimmableLight from things.mock_MovementSensor import FakeMovementSensor from things.mock_PositionDevice import Fa...
#!/usr/bin/python3 import itertools # Representation of propositional formulas in Python. # # The basic connectives are NOT, AND and OR. # IMPL and EQVI are reduced to these through the obvious reductions. # We have a separate class for formulas with different outermost # connectives, as well as for atomic formulas (...
from collections import namedtuple Unit = namedtuple("Unit", ["symbol", "convertion_factor"]) #Length units nano_meter = Unit("nm", 10**9) micro_meter = Unit("µm", 10**6) milli_meter = Unit("mm", 10**3) centi_meter = Unit("cm", 10**2) meter = Unit("m", 1) #Unitless nano = Unit("e-9", 10**9) micro = Unit("e-6", 10**...
"""This module is used for x-references.""" import ast class ReferenceFilteringVisitor(ast.NodeVisitor): """Check whether an AST contains an import for a given name. We use this to narrow down the set of files in which to search for global references. """ def __init__(self, name=None): ...
# -*- coding: utf-8 -*- # Author: calfcrusher@inventati.org import os import signal import time import subprocess import json import sqlite3 from googlesearch import search from urllib.parse import urlparse from pathlib import Path from termcolor import colored from subprocess import check_output from prettytable imp...
from cProfile import label import os import pickle import math import json import jieba from janome.tokenizer import Tokenizer from tqdm import tqdm import numpy as np import scipy.sparse as ssp import pandas as pd import sklearn from .dictionary import Dictionary def build_aichallenger_dataset(dataset_dir,reusult_...
# Maple Hall (10000) sm.showEffect("Map/Effect.img/maplemap/enter/10000") sm.dispose()
#! /usr/bin/env python3 import sys import os import argparse import datetime # Parse command line options def get_options(): parser = argparse.ArgumentParser(description='Create a Makefile for Xilinx IP.') parser.add_argument('--ip_name', type=str, default=None, help='Name for the IP core') parser.add_arg...
import torch import timeit import warnings def find_optimal_workers( loader, start_workers=0, max_workers=12, worker_step=1, iterations_per_worker=20, num_averages=3, set_pin_memory=True, verbose=True, ): """ Find the (approximately) best number of workers to use for a part...
class Solution: def numJewelsInStones(self, J: str, S: str) -> int: sum = 0 for j in J: sum = sum+S.count(j) return sum if __name__ == '__main__': J = "aA" S = "aAAAbbbbb" solution = Solution() print(solution.numJewelsInStones(J,S))
from django.shortcuts import render __author__ = '' def raise_404(request): return render(request, '404.html', status=404) def raise_401(request, context): return render(request, '403.html', context, status=403)
# Make sure to have CoppeliaSim running, with followig scene loaded: # # scenes/messaging/movementViaRemoteApi.ttt # # Do not launch simulation, then run this script import math from zmqRemoteApi import RemoteAPIClient def movCallback(config,vel,accel,handles): for i in range(len(handles)): if sim.getJoi...
from django import forms from django.utils.translation import gettext_lazy as _ from api.forms import ContextAwareModelForm, HashidModelChoiceField from submissions.models import Submission from voting.helpers import pastaporto_user_info_can_vote from voting.models import Vote from .fields import VoteValueField cla...
# Copyright 2021 BlackRock, 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...
from .common import BaseHelpers from .common.logger import init_logger from requests.exceptions import ReadTimeout import requests import json class Vhinny(): BACKEND_URL = 'https://7pwlq44lyc.execute-api.us-east-1.amazonaws.com/production/api-financials' log = init_logger('Vhinny', log_level='INFO') lo...
#!/usr/bin/python # Classification (U) """Program: main.py Description: Integration testing of main in elastic_db_repo.py. Usage: test/integration/elastic_db_repo/main.py Arguments: """ # Libraries and Global Variables # Standard import sys import os import shutil import time if sys.versio...
from flask import Blueprint api_v1 = Blueprint('classes-api', __name__) from app.routes.api.classes import routes
from django.conf.urls import url from .views import TreeView urlpatterns = [ url(r'^docs/', TreeView.as_view(), name='api-tree'), ]
from skimage.metrics import structural_similarity as ssim from PIL import Image import numpy as np import cv2 class ImageCompare: def compare_ssim(self, image_one, image_two): imageA = self.get_proper_image(image_one) imageB = self.get_proper_image(image_two) h, w = imageA.shape[:2] ...
#coding: latin1 from collections import Container, Iterable, Sized #[full class RangeSet(Container, Iterable, Sized): def __init__(self, min: "int", max: "int"): self._min, self._max = min, max def __contains__(self, v: "int") -> "bool": return self._min <= v <= self._max ...
from __future__ import absolute_import from __future__ import print_function from ...common._base import BaseServer import json from .parameters import ClusterProtocol ######################################################################## class Clusters(BaseServer): """ This resource is a collection of all th...
""" Unit test file for config injector """ __author__ = "Jakub Wlodek" __copyright__ = "Copyright June 2019, Brookhaven Science Associates" # unit test include import pytest # installSynApps include import installSynApps.data_model.install_config as InstallConfig import installSynApps.data_model.install_modu...
# Python program to implement server of controller software import argparse import socket try: from RaspberryPi.cam import Streamer from RaspberryPi.server.command_handler import CommandHandler from RaspberryPi.server.printing_command_handler import PrintingCommandHandler except ModuleNotFoundError: fr...
# cs50 pset 6 from cs50 import get_string import sys def main(): if len(sys.argv) != 2: print("Usage: ./caesar key") # Remind user to giv an argument # converts the word into int key = int(sys.argv[1]) word = get_string("Plaintext: ") print("Cyphertext: ", end="") #loop through each...
# proxy module from __future__ import absolute_import from envisage.plugins.remote_editor.actions import *
import numpy as np # Standard matrix operations import random # Randomizing functions import sys, os import time import tensorflow as tf import torch import torch.nn as nn import torch.nn.functional as F import argparse #device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") device = "cpu" ...
from datetime import datetime, timedelta from fastapi import HTTPException import jwt from starlette.status import HTTP_401_UNAUTHORIZED from app import settings CREDENTIALS_EXCEPTION = HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate"...
# setup.py # # 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 # distrib...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import re import sys reload(sys) sys.setdefaultencoding('utf-8') class SubVersionChecker(object): def __init__(self, txn, repos): self.repos = repos self.txn = txn def get_commit_logs(self): commit_log_fd = os.popen('svnlook chan...
from machine import Pin, Signal # ESP12 module as used by many boards # Blue LED on pin 2, active low (inverted) LED = Signal(2, Pin.OUT, invert=True)
import gym import gym_schafkopf #used for batches and memory: import random from copy import deepcopy # used for baches and memory import numpy as np import datetime # use ray for remote / parallel playing games speed up of 40% import ray # pip install ray==0.8.1 this does not work:...
#!/usr/bin/python import sys import matplotlib.pyplot as plt ax = [0,0,0,0,0,0,0,0] def hist2d(filename, i): fobj = open(filename, "r") x = [] y = [] z = [] line_nr = 0 xBins = 0 yBins = 0 for line in fobj: if line_nr == 0: pass elif line_nr == 1: xBins = float(line.rstrip()) elif line_nr ==...
""" Motion controller module. """ import asyncio from dataclasses import dataclass from enum import Enum from highlevel.logger import LOGGER from highlevel.robot.controller.motion.position import PositionController from highlevel.robot.entity.configuration import Configuration from highlevel.robot.gateway.motor import...
#!/usr/bin/env python import json import os import sys import uuid from copy import deepcopy from xml.etree import ElementTree as ET import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning SCHEMA = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2" XMLNS_S = "{http://www.w3.org/2003/...
import numpy as np import matplotlib.pyplot as plt def precalculatedKcoeffs(Ndim, path2kernels): fftdim = 2*Ndim-1; kernel = np.fromfile(path2kernels+'KernelD'+str(Ndim)+'.dat', dtype=np.complex128) kernel = (np.flip(kernel)).reshape((fftdim,Ndim,Ndim)) return kernel def PSrepresentationF...