content
stringlengths
5
1.05M
import json import torch import pandas as pd from os.path import join from torch.utils.data import Dataset class VCTKDataset(Dataset): def __init__(self, path, partition_table, split, bucketing, batch_size, spkr_map): """ Arg: split: one in ['train', 'dev', 'test'] path: r...
# Copyright 2015-2017 Capital One Services, 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
from yafs.selection import Selection import networkx as nx from collections import Counter class DeviceSpeedAwareRouting(Selection): def __init__(self): self.cache = {} self.counter = Counter(list()) self.invalid_cache_value = True self.controlServices = {} # key: a servic...
# This file is part of Scapy # See http://www.secdev.org/projects/scapy for more information # Copyright (C) Philippe Biondi <phil@secdev.org> # This program is published under a GPLv2 license """ Functions to send and receive packets. """ from __future__ import absolute_import, print_function import itertools from t...
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2020: TelelBirds # # ######################################################################### from __future__ import unicode_literals import os import datetime from django.core.validators import MaxValu...
import unittest from selenium import webdriver class NewVisitorTest(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() def tearDown(self): self.browser.quit() def test_user_can_login(self): # Clive knows of a website which contains lots of torrent that he want...
import csv import sys from entities.Location import Location from structures.Graph import Graph from .Logger import Logger sys.path.append("..") class RouteLoader: """Loads the distance table from a file.""" def __init__(self, filename): super().__init__() self.filename = filename sel...
number = str(input()) # разделение числа на две части first_half = int(number) // 1000 second_half = int(number) % 1000 # цифры первой половины first = first_half // 100 second = first_half % 100 // 10 third = first_half % 100 % 10 # цифры второй половины fourth = second_half // 100 fifth = second_half % 100 // 10 s...
from discord.ext import commands from Bot.utils.staff.staff_checks import * from main import main_db from pathlib import Path from config import prefixes users = main_db["users"] blacklisted_files = ["shutdown", "start", "reload"] class devtools(commands.Cog): def __init__(self, bot): self.bot = bot ...
'''Crie um programa que leia o ano de nascimento de sete pessoas. No final, mostre quantas pessoas ainda não atingiram a maioridade e quantas já são maiores.''' from datetime import date totmaior = 0 totmenor = 0 for c in range(1, 8): nasc = int(input('Digite o ano de nascimento da {}º pessoa: '.format(c))) ida...
""" wordprocessing.py """ import string from collections import OrderedDict, Counter import sys import re import spacy import numpy as np def keyword_extractor(data: list) -> list: """ Function to extract keywords from the headers and paragraphs of slides :param data: The list of dictionaries of the form...
from setuptools import setup setup(name='ascii_enine', version='0.0.1', description='Create ASCII-based programs', url='http://github.com/carlosmaniero/ascii-engine', author='Carlos Maniero', author_email='carlosmaniero@gmail.com', license='MIT', packages=['ascii_engine'], ...
""" Big data processing (enhanced version). Author: lj1218 Date : 2018-12-09 =========================================== 条件: 1、x,y 从B列取值;z从A列取值; 2、z > y > x. 求解: 1、精确到小数点后2位,求 (z-y)/(y-x); 2、出现频率最高的比值,列出所对应的x,y,z组合. =========================================== """ import os import sys import time from functools impor...
""" StarryPy species whitelist plugin Prevents players with unknown species from joining the server. This is necessary due to a year+ old "bug" detailed here: https://community.playstarbound.com/threads/119569/ Original Authors: GermaniumSystem """ from base_plugin import BasePlugin from data_parser import ConnectFa...
# encoding: utf-8 # # Copyright 2009-2017 Greg Neagle. # # 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 l...
# モジュールのインポート import sys sys.setrecursionlimit(1000000) # 標準入力を取得 N, Q = list(map(int, input().split())) g = {i: [] for i in range(1, N + 1)} for _ in range(N - 1): a, b = list(map(int, input().split())) g[a].append(b) g[b].append(a) q = [] for _ in range(Q): c, d = list(map(int, input().split())) ...
# ================================================================================ # # httpsRequest.py # # This is the https client request program written for my proof of concept program # to demonstrate the SSLv3 Padding Oracle On Downgraded Legacy Encryption. # (POODLE) attack. # # Written in Python 2.7.7, ...
# 使用多线程: 在协程中集成阻塞io import asyncio import socket import time from concurrent.futures.thread import ThreadPoolExecutor from urllib.parse import urlparse def get_url(url): url = urlparse(url) path = url.path host = url.netloc if path == "": path = "/" # client 为固定写法 client = socket.socket(socket.AF_INET, sock...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 OpenStack 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
"""Give and take items to/from a character.""" from . import numbers as no class ItemGiver: """The ItemGiver class.""" def give(self, character): """Give or take items.""" raise NotImplementedError() class Add(ItemGiver): """Add an item.""" def __init__(self, item, value=no.Consta...
import functools import importlib import pathlib import pkgutil import re import click from . import builders from .formatter import AssetFormatter from .writer import AssetWriter def make_symbol_name(base=None, working_path=None, input_file=None, input_type=None, input_subtype=None, prefix=None): if base is No...
import torch import torch.nn as nn import torch.nn.functional as F class BatchRNN(nn.Module): """ RNN layer with BatchNormalization and parameter reset, convert input: (batch, windows, in_features) into output: (batch, windows, out_features) optional: bidirectional default set to be True which means u...
import os import re import sys from atlassian import Confluence from bs4 import BeautifulSoup def verify_environment_variables(): return os.getenv("ATLASSIAN_EMAIL") and os.getenv("ATLASSIAN_API_TOKEN") def trim_html_tags(html): soup = BeautifulSoup(html, "html.parser") return soup.get_text() def ext...
""" parses the input file for keywords """ from autoparse.find import first_capture from autoparse.find import all_captures from autoparse.pattern import capturing from autoparse.pattern import zero_or_more from autoparse.pattern import one_or_more from autoparse.pattern import escape from autoparse.pattern import NON...
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.utils import cint from frappe.model.document import Document class Report(Document): def validate(self): """only administrat...
import argparse import numpy as np from sklearn.preprocessing import normalize from sklearn.neighbors import NearestNeighbors from sklearn.metrics.pairwise import cosine_similarity from transformers import RobertaTokenizer import logging from ..models.multnat_model import MultNatModel def print_nn(pattern: np.array, ...
# Implementar los metodos de la capa de datos de socios. from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from practico_05.ejercicio_01 import Base, Socio class DatosSocio(object): def __init__(self): engine = create_engine('sqlite:///socios.db') Base.metadata.bind =...
def assign_fallback(config, default): return config if config is not None else default def assign_raise(config): if config is None or config == "": raise ValueError() else: return config
"""A simple parser for SWF files.""" def byte_align(pos): """Return the smallest multiple of 8 greater than ``pos``. Raises ``ValueError`` if ``pos`` is negative. """ if pos < 0: msg = "Expected positive integer, got {}" raise ValueError(msg.format(pos)) return ((pos + 7) // 8) * 8 ...
from .mixins import PreviewMixin
from __future__ import print_function from eventlet import event as _event class metaphore(object): """This is sort of an inverse semaphore: a counter that starts at 0 and waits only if nonzero. It's used to implement a "wait for all" scenario. >>> from eventlet import coros, spawn_n >>> count = cor...
#!/usr/bin/env python #coding=utf-8 """ counters.py: because we are using complex structures, we think it is a good idea to have a file for the purpose. """ __author__ = "Francisco Maria Calisto" __maintainer__ = "Francisco Maria Calisto" __email__ = "francisco.calisto@tecnico.ulisboa.pt" __l...
# -*- coding: utf-8 -*- ## @package inversetoon.geometry.line # # Implementation of a 2D line. # @author tody # @date 2015/08/12 import numpy as np from inversetoon.np.norm import normalizeVector from inversetoon.geometry.bounding_box import BoundingBox ## Implementation of a 2D line. class Line: ...
# This function is triggered by an S3 event when an object is created. It # starts a transcription job with the media file, and sends an email notifying # the user that the job has started. import boto3 import uuid import os import re import urllib.parse s3 = boto3.client('s3') ses = boto3.client('ses') transcribe = ...
import sys from PyQt5 import QtWidgets from src.config import Window if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) window = Window() sys.exit(app.exec_())
""" Creates data visualizations for hierarchical Fides resource types. """ from typing import Generator, List, Dict import plotly import plotly.graph_objects as go from fidesctl.core import config FIDES_KEY_NAME = "fides_key" FIDES_PARENT_NAME = "parent_key" def hierarchy_figures( categories: List[dict], ...
import cv2 import numpy as np classificador = cv2.CascadeClassifier("haarcascade-frontalface-default.xml") classificadorOlhos = cv2.CascadeClassifier("haarcascade-eye.xml") camera = cv2.VideoCapture(0) amostra = 1 numeroAmostra = 25 id = input('Digite o seu identificador: ') largura, altura = 220, 220 print("Capturand...
# python scraperv2.py https://www.bog.gov.gh/treasury-and-the-markets/treasury-bill-rates/ # python scraperv2.py https://www.bog.gov.gh/treasury-and-the-markets/historical-interbank-fx-rates/ import requests from bs4 import BeautifulSoup as bs import urllib3 from _datetime import datetime import csv import s...
# Licensed to Modin Development Team under one or more contributor license agreements. # See the NOTICE file distributed with this work for additional information regarding # copyright ownership. The Modin Development Team licenses this file to you under the # Apache License, Version 2.0 (the "License"); you may not u...
""" 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 distri...
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor from ..utils import unified_timestamp class InternazionaleIE(InfoExtractor): _VALID_URL = ( r"https?://(?:www\.)?internazionale\.it/video/(?:[^/]+/)*(?P<id>[^/?#&]+)" ) _TESTS = [ { "url"...
from itertools import chain from math import ceil from pathlib import Path from typing import Tuple import numpy as np import torch import torch.distributions as td from visdom import Visdom from .optimizer import Optimizer from .rssm import Rssm, State, kl_divergence_between_states from .utils import Dataset, Freeze...
fiboValuePre = 0 fiboValueNext = 1 sumValue = 0 fiboValueNextNext = 0 while fiboValueNextNext <= 4000000 : fiboValueNextNext = fiboValuePre+fiboValueNext if fiboValueNextNext%2==0 : sumValue += fiboValueNextNext fiboValuePre = fiboValueNext fiboValueNext = fiboValueNextNext print(str(sumVal...
''' This script uploads our datasets into openml with its API. It then produces a python snippet to be pasted in the web page to import the dataset via sklearn through openml Notes: 1. We remove non-ascii characters within the categorical (nominal) values (it does not work if we don't do this) 2. We remove the...
import numpy as np """ some really utils functions """ def get_score_label_array_from_dict(score_dict, label_dict): """ :param score_dict: defaultdict(list) :param label_dict: defaultdict(list) :return: np array with score and label """ assert len(score_dict) == len(label_dict), "The score_di...
import os from src.Downloaders import * def archiveUpdate(dirList=[],keep_text_format=False): if not dirList: dirList=os.listdir('./novel_list') print("list=") print(dirList) for novel_folder in dirList: print() novelInfo=getNovelInfoFromFolderName(novel_folder) #chan...
from menten_gcn import DataMaker import menten_gcn.decorators as decs import numpy as np class Maguire_Grattarola_2021(DataMaker): def __init__(self): decorators = [decs.Sequence(), decs.CACA_dist(), decs.PhiPsiRadians(), decs.ChiAngleDecorator(), decs.trRosettaEdges(), ...
#!/usr/bin/env python # # json_serializers.py # Contains JSON (de)serializers for: # torch.Tensor # numpy.ndarray # numpy.dtype # numpy.floating # numpy.integer from __future__ import print_function import six import json import base64 import io import numpy as np import torch def deserialize_t...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('core', '0028_auto_20151222_1711'), ] operations = [ migrations.AddField( model_name='customer', name...
# -*- coding: utf-8 -*- """ Created on Fri Apr 26 11:15:35 2019 @author: michaelek """ import os import pandas as pd from hydrointerp import Interp from ecandbparams import sql_arg from pdsql import mssql import parameters as param import eto_estimates as eto pd.options.display.max_columns = 10 #####################...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging from fairseq.tasks import register_task from fairseq.tasks.joint_task import JointTrainingTask logger = logging.getLogger(__...
""" Make a list of people who should take the favorite languages poll and then loop through the list and find some new member for the poll """ favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } names = ['james', 'sarah', 'carolina', 'edward', 'cynthya'] for n...
class Solution: def findNumbers(self, nums: List[int]) -> int: max1 = 0 for i in nums: count = 0 while(i): i = i // 10 count += 1 if not (count % 2): max1 += 1 return max1
import sys from classFinder import * if len(sys.argv) != 2: print "Parses documentation to find commands for each kind of commandable object" print "Usage: %s <javadoc dir>"%(sys.argv[0]) sys.exit() docDir=sys.argv[1] # Look for all classes lib=ClassLibrary() lib.findClasses(docDir) ## Get all extensions of BaseS...
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages setup( name='librarywatch', version='1.0.1', description='A utility to check PyPi for updates to currently installed packages', author='Jeff Triplett / Adam Fast', author_email='adamfast@gmail.com', url='h...
# Copyright 2014-2018 The PySCF Developers. 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 appl...
# DNA -> RNA Transcription def transcribe(seq: str) -> str: """ transcribes DNA to RNA by generating the complement sequence with T -> U replacement """ seq_list = list(seq) for i in range(len(seq_list)): if seq_list[i] == 'A': seq_list[i] = 'U' elif seq_list[i] == ...
# -*- coding: UTF-8 -*- from GameMessage import Message from Core import Packer import asyncore, socket import threading import time import sys import Setting MESSAGES = [] class ClientInput(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.is_inputing = False se...
# This class expects to be useless, except from the point # of storytelling. It tells you the story that you can use # all the nice pytest fixtures from Kotti itself in your # tests without the need of deriving from UnitTestCase. # The db_session parameter is a fixture, defined in here: # https://github.com/Pylons/Kot...
from functools import partial, wraps import simpy import matplotlib import numpy as np import matplotlib.pyplot as plt import networkx as nx import time def trace(env, callback): def get_wrapper(env_step, callback): @wraps(env_step) def tracing_step(): if len(env._queue): t, prio, eid, event = env._queue...
''' Python has something called "duck typing". It's not special, but the idea is "If it walks like a duck and quacks like a duck, it's a duck" Because nothing is strongly typed (like C, C++, C#, Java) you can pass anything anywhere you want. This is super flexible for developers, but it's al...
""" Unit test the NodeExecutor class. Full coverage achieved, refactoring for readability & efficiency ongoing. """ import unittest from unittest.mock import patch, call from collections import namedtuple import sys from NodeExecutor import NodeExecutor class Test_environment(unittest.TestCase): """Test the env...
# coding=utf-8 """ Copyright 2012 Ali Ok (aliokATapacheDOTorg) 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 ...
# Strings are immutable # The variables which are assigned to a strings are actually # object references and not the objects inself #Concatenation in strings str1 = "New "+"York "+"city" print(str1) # Augmented assignment operator str1= "New " str1+= "York " str1+= "City" print(str1) """ # Use of join() method ...
import json from django.http import JsonResponse from rest_framework import generics from currency.models import Rate from .serializers import RateSerializer def hello_world(request): return JsonResponse({'hello': 'world'}) # http://localhost:8000/api/v1/currency/rates/ class RatesView(generics.ListCreateAPI...
def convert(substr): assoc_table = {"A": "0", "C": "1", "G": "2", "T": "3"} return int("".join([assoc_table[string] for string in list(substr)]), 4) if __name__ == "__main__": text = str(input()) k = int(input()) acid_dna = [0] * (4 ** k) for i in range(len(text) - k + 1): acid_dna[co...
import argparse import copy import os, sys import numpy as np from sklearn.model_selection import train_test_split import tensorflow as tf import tensorflow.keras as keras from tensorflow.keras.preprocessing.image import ImageDataGenerator BASE_PATH = os.path.dirname(os.path.realpath(__file__)) MODULES_PATH = os.path...
import glob import numpy as np import os.path as osp from PIL import Image import random import struct from torch.utils.data import Dataset import scipy.ndimage as ndimage import cv2 from skimage.measure import block_reduce import h5py import scipy.ndimage as ndimage class BatchLoader(Dataset): def __init__(self...
""" """ #all this importation stuff? import SimReceiver import SimBoard import SimMotor import SimSensors class FHackflightFlightManager(FFlightManager): def __init__(self, pawn, mixer, motors, dynamics\ pidEnabled = True ): #??? FFlightManager(dynamics) self....
# doticompile.py # # Manage .icompile files import ConfigParser, string, os, copyifnewer, templateG3D, templateHello from utils import * from doxygen import * from variables import * from help import * # If True, the project will not be rebuilt if all dependencies # other than iCompile are up to date. This is handy...
# Copyright (c) 2022 PaddlePaddle 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 app...
from dopy.manager import DoError class DoMissingVariableError(DoError): def __init__(self, message=None): self.message = message if message is None: self.message = "Missing Required Variable" super(DoMissingVariableError, self).__init__(self.message) class DoEnvironmentError(...
from abc import abstractmethod, ABC from gym_cooking.cooking_world.constants import * class Object(ABC): def __init__(self, location, movable, walkable): self.location = location self.movable = movable # you can pick this one up self.walkable = walkable # you can walk on it def nam...
""" Config flow for APC Home """
from pdfminer.psparser import LIT, PSLiteral, PSStackParser, PSKeyword, PSEOF, keyword_name from pdfminer.pdftypes import PDFObjRef, resolve1, dict_value, stream_value, list_value, PDFStream from PIL import ImageCms from io import BytesIO import numpy as np from itertools import product class colorSpaces: @prop...
import json import logging import os import sys from confluent_kafka import Consumer, KafkaException from dnsagent import agent logger = logging.getLogger(__name__) def consume(): brokers = os.environ.get("RESTKNOT_KAFKA_BROKERS") topic = os.environ.get("RESTKNOT_KAFKA_TOPIC") group_id = os.environ.get...
import argparse import subprocess import wandb from config import PROJECT, BUCKET # Initial condition timesteps to gather for training data train_timestamps = ["1", "3", "4", "5", "7", "8", "10", "11", "12"] # Initial condition timesteps to gather for testing data valid_timestamps = ["2", "6", "9"] if __name__ ==...
import time from get_model_and_data import get_model_and_data from probflow.callbacks import TimeOut def test_TimeOut(): # Get a model and data my_model, x, y = get_model_and_data() # Test TimeOut to = TimeOut(2) ts = time.time() my_model.fit(x, y, batch_size=5, epochs=10000, callbacks=[to...
import re def get_text(string): """ normalizing white space and stripping HTML markups. """ text = re.sub('\s+',' ',string) text = re.sub(r'<.*?>',' ',text) return text print get_text("<pre>Hi,<br><br>Unless I&#69;m mistaken, this bill has not been paida Do I know if there is a problem or if it&#69;s just...
import typing from web3 import Web3 from src.common.types import ConfigTeam, ConfigUser, Tus, TeamTask, LootStrategyName, ReinforceStrategyName from .dotenv import getenv import os from typing import List, cast from src.common.exceptions import InvalidConfig, MissingConfig from eth_typing import Address ##############...
from django.http import HttpResponse def index(request): return HttpResponse("Welcome page, project works!")
import os import sys def test_wrong_merge(): p = os.popen("grep -rnw ./djcourses -e \'<<<<<<< HEAD\'").read() if p: print(p) sys.exit(1) sys.exit(0) if __name__ == "__main__": test_wrong_merge()
import unittest import cmdtools class TestProcess(unittest.TestCase): def test_process(self): cmd = "/sum 10 10 10" cmd = cmdtools.Cmd(cmd, convert_args=True) res = cmd.process_cmd(TestProcess.sum) self.assertEqual(res, 30, "boo") def test_match(self): cmd = '/sell "...
# File IO - Append # File my_file = "my_phone_book.txt" # Add def add_entry(first_name, last_name, phone_number): entry = first_name + "," + last_name + "," + phone_number + "\n" with open(my_file, "a") as file_handler: file_handler.write(entry) # Get list def get_list_from_file(file_name): pho...
# 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, software # distributed under t...
from datetime import datetime from .parser import Parser from .simulation import Simulation from ._helpers import properties parser = Parser() simulation = Simulation() warnings = properties["warnings"] messages = properties["messages"] def parse(*args, **kwargs): parser.parse(*args, **kwargs) def run(*args, **k...
# Desafio 101 - FUNÇÕES ''' Crie um programa que tenha uma função chamada voto() que vai Receber o ano de nascimento de uma pessoa, retornando um valor literal indicando se a pessoa tem voto Obrigatório, Facultativo ou não vota. ''' def voto(ano): from datetime import date a = date.today().year ...
from json import dumps import pytest import os def test_model_inference_success(test_client, input_line): """ API /predict' with the valid input results model inference success and return the status code 200 """ response = test_client.post('/predict', data=dumps(input_...
from django.contrib import admin from electricity.models import electricity # Register your models here. admin.site.register(electricity)
''' Instructions You have access to a database of student_scores in the format of a dictionary. The keys in student_scores are the names of the students and the values are their exam scores. Write a program that converts their scores to grades. By the end of your program, you should have a new dictionary called s...
""" Tests for the ``aliquotmaf.filters.ExAC`` class. """ from collections import OrderedDict import pytest from maflib.column_types import NullableFloatColumn from aliquotmaf.converters.builder import get_builder from aliquotmaf.filters import ExAC subpops = [ "nontcga_ExAC_AF_Adj", "nontcga_ExAC_AF", "n...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, division, unicode_literals import binascii import collections import copy import ctypes import datetime import hashlib import uuid import six from . import c from .utils import CObjectWrapper, PrettyOrderedDict, coerce_char_p, coer...
import matplotlib.pyplot as plt from matplotlib.lines import Line2D import numpy as np import pathlib def plot_comparison(control, control_sim, modulated, modulated_sim, num_models, ylabel=None, title=None, x_ticks=tuple(),width=None,height=None,dir_path=None, save=False, filename=None): fig, ...
import numpy as np import torch from torchvision.utils import make_grid from .base import ModelAdapter __all__ = ['Segmentation3dModelAdapter'] class Segmentation3dModelAdapter(ModelAdapter): def __init__(self, config, log_path): super(Segmentation3dModelAdapter, self).__init__(config, log_path) ...
""" https://docs.python.org/3/library/enum.html """ from enum import Enum class Color(Enum): RED = 1 GREEN = 2 BLUE = 3 if __name__ == "__main__": color_names = [c.name for c in Color] color_values = [c.value for c in Color] print(color_names) print(color_values) print(Color["RED"]...
#!/usr/bin/env python import time, struct,sys import bluetooth from mindwavemobile.MindwaveDataPoints import AttentionDataPoint, EEGPowersDataPoint from mindwavemobile.MindwaveDataPointReader import MindwaveDataPointReader import numpy as np import pylab as pl def main(): mdpr = MindwaveDataPointReader() mdpr.st...
"""Entrypoint for `ee`. Functions not decorated with @app are actions to affect state""" import readline # noqa: F401 from typing import List import pyperclip import typer from click import clear from ee_cli import __doc__, __version__ from ee_cli.constants import CONFIGURATION_INFO, HOTWORDS_HELP, MAYBE_TZ_HEADS_UP...
from __future__ import division, unicode_literals from PIL import Image, ImageOps PROCESSORS = {} def build_handler(processors, handler=None): handler = handler or (lambda image, context: image) for part in reversed(processors): if isinstance(part, (list, tuple)): handler = PROCESSORS[...
from .neumann import TruncatedNeumannEstimator
from gym.envs.registration import register register( id='Hacktrick-v0', entry_point='hacktrick_ai_py.mdp.hacktrick_env:Hacktrick', )