text
string
size
int64
token_count
int64
# Standard Library import logging import os import socket import sys from collections import defaultdict # First Party from smdebug.core.config_constants import LOG_DUPLICATION_THRESHOLD _logger_initialized = False class MaxLevelFilter(logging.Filter): """Filters (lets through) all messages with level < LEVEL""" def __init__(self, level): super().__init__() self.level = level def filter(self, record): # "<" instead of "<=": since logger.setLevel is inclusive, this should be exclusive return record.levelno < self.level class DuplicateLogFilter: """Filters duplicate messages to prevent spamming users""" def __init__(self): self.msgs = defaultdict(int) self.repeat_threshold = LOG_DUPLICATION_THRESHOLD def filter(self, record): self.msgs[record.msg] += 1 return self.msgs[record.msg] <= self.repeat_threshold def _get_log_level(): default = "info" log_level = os.environ.get("SMDEBUG_LOG_LEVEL", default=default) log_level = log_level.lower() allowed_levels = ["info", "debug", "warning", "error", "critical", "off"] if log_level not in allowed_levels: log_level = default level = None if log_level is None or log_level == "off": level = None else: if log_level == "critical": level = logging.CRITICAL elif log_level == "error": level = logging.ERROR elif log_level == "warning": level = logging.WARNING elif log_level == "info": level = logging.INFO elif log_level == "debug": level = logging.DEBUG return level def get_logger(name="smdebug"): global _logger_initialized if not _logger_initialized: worker_pid = f"{socket.gethostname()}:{os.getpid()}" log_context = os.environ.get("SMDEBUG_LOG_CONTEXT", default=worker_pid) level = _get_log_level() logger = logging.getLogger(name) logger.handlers = [] log_formatter = logging.Formatter( fmt="[%(asctime)s.%(msecs)03d " + log_context + " %(levelname)s %(filename)s:%(lineno)d] %(message)s", datefmt="%Y-%m-%d %H:%M:%S", ) stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setFormatter(log_formatter) if os.environ.get("SMDEBUG_LOG_ALL_TO_STDOUT", default="TRUE").lower() == "false": stderr_handler = logging.StreamHandler(sys.stderr) min_level = logging.DEBUG # lets through all levels less than ERROR stdout_handler.addFilter(MaxLevelFilter(logging.ERROR)) stdout_handler.setLevel(min_level) stderr_handler.setLevel(max(min_level, logging.ERROR)) stderr_handler.setFormatter(log_formatter) logger.addHandler(stderr_handler) logger.addHandler(stdout_handler) logger.addFilter(DuplicateLogFilter()) # SMDEBUG_LOG_PATH is the full path to log file # by default, log is only written to stdout&stderr # if this is set, it is written to file path = os.environ.get("SMDEBUG_LOG_PATH", default=None) if path is not None: fh = logging.FileHandler(path) fh.setFormatter(log_formatter) logger.addHandler(fh) if level: logger.setLevel(level) else: logger.disabled = True logger.propagate = False _logger_initialized = True return logging.getLogger(name)
3,562
1,064
# -*- coding: utf-8 -*- # Scrapy settings for scrapper project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # http://doc.scrapy.org/en/latest/topics/settings.html # http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html # http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html import os # CATEGORY MAPPING SETTINGS CATEGORY_MAPPING = { "dafiti": { "calcados femininos": ["Feminino", "Calçados"], "calcados masculinos": ["Masculino", "Calçados"], "calcados infantis": ["Infantil", "Calçados"], "esporte masculino": ["Masculino", "Esporte"], "esporte feminino": ["Feminino", "Esporte"], "roupas masculinas": ["Masculino", "Roupas"], "roupas femininas": ["Feminino", "Roupas"], "roupas infantis": ["Infantil", "Roupas"], "bolsas e acessorios masculinos": ["Masculino", "Acessórios"], "bolsas e acessorios femininos": ["Feminino", "Acessórios"], "bolsas e acessorios infantis": ["Infantil", "Acessórios"] }, "kanui": { "feminino-acessorios": ["Feminino", "Acessórios"], "feminino-agasalhos": ["Feminino", "Roupas"], "feminino-alpargatas": ["Feminino", "Calçados"], "feminino-bermudas": ["Feminino", "Roupas"], "feminino-bijouterias": ["Feminino", "Acessórios"], "feminino-biquinis": ["Feminino", "Roupas"], "feminino-blazers": ["Feminino", "Roupas"], "feminino-blusas": ["Feminino", "Roupas"], "feminino-bodys": ["Feminino", "Roupas"], "feminino-bolsas": ["Feminino", "Acessórios"], "feminino-bones": ["Feminino", "Acessórios"], "feminino-botas": ["Feminino", "Calçados"], "feminino-cachecois": ["Feminino", "Acessórios"], "feminino-calcados": ["Feminino", "Calçados"], "feminino-calcas": ["Feminino", "Roupas"], "feminino-calcinha": ["Feminino", "Roupas"], "feminino-camisas": ["Feminino", "Roupas"], "feminino-camisetas": ["Feminino", "Roupas"], "feminino-carteiras": ["Feminino", "Acessórios"], "feminino-casacos": ["Feminino", "Roupas"], "feminino-casuais": ["Feminino", "Roupas"], "feminino-chinelos": ["Feminino", "Calçados"], "feminino-chuteiras": ["Feminino", "Esporte"], "feminino-ciclismo": ["Feminino", "Esporte"], "feminino-cintos": ["Feminino", "Acessórios"], "feminino-coletes": ["Feminino", "Roupas"], "feminino-cueca": ["Feminino", "Roupas"], "feminino-docksides": ["Feminino", "Calçados"], "feminino-equipamentos": ["Feminino", "Esporte"], "feminino-gorros": ["Feminino", "Acessórios"], "feminino-jaquetas": ["Feminino", "Roupas"], "feminino-jardineiras": ["Feminino", "Roupas"], "feminino-kimonos": ["Feminino", "Esporte"], "feminino-lencos": ["Feminino", "Roupas"], "feminino-lingeries": ["Feminino", "Roupas"], "feminino-luvas": ["Feminino", "Acessórios"], "feminino-macacoes": ["Feminino", "Roupas"], "feminino-macaquinhos": ["Feminino", "Roupas"], "feminino-maios": ["Feminino", "Roupas"], "feminino-meias": ["Feminino", "Roupas"], "feminino-mocassins": ["Feminino", "Roupas"], "feminino-moletons": ["Feminino", "Roupas"], "feminino-oxfords": ["Feminino", "Calçados"], "feminino-polos": ["Feminino", "Roupas"], "feminino-protetores": ["Feminino", "Esporte"], "feminino-relogios": ["Feminino", "Acessórios"], "feminino-roupas": ["Feminino", "Roupas"], "feminino-saias": ["Feminino", "Roupas"], "feminino-sapatenis": ["Feminino", "Calçados"], "feminino-sapatilhas": ["Feminino", "Calçados"], "feminino-shorts": ["Feminino", "Roupas"], "feminino-slippers": ["Feminino", "Calçados"], "feminino-tenis": ["Feminino", "Calçados"], "feminino-tops": ["Feminino", "Roupas"], "feminino-tricots": ["Feminino", "Roupas"], "feminino-vestidos": ["Feminino", "Roupas"], "feminino-viseiras": ["Feminino", "Esporte"], "feminino-wetsuits": ["Feminino", "Esporte"], "masculino-acessorios": ["Masculino", "Acessórios"], "masculino-agasalhos": ["Masculino", "Roupas"], "masculino-alpargatas": ["Masculino", "Calçados"], "masculino-bermuda": ["Masculino", "Roupas"], "masculino-bermudas": ["Masculino", "Roupas"], "masculino-bijouterias": ["Masculino", "Acessórios"], "masculino-blusas": ["Masculino", "Roupas"], "masculino-bolsas": ["Masculino", "Acessórios"], "masculino-bones": ["Masculino", "Acessórios"], "masculino-botas": ["Masculino", "Calçados"], "masculino-cachecois": ["Masculino", "Acessórios"], "masculino-calcados": ["Masculino", "Calçados"], "masculino-calcas": ["Masculino", "Roupas"], "masculino-camisas": ["Masculino", "Roupas"], "masculino-camisetas": ["Masculino", "Roupas"], "masculino-carteiras": ["Masculino", "Acessórios"], "masculino-casacos": ["Masculino", "Roupas"], "masculino-chinelos": ["Masculino", "Calçados"], "masculino-chuteiras": ["Masculino", "Esporte"], "masculino-ciclismo": ["Masculino", "Esporte"], "masculino-cintos": ["Masculino", "Acessórios"], "masculino-coletes": ["Masculino", "Roupas"], "masculino-corrida": ["Masculino", "Esporte"], "masculino-cueca": ["Masculino", "Roupas"], "masculino-equipamentos": ["Masculino", "Esporte"], "masculino-gorros": ["Masculino", "Acessórios"], "masculino-jaquetas": ["Masculino", "Roupas"], "masculino-kimonos": ["Masculino", "Esporte"], "masculino-lingeries": ["Masculino", "Roupas"], "masculino-luvas": ["Masculino", "Acessórios"], "masculino-meias": ["Masculino", "Roupas"], "masculino-mocassins": ["Masculino", "Roupas"], "masculino-moletom": ["Masculino", "Roupas"], "masculino-moletons": ["Masculino", "Roupas"], "masculino-oculos": ["Masculino", "Acessórios"], "masculino-polos": ["Masculino", "Roupas"], "masculino-protetores": ["Masculino", "Esporte"], "masculino-relogios": ["Masculino", "Acessórios"], "masculino-roupas": ["Masculino", "Roupas"], "masculino-sacos": ["Masculino", "Esporte"], "masculino-saias": ["Masculino", "Roupas"], "masculino-sapatenis": ["Masculino", "Calçados"], "masculino-sapatilhas": ["Masculino", "Calçados"], "masculino-shorts": ["Masculino", "Roupas"], "masculino-sungas": ["Masculino", "Roupas"], "masculino-tenis": ["Masculino", "Calçados"], "masculino-vestidos": ["Masculino", "Roupas"], "masculino-wetsuits": ["Masculino", "Esporte"], "menina-acessorios": ["Infantil", "Acessórios"], "menina-bermudas": ["Infantil", "Roupas"], "menina-bijouterias": ["Infantil", "Acessórios"], "menina-blusas": ["Infantil", "Roupas"], "menina-bodys": ["Infantil", "Roupas"], "menina-bolsas": ["Infantil", "Acessórios"], "menina-botas": ["Infantil", "Calçados"], "menina-calcados": ["Infantil", "Calçados"], "menina-camisetas": ["Infantil", "Roupas"], "menina-chinelos": ["Infantil", "Calçados"], "menina-lingeries": ["Infantil", "Roupas"], "menina-macaquinhos": ["Infantil", "Roupas"], "menina-mochilas": ["Infantil", "Acessórios"], "menina-roupas": ["Infantil", "Roupas"], "menina-saias": ["Infantil", "Roupas"], "menina-sapatilhas": ["Infantil", "Calçados"], "menina-slippers": ["Infantil", "Calçados"], "menina-tenis": ["Infantil", "Calçados"], "menina-vestidos": ["Infantil", "Roupas"], "menino-acessorios": ["Infantil", "Acessórios"], "menino-bermudas": ["Infantil", "Roupas"], "menino-botas": ["Infantil", "Calçados"], "menino-calcados": ["Infantil", "Calçados"], "menino-calcas": ["Infantil", "Roupas"], "menino-camisetas": ["Infantil", "Roupas"], "menino-chinelos": ["Infantil", "Calçados"], "menino-cueca": ["Infantil", "Roupas"], "menino-jaquetas": ["Infantil", "Roupas"], "menino-mochilas": ["Infantil", "Acessórios"], "menino-polos": ["Infantil", "Roupas"], "menino-relogios": ["Infantil", "Acessórios"], "menino-roupas": ["Infantil", "Roupas"], "menino-sapatenis": ["Infantil", "Calçados"], "menino-sapatilhas": ["Infantil", "Calçados"], "menino-tenis": ["Infantil", "Calçados"], "unissex-acessorios": ["Unissex", "Acessórios"], "unissex-alpargatas": ["Unissex", "Roupas"], "unissex-bermudas": ["Unissex", "Roupas"], "unissex-bijouterias": ["Unissex", "Acessórios"], "unissex-blusas": ["Unissex", "Roupas"], "unissex-bodys": ["Unissex", "Roupas"], "unissex-bolsas": ["Unissex", "Acessórios"], "unissex-bones": ["Unissex", "Acessórios"], "unissex-botas": ["Unissex", "Roupas"], "unissex-cachecois": ["Unissex", "Roupas"], "unissex-calcados": ["Unissex", "Roupas"], "unissex-calcas": ["Unissex", "Roupas"], "unissex-camisas": ["Unissex", "Roupas"], "unissex-camisetas": ["Unissex", "Roupas"], "unissex-carteiras": ["Unissex", "Acessórios"], "unissex-chinelos": ["Unissex", "Roupas"], "unissex-ciclismo": ["Unissex", "Esporte"], "unissex-cintos": ["Unissex", "Acessórios"], "unissex-corrida": ["Unissex", "Esporte"], "unissex-cueca": ["Unissex", "Roupas"], "unissex-equipamentos": ["Unissex", "Esporte"], "unissex-jaquetas": ["Unissex", "Roupas"], "unissex-kimonos": ["Unissex", "Esporte"], "unissex-lingeries": ["Unissex", "Roupas"], "unissex-luvas": ["Unissex", "Roupas"], "unissex-meias": ["Unissex", "Roupas"], "unissex-mocassins": ["Unissex", "Roupas"], "unissex-mochilas": ["Unissex", "Roupas"], "unissex-moletons": ["Unissex", "Roupas"], "unissex-oculos": ["Unissex", "Acessórios"], "unissex-protetores": ["Unissex", "Esporte"], "unissex-relogios": ["Unissex", "Acessórios"], "unissex-roupas": ["Unissex", "Roupas"], "unissex-sapatenis": ["Unissex", "Roupas"], "unissex-sapatilhas": ["Unissex", "Roupas"], "unissex-shorts": ["Unissex", "Roupas"], "unissex-sungas": ["Unissex", "Roupas"], "unissex-tenis": ["Unissex", "Roupas"], "unissex-toucas": ["Unissex", "Acessórios"], "unissex-vestidos": ["Unissex", "Roupas"], "unissex-wetsuits": ["Unissex", "Esporte"] }, "farfetch": { "kids-luxe-meninas - roupa infantil": ["Infantil", "Roupas"], "kids-luxe-roupa infantil": ["Infantil", "Roupas"], "kids-luxe-roupa para bebe": ["Infantil", "Roupas"], "kids-luxe-roupas para bebe menina": ["Infantil", "Roupas"], "men-luxe-acessorios": ["Masculino", "Acessórios"], "men-luxe-bijoux & joias": ["Masculino", "Acessórios"], "men-luxe-bolsas": ["Masculino", "Acessórios"], "men-luxe-fitness": ["Masculino", "Esporte"], "men-luxe-roupas": ["Masculino", "Roupas"], "men-luxe-sapatos": ["Masculino", "Calçados"], "unisex-luxe-acessorios": ["Unissex", "Acessórios"], "unisex-luxe-bijoux & joias": ["Unissex", "Acessórios"], "unisex-luxe-bolsas": ["Unissex", "Acessórios"], "unisex-luxe-fitness": ["Unissex", "Esporte"], "unisex-luxe-roupas": ["Unissex", "Roupas"], "unisex-luxe-sapatos": ["Unissex", "Calçados"], "women-luxe-acessorios": ["Feminino", "Acessórios"], "women-luxe-bijoux & joias": ["Feminino", "Acessórios"], "women-luxe-bolsas": ["Feminino", "Acessórios"], "women-luxe-fitness": ["Feminino", "Esporte"], "women-luxe-roupas": ["Feminino", "Roupas"], "women-luxe-sapatos": ["Feminino", "Calçados"] }, "passarela": { "feminino-acessorios": ["Feminino", "Acessórios"], "feminino-calcados": ["Feminino", "Calçados"], "feminino-moda intima": ["Feminino", "Roupas"], "feminino-roupas": ["Feminino", "Roupas"], "infantil-acessorios": ["Infantil", "Acessórios"], "infantil-calcados": ["Infantil", "Calçados"], "infantil-moda intima": ["Infantil", "Roupas"], "infantil-roupas": ["Infantil", "Roupas"], "masculino-acessorios": ["Masculino", "Acessórios"], "masculino-calcados": ["Masculino", "Calçados"], "masculino-moda intima": ["Masculino", "Roupas"], "masculino-roupas": ["Masculino", "Roupas"], "unissex-acessorios": ["Unissex", "Acessórios"] } } BOT_NAME = 'scrapper' SPIDER_MODULES = ['scrapper.spiders'] NEWSPIDER_MODULE = 'scrapper.spiders' LOG_LEVEL='INFO' # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'scrapper (+http://www.yourdomain.com)' # Obey robots.txt rules ROBOTSTXT_OBEY = True # Configure maximum concurrent requests performed by Scrapy (default: 16) #CONCURRENT_REQUESTS = 32 # Configure a delay for requests for the same website (default: 0) # See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay # See also autothrottle settings and docs #DOWNLOAD_DELAY = 3 # The download delay setting will honor only one of: #CONCURRENT_REQUESTS_PER_DOMAIN = 16 #CONCURRENT_REQUESTS_PER_IP = 16 # Disable cookies (enabled by default) #COOKIES_ENABLED = False # Disable Telnet Console (enabled by default) #TELNETCONSOLE_ENABLED = False # Override the default request headers: #DEFAULT_REQUEST_HEADERS = { # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', # 'Accept-Language': 'en', #} # Enable or disable spider middlewares # See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html # SPIDER_MIDDLEWARES = { # 'scrapy_splash.SplashDeduplicateArgsMiddleware': 100, # } # Enable or disable downloader middlewares # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html # DOWNLOADER_MIDDLEWARES = { # 'scrapy_splash.SplashCookiesMiddleware': 723, # 'scrapy_splash.SplashMiddleware': 725, # 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810, # } # Scrapy currently doesn’t provide a way to override request fingerprints calculation globally, # so you will also have to set a custom DUPEFILTER_CLASS and a custom cache storage backend: # DUPEFILTER_CLASS = 'scrapy_splash.SplashAwareDupeFilter' # HTTPCACHE_STORAGE = 'scrapy_splash.SplashAwareFSCacheStorage' # Enable or disable extensions # See http://scrapy.readthedocs.org/en/latest/topics/extensions.html #EXTENSIONS = { # 'scrapy.extensions.telnet.TelnetConsole': None, #} # Configure item pipelines # See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html ITEM_PIPELINES = { # 'scrapy.pipelines.images.ImagesPipeline': 1, 'scrapper.pipelines.CleanPipeline': 100, 'scrapper.pipelines.MongoDBPipeline': 200 } # IMAGE DIRECTORY # IMAGES_STORE = os.path.abspath(os.path.dirname(__file__)) + '/spiders/images' # ALLOW IMAGE REDIRECT MEDIA_ALLOW_REDIRECTS = True # SPLASH_URL = 'http://localhost:8050/' # PROD DB MONGODB_CONNECTION_STRING = 'mongodb://admin:azzaropourhome2@ds155411.mlab.com:55411/fashionbot' # LOCAL DEV # MONGODB_CONNECTION_STRING = 'mongodb://localhost:27017/fashionbot' MONGODB_SERVER = 'ds155411.mlab.com:55411/fashionbot' MONGODB_USER = 'admin' MONGODB_PASSWORD = 'azzaropourhome2' MONGODB_PORT = 27017 MONGODB_DB = 'fashionbot' MONGODB_COLLECTION = 'clothes' # Enable and configure the AutoThrottle extension (disabled by default) # See http://doc.scrapy.org/en/latest/topics/autothrottle.html #AUTOTHROTTLE_ENABLED = True # The initial download delay #AUTOTHROTTLE_START_DELAY = 5 # The maximum download delay to be set in case of high latencies #AUTOTHROTTLE_MAX_DELAY = 60 # The average number of requests Scrapy should be sending in parallel to # each remote server #AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0 # Enable showing throttling stats for every response received: #AUTOTHROTTLE_DEBUG = False # Enable and configure HTTP caching (disabled by default) # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings #HTTPCACHE_ENABLED = True #HTTPCACHE_EXPIRATION_SECS = 0 #HTTPCACHE_DIR = 'httpcache' #HTTPCACHE_IGNORE_HTTP_CODES = [] #HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
15,883
6,732
# # This file is part of datacube-classification # Copyright (C) 2021 INPE. # # datacube-classification Library is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. # """classification models module""" import pandas as pd def train_sklearn_model(model, labeled_timeseries: pd.DataFrame, label_col="label"): """Train a sklearn model using the time series extracted with the `datacube_classification.sits.datacube_get_sits` function This function receives time series with associated labels and performs the model training. To do this, each of the instances present in the input table (labeled_timeseries) must contain a column (label_col) with the associated label information Args: model (object): scikit-learn classification model labeled_timeseries (pd.DataFrame): table with time-series extracted from a data cube. Each instance must be have a label associated label_col (str): column where labels is in `labeled_timeseries` Returns: object: scikit-learn treined model """ x = labeled_timeseries[labeled_timeseries.columns.difference([label_col])] y = labeled_timeseries[label_col].astype(int) return model.fit(x, y)
1,292
368
#!/usr/bin/env python # -*- coding: utf-8 -*- from redis import StrictRedis from HeartbeatMaker import HeartbeatMaker import arrow def test(it): print('%s:%s:心跳' % (arrow.now(), it)) maker = HeartbeatMaker('redis://localhost:6379/0', 'test-beat', test) # maker.clean() # maker.beat_it('bac', 6,'bac-par') # maker.beat_it('shawn', 2,'par') # maker.omit_it('jack') maker.beat_it('jack', 5,'par') # maker.start()
421
190
# Copyright 2021 RushanNotOfficial#1146. 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 applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """ Run the main bot """ from discord_components import DiscordComponents # library for interacting with buttons and components from discord.ext import commands # library for make a client and registering commands TOKEN = "" client = commands.Bot(command_prefix="") # make the bot object client.remove_command("help") # remove the basic help command as we have a better one @client.event # register a new event async def on_ready(): # event name is 'on_ready' which occuurs when the bot reconnects or starts up DiscordComponents(client) # initialize the client with component support print(f'Logged in as: {client.user.name}') # print username to console @client.event # register a new event async def on_message(ctx): # event name is 'on_message' which occurs when a new message is sent anywhere where the bot exists await client.process_commands(ctx) # process the commands if it is a command which is registered cogs = ("cogs.help") # cogs which we want to register. (using a tuple as it takes less space than a array) for cog in cogs: client.load_extension(cog) # load the cog/extension print(f"Loaded {cog} cog") # print the cog name to console client.run(TOKEN) # now, lets run the bot
2,304
564
"""File containing a class for the main gauge.""" from tkinter import font, Label, Frame from classes.widgets.main_gauge import MainGauge from classes.pub_sub import Subscriber class EngineGauge(MainGauge, Subscriber): """ A gauge that displays the speed, acceleration and average speed. """ def __init__(self, app, *args, **kwargs): MainGauge.__init__(self, *args, **kwargs) self.app = app def update(self, message, value): if message == "OBD-ENGINE_LOAD": if value is None: self.update_values(value="--%") else: self.update_values(value=str(int(value))+"%") if message == "OBD-COOLANT_TEMP": if value is None: self.update_values(subvalue="--°C") else: self.update_values(subvalue=str(int(value))+"°C") if message == "OBD-RPM": if value is None: self.update_values(subvalue2="----") else: self.update_values(subvalue2=int(value))
1,076
318
from .core import ( mean, sum, exp, sin, cos, tan, log, tensor, grad_tensor, zeros, ones, randn, rand, Tensor, argmax, ) from .linear import Linear from .model import Module, Sequential from .sampler import TensorSample
280
99
from eth_tester.exceptions import TransactionFailed from utils import captureFilteredLogs, AssertLog, nullAddress, TokenDelta, PrintGasUsed from pytest import raises, mark pytestmark = mark.skip(reason="We might not even need governance and currently dont account for transfering ownership") def test_gov(contractsFixture, universe, reputationToken, cash): if not contractsFixture.paraAugur: return nexus = contractsFixture.contracts["OINexus"] deployer = contractsFixture.accounts[0] bob = contractsFixture.accounts[1] alice = contractsFixture.accounts[2] reputationToken.faucet(100, sender=bob) reputationToken.faucet(100, sender=alice) feePot = contractsFixture.getFeePot(universe) cash.faucet(10000) cash.approve(feePot.address, 10000000000000000) reputationToken.approve(feePot.address, 10000000000000000, sender=bob) reputationToken.approve(feePot.address, 10000000000000000, sender=alice) rewardsToken = contractsFixture.upload('../src/contracts/Cash.sol', "rewardsToken") lpToken = contractsFixture.upload('../src/contracts/Cash.sol', "lpToken") # Deploy GOV token govToken = contractsFixture.upload("../src/contracts/gov/GovToken.sol", constructorArgs=[deployer]) # Deploy Timelock timelock = contractsFixture.upload("../src/contracts/gov/Timelock.sol", constructorArgs=[deployer]) # Deploy a FeePotStakingContract for S_REP (Fee Pot Tokens) feePotStakingContract = contractsFixture.upload("../src/contracts/gov/FeePotStakingRewards.sol", constructorArgs=[deployer, deployer, govToken.address, feePot.address]) initialSupply = 11 * 10**6 * 10**18 govToken.setMintAllowance(feePotStakingContract.address, initialSupply) feePotStakingContract.notifyRewardAmount(initialSupply) # Deploy Governance governance = contractsFixture.upload("../src/contracts/gov/Governance.sol", constructorArgs=[timelock.address, govToken.address]) # Cede control of Timelock to Governance timelock.setAdmin(governance.address) # Cede control of GOV Token to Governance govToken.transferOwnership(timelock.address) # Cede control of OINexus to Governance nexus.transferOwnership(timelock.address) # Cede control of FeePotStakingContract to Governance feePotStakingContract.setRewardsDistribution(timelock.address) feePotStakingContract.transferOwnership(timelock.address) # Get S_REP feePot.stake(1, sender=alice) # Stake feePot.approve(feePotStakingContract.address, 100, sender=alice) feePotStakingContract.stake(1, sender=alice) # Move time timestamp = contractsFixture.eth_tester.backend.chain.header.timestamp contractsFixture.eth_tester.time_travel(int(timestamp + 24 * 60 * 60)) # Redeem feePotStakingContract.exit(sender=alice) totalSupply = govToken.totalSupply() assert governance.quorumVotes() - (totalSupply / 25) == 0 assert governance.proposalThreshold() - (totalSupply / 1000) == 0 assert govToken.balanceOf(alice) == totalSupply target = govToken.address signature = "" calldata = govToken.mint_encode(bob, 100) # Delegate votes to self and propose to mint GOV and fail due to time constraint govToken.delegate(alice, sender=alice) with raises(TransactionFailed): governance.propose([target], [0], [signature], [calldata], "Give Bob the Monies", sender=alice) # Move time forward timestamp = contractsFixture.eth_tester.backend.chain.header.timestamp contractsFixture.eth_tester.time_travel(int(timestamp + 24 * 60 * 60 * 7)) # Propose to mint GOV to Bob proposalId = governance.propose([target], [0], [signature], [calldata], "Give Bob the Monies", sender=alice) # Vote it into effect contractsFixture.eth_tester.backend.chain.mine_block() governance.castVote(proposalId, True, sender=alice) # Queue the proposal timestamp = contractsFixture.eth_tester.backend.chain.header.timestamp contractsFixture.eth_tester.time_travel(int(timestamp + 24 * 60 * 60 * 3)) governance.queue(proposalId) # Execute the proposal timestamp = contractsFixture.eth_tester.backend.chain.header.timestamp contractsFixture.eth_tester.time_travel(int(timestamp + 24 * 60 * 60 * 2)) governance.execute(proposalId) assert govToken.balanceOf(bob) == 100
4,358
1,572
# terrascript/resource/hashicorp/ad.py # Automatically generated by tools/makecode.py (24-Sep-2021 15:10:57 UTC) import terrascript class ad_computer(terrascript.Resource): pass class ad_gplink(terrascript.Resource): pass class ad_gpo(terrascript.Resource): pass class ad_gpo_security(terrascript.Resource): pass class ad_group(terrascript.Resource): pass class ad_group_membership(terrascript.Resource): pass class ad_ou(terrascript.Resource): pass class ad_user(terrascript.Resource): pass __all__ = [ "ad_computer", "ad_gplink", "ad_gpo", "ad_gpo_security", "ad_group", "ad_group_membership", "ad_ou", "ad_user", ]
700
279
import sys from utils import my_train, flickr_train_params, flickr_params, my_test, copy_networks if __name__ == "__main__": do_import = True first_arg = sys.argv[0] if do_import: copy_networks(model_to_import="celeba_cycle", iter="2") flickr_train_params["continue_train"] = True flickr_params["name"] = "flickr_import" params = flickr_params.copy() params.update(flickr_train_params) my_train(params, first_arg) my_test(flickr_params, first_arg, benchmark=True, results_dir="benchmark_results")
557
204
#!/usr/bin/env python import sys import platform from setuptools import setup # from Cython.Build import cythonize def get_version(): with open("pymorphy2/version.py", "rt") as f: return f.readline().split("=")[1].strip(' "\n') # TODO: use environment markres instead of Python code in order to # allow building proper wheels. Markers are not enabled right now because # of setuptools/wheel incompatibilities and the 'pip >= 6.0' requirement. # extras_require = { # 'fast:platform_python_implementation==CPython': ["DAWG>=0.7.7"], # 'fast:platform_python_implementation==CPython and python_version<3.5': [ # "fastcache>=1.0.2" # ], # ':python_version<"3.0"': [ # "backports.functools_lru_cache>=1.0.1", # ], # } is_cpython = platform.python_implementation() == 'CPython' py_version = sys.version_info[:2] install_requires = [ 'dawg-python >= 0.7.1', 'pymorphy2-dicts-ru >=2.4, <3.0', 'docopt >= 0.6', ] if py_version < (3, 0): install_requires.append("backports.functools_lru_cache >= 1.0.1") extras_require = {'fast': []} if is_cpython: extras_require['fast'].append("DAWG >= 0.8") if py_version < (3, 5): # lru_cache is optimized in Python 3.5 extras_require['fast'].append("fastcache >= 1.0.2") setup( name='pymorphy2', version=get_version(), author='Mikhail Korobov', author_email='kmike84@gmail.com', url='https://github.com/kmike/pymorphy2/', description='Morphological analyzer (POS tagger + inflection engine) for Russian language.', long_description=open('README.rst').read(), license='MIT license', packages=[ 'pymorphy2', 'pymorphy2.units', 'pymorphy2.lang', 'pymorphy2.lang.ru', 'pymorphy2.lang.uk', 'pymorphy2.opencorpora_dict', ], entry_points={ 'console_scripts': ['pymorphy = pymorphy2.cli:main'] }, install_requires=install_requires, extras_require=extras_require, zip_safe=False, # ext_modules=cythonize([ # 'pymorphy2/*.py', # 'pymorphy2/units/*.py', # 'pymorphy2/opencorpora_dict/*.py', # ], annotate=True, profile=True), classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Natural Language :: Russian', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Scientific/Engineering :: Information Analysis', 'Topic :: Text Processing :: Linguistic', ], )
3,153
1,081
#!/usr/bin/env python3 # 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 hashlib import os import os.path as osp import pickle import time import attr import gym import magnum as mn import numpy as np import quaternion import habitat_sim from habitat_sim.nav import NavMeshSettings from habitat_sim.physics import MotionType def make_render_only(obj_idx, sim): if hasattr(MotionType, "RENDER_ONLY"): sim.set_object_motion_type(MotionType.RENDER_ONLY, obj_idx) else: sim.set_object_motion_type(MotionType.KINEMATIC, obj_idx) sim.set_object_is_collidable(False, obj_idx) def get_collision_matches(link, colls, search_key="link"): matches = [] for coll0, coll1 in colls: if link in [coll0[search_key], coll1[search_key]]: matches.append((coll0, coll1)) return matches def get_other_matches(link, colls): matches = get_collision_matches(link, colls) other_surfaces = [b if a["link"] == link else a for a, b in matches] return other_surfaces def coll_name(coll, name): return coll_prop(coll, name, "name") def coll_prop(coll, val, prop): return val in [coll[0][prop], coll[1][prop]] def coll_link(coll, link): return coll_prop(coll, link, "link") def swap_axes(x): x[1], x[2] = x[2], x[1] return x @attr.s(auto_attribs=True, kw_only=True) class CollDetails: obj_scene_colls: int = 0 robo_obj_colls: int = 0 robo_scene_colls: int = 0 def rearrange_collision( colls, snapped_obj_id, count_obj_colls, verbose=False, ignore_names=None, ignore_base=True, ): """ Defines what counts as a collision for the Rearrange environment execution """ # Filter out any collisions from the base if ignore_base: colls = [ x for x in colls if not ("base" in x[0]["link"] or "base" in x[1]["link"]) ] def should_keep(x): if ignore_names is None: return True return any(coll_name(x, ignore_name) for ignore_name in ignore_names) # Filter out any collisions with the ignore objects colls = list(filter(should_keep, colls)) # Check for robot collision robo_obj_colls = 0 robo_scene_colls = 0 robo_scene_matches = get_collision_matches("fetch", colls, "name") for match in robo_scene_matches: urdf_on_urdf = ( match[0]["type"] == "URDF" and match[1]["type"] == "URDF" ) with_stage = coll_prop(match, "Stage", "type") fetch_on_fetch = ( match[0]["name"] == "fetch" and match[1]["name"] == "fetch" ) if fetch_on_fetch: continue if urdf_on_urdf or with_stage: robo_scene_colls += 1 else: robo_obj_colls += 1 # Checking for holding object collision obj_scene_colls = 0 if count_obj_colls and snapped_obj_id is not None: matches = get_collision_matches( "id %i" % snapped_obj_id, colls, "link" ) for match in matches: if coll_name(match, "fetch"): continue obj_scene_colls += 1 total_colls = robo_obj_colls + robo_scene_colls + obj_scene_colls return total_colls > 0, CollDetails( obj_scene_colls=min(obj_scene_colls, 1), robo_obj_colls=min(robo_obj_colls, 1), robo_scene_colls=min(robo_scene_colls, 1), ) def get_nav_mesh_settings(agent_config): return get_nav_mesh_settings_from_height(agent_config.HEIGHT) def get_nav_mesh_settings_from_height(height): navmesh_settings = NavMeshSettings() navmesh_settings.set_defaults() navmesh_settings.agent_radius = 0.4 navmesh_settings.agent_height = height navmesh_settings.agent_max_climb = 0.05 return navmesh_settings def convert_legacy_cfg(obj_list): if len(obj_list) == 0: return obj_list def convert_fn(obj_dat): fname = "/".join(obj_dat[0].split("/")[-2:]) if ".urdf" in fname: obj_dat[0] = osp.join("data/replica_cad/urdf", fname) else: obj_dat[0] = obj_dat[0].replace( "data/objects/", "data/objects/ycb/" ) if ( len(obj_dat) == 2 and len(obj_dat[1]) == 4 and np.array(obj_dat[1]).shape == (4, 4) ): # Specifies the full transformation, no object type return (obj_dat[0], (obj_dat[1], int(MotionType.DYNAMIC))) elif len(obj_dat) == 2 and len(obj_dat[1]) == 3: # Specifies XYZ, no object type trans = mn.Matrix4.translation(mn.Vector3(obj_dat[1])) return (obj_dat[0], (trans, int(MotionType.DYNAMIC))) else: # Specifies the full transformation and the object type return (obj_dat[0], obj_dat[1]) return list(map(convert_fn, obj_list)) def get_aabb(obj_id, sim, transformed=False): obj_node = sim.get_object_scene_node(obj_id) obj_bb = obj_node.cumulative_bb if transformed: obj_bb = habitat_sim.geo.get_transformed_bb( obj_node.cumulative_bb, obj_node.transformation ) return obj_bb def euler_to_quat(rpy): rot = quaternion.from_euler_angles(rpy) rot = mn.Quaternion(mn.Vector3(rot.vec), rot.w) return rot def allowed_region_to_bb(allowed_region): if len(allowed_region) == 0: return allowed_region return mn.Range2D(allowed_region[0], allowed_region[1]) def recover_nav_island_point(v, ref_v, sim): """ Snaps a point to the LARGEST island. """ nav_vs = sim.pathfinder.build_navmesh_vertices() ref_r = sim.pathfinder.island_radius(ref_v) nav_vs_r = { i: sim.pathfinder.island_radius(nav_v) for i, nav_v in enumerate(nav_vs) } # Get the points closest to "v" v_dist = np.linalg.norm(v - nav_vs, axis=-1) ordered_idxs = np.argsort(v_dist) # Go through the closest points until one has the same island radius. for i in ordered_idxs: if nav_vs_r[i] == ref_r: return nav_vs[i] print("Could not find point off of island") return v CACHE_PATH = "./data/cache" class CacheHelper: def __init__( self, cache_name, lookup_val, def_val=None, verbose=False, rel_dir="" ): self.use_cache_path = osp.join(CACHE_PATH, rel_dir) if not osp.exists(self.use_cache_path): os.makedirs(self.use_cache_path) sec_hash = hashlib.md5(str(lookup_val).encode("utf-8")).hexdigest() cache_id = f"{cache_name}_{sec_hash}.pickle" self.cache_id = osp.join(self.use_cache_path, cache_id) self.def_val = def_val self.verbose = verbose def exists(self): return osp.exists(self.cache_id) def load(self, load_depth=0): if not self.exists(): return self.def_val try: with open(self.cache_id, "rb") as f: if self.verbose: print("Loading cache @", self.cache_id) return pickle.load(f) except EOFError as e: if load_depth == 32: raise e # try again soon print( "Cache size is ", osp.getsize(self.cache_id), "for ", self.cache_id, ) time.sleep(1.0 + np.random.uniform(0.0, 1.0)) return self.load(load_depth + 1) def save(self, val): with open(self.cache_id, "wb") as f: if self.verbose: print("Saving cache @", self.cache_id) pickle.dump(val, f) def reshape_obs_space(obs_space, new_shape): assert isinstance(obs_space, gym.spaces.Box) return gym.spaces.Box( shape=new_shape, high=obs_space.low.reshape(-1)[0], low=obs_space.high.reshape(-1)[0], dtype=obs_space.dtype, )
8,031
2,812
############### ## LIBRARIES ## ############### import click from copy import deepcopy from pprint import pprint from arcgis.gis import GIS from arcgis import features import geopandas as gpd ################## ## FUNCTION(S) ## ################## def agol_to_gdf(fset): gdf = gpd.read_file(fset.to_geojson) gdf.crs = {'init': f'epsg:{fset.spatial_reference["latestWkid"]}'} gdf['geometry'] = gdf['geometry'].to_crs(epsg = 4326) return gdf def park_piper(gis, piper_item, piper_layer, piper_feature_id_field, piper_update_field, parks_item, parks_layer, parks_transfer_field): # Parks parks_flayer = gis.content.get(parks_item).layers[parks_layer] parks_fset = parks_flayer.query() parks_gdf = agol_to_gdf(parks_fset) # Piper features piper_flayer = gis.content.get(piper_item).layers[piper_layer] ## Create a featureset of the full piper dataset piper_full_fset = piper_flayer.query() ## Create a featureset and GeoDataFrame of the features that will be updated piper_to_update_fset = piper_flayer.query(where = f"{piper_update_field} IS NULL") try: piper_to_update_gdf = agol_to_gdf(piper_to_update_fset) # Assign parks to piper points that need to be updated piper_to_update_gdf[piper_update_field] = piper_to_update_gdf.apply(lambda x: parks_gdf.loc[parks_gdf['geometry'].contains(x['geometry'])][parks_transfer_field].iloc[0] if len(parks_gdf.loc[parks_gdf['geometry'].contains(x['geometry'])]) > 0 else "Park Unknown", axis = 1) features_for_update = [] all_features = piper_full_fset.features for id in piper_to_update_gdf[piper_feature_id_field]: original_feature = [f for f in all_features if f.attributes[piper_feature_id_field] == id][0] feature_to_be_updated = deepcopy(original_feature) print(f'------------- {id} -------------') matching_row = piper_to_update_gdf.loc[piper_to_update_gdf[piper_feature_id_field] == id] print(id, ' >>> ', matching_row) feature_to_be_updated.attributes[piper_update_field] = matching_row[piper_update_field].values[0] features_for_update.append(feature_to_be_updated) print(features_for_update) piper_flayer.edit_features(updates = features_for_update) except Exception as e: print(e) pass @click.command() @click.argument('portal') @click.argument('username') @click.argument('password') @click.option('--piper_item', help = 'Item ID of piper item on ArcGIS Online') @click.option('--piper_layer', default = 0, show_default = True, help = 'Layer number in service being updated') @click.option('--piper_feature_id_field', default = 'OBJECTID', show_default = True, help = 'Unique ID field for piper layer') @click.option('--piper_update_field', default = 'NAME', show_default = True, help = 'Field in piper layer to update') @click.option('--parks_item', help = 'Item ID of parks item on ArcGIS Online') @click.option('--parks_layer', default = 0, show_default = True, help = 'Layer number in parks servce') @click.option('--parks_transfer_field', default = 'NAME', show_default = True, help = 'Field in parks layer to transfer over to piper update field') def main(portal, username, password, piper_item, piper_layer, piper_feature_id_field, piper_update_field, parks_item, parks_layer, parks_transfer_field): gis = GIS(portal, username, password) park_piper(gis, piper_item, piper_layer, piper_feature_id_field, piper_update_field, parks_item, parks_layer, parks_transfer_field) if __name__ == "__main__": main()
3,614
1,258
# PyOS # Made for Python 2.7 # programs/mv.py # Import Libraries # PyOS Scripts import internal.extra import os from programs.cp import displayCwdFiles, getFileOrigin def app(): print(internal.extra.colors.OKGREEN + "Moving (renaming) files: " + internal.extra.colors.ENDC) print(internal.extra.colors.BOLD + "File to move/rename (enter filename or number of file): " + internal.extra.colors.ENDC) file_list = displayCwdFiles() origin_file = getFileOrigin(file_list) # Validate chosen file to move while not os.path.isfile(origin_file): print(internal.extra.colors.BOLD + "Warning! file " + origin_file + " does not yet exist.\n\n" + internal.extra.colors.ENDC) origin_file = getFileOrigin(file_list) print(internal.extra.colors.BOLD + origin_file + " selected for moving." + internal.extra.colors.ENDC) target_file = raw_input(internal.extra.colors.BOLD + "Enter filename to move to [Enter to backup]:" + internal.extra.colors.ENDC) if target_file == "": target_file = origin_file + ".bak" if os.path.isfile(target_file): existing_check = raw_input( internal.extra.colors.BOLD + "Warning! File " + target_file + " exists.\nOverwrite [y/0/Enter] or back-up [b/1]?" + internal.extra.colors.ENDC) if existing_check.lower() == 'b' or existing_check == '1': target_file += '.bak' elif existing_check != '' or existing_check.lower() != 'y' or existing_check != '0': target_file = origin_file print("Target file: " + target_file + " selected.") os.rename(origin_file, target_file)
1,646
525
""" 382. Linked List Random Node Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen. Implement the Solution class: Solution(ListNode head) Initializes the object with the integer array nums. int getRandom() Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be choosen. Examples -------- Example 1: Input ["Solution", "getRandom", "getRandom", "getRandom", "getRandom", "getRandom"] [[[1, 2, 3]], [], [], [], [], []] Output [null, 1, 3, 2, 2, 3] Explanation solution = Solution([1, 2, 3]); solution.getRandom(); // return 1 solution.getRandom(); // return 3 solution.getRandom(); // return 2 solution.getRandom(); // return 2 solution.getRandom(); // return 3 // getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning. Constraints ----------- * The number of nodes in the linked list will be in the range [1, 104]. * -104 <= Node.val <= 104 * At most 104 calls will be made to getRandom. """ import random from typing import Optional # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: """ Your Solution object will be instantiated and called as such: obj = Solution(head) param_1 = obj.getRandom() """ def __init__(self, head: Optional[ListNode]): node_vals = [] node = head while node: node_vals.append(node.val) node = node.next self.list_len = len(node_vals) self.node_vals = node_vals def getRandom(self) -> int: return self.node_vals[random.randint(0, self.list_len - 1)]
1,867
580
from datetime import timedelta from uuid import uuid1 from snuba.redis import redis_client from snuba.subscriptions.data import SubscriptionData from snuba.subscriptions.store import RedisSubscriptionDataStore from tests.subscriptions import BaseSubscriptionTest class TestRedisSubscriptionStore(BaseSubscriptionTest): @property def subscription(self) -> SubscriptionData: return SubscriptionData( project_id=self.project_id, conditions=[["platform", "IN", ["a"]]], aggregations=[["count()", "", "count"]], time_window=timedelta(minutes=500), resolution=timedelta(minutes=1), ) def build_store(self, key="1") -> RedisSubscriptionDataStore: return RedisSubscriptionDataStore(redis_client, self.dataset, key) def test_create(self): store = self.build_store() subscription_id = uuid1() store.create(subscription_id, self.subscription) assert store.all() == [(subscription_id, self.subscription)] def test_delete(self): store = self.build_store() subscription_id = uuid1() store.create(subscription_id, self.subscription) assert store.all() == [(subscription_id, self.subscription)] store.delete(subscription_id) assert store.all() == [] def test_all(self): store = self.build_store() assert store.all() == [] subscription_id = uuid1() store.create(subscription_id, self.subscription) assert store.all() == [(subscription_id, self.subscription)] new_subscription = SubscriptionData( project_id=self.project_id, conditions=[["platform", "IN", ["b"]]], aggregations=[["count()", "", "something"]], time_window=timedelta(minutes=400), resolution=timedelta(minutes=2), ) new_subscription_id = uuid1() store.create(new_subscription_id, new_subscription) assert sorted(store.all(), key=lambda row: row[0]) == [ (subscription_id, self.subscription), (new_subscription_id, new_subscription), ] def test_partitions(self): store_1 = self.build_store("1") store_2 = self.build_store("2") subscription_id = uuid1() store_1.create(subscription_id, self.subscription) assert store_2.all() == [] assert store_1.all() == [(subscription_id, self.subscription)] new_subscription = SubscriptionData( project_id=self.project_id, conditions=[["platform", "IN", ["b"]]], aggregations=[["count()", "", "something"]], time_window=timedelta(minutes=400), resolution=timedelta(minutes=2), ) new_subscription_id = uuid1() store_2.create(new_subscription_id, new_subscription) assert store_1.all() == [(subscription_id, self.subscription)] assert store_2.all() == [(new_subscription_id, new_subscription)]
3,003
877
import pytest from app.broadcast_areas.models import CustomBroadcastAreas from app.models.broadcast_message import BroadcastMessage from tests import broadcast_message_json @pytest.mark.parametrize('areas, expected_area_ids', [ ({'simple_polygons': []}, []), ({'ids': ['123'], 'simple_polygons': []}, ['123']) ]) def test_area_ids( areas, expected_area_ids, ): broadcast_message = BroadcastMessage(broadcast_message_json( areas=areas )) assert broadcast_message.area_ids == expected_area_ids def test_simple_polygons(): broadcast_message = BroadcastMessage(broadcast_message_json( area_ids=[ # Hackney Central 'wd20-E05009372', # Hackney Wick 'wd20-E05009374', ], )) assert [ [ len(polygon) for polygon in broadcast_message.polygons.as_coordinate_pairs_lat_long ], [ len(polygon) for polygon in broadcast_message.simple_polygons.as_coordinate_pairs_lat_long ], ] == [ # One polygon for each area [27, 31], # Because the areas are close to each other, the simplification # and unioning process results in a single polygon with fewer # total coordinates [57], ] def test_content_comes_from_attribute_not_template(): broadcast_message = BroadcastMessage(broadcast_message_json()) assert broadcast_message.content == 'This is a test' @pytest.mark.parametrize(('areas', 'expected_length'), [ ({'ids': []}, 0), ({'ids': ['wd20-E05009372']}, 1), ({'no data': 'just created'}, 0), ({'names': ['somewhere'], 'simple_polygons': [[[3.5, 1.5]]]}, 1) ]) def test_areas( areas, expected_length ): broadcast_message = BroadcastMessage(broadcast_message_json( areas=areas )) assert len(list(broadcast_message.areas)) == expected_length def test_areas_treats_missing_ids_as_custom_broadcast(notify_admin): broadcast_message = BroadcastMessage(broadcast_message_json( areas={ 'ids': [ 'wd20-E05009372', 'something else', ], # although the IDs may no longer be usable, we can # expect the broadcast to have names and polygons, # which is enough to show the user something 'names': [ 'wd20 name', 'something else name' ], 'simple_polygons': [[[1, 2]]] } )) assert len(list(broadcast_message.areas)) == 2 assert type(broadcast_message.areas) == CustomBroadcastAreas @pytest.mark.parametrize('area_ids, approx_bounds', ( ([ 'ctry19-N92000002', # Northern Ireland (UTM zone 29N) 'ctry19-W92000004', # Wales (UTM zone 30N) ], [ -8.2, 51.5, -2.1, 55.1 ]), ([ 'lad20-E06000031', # Peterborough (UTM zone 30N) 'lad20-E07000146', # Kings Lyn and West Norfolk (UTM zone 31N) ], [ -0.5, 52.5, 0.8, 53.0 ]), ([ 'wd20-E05009372', # Hackney Central (UTM zone 30N) 'wd20-E05009374', # Hackney Wick (UTM zone 30N) ], [ -0.1, 51.5, -0.0, 51.6 ]), ([ 'wd20-E05009372', # Hackney Central (UTM zone 30N) 'test-santa-claus-village-rovaniemi-a', # (UTM zone 35N) ], [ -0.1, 51.5, 25.9, 66.6 ]), )) def test_combining_multiple_areas_keeps_same_bounds(area_ids, approx_bounds): broadcast_message = BroadcastMessage(broadcast_message_json( areas={'ids': area_ids} )) assert [ round(coordinate, 1) for coordinate in broadcast_message.polygons.bounds ] == [ round(coordinate, 1) for coordinate in broadcast_message.simple_polygons.bounds ] == ( approx_bounds )
3,833
1,391
#coding:utf-8 """ 对处理数据域的抽象 """ from torchtext.data.field import RawField, Field, LabelField class WordField(Field): """ 数据词域的抽象 """ def __init__(self, **kwarg): print(kwarg) super(WordField, self).__init__(**kwarg) class CharField(Field): """ 数据字符域的抽象 """ def __init__(self, **kwarg): super(CharField, self).__init__(**kwarg) class SiteField(Field): """ 站点域的抽象 """ def __init__(self, **kwarg): super(SiteField, self).__init__(**kwarg)
521
221
from __future__ import print_function, division from warnings import warn from nilmtk.disaggregate import Disaggregator import pandas as pd import numpy as np from collections import OrderedDict import matplotlib.pyplot as plt from sklearn.decomposition import MiniBatchDictionaryLearning, SparseCoder from sklearn.metrics import mean_squared_error import time import warnings warnings.filterwarnings("ignore") class DSC(Disaggregator): def __init__(self, params): self.MODEL_NAME = 'DSC' # Add the name for the algorithm self.chunk_wise_training = False self.dictionaries = OrderedDict() self.power = OrderedDict() self.shape = 60*2 self.learning_rate = 1e-9 self.iterations = 3000 self.sparsity_coef = 20 self.n_components = 10 self.shape = params.get('shape',self.shape) self.learning_rate = params.get('learning_rate',self.learning_rate) self.iterations = params.get('iterations',self.iterations) self.n_epochs = self.iterations self.n_components = params.get('n_components',self.n_components) def learn_dictionary(self, appliance_main, app_name): if appliance_main.size%self.shape!=0: extra_values = self.shape - (appliance_main.size)%(self.shape) appliance_main = list(appliance_main.values.flatten()) + [0]*extra_values appliance_main = np.array(appliance_main).reshape((-1,self.shape)).T self.power[app_name] = appliance_main if app_name not in self.dictionaries: print ("Training First dictionary for ",app_name) model = MiniBatchDictionaryLearning(n_components=self.n_components,positive_code=True,positive_dict=True,transform_algorithm='lasso_lars',alpha=self.sparsity_coef) else: print ("Re-training dictionary for ",app_name) model = self.dictionaries[app_name] model.fit(appliance_main.T) reconstruction = np.matmul(model.components_.T,model.transform(appliance_main.T).T) print ("RMSE reconstruction for appliance %s is %s"%(app_name,mean_squared_error(reconstruction,appliance_main)**(.5))) self.dictionaries[app_name] = model def discriminative_training(self,concatenated_activations,concatenated_bases, verbose = 100): # Making copies of concatenated bases and activation. optimal_a = np.copy(concatenated_activations) predicted_b = np.copy(concatenated_bases) ''' Next step is to modify bases such that, we get optimal A upon sparse coding We want to get a_opt on finding activations from b_hat ''' alpha = self.learning_rate least_error = 1e10 total_power = self.total_power v_size = .20 v_index = int(total_power.shape[1] * v_size) train_power = total_power[:,:-v_index] v_power = total_power[:,-v_index:] train_optimal_a = optimal_a[:,:-v_index] v_optimal_a = optimal_a[:,-v_index:] print ("If Iteration wise errors are not decreasing, then please decrease the learning rate") for i in range(self.iterations): a = time.time() # Finding activations for the given bases model = SparseCoder(dictionary=predicted_b.T,positive_code=True,transform_algorithm='lasso_lars',transform_alpha=self.sparsity_coef) train_predicted_a = model.transform(train_power.T).T model = SparseCoder(dictionary=predicted_b.T,positive_code=True,transform_algorithm='lasso_lars',transform_alpha=self.sparsity_coef) val_predicted_a = model.transform(v_power.T).T err = np.mean(np.abs(val_predicted_a - v_optimal_a)) if err<least_error: #print ("Chose the best") least_error = err best_b = np.copy(predicted_b) # Modify the bases b_hat so that they result activations closer to a_opt T1 = (train_power - predicted_b@train_predicted_a)@train_predicted_a.T T2 = (train_power - predicted_b@train_optimal_a)@train_optimal_a.T predicted_b = predicted_b - alpha *( T1 - T2) predicted_b = np.where(predicted_b>0,predicted_b,0) # Making sure that columns sum to 1 predicted_b = (predicted_b.T/np.linalg.norm(predicted_b.T,axis=1).reshape((-1,1))).T #if i%verbose==0: print ("Iteration ",i," Error ",err) return best_b def print_appliance_wise_errors(self, activations, bases): start_comp = 0 for cnt, i in enumerate(self.power): X = self.power[i] n_comps = self.dictionaries[i].n_components pred = np.matmul(bases[:,start_comp:start_comp+n_comps],activations[start_comp:start_comp+n_comps,:]) start_comp+=n_comps #plt.plot(pred.T[home_id],label=i) print ("Error for ",i," is ",mean_squared_error(pred, X)**(.5)) def partial_fit(self, train_main, train_appliances, **load_kwargs): print("...............DSC partial_fit running...............") #print (train_main[0]) train_main = pd.concat(train_main,axis=1) #np.array([i.values.reshape((self.sequence_length,1)) for i in train_main]) if train_main.size%self.shape!=0: extra_values = self.shape - (train_main.size)%(self.shape) train_main = list(train_main.values.flatten()) + [0]*extra_values train_main = np.array(train_main).reshape((-1,self.shape)).T self.total_power = train_main new_train_appliances = [] for app_name, app_df in train_appliances: app_df = pd.concat(app_df) new_train_appliances.append((app_name, app_df)) train_appliances = new_train_appliances if len(train_main)>10: for appliance_name, power in train_appliances: self.learn_dictionary(power, appliance_name) concatenated_bases = [] concatenated_activations = [] for i in self.dictionaries: model = self.dictionaries[i] concatenated_bases.append(model.components_.T) concatenated_activations.append(model.transform(self.power[i].T).T) concatenated_bases = np.concatenate(concatenated_bases,axis=1) concatenated_activations = np.concatenate(concatenated_activations,axis=0) print ("--"*15) print ("Optimal Errors") self.print_appliance_wise_errors(concatenated_activations, concatenated_bases) print ("--"*15) model = SparseCoder(dictionary=concatenated_bases.T,positive_code=True,transform_algorithm='lasso_lars',transform_alpha=self.sparsity_coef) predicted_activations = model.transform(train_main.T).T print ('\n\n') print ("--"*15) print ("Error in prediction before discriminative sparse coding") self.print_appliance_wise_errors(predicted_activations, concatenated_bases) print ("--"*15) print ('\n\n') optimal_b = self.discriminative_training(concatenated_activations,concatenated_bases) model = SparseCoder(dictionary=optimal_b.T,positive_code=True,transform_algorithm='lasso_lars',transform_alpha=self.sparsity_coef) self.disggregation_model = model predicted_activations = model.transform(train_main.T).T print ("--"*15) print ("Model Errors after Discriminative Training") self.print_appliance_wise_errors(predicted_activations, concatenated_bases) print ("--"*15) self.disaggregation_bases = optimal_b self.reconstruction_bases = concatenated_bases else: print ("This chunk has small number of samples, so skipping the training") def disaggregate_chunk(self, test_main_list): test_predictions = [] for test_main in test_main_list: if test_main.size%self.shape!=0: extra_values = self.shape - (test_main.size)%(self.shape) test_main = list(test_main.values.flatten()) + [0]*extra_values test_main = np.array(test_main).reshape((-1,self.shape)).T predicted_activations = self.disggregation_model.transform(test_main.T).T #predicted_usage = self.reconstruction_bases@predicted_activations disggregation_dict = {} start_comp = 0 for cnt, app_name in enumerate(self.power): n_comps = self.dictionaries[app_name].n_components predicted_usage = np.matmul(self.reconstruction_bases[:,start_comp:start_comp+n_comps],predicted_activations[start_comp:start_comp+n_comps,:]) start_comp+=n_comps predicted_usage = predicted_usage.T.flatten() flat_mains = test_main.T.flatten() predicted_usage = np.where(predicted_usage>flat_mains,flat_mains,predicted_usage) disggregation_dict[app_name] = pd.Series(predicted_usage) results = pd.DataFrame(disggregation_dict, dtype='float32') test_predictions.append(results) return test_predictions
9,460
2,901
def test_with_missing_fixture(not_existing_fixture): pass
62
23
from plugins import PluginUtil from plugins.task_affinity import TaskAffinityPlugin plugin = TaskAffinityPlugin() def test_regex(): text ='intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);' assert PluginUtil.contains(plugin.NEW_TASK, text) def test_regex1(): text = 'intent.setFlags(Intent.FLAGACTIVITYNEWTASK);' assert not PluginUtil.contains(plugin.NEW_TASK, text) def test_regex2(): text = 'intent.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);' assert not PluginUtil.contains(plugin.NEW_TASK, text) def test_regex3(): text = 'intent.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);' assert PluginUtil.contains(plugin.MULTIPLE_TASK, text) def test_regex4(): text = 'intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);' assert not PluginUtil.contains(plugin.MULTIPLE_TASK, text) def test_regex5(): text = 'intent.setFlags(Intent.FLAGACTIVITYMULTIPLETASK);' assert not PluginUtil.contains(plugin.MULTIPLE_TASK, text) if __name__ == '__main__': test_regex() test_regex1() test_regex2() test_regex3() test_regex4() test_regex5()
1,099
413
from __future__ import print_function import pyzbar.pyzbar as pyzbar import numpy as np import cv2 class QRdetect: def __init__(self, QRcode_image, k=np.array([[376.0, 0, 376], [0, 376.0, 240.0], [0, 0, 1]])): if QRcode_image is None: return self.query_image = QRcode_image self.K = k # points order is: # A-------D # | | # | | # B-------C self.query_image_position = self.QRcode_Position(self.query_image) print("query QRcode position: ", self.query_image_position) query_image = self.drawPoints(self.query_image.copy(), self.query_image_position) cv2.imwrite("query_detected.png", query_image) self.train_qrcode_position = None self.found_QRcode = False def decode(self, image): decodedObjects = pyzbar.decode(image) if not decodedObjects: return None # There could be multiple qr codes in the same image # each detected qr code has a type and corresponding polygon for obj in decodedObjects: print('Type : ', obj.type) print('Polygon : ', obj.polygon) if obj.type is not "QRCODE": return None return decodedObjects # Display barcode and QR code location def display(self, image): decodedObjects = self.decode(image) # Loop over all decoded objects for decodedObject in decodedObjects: points = decodedObject.polygon # If the points do not form a quad, find convex hull if len(points) > 4: hull = cv2.convexHull(np.array([point for point in points], dtype=np.float32)) hull = list(map(tuple, np.squeeze(hull))) else: hull = points # Number of points in the convex hull n = len(hull) # Draw the convext hull for j in range(0, n): cv2.line(image, hull[j], hull[(j + 1) % n], (255, 0, 0), 3) # Display results # image = cv2.resize(image, (np.shape(image)[1] / 3, np.shape(image)[0] / 3), interpolation=cv2.INTER_CUBIC) # cv2.imshow("Results", image) # cv2.waitKey(5000) def QRcode_Position(self, image): qrcode_results = self.decode(image) if not qrcode_results: return None if len(qrcode_results) > 0: # assume there is only one qr code in the FOV qrcode_result = qrcode_results[0] polygon = qrcode_result.polygon print("polygon: ", polygon) qrcode_position = np.array([[polygon[0][0], polygon[0][1]], [polygon[1][0], polygon[1][1]], [polygon[2][0], polygon[2][1]], [polygon[3][0], polygon[3][1]]], dtype="float32") print(qrcode_position) return qrcode_position else: return None def drawPoints(self, image, target_qrcode_position): if target_qrcode_position is None: return for p in target_qrcode_position: image = cv2.circle(image, (p[0], p[1]), 10, (0, 255, 0)) image = cv2.putText(image, str(p[0]) + ", " + str(p[1]), (p[0], p[1]), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1, cv2.LINE_AA) return image def getPerspectiveTransformaAndWarpedImage(self, train_qrcode_image): train_qrcode_position = self.QRcode_Position(train_qrcode_image) # print("Incoming train image qr code position: ", train_qrcode_position) if train_qrcode_position is None: return None, None train_image = self.drawPoints(train_qrcode_image.copy(), train_qrcode_position) # print("train_qrcode_position: \n", train_qrcode_position) if train_image is not None: cv2.imwrite("train_detected.png", train_image) # train_qrcode_position: current incoming image # query_image_position: pre-set target qrcode image #H = cv2.getPerspectiveTransform(train_qrcode_position, self.query_image_position) H = cv2.getPerspectiveTransform(train_qrcode_position, self.query_image_position) self.train_qrcode_position = train_qrcode_position (h, w, c) = train_qrcode_image.shape warped_image = cv2.warpPerspective(train_qrcode_image, H, (w, h)) cv2.imwrite("warped_image.png", warped_image) return H, warped_image # from train image to query image def recoverRTfromHomographyMat(self, H): _, Rotations, translations, normals = cv2.decomposeHomographyMat(H, self.K) return Rotations, translations, normals # def process_image(self, image): # # H, warped_image = self.getPerspectiveTransformaAndWarpedImage(image) # # if H is None: # self.found_QRcode = False # return None, None, None # # Rs, ts, ns = self.recoverRTfromHomographyMat(H) # self.found_QRcode = True # # train_image_camera_points = self.pixel2cameraWithoutScale(self.train_qrcode_position) # # # return Rs, ts, ns # new_Rs = [] # new_ts = [] # new_normals = [] # idxs = [] # for index, normal in enumerate(ns): # for pt in train_image_camera_points: # result = np.dot(normal.T, np.array(pt)) # if result < 0: # continue # else: # idxs.append(index) # # idxs = set(idxs) # for idx in idxs: # new_Rs.append(Rs[idx]) # new_ts.append(ts[idx]) # new_normals.append(ns[idx]) # # return new_Rs, new_ts, new_normals def process_image(self, image): H, warped_image = self.getPerspectiveTransformaAndWarpedImage(image) if H is None: self.found_QRcode = False return None, None, None Rs, ts, ns = self.recoverRTfromHomographyMat(H) self.found_QRcode = True return Rs, ts, ns def pixel2cameraWithoutScale(self, pixel_points): camera_points = [] camera_point = [0, 0, 0] for pixel in pixel_points: # assume depth is 1 depth = 1 camera_point[0] = (pixel[0] - 376.0) / 376.0 camera_point[1] = (pixel[1] - 376.0) / 240.0 camera_point[2] = depth camera_points.append(camera_point) return camera_points if __name__ == '__main__': train_image = cv2.imread('target.png') query_image = cv2.imread('target.png') cv2.imwrite("train_image.png", train_image) qr = QRdetect(query_image) R, t = qr.process_image(train_image) print("R: ", R) print("t: ", t)
7,033
2,328
import unittest from app.models import User,Role,Post,Comment class CommentModelTest(unittest.TestCase): def setUp(self): self.new_user=User(name="Francis Githae",username='fgithae',password='password',email="francis@gmail.com",role=Role.query.filter_by(id=1).first()) self.new_post=Post(user=self.new_user,title="The beginning",content="This is the first post ever in this channel.The fluent debutter",banner_path="images/img1.jpg") self.new_comment=Comment(user=self.new_user,post=self.new_post,content="It's actually good") def tearDown(self): Comment.query.delete() Post.query.delete() User.query.delete() def test_check_instance_variables(self): self.assertEquals(self.new_comment.user,self.new_user) self.assertEquals(self.new_comment.post,self.new_post) self.assertEquals(self.new_comment.content,"It's actually good") def test_save_comment(self): self.new_comment.save_comment() self.assertTrue(len(Comment.query.all())>0) def test_delete_comment(self): self.new_comment.delete_comment() self.assertEquals(self.new_comment.status,'archived')
1,124
377
import logging import os class Logger(object): """ set logger """ def __init__(self, logger_path): self.logger = logging.getLogger() self.logger.setLevel(logging.DEBUG) self.logfile = logging.FileHandler(logger_path) # self.logfile.setLevel(logging.DEBUG) # formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') formatter = logging.Formatter( '%(asctime)s -%(filename)s:%(lineno)s - %(levelname)s - %(message)s') self.logfile.setFormatter(formatter) self.logdisplay = logging.StreamHandler() # self.logdisplay.setLevel(logging.DEBUG) self.logdisplay.setFormatter(formatter) self.logger.addHandler(self.logfile) self.logger.addHandler(self.logdisplay) def get_logger(self): return self.logger
881
276
from state import print_solution_path from search import BBS, A_star_search from puzzle import generate from write_to_file import write_to_csv, write_to_txt ''' CS461 - Artificial Intelligence Homework 3 Group members: * Fuad Aghazada * Can Özgürel * Çağatay Sel * Utku Mert Topçuoğlu * Kaan Kıranbay As heuristic function h (sum of Eucledian distances of the tiles from their goal positions) has been used @authors: fuadaghazada, canozgurel @date: 21/3/2019 ''' ''' Generating N distinct puzzles ''' def generate_n_puzzles(n): distinct_puzzles = [] while len(distinct_puzzles) != n: puzzle = generate() if puzzle not in distinct_puzzles: distinct_puzzles.append(puzzle) return distinct_puzzles ###### GENERATING 25 Distinct Puzzles ####### puzzles = generate_n_puzzles(25) index = 1 path = None # X and Y values for the puzzle solved with BBS and A* data = [] for puzzle in puzzles: path, num_moves_bbs = BBS(puzzle) path, num_moves_a_star = A_star_search(puzzle) data.append([index, num_moves_bbs, num_moves_a_star]) index += 1 # Write puzzles (initial states) to txt write_to_txt(puzzles) # Writing result into csv file write_to_csv(data) # Print the trace for the last puzzle print("\n\n----Solution trace for last puzzle!----\n\n") if path: print_solution_path(path)
1,429
522
import ccxt from datetime import datetime from datetime import timedelta import calendar import time from enum import Enum import ccxtWrapper import math import LineNotify import orderInfo class orderManagementEnum(Enum): NO_POSITION = 0 HAVE_POSITION = 1 class orderManager(ccxtWrapper.ccxtWrapper): orderManagementState = orderManagementEnum(0) exchangeInstance = None orderErrorCounter = 0 isPosition = False balance = None orderAmount = 0 positionAmount = 0 size = 0 preSize = 0 btcAmount = 0 averagePrice = 0 liquidationPrice = 0 # 清算価格 maintMargin = 0 realisedPnl = 0 # 実現損益 unrealisedPnl = 0 # 未実現損益 unrealisedRoePcnt = 0 # 未実現損益(ROE%) satoshiUnit = 0.00000001 totalBlance = 0 diffBalance = 0 def __init__(self, instance: ccxtWrapper.ccxtWrapper): self.orderManagementState = orderManagementEnum.NO_POSITION self.exchangeInstance = instance self.changeToNoPositionState() self.setPositionDirection() def setPositionDirection(self): positions = self.exchangeInstance.privateGetPosition() if positions != None and len(positions) > 0: if positions[0]["currentQty"] != None: self.preSize = self.size self.size = positions[0]["currentQty"] if positions[0]["homeNotional"] != None: self.btcAmount = abs(positions[0]["homeNotional"]) if positions[0]["avgCostPrice"] != None: self.averagePrice = "{:.2f}".format(positions[0]["avgCostPrice"]) if positions[0]["liquidationPrice"] != None: self.liquidationPrice = positions[0]["liquidationPrice"] if positions[0]["maintMargin"] != None: self.maintMargin = "{:.4f}".format(positions[0]["maintMargin"] * self.satoshiUnit) if positions[0]["realisedPnl"] != None and positions[0]["rebalancedPnl"] != None: self.realisedPnl = "{:.4f}".format((positions[0]["realisedPnl"] + positions[0]["rebalancedPnl"]) * self.satoshiUnit) if positions[0]["unrealisedPnl"] != None: self.unrealisedPnl = "{:.4f}".format(positions[0]["unrealisedPnl"] * self.satoshiUnit) if positions[0]["unrealisedRoePcnt"] != None: self.unrealisedRoePcnt = "{:.2f}".format(positions[0]["unrealisedRoePcnt"] * 100) balance = self.exchangeInstance.fetchBalance() if balance != None: # 起動時の一回目に資産情報を通知 if self.balance == None: LineNotify.PostMessage("監視botを起動しました\r\n資産は" + "{:.4f}".format(balance["total"]) + "XBTです") self.balance = balance if self.balance != None and self.isPosition == False: self.totalBlance = self.balance["total"] # イン-アウトの損益計算用に記憶 usdPosition = None if positions != None: for position in positions: if position["symbol"] == "XBTUSD": usdPosition = position if usdPosition == None or usdPosition["currentQty"] == 0: self.isPosition = False self.positionAmount = 0 else: self.isPosition = True self.positionAmount = abs(usdPosition["currentQty"]) # else: # エラーの場合は前回値を残しておいた方が良いかも? # self.isPosition = False # self.positionAmount = 0 def switchState(self): print("現在の発注管理状態:" + str(self.orderManagementState)) self.setPositionDirection() # 状態毎に処理する関数を分岐 if self.orderManagementState == orderManagementEnum.NO_POSITION: self.noPositionState() elif self.orderManagementState == orderManagementEnum.HAVE_POSITION: self.havePositionState() else: print(str(self.orderManagementState) + ":定義されていない状態です") print("強制的に初期化します") self.changeToNoPositionState() def noPositionState(self): ret = None if self.isPosition == True: self.changeToHavePositionState() self.sendPositionMessage("ポジションを持ちました\r\n") return ret def havePositionState(self): if self.isPosition == False: balance = self.exchangeInstance.fetchBalance() if balance != None: self.diffBalance = balance["total"] - self.totalBlance self.totalBalance = balance["total"] LineNotify.PostMessage("ポジションを決済しました\r\n今回の取引結果は" + "{:.4f}".format(self.diffBalance) + "XBTです\r\n現在の合計資産は" + "{:.4f}".format(self.totalBalance) + "XBTです") self.changeToNoPositionState() else: LineNotify.PostMessage("ポジションを決済しました\r\nエラーが発生して資産情報は読めませんでした\r\n再度資産情報を読みます") else: if self.size != self.preSize: self.sendPositionMessage("ポジションが変更されました\r\n") return None def sendPositionMessage(self, message: str): balanceMessage = message # 資産情報を通知 balanceMessage = balanceMessage + orderInfo.getBalanceText(self.balance) + "\r\n" balanceMessage = balanceMessage + "サイズ:" + str(self.size) + "\r\n" balanceMessage = balanceMessage + "値:" + str(self.btcAmount) + " XBT\r\n" balanceMessage = balanceMessage + "参入価格:" + str(self.averagePrice) + "\r\n" balanceMessage = balanceMessage + "清算価格:" + str(self.liquidationPrice) + "\r\n" balanceMessage = balanceMessage + "証拠金:" + str(self.maintMargin) + " XBT\r\n" balanceMessage = balanceMessage + "未実現損益(ROE%):" + str(self.unrealisedPnl) + " XBT (" + str(self.unrealisedRoePcnt) + "%)\r\n" balanceMessage = balanceMessage + "実現損益:" + str(self.realisedPnl) + " XBT\r\n" LineNotify.PostMessage(balanceMessage) def changeToNoPositionState(self): self.orderErrorCounter = 0 self.orderManagementState = orderManagementEnum.NO_POSITION print("発注管理状態変更:" + str(self.orderManagementState)) def changeToHavePositionState(self): self.orderErrorCounter = 0 self.orderManagementState = orderManagementEnum.HAVE_POSITION print("発注管理状態変更:" + str(self.orderManagementState))
6,224
2,172
import os from lxml import html import requests def get_dir_list(path): return [p for p in os.listdir(path) if os.path.isdir(p)] def get_file_list(path): return [p for p in os.listdir(path) if os.path.isfile(p)] def get_number(str): res = ''.join(list(filter(lambda x: '0'<=x<='9', str))) if res: return res return None def get_code_dir(path, numberStr): for p in os.listdir(path): p = path + '/' + p if not os.path.isdir(p): continue if numberStr not in p: continue req = ['solution.cpp', 'solution.java', 'solution.py'] if all(r in os.listdir(p) for r in req): return p.replace(' ', '%20') return False for chapter in get_dir_list('./'): md_path = os.path.join(chapter, 'README.md') new_md = [] with open(md_path, "r", encoding="UTF8") as f: for line in f.readlines(): line = line.strip() row = line.split('|') numberStr : str = get_number(row[2]) if numberStr: res = requests.get('http://boj.kr/' + numberStr) res.raise_for_status() res.encoding = 'UTF-8' tree = html.fromstring(res.text) title = tree.xpath('//title/text()')[0].split(' ', 1)[1] row[1] = title codePath = get_code_dir(chapter+'/문제별 코드', numberStr) row[2] = f"[링크](http://boj.kr/{numberStr})" if codePath: row[3] = f'[링크](https://github.com/rhs0266/FastCampus/tree/main/%EA%B0%95%EC%9D%98%20%EC%9E%90%EB%A3%8C/02-%EC%95%8C%EA%B3%A0%EB%A6%AC%EC%A6%98/{codePath})' else: if len(row[3]) < 10: row[3] = f'[링크]' new_md.append('|'.join(row)) with open(md_path, "w", encoding="UTF8") as f: f.write('\n'.join(new_md))
1,917
714
from utilidadesCeV import moeda preco = float(input('Digite o preço: R$')) porcentagem = float(input('Digite a aliquota:')) print(f'A metade de {moeda.moeda(preco)} é {moeda.metade(preco, True)}') print(f'O dobro de {moeda.moeda(preco)} é {moeda.dobro(preco, True)}') print(f'Aumentando {moeda.moeda(preco)} em {porcentagem}% temos {moeda.aumentar(preco, porcentagem, True)}') print(f'Diminuindo {moeda.moeda(preco)} em {porcentagem}% temos {moeda.diminuir(preco, porcentagem, True)}')
488
202
# Generated by Django 3.0.3 on 2021-05-07 01:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('leagues', '0014_rotomultileagues_is_active'), ] operations = [ migrations.AddField( model_name='rotomultileagues', name='domain', field=models.CharField(blank=True, max_length=512, null=True, verbose_name='Domain'), ), ]
449
154
# Copyright (c) 2020 Chris ter Beke. # Thingiverse plugin is released under the terms of the LGPLv3 or higher. import logging from typing import List, Callable, Any, Tuple, Optional from abc import ABC, abstractmethod from PyQt5.QtCore import QUrl from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkReply, QNetworkRequest from UM.Logger import Logger # type: ignore from .ApiHelper import ApiHelper from .JsonObject import Thing, ThingFile, Collection, ApiError class AbstractApiClient(ABC): """ Client for interacting with the Thingiverse API. """ # Re-usable network manager. _manager = QNetworkAccessManager() # Prevent auto-removing running callbacks by the Python garbage collector. _anti_gc_callbacks = [] # type: List[Callable[[], None]] @property @abstractmethod def user_id(self) -> str: """ Get the configured user ID for this provider. :return: The user ID. """ raise NotImplementedError("user_id must be implemented") @abstractmethod def getThingsFromCollectionQuery(self, collection_id: str) -> str: raise NotImplementedError("getThingsFromCollectionQuery must be implemented") @abstractmethod def getThingsLikedByUserQuery(self) -> str: raise NotImplementedError("getThingsLikedByUserQuery must be implemented") @abstractmethod def getThingsByUserQuery(self) -> str: raise NotImplementedError("getThingsByUserQuery must be implemented") @abstractmethod def getThingsMadeByUserQuery(self) -> str: raise NotImplementedError("getThingsMadeByUserQuery must be implemented") @abstractmethod def getPopularThingsQuery(self) -> str: raise NotImplementedError("getPopularThingsQuery must be implemented") @abstractmethod def getFeaturedThingsQuery(self) -> str: raise NotImplementedError("getFeaturedThingsQuery must be implemented") @abstractmethod def getNewestThingsQuery(self) -> str: raise NotImplementedError("getNewestThingsQuery must be implemented") @abstractmethod def getThingsBySearchQuery(self, search_terms: str) -> str: raise NotImplementedError("getThingsBySearchQuery must be implemented") @abstractmethod def getCollections(self, on_finished: Callable[[List[Collection]], Any], on_failed: Optional[Callable[[Optional[ApiError]], Any]]) -> None: """ Get user's collections. :param on_finished: Callback with user's collections. :param on_failed: Callback with server response. """ raise NotImplementedError("getCollections must be implemented") @abstractmethod def getThing(self, thing_id: int, on_finished: Callable[[Thing], Any], on_failed: Optional[Callable[[Optional[ApiError]], Any]] = None) -> None: """ Get a single thing by ID. :param thing_id: The thing ID. :param on_finished: Callback method to receive the async result on. :param on_failed: Callback method to receive failed request on. """ raise NotImplementedError("getThing must be implemented") @abstractmethod def getThingFiles(self, thing_id: int, on_finished: Callable[[List[ThingFile]], Any], on_failed: Optional[Callable[[Optional[ApiError]], Any]] = None) -> None: """ Get a thing's files by ID. :param thing_id: The thing ID. :param on_finished: Callback method to receive the async result on. :param on_failed: Callback method to receive failed request on. """ raise NotImplementedError("getThingFiles must be implemented") @abstractmethod def downloadThingFile(self, file_id: int, file_name: str, on_finished: Callable[[bytes], Any]) -> None: """ Download a thing file by its ID. :param file_id: The file ID to download. :param file_name: The file's name including extension. :param on_finished: Callback method to receive the async result on as bytes. """ raise NotImplementedError("downloadThingFile must be implemented") @abstractmethod def getThings(self, query: str, page: int, on_finished: Callable[[List[Thing]], Any], on_failed: Optional[Callable[[Optional[ApiError]], Any]] = None) -> None: """ Get things by query. :param query: The things to get. :param page: Page number of query results (for pagination). :param on_finished: Callback method to receive the async result on. :param on_failed: Callback method to receive failed request on. """ raise NotImplementedError("get must be implemented") @property @abstractmethod def _root_url(self) -> str: """ Get the API root URL for this provider. :returns: The root URL as string. """ raise NotImplementedError("_root_url must be implemented") @abstractmethod def _setAuth(self, request: QNetworkRequest): """ Get the API authentication method for this provider. """ raise NotImplementedError("_auth must be implemented") def _createEmptyRequest(self, url: str, content_type: str = "application/json") -> QNetworkRequest: """ Create a new network request with the needed HTTP headers. :param url: The full URL to do the request on. :param content_type: Content-Type header value :return: The QNetworkRequest. """ request = QNetworkRequest(QUrl(url)) request.setHeader(QNetworkRequest.ContentTypeHeader, content_type) request.setAttribute(QNetworkRequest.RedirectPolicyAttribute, True) # file downloads reply with a 302 first self._setAuth(request) return request def _addCallback(self, reply: QNetworkReply, on_finished: Callable[[Any], Any], on_failed: Optional[Callable[[Optional[ApiError]], Any]] = None, parser: Optional[Callable[[QNetworkReply], Tuple[int, Any]]] = None) -> None: """ Creates a callback function so that it includes the parsing of the response into the correct model. The callback is added to the 'finished' signal of the reply. :param reply: The reply that should be listened to. :param on_finished: The callback in case the request is successful. :param on_failed: The callback in case the request fails. :param parser: A custom parser for the response data, defaults to a JSON parser. """ def parse() -> None: self._anti_gc_callbacks.remove(parse) status_code, response = parser(reply) if parser else ApiHelper.parseReplyAsJson(reply) if not status_code or status_code >= 400 or response is None: Logger.warning("API returned with status {} and body {}".format(status_code, response)) if on_failed and isinstance(response, dict): error_response = ApiError(response) on_failed(error_response) else: on_finished(response) reply.deleteLater() self._anti_gc_callbacks.append(parse) reply.finished.connect(parse) # type: ignore
7,329
1,969
from . import test_conversion from . import test_generic from . import test_idxgz from . import test_settings
110
31
import subprocess import time import os import sys def generate_el_commands(kernel): commands = [] if (kernel == "TC"): sym_test = [True] else: sym_test = [True, False] for symmetrize in sym_test: for npes in range(2,6): for v in [9,14]: for e in [8,9,11,22,23]: el = "v" + str(v) + "_e" + str(e) + ".el" oshmem = "oshrun -np " + str(npes) + " ./" + kernel + " -f EdgeLists/" + el openmp = "../gapbs/gapbs/src/" + kernel + " -f EdgeLists/" + el if (symmetrize): oshmem = oshmem + " -s -n 3 -v" openmp = openmp + " -s -n 3 -v" else: oshmem = oshmem + " -n 3 -v" openmp = openmp + " -n 3 -v" commands.append(oshmem) commands.append(openmp) return commands def generate_synthetic_commands(kernel): commands = [] for npes in [2,3,4,6]: for gtype in [" -u ", " -g "]: for size in [10, 15]: oshmem = "oshrun -np " + str(npes) + " ./" + kernel + gtype + str(size) + " -n 3 -v" openmp = "../gapbs/gapbs/src/" + kernel + gtype + str(size) + " -n 3 -v" commands.append(oshmem) commands.append(openmp) return commands def generate_real_commands(kernel): commands = [] graphs = ["twitter.el", "USA-road-d.USA.gr"] for g in graphs: for npes in range(4, 5, 6): commands.append("oshrun -np " + str(npes) + " ./" + kernel + " -f ../gapbs/gapbs/benchmark/graphs/raw/" + g + " -n 3 -v") commands.append("../gapbs/gapbs/src/" + kernel + " -f ../gapbs/gapbs/benchmark/graphs/raw/" + g + " -n 3 -v") return commands def prettify(commands): i = 0 temp = [] for c in commands: if i % 2 == 0: temp.append(c) i+=1 with open("harness_results.txt", "r") as infile: relevant = [] for l in infile.readlines(): if (l.find("Verification:") > -1 and l.find("PE") == -1): relevant.append(l) infile.close() with open("results.txt", "w") as outfile: i = 0 for c in commands: outfile.write(c+"\n") outfile.writelines(relevant[i:i+3]) i += 3 commands = generate_synthetic_commands(kernel) commands = commands + generate_real_commands(kernel) commands = commands + generate_el_commands(kernel) prettify(commands)
2,545
899
import numpy as np from kneeOsteoarthritisDataset.KneeOsteoarthritsDataset import KneeOsteoarthritsDataset data_path = '/home/biomech/Documents/OsteoData/KneeXrayData/ClsKLData/kneeKL299' kneeosteo = KneeOsteoarthritsDataset(data_path = data_path) imgs, labels = kneeosteo.load_imgs() rand_idx = np.random.randint(low=0,high=len(labels)) img = imgs[rand_idx] label = labels[rand_idx] kneeosteo.plot_img(img,label) counter = 0 for item in labels: if item == 2: counter += 1 print(counter)
504
219
print("SD bootloader") import pycom import time import machine import sys import uos #paths for the code/lib/mount locations SD_MOUNTPOINT = '/sd' CODE_PATH = '/sd/src' LIB_PATH = '/sd/src/lib' #LED colors #for errors (full brightness) C_YELLOW = 0xffff00 C_RED = 0xff0000 C_PURPLE = 0xff00ff C_BLUE = 0x0000ff #for normal boot (dimmed) C_WHITE_DIM = 0x030303 C_RED_DIM = 0x060000 ### Functions ### def mount_sd(): try: sd = machine.SD() os.mount(sd, SD_MOUNTPOINT) return True except OSError: return False def endless_blink(color1: int, color2: int): pycom.heartbeat(False) while True: pycom.rgbled(color1) time.sleep(0.5) pycom.rgbled(color2) time.sleep(0.5) ### Main Code ### pycom.heartbeat(False) pycom.rgbled(C_RED_DIM) if mount_sd(): print("booting from SD") pycom.rgbled(C_WHITE_DIM) #add code and lib dir on sd to import path sys.path.append(CODE_PATH) sys.path.append(LIB_PATH) #change working dir to code directory try: uos.chdir(CODE_PATH) except Exception: print("could not change to code folder:") print(CODE_PATH) endless_blink(C_PURPLE,C_RED) print("sys.path:") print(sys.path) print("uos.getcwd():") print(uos.getcwd()) #execute code from SD try: execfile('main.py') except Exception: print("could not execute main.py") endless_blink(C_BLUE,C_RED) #sd was not mounted print("no SD found") endless_blink(C_YELLOW,C_RED)
1,551
622
import os import sys import copy from math import gcd from driver_config_macros import * from data_capture_macros import * from signal_generator_macros import * from power_operation_macros import * from capture_config_macros import * from trig_config_macros import * from data_processing_macros import * from PyQt5 import QtCore, QtGui, QtWidgets import matplotlib matplotlib.use('Qt5Agg') from matplotlib import pyplot as plt from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg from matplotlib.figure import Figure app_ = QtWidgets.QApplication(sys.argv) w, h = app_.primaryScreen().size().width(), app_.primaryScreen().size().height() #Screen Ratio Corrections gcd_ = gcd(w, h) resRatio = w/h baseRatio = 16/9 wR = w/(gcd_*16) #Ratio Correction hR = h/(gcd_*9) #Ratio Correction widthRatio = 1#1/wR #Full Width Ratio Correction heightRatio = 1#1/hR #Full Height Ratio Correction app_.exit() conditionList = {'conditionTab': [], 'extConditionLabel': [], 'aConditionLabel': [], 'bConditionLabel': [], 'cConditionLabel': [], 'dConditionLabel': [], 'aStateComboBox': [], 'bStateComboBox': [], 'cStateComboBox': [], 'dStateComboBox': [], 'extStateComboBox': [], 'stateLabel': []} runList = {'runTab': [], 'stackedWidget': [], 'captureTab': []} class Canvas(FigureCanvasQTAgg): def __init__(self, parent=None, width=4.61*widthRatio, height=3.61*heightRatio, dpi=100): fig, self.axes = plt.subplots(figsize=(width, height), dpi=dpi) super().__init__(fig) class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(801*widthRatio, 580*heightRatio) MainWindow.setMinimumSize(QtCore.QSize(801*widthRatio, 580*heightRatio)) MainWindow.setMaximumSize(QtCore.QSize(801*widthRatio, 580*heightRatio)) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(".\\icon.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) MainWindow.setWindowIcon(icon) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setEnabled(True) self.centralwidget.setObjectName("centralwidget") self.driverLabel = QtWidgets.QLabel(self.centralwidget) self.driverLabel.setGeometry(QtCore.QRect(20*widthRatio, 10*heightRatio, 51*widthRatio, 21*heightRatio)) self.driverLabel.setObjectName("driverLabel") self.presetComboBox = QtWidgets.QComboBox(self.centralwidget) self.presetComboBox.setGeometry(QtCore.QRect(60*widthRatio, 40*heightRatio, 91*widthRatio, 22*heightRatio)) self.presetComboBox.setEditable(False) self.presetComboBox.setObjectName("presetComboBox") self.presetComboBox.addItem("") self.presetLabel = QtWidgets.QLabel(self.centralwidget) self.presetLabel.setGeometry(QtCore.QRect(20*widthRatio, 40*heightRatio, 41*widthRatio, 21*heightRatio)) self.presetLabel.setObjectName("presetLabel") self.channelBox = QtWidgets.QGroupBox(self.centralwidget) self.channelBox.setGeometry(QtCore.QRect(210*widthRatio, 0*heightRatio, 281*widthRatio, 121*heightRatio)) self.channelBox.setObjectName("channelBox") self.aLabel = QtWidgets.QLabel(self.channelBox) self.aLabel.setGeometry(QtCore.QRect(10*widthRatio, 30*heightRatio, 21*widthRatio, 16*heightRatio)) self.aLabel.setObjectName("aLabel") self.bLabel = QtWidgets.QLabel(self.channelBox) self.bLabel.setGeometry(QtCore.QRect(10*widthRatio, 50*heightRatio, 21*widthRatio, 16*heightRatio)) self.bLabel.setObjectName("bLabel") self.cLabel = QtWidgets.QLabel(self.channelBox) self.cLabel.setGeometry(QtCore.QRect(10*widthRatio, 70*heightRatio, 21*widthRatio, 16*heightRatio)) self.cLabel.setObjectName("cLabel") self.dLabel = QtWidgets.QLabel(self.channelBox) self.dLabel.setGeometry(QtCore.QRect(10*widthRatio, 90*heightRatio, 21*widthRatio, 16*heightRatio)) self.dLabel.setObjectName("dLabel") self.aCheck = QtWidgets.QCheckBox(self.channelBox) self.aCheck.setGeometry(QtCore.QRect(30*widthRatio, 30*heightRatio, 16*widthRatio, 17*heightRatio)) self.aCheck.setText("") self.aCheck.setObjectName("aCheck") self.bCheck = QtWidgets.QCheckBox(self.channelBox) self.bCheck.setGeometry(QtCore.QRect(30*widthRatio, 50*heightRatio, 16*widthRatio, 17*heightRatio)) self.bCheck.setText("") self.bCheck.setObjectName("bCheck") self.cCheck = QtWidgets.QCheckBox(self.channelBox) self.cCheck.setGeometry(QtCore.QRect(30*widthRatio, 70*heightRatio, 16*widthRatio, 17*heightRatio)) self.cCheck.setText("") self.cCheck.setObjectName("cCheck") self.dCheck = QtWidgets.QCheckBox(self.channelBox) self.dCheck.setGeometry(QtCore.QRect(30*widthRatio, 90*heightRatio, 16*widthRatio, 17*heightRatio)) self.dCheck.setText("") self.dCheck.setObjectName("dCheck") self.aRangeComboBox = QtWidgets.QComboBox(self.channelBox) self.aRangeComboBox.setGeometry(QtCore.QRect(60*widthRatio, 30*heightRatio, 69*widthRatio, 16*heightRatio)) self.aRangeComboBox.setObjectName("aRangeComboBox") self.aRangeComboBox.addItem("") self.aRangeComboBox.addItem("") self.aRangeComboBox.addItem("") self.aRangeComboBox.addItem("") self.aRangeComboBox.addItem("") self.aRangeComboBox.addItem("") self.aRangeComboBox.addItem("") self.aRangeComboBox.addItem("") self.aRangeComboBox.addItem("") self.aRangeComboBox.addItem("") self.aRangeComboBox.addItem("") self.aRangeComboBox.addItem("") self.bRangeComboBox = QtWidgets.QComboBox(self.channelBox) self.bRangeComboBox.setGeometry(QtCore.QRect(60*widthRatio, 50*heightRatio, 69*widthRatio, 16*heightRatio)) self.bRangeComboBox.setObjectName("bRangeComboBox") self.bRangeComboBox.addItem("") self.bRangeComboBox.addItem("") self.bRangeComboBox.addItem("") self.bRangeComboBox.addItem("") self.bRangeComboBox.addItem("") self.bRangeComboBox.addItem("") self.bRangeComboBox.addItem("") self.bRangeComboBox.addItem("") self.bRangeComboBox.addItem("") self.bRangeComboBox.addItem("") self.bRangeComboBox.addItem("") self.bRangeComboBox.addItem("") self.cRangeComboBox = QtWidgets.QComboBox(self.channelBox) self.cRangeComboBox.setGeometry(QtCore.QRect(60*widthRatio, 70*heightRatio, 69*widthRatio, 16*heightRatio)) self.cRangeComboBox.setObjectName("cRangeComboBox") self.cRangeComboBox.addItem("") self.cRangeComboBox.addItem("") self.cRangeComboBox.addItem("") self.cRangeComboBox.addItem("") self.cRangeComboBox.addItem("") self.cRangeComboBox.addItem("") self.cRangeComboBox.addItem("") self.cRangeComboBox.addItem("") self.cRangeComboBox.addItem("") self.cRangeComboBox.addItem("") self.cRangeComboBox.addItem("") self.cRangeComboBox.addItem("") self.dRangeComboBox = QtWidgets.QComboBox(self.channelBox) self.dRangeComboBox.setGeometry(QtCore.QRect(60*widthRatio, 90*heightRatio, 69*widthRatio, 16*heightRatio)) self.dRangeComboBox.setObjectName("dRangeComboBox") self.dRangeComboBox.addItem("") self.dRangeComboBox.addItem("") self.dRangeComboBox.addItem("") self.dRangeComboBox.addItem("") self.dRangeComboBox.addItem("") self.dRangeComboBox.addItem("") self.dRangeComboBox.addItem("") self.dRangeComboBox.addItem("") self.dRangeComboBox.addItem("") self.dRangeComboBox.addItem("") self.dRangeComboBox.addItem("") self.dRangeComboBox.addItem("") self.aOffsetSpinBox = QtWidgets.QDoubleSpinBox(self.channelBox) self.aOffsetSpinBox.setGeometry(QtCore.QRect(150*widthRatio, 30*heightRatio, 62*widthRatio, 16*heightRatio)) self.aOffsetSpinBox.setMaximum(999999.0) self.aOffsetSpinBox.setObjectName("aOffsetSpinBox") self.bOffsetSpinBox = QtWidgets.QDoubleSpinBox(self.channelBox) self.bOffsetSpinBox.setGeometry(QtCore.QRect(150*widthRatio, 50*heightRatio, 62*widthRatio, 16*heightRatio)) self.bOffsetSpinBox.setMaximum(999999.0) self.bOffsetSpinBox.setObjectName("bOffsetSpinBox") self.cOffsetSpinBox = QtWidgets.QDoubleSpinBox(self.channelBox) self.cOffsetSpinBox.setGeometry(QtCore.QRect(150*widthRatio, 70*heightRatio, 62*widthRatio, 16*heightRatio)) self.cOffsetSpinBox.setMaximum(999999.0) self.cOffsetSpinBox.setObjectName("cOffsetSpinBox") self.dOffsetSpinBox = QtWidgets.QDoubleSpinBox(self.channelBox) self.dOffsetSpinBox.setGeometry(QtCore.QRect(150*widthRatio, 90*heightRatio, 62*widthRatio, 16*heightRatio)) self.dOffsetSpinBox.setMaximum(999999.0) self.dOffsetSpinBox.setObjectName("dOffsetSpinBox") self.rangeLabel = QtWidgets.QLabel(self.channelBox) self.rangeLabel.setGeometry(QtCore.QRect(80*widthRatio, 10*heightRatio, 47*widthRatio, 13*heightRatio)) self.rangeLabel.setObjectName("rangeLabel") self.offsetLabel = QtWidgets.QLabel(self.channelBox) self.offsetLabel.setGeometry(QtCore.QRect(160*widthRatio, 10*heightRatio, 47*widthRatio, 13*heightRatio)) self.offsetLabel.setObjectName("offsetLabel") self.couplingLabel = QtWidgets.QLabel(self.channelBox) self.couplingLabel.setGeometry(QtCore.QRect(230*widthRatio, 10*heightRatio, 47*widthRatio, 13*heightRatio)) self.couplingLabel.setObjectName("couplingLabel") self.aCouplingComboBox = QtWidgets.QComboBox(self.channelBox) self.aCouplingComboBox.setGeometry(QtCore.QRect(230*widthRatio, 30*heightRatio, 41*widthRatio, 16*heightRatio)) self.aCouplingComboBox.setObjectName("aCouplingComboBox") self.aCouplingComboBox.addItem("") self.aCouplingComboBox.addItem("") self.bCouplingComboBox = QtWidgets.QComboBox(self.channelBox) self.bCouplingComboBox.setGeometry(QtCore.QRect(230*widthRatio, 50*heightRatio, 41*widthRatio, 16*heightRatio)) self.bCouplingComboBox.setObjectName("bCouplingComboBox") self.bCouplingComboBox.addItem("") self.bCouplingComboBox.addItem("") self.cCouplingComboBox = QtWidgets.QComboBox(self.channelBox) self.cCouplingComboBox.setGeometry(QtCore.QRect(230*widthRatio, 70*heightRatio, 41*widthRatio, 16*heightRatio)) self.cCouplingComboBox.setObjectName("cCouplingComboBox") self.cCouplingComboBox.addItem("") self.cCouplingComboBox.addItem("") self.dCouplingComboBox = QtWidgets.QComboBox(self.channelBox) self.dCouplingComboBox.setGeometry(QtCore.QRect(230*widthRatio, 90*heightRatio, 41*widthRatio, 16*heightRatio)) self.dCouplingComboBox.setObjectName("dCouplingComboBox") self.dCouplingComboBox.addItem("") self.dCouplingComboBox.addItem("") self.captureBox = QtWidgets.QGroupBox(self.centralwidget) self.captureBox.setGeometry(QtCore.QRect(500*widthRatio, 0*heightRatio, 291*widthRatio, 121*heightRatio)) self.captureBox.setObjectName("captureBox") self.modeComboBox = QtWidgets.QComboBox(self.captureBox) self.modeComboBox.setGeometry(QtCore.QRect(40*widthRatio, 20*heightRatio, 81*widthRatio, 22*heightRatio)) self.modeComboBox.setObjectName("modeComboBox") self.modeComboBox.addItem("") self.modeComboBox.addItem("") self.modeComboBox.addItem("") self.modeLabel = QtWidgets.QLabel(self.captureBox) self.modeLabel.setGeometry(QtCore.QRect(10*widthRatio, 20*heightRatio, 31*widthRatio, 21*heightRatio)) self.modeLabel.setObjectName("modeLabel") self.preTriggerSamplesLabel = QtWidgets.QLabel(self.captureBox) self.preTriggerSamplesLabel.setGeometry(QtCore.QRect(130*widthRatio, 50*heightRatio, 101*widthRatio, 16*heightRatio)) self.preTriggerSamplesLabel.setObjectName("preTriggerSamplesLabel") self.postTriggerSamplesLabel = QtWidgets.QLabel(self.captureBox) self.postTriggerSamplesLabel.setGeometry(QtCore.QRect(130*widthRatio, 70*heightRatio, 101*widthRatio, 16*heightRatio)) self.postTriggerSamplesLabel.setObjectName("postTriggerSamplesLabel") self.preTriggerSamplesSpinBox = QtWidgets.QSpinBox(self.captureBox) self.preTriggerSamplesSpinBox.setEnabled(True) self.preTriggerSamplesSpinBox.setGeometry(QtCore.QRect(231*widthRatio, 50*heightRatio, 51*widthRatio, 16*heightRatio)) self.preTriggerSamplesSpinBox.setAutoFillBackground(False) self.preTriggerSamplesSpinBox.setReadOnly(False) self.preTriggerSamplesSpinBox.setProperty("showGroupSeparator", False) self.preTriggerSamplesSpinBox.setMaximum(999999) self.preTriggerSamplesSpinBox.setObjectName("preTriggerSamplesSpinBox") self.postTriggerSamplesSpinBox = QtWidgets.QSpinBox(self.captureBox) self.postTriggerSamplesSpinBox.setGeometry(QtCore.QRect(231*widthRatio, 70*heightRatio, 51*widthRatio, 16*heightRatio)) self.postTriggerSamplesSpinBox.setMaximum(999999) self.postTriggerSamplesSpinBox.setObjectName("postTriggerSamplesSpinBox") self.timebaseLabel = QtWidgets.QLabel(self.captureBox) self.timebaseLabel.setGeometry(QtCore.QRect(10*widthRatio, 50*heightRatio, 47*widthRatio, 13*heightRatio)) self.timebaseLabel.setObjectName("timebaseLabel") self.timebaseSpinBox = QtWidgets.QSpinBox(self.captureBox) self.timebaseSpinBox.setGeometry(QtCore.QRect(60*widthRatio, 50*heightRatio, 42*widthRatio, 16*heightRatio)) self.timebaseSpinBox.setMaximum(999999) self.timebaseSpinBox.setObjectName("timebaseSpinBox") self.segmentsLabel = QtWidgets.QLabel(self.captureBox) self.segmentsLabel.setGeometry(QtCore.QRect(10*widthRatio, 70*heightRatio, 47*widthRatio, 13*heightRatio)) self.segmentsLabel.setObjectName("segmentsLabel") self.capturesLabel = QtWidgets.QLabel(self.captureBox) self.capturesLabel.setGeometry(QtCore.QRect(10*widthRatio, 90*heightRatio, 47*widthRatio, 13*heightRatio)) self.capturesLabel.setObjectName("capturesLabel") self.segmentsSpinBox = QtWidgets.QSpinBox(self.captureBox) self.segmentsSpinBox.setGeometry(QtCore.QRect(60*widthRatio, 70*heightRatio, 42*widthRatio, 16*heightRatio)) self.segmentsSpinBox.setMaximum(999999) self.segmentsSpinBox.setObjectName("segmentsSpinBox") self.capturesSpinBox = QtWidgets.QSpinBox(self.captureBox) self.capturesSpinBox.setGeometry(QtCore.QRect(60*widthRatio, 90*heightRatio, 42*widthRatio, 16*heightRatio)) self.capturesSpinBox.setMaximum(999999) self.capturesSpinBox.setObjectName("capturesSpinBox") self.timeUnitsLabel = QtWidgets.QLabel(self.captureBox) self.timeUnitsLabel.setGeometry(QtCore.QRect(130*widthRatio, 30*heightRatio, 71*widthRatio, 16*heightRatio)) self.timeUnitsLabel.setObjectName("timeUnitsLabel") self.totalRuntimeLabel = QtWidgets.QLabel(self.captureBox) self.totalRuntimeLabel.setGeometry(QtCore.QRect(130*widthRatio, 10*heightRatio, 81*widthRatio, 16*heightRatio)) self.totalRuntimeLabel.setObjectName("totalRuntimeLabel") self.totalRuntimeSpinBox = QtWidgets.QSpinBox(self.captureBox) self.totalRuntimeSpinBox.setGeometry(QtCore.QRect(201*widthRatio, 10*heightRatio, 81*widthRatio, 16*heightRatio)) self.totalRuntimeSpinBox.setMaximum(999999999) self.totalRuntimeSpinBox.setObjectName("totalRuntimeSpinBox") self.timeUnitsComboBox = QtWidgets.QComboBox(self.captureBox) self.timeUnitsComboBox.setGeometry(QtCore.QRect(210*widthRatio, 30*heightRatio, 69*widthRatio, 16*heightRatio)) self.timeUnitsComboBox.setObjectName("timeUnitsComboBox") self.timeUnitsComboBox.addItem("") self.timeUnitsComboBox.addItem("") self.timeUnitsComboBox.addItem("") self.timeUnitsComboBox.addItem("") self.timeUnitsComboBox.addItem("") self.timeUnitsComboBox.addItem("") self.samplesPerBufferLabel = QtWidgets.QLabel(self.captureBox) self.samplesPerBufferLabel.setGeometry(QtCore.QRect(130*widthRatio, 90*heightRatio, 101*widthRatio, 16*heightRatio)) self.samplesPerBufferLabel.setObjectName("samplesPerBufferLabel") self.samplesPerBufferSpinBox = QtWidgets.QSpinBox(self.captureBox) self.samplesPerBufferSpinBox.setGeometry(QtCore.QRect(231*widthRatio, 90*heightRatio, 51*widthRatio, 16*heightRatio)) self.samplesPerBufferSpinBox.setMaximum(999999) self.samplesPerBufferSpinBox.setObjectName("samplesPerBufferSpinBox") self.driverLineEdit = QtWidgets.QLineEdit(self.centralwidget) self.driverLineEdit.setGeometry(QtCore.QRect(60*widthRatio, 10*heightRatio, 71*widthRatio, 22*heightRatio)) self.driverLineEdit.setReadOnly(True) self.driverLineEdit.setObjectName("driverLineEdit") self.outFileCheckBox = QtWidgets.QCheckBox(self.centralwidget) self.outFileCheckBox.setGeometry(QtCore.QRect(30*widthRatio, 80*heightRatio, 81*widthRatio, 17*heightRatio)) self.outFileCheckBox.setObjectName("outFileCheckBox") self.outFileNameLineEdit = QtWidgets.QLineEdit(self.centralwidget) self.outFileNameLineEdit.setGeometry(QtCore.QRect(30*widthRatio, 100*heightRatio, 113*widthRatio, 20*heightRatio)) self.outFileNameLineEdit.setObjectName("outFileNameLineEdit") self.triggerBox = QtWidgets.QGroupBox(self.centralwidget) self.triggerBox.setGeometry(QtCore.QRect(500*widthRatio, 130*heightRatio, 291*widthRatio, 391*heightRatio)) self.triggerBox.setObjectName("triggerBox") self.triggerTypeLabel = QtWidgets.QLabel(self.triggerBox) self.triggerTypeLabel.setGeometry(QtCore.QRect(10*widthRatio, 20*heightRatio, 47*widthRatio, 16*heightRatio)) self.triggerTypeLabel.setObjectName("triggerTypeLabel") self.triggerTypeComboBox = QtWidgets.QComboBox(self.triggerBox) self.triggerTypeComboBox.setGeometry(QtCore.QRect(40*widthRatio, 20*heightRatio, 69*widthRatio, 21*heightRatio)) self.triggerTypeComboBox.setObjectName("triggerTypeComboBox") self.triggerTypeComboBox.addItem("") self.triggerTypeComboBox.addItem("") self.aAutotriggerSpinBox = QtWidgets.QSpinBox(self.triggerBox) self.aAutotriggerSpinBox.setGeometry(QtCore.QRect(231*widthRatio, 10*heightRatio, 51*widthRatio, 16*heightRatio)) self.aAutotriggerSpinBox.setMaximum(999999) self.aAutotriggerSpinBox.setObjectName("aAutotriggerSpinBox") self.aDelaySpinBox = QtWidgets.QSpinBox(self.triggerBox) self.aDelaySpinBox.setGeometry(QtCore.QRect(231*widthRatio, 30*heightRatio, 51*widthRatio, 16*heightRatio)) self.aDelaySpinBox.setMaximum(999999) self.aDelaySpinBox.setObjectName("aDelaySpinBox") self.triggerAutotriggerLabel = QtWidgets.QLabel(self.triggerBox) self.triggerAutotriggerLabel.setGeometry(QtCore.QRect(160*widthRatio, 10*heightRatio, 71*widthRatio, 21*heightRatio)) self.triggerAutotriggerLabel.setObjectName("triggerAutotriggerLabel") self.triggerDelayLabel = QtWidgets.QLabel(self.triggerBox) self.triggerDelayLabel.setGeometry(QtCore.QRect(190*widthRatio, 30*heightRatio, 41*widthRatio, 16*heightRatio)) self.triggerDelayLabel.setObjectName("triggerDelayLabel") self.cUpperThresholdSpinBox = QtWidgets.QSpinBox(self.triggerBox) self.cUpperThresholdSpinBox.setGeometry(QtCore.QRect(51*widthRatio, 120*heightRatio, 51*widthRatio, 16*heightRatio)) self.cUpperThresholdSpinBox.setMaximum(32512) self.cUpperThresholdSpinBox.setObjectName("cUpperThresholdSpinBox") self.dUpperThresholdSpinBox = QtWidgets.QSpinBox(self.triggerBox) self.dUpperThresholdSpinBox.setGeometry(QtCore.QRect(51*widthRatio, 140*heightRatio, 51*widthRatio, 16*heightRatio)) self.dUpperThresholdSpinBox.setMaximum(32512) self.dUpperThresholdSpinBox.setObjectName("dUpperThresholdSpinBox") self.aUpperThresholdSpinBox = QtWidgets.QSpinBox(self.triggerBox) self.aUpperThresholdSpinBox.setGeometry(QtCore.QRect(51*widthRatio, 80*heightRatio, 51*widthRatio, 16*heightRatio)) self.aUpperThresholdSpinBox.setMaximum(32512) self.aUpperThresholdSpinBox.setObjectName("aUpperThresholdSpinBox") self.cTriggerCheck = QtWidgets.QCheckBox(self.triggerBox) self.cTriggerCheck.setGeometry(QtCore.QRect(30*widthRatio, 120*heightRatio, 16*widthRatio, 17*heightRatio)) self.cTriggerCheck.setText("") self.cTriggerCheck.setObjectName("cTriggerCheck") self.aTriggerCheck = QtWidgets.QCheckBox(self.triggerBox) self.aTriggerCheck.setGeometry(QtCore.QRect(30*widthRatio, 80*heightRatio, 16*widthRatio, 17*heightRatio)) self.aTriggerCheck.setText("") self.aTriggerCheck.setObjectName("aTriggerCheck") self.bTriggerLabel = QtWidgets.QLabel(self.triggerBox) self.bTriggerLabel.setGeometry(QtCore.QRect(10*widthRatio, 100*heightRatio, 16*widthRatio, 16*heightRatio)) self.bTriggerLabel.setObjectName("bTriggerLabel") self.bUpperThresholdSpinBox = QtWidgets.QSpinBox(self.triggerBox) self.bUpperThresholdSpinBox.setGeometry(QtCore.QRect(51*widthRatio, 100*heightRatio, 51*widthRatio, 16*heightRatio)) self.bUpperThresholdSpinBox.setMaximum(32512) self.bUpperThresholdSpinBox.setObjectName("bUpperThresholdSpinBox") self.aTriggerLabel = QtWidgets.QLabel(self.triggerBox) self.aTriggerLabel.setGeometry(QtCore.QRect(10*widthRatio, 80*heightRatio, 16*widthRatio, 16*heightRatio)) self.aTriggerLabel.setObjectName("aTriggerLabel") self.cTriggerLabel = QtWidgets.QLabel(self.triggerBox) self.cTriggerLabel.setGeometry(QtCore.QRect(10*widthRatio, 120*heightRatio, 16*widthRatio, 16*heightRatio)) self.cTriggerLabel.setObjectName("cTriggerLabel") self.dTriggerCheck = QtWidgets.QCheckBox(self.triggerBox) self.dTriggerCheck.setGeometry(QtCore.QRect(30*widthRatio, 140*heightRatio, 16*widthRatio, 17*heightRatio)) self.dTriggerCheck.setText("") self.dTriggerCheck.setObjectName("dTriggerCheck") self.triggerUpperThresholdLabel = QtWidgets.QLabel(self.triggerBox) self.triggerUpperThresholdLabel.setGeometry(QtCore.QRect(50*widthRatio, 50*heightRatio, 51*widthRatio, 31*heightRatio)) self.triggerUpperThresholdLabel.setWordWrap(True) self.triggerUpperThresholdLabel.setObjectName("triggerUpperThresholdLabel") self.dTriggerLabel = QtWidgets.QLabel(self.triggerBox) self.dTriggerLabel.setGeometry(QtCore.QRect(10*widthRatio, 140*heightRatio, 16*widthRatio, 16*heightRatio)) self.dTriggerLabel.setObjectName("dTriggerLabel") self.bTriggerCheck = QtWidgets.QCheckBox(self.triggerBox) self.bTriggerCheck.setGeometry(QtCore.QRect(30*widthRatio, 100*heightRatio, 16*widthRatio, 17*heightRatio)) self.bTriggerCheck.setText("") self.bTriggerCheck.setObjectName("bTriggerCheck") self.deleteConditionButton = QtWidgets.QPushButton(self.triggerBox) self.deleteConditionButton.setGeometry(QtCore.QRect(100*widthRatio, 340*heightRatio, 91*widthRatio, 23*heightRatio)) self.deleteConditionButton.setObjectName("deleteConditionButton") self.newConditionButton = QtWidgets.QPushButton(self.triggerBox) self.newConditionButton.setGeometry(QtCore.QRect(10*widthRatio, 340*heightRatio, 81*widthRatio, 21*heightRatio)) self.newConditionButton.setObjectName("newConditionButton") self.conditionsTabWidget = QtWidgets.QTabWidget(self.triggerBox) self.conditionsTabWidget.setEnabled(True) self.conditionsTabWidget.setGeometry(QtCore.QRect(10*widthRatio, 180*heightRatio, 121*widthRatio, 151*heightRatio)) self.conditionsTabWidget.setObjectName("conditionsTabWidget") self.newCondition() self.dUpperHysteresisSpinBox = QtWidgets.QSpinBox(self.triggerBox) self.dUpperHysteresisSpinBox.setGeometry(QtCore.QRect(111*widthRatio, 140*heightRatio, 51*widthRatio, 16*heightRatio)) self.dUpperHysteresisSpinBox.setMaximum(32512) self.dUpperHysteresisSpinBox.setObjectName("dUpperHysteresisSpinBox") self.bUpperHysteresisSpinBox = QtWidgets.QSpinBox(self.triggerBox) self.bUpperHysteresisSpinBox.setGeometry(QtCore.QRect(111*widthRatio, 100*heightRatio, 51*widthRatio, 16*heightRatio)) self.bUpperHysteresisSpinBox.setMaximum(32512) self.bUpperHysteresisSpinBox.setObjectName("bUpperHysteresisSpinBox") self.triggerUpperHysteresisLabel = QtWidgets.QLabel(self.triggerBox) self.triggerUpperHysteresisLabel.setGeometry(QtCore.QRect(110*widthRatio, 50*heightRatio, 51*widthRatio, 31*heightRatio)) self.triggerUpperHysteresisLabel.setWordWrap(True) self.triggerUpperHysteresisLabel.setObjectName("triggerUpperHysteresisLabel") self.aUpperHysteresisSpinBox = QtWidgets.QSpinBox(self.triggerBox) self.aUpperHysteresisSpinBox.setGeometry(QtCore.QRect(111*widthRatio, 80*heightRatio, 51*widthRatio, 16*heightRatio)) self.aUpperHysteresisSpinBox.setMaximum(32512) self.aUpperHysteresisSpinBox.setObjectName("aUpperHysteresisSpinBox") self.cUpperHysteresisSpinBox = QtWidgets.QSpinBox(self.triggerBox) self.cUpperHysteresisSpinBox.setGeometry(QtCore.QRect(111*widthRatio, 120*heightRatio, 51*widthRatio, 16*heightRatio)) self.cUpperHysteresisSpinBox.setMaximum(32512) self.cUpperHysteresisSpinBox.setObjectName("cUpperHysteresisSpinBox") self.dLowerThresholdSpinBox = QtWidgets.QSpinBox(self.triggerBox) self.dLowerThresholdSpinBox.setGeometry(QtCore.QRect(171*widthRatio, 140*heightRatio, 51*widthRatio, 16*heightRatio)) self.dLowerThresholdSpinBox.setMaximum(32512) self.dLowerThresholdSpinBox.setObjectName("dLowerThresholdSpinBox") self.dLowerHysteresisSpinBox = QtWidgets.QSpinBox(self.triggerBox) self.dLowerHysteresisSpinBox.setGeometry(QtCore.QRect(231*widthRatio, 140*heightRatio, 51*widthRatio, 16*heightRatio)) self.dLowerHysteresisSpinBox.setMaximum(32512) self.dLowerHysteresisSpinBox.setObjectName("dLowerHysteresisSpinBox") self.triggerLowerHysteresisLabel = QtWidgets.QLabel(self.triggerBox) self.triggerLowerHysteresisLabel.setGeometry(QtCore.QRect(230*widthRatio, 50*heightRatio, 51*widthRatio, 31*heightRatio)) self.triggerLowerHysteresisLabel.setWordWrap(True) self.triggerLowerHysteresisLabel.setObjectName("triggerLowerHysteresisLabel") self.aLowerHysteresisSpinBox = QtWidgets.QSpinBox(self.triggerBox) self.aLowerHysteresisSpinBox.setGeometry(QtCore.QRect(231*widthRatio, 80*heightRatio, 51*widthRatio, 16*heightRatio)) self.aLowerHysteresisSpinBox.setMaximum(32512) self.aLowerHysteresisSpinBox.setObjectName("aLowerHysteresisSpinBox") self.bLowerThresholdSpinBox = QtWidgets.QSpinBox(self.triggerBox) self.bLowerThresholdSpinBox.setGeometry(QtCore.QRect(171*widthRatio, 100*heightRatio, 51*widthRatio, 16*heightRatio)) self.bLowerThresholdSpinBox.setMaximum(32512) self.bLowerThresholdSpinBox.setObjectName("bLowerThresholdSpinBox") self.bLowerHysteresisSpinBox = QtWidgets.QSpinBox(self.triggerBox) self.bLowerHysteresisSpinBox.setGeometry(QtCore.QRect(231*widthRatio, 100*heightRatio, 51*widthRatio, 16*heightRatio)) self.bLowerHysteresisSpinBox.setMaximum(32512) self.bLowerHysteresisSpinBox.setObjectName("bLowerHysteresisSpinBox") self.cLowerHysteresisSpinBox = QtWidgets.QSpinBox(self.triggerBox) self.cLowerHysteresisSpinBox.setGeometry(QtCore.QRect(231*widthRatio, 120*heightRatio, 51*widthRatio, 16*heightRatio)) self.cLowerHysteresisSpinBox.setMaximum(32512) self.cLowerHysteresisSpinBox.setObjectName("cLowerHysteresisSpinBox") self.triggerLowerThresholdLabel = QtWidgets.QLabel(self.triggerBox) self.triggerLowerThresholdLabel.setGeometry(QtCore.QRect(170*widthRatio, 50*heightRatio, 51*widthRatio, 31*heightRatio)) self.triggerLowerThresholdLabel.setWordWrap(True) self.triggerLowerThresholdLabel.setObjectName("triggerLowerThresholdLabel") self.aLowerThresholdSpinBox = QtWidgets.QSpinBox(self.triggerBox) self.aLowerThresholdSpinBox.setGeometry(QtCore.QRect(171*widthRatio, 80*heightRatio, 51*widthRatio, 16*heightRatio)) self.aLowerThresholdSpinBox.setMaximum(32512) self.aLowerThresholdSpinBox.setObjectName("aLowerThresholdSpinBox") self.cLowerThresholdSpinBox = QtWidgets.QSpinBox(self.triggerBox) self.cLowerThresholdSpinBox.setGeometry(QtCore.QRect(171*widthRatio, 120*heightRatio, 51*widthRatio, 16*heightRatio)) self.cLowerThresholdSpinBox.setMaximum(32512) self.cLowerThresholdSpinBox.setObjectName("cLowerThresholdSpinBox") self.extTriggerLabel = QtWidgets.QLabel(self.triggerBox) self.extTriggerLabel.setGeometry(QtCore.QRect(10*widthRatio, 160*heightRatio, 16*widthRatio, 16*heightRatio)) self.extTriggerLabel.setObjectName("extTriggerLabel") self.extTriggerCheck = QtWidgets.QCheckBox(self.triggerBox) self.extTriggerCheck.setGeometry(QtCore.QRect(30*widthRatio, 160*heightRatio, 16*widthRatio, 17*heightRatio)) self.extTriggerCheck.setText("") self.extTriggerCheck.setObjectName("extTriggerCheck") self.extUpperThresholdSpinBox = QtWidgets.QSpinBox(self.triggerBox) self.extUpperThresholdSpinBox.setGeometry(QtCore.QRect(51*widthRatio, 160*heightRatio, 51*widthRatio, 16*heightRatio)) self.extUpperThresholdSpinBox.setMaximum(32767) self.extUpperThresholdSpinBox.setObjectName("extUpperThresholdSpinBox") self.extUpperHysteresisSpinBox = QtWidgets.QSpinBox(self.triggerBox) self.extUpperHysteresisSpinBox.setGeometry(QtCore.QRect(111*widthRatio, 160*heightRatio, 51*widthRatio, 16*heightRatio)) self.extUpperHysteresisSpinBox.setMaximum(32767) self.extUpperHysteresisSpinBox.setObjectName("extUpperHysteresisSpinBox") self.extLowerThresholdSpinBox = QtWidgets.QSpinBox(self.triggerBox) self.extLowerThresholdSpinBox.setGeometry(QtCore.QRect(171*widthRatio, 160*heightRatio, 51*widthRatio, 16*heightRatio)) self.extLowerThresholdSpinBox.setMaximum(32767) self.extLowerThresholdSpinBox.setObjectName("extLowerThresholdSpinBox") self.extLowerHysteresisSpinBox = QtWidgets.QSpinBox(self.triggerBox) self.extLowerHysteresisSpinBox.setGeometry(QtCore.QRect(231*widthRatio, 160*heightRatio, 51*widthRatio, 16*heightRatio)) self.extLowerHysteresisSpinBox.setMaximum(32767) self.extLowerHysteresisSpinBox.setObjectName("extLowerHysteresisSpinBox") self.triggerDirectionLabel = QtWidgets.QLabel(self.triggerBox) self.triggerDirectionLabel.setGeometry(QtCore.QRect(140*widthRatio, 200*heightRatio, 47*widthRatio, 21*heightRatio)) self.triggerDirectionLabel.setObjectName("triggerDirectionLabel") self.aThresholdModeComboBox = QtWidgets.QComboBox(self.triggerBox) self.aThresholdModeComboBox.setGeometry(QtCore.QRect(220*widthRatio, 220*heightRatio, 61*widthRatio, 16*heightRatio)) self.aThresholdModeComboBox.setObjectName("aThresholdModeComboBox") self.aThresholdModeComboBox.addItem("") self.aThresholdModeComboBox.addItem("") self.bDirectionComboBox = QtWidgets.QComboBox(self.triggerBox) self.bDirectionComboBox.setGeometry(QtCore.QRect(140*widthRatio, 240*heightRatio, 71*widthRatio, 16*heightRatio)) self.bDirectionComboBox.setObjectName("bDirectionComboBox") self.bDirectionComboBox.addItem("") self.bDirectionComboBox.addItem("") self.bDirectionComboBox.addItem("") self.bDirectionComboBox.addItem("") self.bDirectionComboBox.addItem("") self.bDirectionComboBox.addItem("") self.bDirectionComboBox.addItem("") self.bDirectionComboBox.addItem("") self.bDirectionComboBox.addItem("") self.bDirectionComboBox.addItem("") self.bDirectionComboBox.addItem("") self.extDirectionComboBox = QtWidgets.QComboBox(self.triggerBox) self.extDirectionComboBox.setGeometry(QtCore.QRect(140*widthRatio, 300*heightRatio, 71*widthRatio, 16*heightRatio)) self.extDirectionComboBox.setObjectName("extDirectionComboBox") self.extDirectionComboBox.addItem("") self.extDirectionComboBox.addItem("") self.extDirectionComboBox.addItem("") self.extDirectionComboBox.addItem("") self.extDirectionComboBox.addItem("") self.extDirectionComboBox.addItem("") self.extDirectionComboBox.addItem("") self.extDirectionComboBox.addItem("") self.extDirectionComboBox.addItem("") self.extDirectionComboBox.addItem("") self.extDirectionComboBox.addItem("") self.dDirectionComboBox = QtWidgets.QComboBox(self.triggerBox) self.dDirectionComboBox.setGeometry(QtCore.QRect(140*widthRatio, 280*heightRatio, 71*widthRatio, 16*heightRatio)) self.dDirectionComboBox.setObjectName("dDirectionComboBox") self.dDirectionComboBox.addItem("") self.dDirectionComboBox.addItem("") self.dDirectionComboBox.addItem("") self.dDirectionComboBox.addItem("") self.dDirectionComboBox.addItem("") self.dDirectionComboBox.addItem("") self.dDirectionComboBox.addItem("") self.dDirectionComboBox.addItem("") self.dDirectionComboBox.addItem("") self.dDirectionComboBox.addItem("") self.dDirectionComboBox.addItem("") self.thresholdModeLabel = QtWidgets.QLabel(self.triggerBox) self.thresholdModeLabel.setGeometry(QtCore.QRect(220*widthRatio, 200*heightRatio, 47*widthRatio, 21*heightRatio)) self.thresholdModeLabel.setObjectName("thresholdModeLabel") self.cDirectionComboBox = QtWidgets.QComboBox(self.triggerBox) self.cDirectionComboBox.setGeometry(QtCore.QRect(140*widthRatio, 260*heightRatio, 71*widthRatio, 16*heightRatio)) self.cDirectionComboBox.setObjectName("cDirectionComboBox") self.cDirectionComboBox.addItem("") self.cDirectionComboBox.addItem("") self.cDirectionComboBox.addItem("") self.cDirectionComboBox.addItem("") self.cDirectionComboBox.addItem("") self.cDirectionComboBox.addItem("") self.cDirectionComboBox.addItem("") self.cDirectionComboBox.addItem("") self.cDirectionComboBox.addItem("") self.cDirectionComboBox.addItem("") self.cDirectionComboBox.addItem("") self.aDirectionComboBox = QtWidgets.QComboBox(self.triggerBox) self.aDirectionComboBox.setGeometry(QtCore.QRect(140*widthRatio, 220*heightRatio, 71*widthRatio, 16*heightRatio)) self.aDirectionComboBox.setObjectName("aDirectionComboBox") self.aDirectionComboBox.addItem("") self.aDirectionComboBox.addItem("") self.aDirectionComboBox.addItem("") self.aDirectionComboBox.addItem("") self.aDirectionComboBox.addItem("") self.aDirectionComboBox.addItem("") self.aDirectionComboBox.addItem("") self.aDirectionComboBox.addItem("") self.aDirectionComboBox.addItem("") self.aDirectionComboBox.addItem("") self.aDirectionComboBox.addItem("") self.dThresholdModeComboBox = QtWidgets.QComboBox(self.triggerBox) self.dThresholdModeComboBox.setGeometry(QtCore.QRect(220*widthRatio, 280*heightRatio, 61*widthRatio, 16*heightRatio)) self.dThresholdModeComboBox.setObjectName("dThresholdModeComboBox") self.dThresholdModeComboBox.addItem("") self.dThresholdModeComboBox.addItem("") self.bThresholdModeComboBox = QtWidgets.QComboBox(self.triggerBox) self.bThresholdModeComboBox.setGeometry(QtCore.QRect(220*widthRatio, 240*heightRatio, 61*widthRatio, 16*heightRatio)) self.bThresholdModeComboBox.setObjectName("bThresholdModeComboBox") self.bThresholdModeComboBox.addItem("") self.bThresholdModeComboBox.addItem("") self.extThresholdModeComboBox = QtWidgets.QComboBox(self.triggerBox) self.extThresholdModeComboBox.setGeometry(QtCore.QRect(220*widthRatio, 300*heightRatio, 61*widthRatio, 16*heightRatio)) self.extThresholdModeComboBox.setObjectName("extThresholdModeComboBox") self.extThresholdModeComboBox.addItem("") self.extThresholdModeComboBox.addItem("") self.cThresholdModeComboBox = QtWidgets.QComboBox(self.triggerBox) self.cThresholdModeComboBox.setGeometry(QtCore.QRect(220*widthRatio, 260*heightRatio, 61*widthRatio, 16*heightRatio)) self.cThresholdModeComboBox.setObjectName("cThresholdModeComboBox") self.cThresholdModeComboBox.addItem("") self.cThresholdModeComboBox.addItem("") self.runButton = QtWidgets.QPushButton(self.centralwidget) self.runButton.setGeometry(QtCore.QRect(720*widthRatio, 530*heightRatio, 75*widthRatio, 23*heightRatio)) self.runButton.setObjectName("runButton") self.runsLabel = QtWidgets.QLabel(self.centralwidget) self.runsLabel.setGeometry(QtCore.QRect(120*widthRatio, 70*heightRatio, 47*widthRatio, 16*heightRatio)) self.runsLabel.setObjectName("runsLabel") self.runsSpinBox = QtWidgets.QSpinBox(self.centralwidget) self.runsSpinBox.setGeometry(QtCore.QRect(160*widthRatio, 70*heightRatio, 42*widthRatio, 16*heightRatio)) self.runsSpinBox.setObjectName("runsSpinBox") self.runsSpinBox.setMaximum(999999999) self.tabWidget = QtWidgets.QTabWidget(self.centralwidget) self.tabWidget.setGeometry(QtCore.QRect(20*widthRatio, 130*heightRatio, 471*widthRatio, 391*heightRatio)) self.tabWidget.setObjectName("tabWidget") runList['runTab'].append(QtWidgets.QWidget()) runList['runTab'][-1].setObjectName("run_1") runList['stackedWidget'].append(QtWidgets.QStackedWidget(runList['runTab'][-1])) runList['stackedWidget'][-1].setGeometry(QtCore.QRect(0*widthRatio, 0*heightRatio, 461*widthRatio, 361*heightRatio)) runList['stackedWidget'][-1].setObjectName("stackedWidget_1") self.tabWidget.addTab(runList['runTab'][-1], "") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0*widthRatio, 0*heightRatio, 801*widthRatio, 21*heightRatio)) self.menubar.setObjectName("menubar") self.menuPreset = QtWidgets.QMenu(self.menubar) self.menuPreset.setObjectName("menuPreset") MainWindow.setMenuBar(self.menubar) self.actionLoad_Preset = QtWidgets.QAction(MainWindow) self.actionLoad_Preset.setObjectName("actionLoad_Preset") self.actionSave_Preset = QtWidgets.QAction(MainWindow) self.actionSave_Preset.setObjectName("actionSave_Preset") self.menuPreset.addAction(self.actionSave_Preset) self.menuPreset.addAction(self.actionLoad_Preset) self.menubar.addAction(self.menuPreset.menuAction()) self.nextPushButton = QtWidgets.QPushButton(self.centralwidget) self.nextPushButton.setGeometry(QtCore.QRect(260*widthRatio, 530*heightRatio, 75*widthRatio, 23*heightRatio)) self.nextPushButton.setObjectName("nextPushButton") self.pageNumLineEdit = QtWidgets.QLineEdit(self.centralwidget) self.pageNumLineEdit.setGeometry(QtCore.QRect(232*widthRatio, 531*heightRatio, 21*widthRatio, 20*heightRatio)) self.pageNumLineEdit.setObjectName("pageNumLineEdit") self.previousPushButton = QtWidgets.QPushButton(self.centralwidget) self.previousPushButton.setGeometry(QtCore.QRect(150*widthRatio, 530*heightRatio, 75*widthRatio, 23*heightRatio)) self.previousPushButton.setObjectName("previousPushButton") self.graphCheck = QtWidgets.QCheckBox(self.centralwidget) self.graphCheck.setGeometry(QtCore.QRect(650*widthRatio, 530*heightRatio, 70*widthRatio, 21*heightRatio)) self.graphCheck.setObjectName("graphCheck") self.retranslateUi(MainWindow) self.conditionsTabWidget.setCurrentIndex(0) self.tabWidget.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "Logger")) self.driverLabel.setText(_translate("MainWindow", "Driver")) self.presetComboBox.setItemText(0, _translate("MainWindow", "Manual")) self.presetLabel.setText(_translate("MainWindow", "Preset")) self.channelBox.setTitle(_translate("MainWindow", "Channels")) self.aLabel.setText(_translate("MainWindow", "A")) self.bLabel.setText(_translate("MainWindow", "B")) self.cLabel.setText(_translate("MainWindow", "C")) self.dLabel.setText(_translate("MainWindow", "D")) self.aRangeComboBox.setItemText(0, _translate("MainWindow", "10 mV")) self.aRangeComboBox.setItemText(1, _translate("MainWindow", "20 mV")) self.aRangeComboBox.setItemText(2, _translate("MainWindow", "50 mV")) self.aRangeComboBox.setItemText(3, _translate("MainWindow", "100 mV")) self.aRangeComboBox.setItemText(4, _translate("MainWindow", "200 mV")) self.aRangeComboBox.setItemText(5, _translate("MainWindow", "500 mV")) self.aRangeComboBox.setItemText(6, _translate("MainWindow", "1 V")) self.aRangeComboBox.setItemText(7, _translate("MainWindow", "2 V")) self.aRangeComboBox.setItemText(8, _translate("MainWindow", "5 V")) self.aRangeComboBox.setItemText(9, _translate("MainWindow", "10 V")) self.aRangeComboBox.setItemText(10, _translate("MainWindow", "20 V")) self.aRangeComboBox.setItemText(11, _translate("MainWindow", "50 V")) self.bRangeComboBox.setItemText(0, _translate("MainWindow", "10 mV")) self.bRangeComboBox.setItemText(1, _translate("MainWindow", "20 mV")) self.bRangeComboBox.setItemText(2, _translate("MainWindow", "50 mV")) self.bRangeComboBox.setItemText(3, _translate("MainWindow", "100 mV")) self.bRangeComboBox.setItemText(4, _translate("MainWindow", "200 mV")) self.bRangeComboBox.setItemText(5, _translate("MainWindow", "500 mV")) self.bRangeComboBox.setItemText(6, _translate("MainWindow", "1 V")) self.bRangeComboBox.setItemText(7, _translate("MainWindow", "2 V")) self.bRangeComboBox.setItemText(8, _translate("MainWindow", "5 V")) self.bRangeComboBox.setItemText(9, _translate("MainWindow", "10 V")) self.bRangeComboBox.setItemText(10, _translate("MainWindow", "20 V")) self.bRangeComboBox.setItemText(11, _translate("MainWindow", "50 V")) self.cRangeComboBox.setItemText(0, _translate("MainWindow", "10 mV")) self.cRangeComboBox.setItemText(1, _translate("MainWindow", "20 mV")) self.cRangeComboBox.setItemText(2, _translate("MainWindow", "50 mV")) self.cRangeComboBox.setItemText(3, _translate("MainWindow", "100 mV")) self.cRangeComboBox.setItemText(4, _translate("MainWindow", "200 mV")) self.cRangeComboBox.setItemText(5, _translate("MainWindow", "500 mV")) self.cRangeComboBox.setItemText(6, _translate("MainWindow", "1 V")) self.cRangeComboBox.setItemText(7, _translate("MainWindow", "2 V")) self.cRangeComboBox.setItemText(8, _translate("MainWindow", "5 V")) self.cRangeComboBox.setItemText(9, _translate("MainWindow", "10 V")) self.cRangeComboBox.setItemText(10, _translate("MainWindow", "20 V")) self.cRangeComboBox.setItemText(11, _translate("MainWindow", "50 V")) self.dRangeComboBox.setItemText(0, _translate("MainWindow", "10 mV")) self.dRangeComboBox.setItemText(1, _translate("MainWindow", "20 mV")) self.dRangeComboBox.setItemText(2, _translate("MainWindow", "50 mV")) self.dRangeComboBox.setItemText(3, _translate("MainWindow", "100 mV")) self.dRangeComboBox.setItemText(4, _translate("MainWindow", "200 mV")) self.dRangeComboBox.setItemText(5, _translate("MainWindow", "500 mV")) self.dRangeComboBox.setItemText(6, _translate("MainWindow", "1 V")) self.dRangeComboBox.setItemText(7, _translate("MainWindow", "2 V")) self.dRangeComboBox.setItemText(8, _translate("MainWindow", "5 V")) self.dRangeComboBox.setItemText(9, _translate("MainWindow", "10 V")) self.dRangeComboBox.setItemText(10, _translate("MainWindow", "20 V")) self.dRangeComboBox.setItemText(11, _translate("MainWindow", "50 V")) self.aCouplingComboBox.setItemText(0, _translate("MainWindow", "AC")) self.aCouplingComboBox.setItemText(1, _translate("MainWindow", "DC")) self.bCouplingComboBox.setItemText(0, _translate("MainWindow", "AC")) self.bCouplingComboBox.setItemText(1, _translate("MainWindow", "DC")) self.cCouplingComboBox.setItemText(0, _translate("MainWindow", "AC")) self.cCouplingComboBox.setItemText(1, _translate("MainWindow", "DC")) self.dCouplingComboBox.setItemText(0, _translate("MainWindow", "AC")) self.dCouplingComboBox.setItemText(1, _translate("MainWindow", "DC")) self.rangeLabel.setText(_translate("MainWindow", "Range")) self.offsetLabel.setText(_translate("MainWindow", "Offset")) self.couplingLabel.setText(_translate("MainWindow", "Coupling")) self.captureBox.setTitle(_translate("MainWindow", "Capture")) self.modeComboBox.setItemText(0, _translate("MainWindow", "Block")) self.modeComboBox.setItemText(1, _translate("MainWindow", "Rapid Block")) self.modeComboBox.setItemText(2, _translate("MainWindow", "Streaming")) self.modeLabel.setText(_translate("MainWindow", "Mode")) self.preTriggerSamplesLabel.setText(_translate("MainWindow", "Pre Trigger Samples")) self.postTriggerSamplesLabel.setText(_translate("MainWindow", "Post Trigger Samples")) self.timebaseLabel.setText(_translate("MainWindow", "Timebase")) self.segmentsLabel.setText(_translate("MainWindow", "Segments")) self.capturesLabel.setText(_translate("MainWindow", "Captures")) self.timeUnitsLabel.setText(_translate("MainWindow", "Time Units")) self.totalRuntimeLabel.setText(_translate("MainWindow", "Total Runtime")) self.timeUnitsComboBox.setItemText(0, _translate("MainWindow", "fs")) self.timeUnitsComboBox.setItemText(1, _translate("MainWindow", "ps")) self.timeUnitsComboBox.setItemText(2, _translate("MainWindow", "ns")) self.timeUnitsComboBox.setItemText(3, _translate("MainWindow", "μs")) self.timeUnitsComboBox.setItemText(4, _translate("MainWindow", "ms")) self.timeUnitsComboBox.setItemText(5, _translate("MainWindow", "s")) self.samplesPerBufferLabel.setText(_translate("MainWindow", "Samples per Buffer")) self.outFileCheckBox.setText(_translate("MainWindow", "File Output")) self.triggerBox.setTitle(_translate("MainWindow", "Trigger")) self.triggerTypeLabel.setText(_translate("MainWindow", "Type")) self.triggerTypeComboBox.setItemText(0, _translate("MainWindow", "Simple")) self.triggerTypeComboBox.setItemText(1, _translate("MainWindow", "Complex")) self.triggerAutotriggerLabel.setText(_translate("MainWindow", "Auto-Trigger")) self.triggerDelayLabel.setText(_translate("MainWindow", "Delay")) self.bTriggerLabel.setText(_translate("MainWindow", "B")) self.aTriggerLabel.setText(_translate("MainWindow", "A")) self.cTriggerLabel.setText(_translate("MainWindow", "C")) self.triggerUpperThresholdLabel.setText(_translate("MainWindow", "Upper Threshold")) self.dTriggerLabel.setText(_translate("MainWindow", "D")) self.deleteConditionButton.setText(_translate("MainWindow", "Delete Condition")) self.newConditionButton.setText(_translate("MainWindow", "New Condition")) self.triggerUpperHysteresisLabel.setText(_translate("MainWindow", "Upper Hysteresis")) self.triggerLowerHysteresisLabel.setText(_translate("MainWindow", "Lower Hysteresis")) self.triggerLowerThresholdLabel.setText(_translate("MainWindow", "Lower Threshold")) self.extTriggerLabel.setText(_translate("MainWindow", "Ext")) self.triggerDirectionLabel.setText(_translate("MainWindow", "Direction")) self.aThresholdModeComboBox.setItemText(0, _translate("MainWindow", "Level")) self.aThresholdModeComboBox.setItemText(1, _translate("MainWindow", "Window")) self.bDirectionComboBox.setItemText(0, _translate("MainWindow", "Above")) self.bDirectionComboBox.setItemText(1, _translate("MainWindow", "Below")) self.bDirectionComboBox.setItemText(2, _translate("MainWindow", "Rising")) self.bDirectionComboBox.setItemText(3, _translate("MainWindow", "Falling")) self.bDirectionComboBox.setItemText(4, _translate("MainWindow", "Rising or Falling")) self.bDirectionComboBox.setItemText(5, _translate("MainWindow", "Above Lower")) self.bDirectionComboBox.setItemText(6, _translate("MainWindow", "Below Lower")) self.bDirectionComboBox.setItemText(7, _translate("MainWindow", "Rising Lower")) self.bDirectionComboBox.setItemText(8, _translate("MainWindow", "Falling Lower")) self.bDirectionComboBox.setItemText(9, _translate("MainWindow", "Positive Runt")) self.bDirectionComboBox.setItemText(10, _translate("MainWindow", "Negative Runt")) self.extDirectionComboBox.setItemText(0, _translate("MainWindow", "Above")) self.extDirectionComboBox.setItemText(1, _translate("MainWindow", "Below")) self.extDirectionComboBox.setItemText(2, _translate("MainWindow", "Rising")) self.extDirectionComboBox.setItemText(3, _translate("MainWindow", "Falling")) self.extDirectionComboBox.setItemText(4, _translate("MainWindow", "Rising or Falling")) self.extDirectionComboBox.setItemText(5, _translate("MainWindow", "Above Lower")) self.extDirectionComboBox.setItemText(6, _translate("MainWindow", "Below Lower")) self.extDirectionComboBox.setItemText(7, _translate("MainWindow", "Rising Lower")) self.extDirectionComboBox.setItemText(8, _translate("MainWindow", "Falling Lower")) self.extDirectionComboBox.setItemText(9, _translate("MainWindow", "Positive Runt")) self.extDirectionComboBox.setItemText(10, _translate("MainWindow", "Negative Runt")) self.dDirectionComboBox.setItemText(0, _translate("MainWindow", "Above")) self.dDirectionComboBox.setItemText(1, _translate("MainWindow", "Below")) self.dDirectionComboBox.setItemText(2, _translate("MainWindow", "Rising")) self.dDirectionComboBox.setItemText(3, _translate("MainWindow", "Falling")) self.dDirectionComboBox.setItemText(4, _translate("MainWindow", "Rising or Falling")) self.dDirectionComboBox.setItemText(5, _translate("MainWindow", "Above Lower")) self.dDirectionComboBox.setItemText(6, _translate("MainWindow", "Below Lower")) self.dDirectionComboBox.setItemText(7, _translate("MainWindow", "Rising Lower")) self.dDirectionComboBox.setItemText(8, _translate("MainWindow", "Falling Lower")) self.dDirectionComboBox.setItemText(9, _translate("MainWindow", "Positive Runt")) self.dDirectionComboBox.setItemText(10, _translate("MainWindow", "Negative Runt")) self.thresholdModeLabel.setText(_translate("MainWindow", "Mode")) self.cDirectionComboBox.setItemText(0, _translate("MainWindow", "Above")) self.cDirectionComboBox.setItemText(1, _translate("MainWindow", "Below")) self.cDirectionComboBox.setItemText(2, _translate("MainWindow", "Rising")) self.cDirectionComboBox.setItemText(3, _translate("MainWindow", "Falling")) self.cDirectionComboBox.setItemText(4, _translate("MainWindow", "Rising or Falling")) self.cDirectionComboBox.setItemText(5, _translate("MainWindow", "Above Lower")) self.cDirectionComboBox.setItemText(6, _translate("MainWindow", "Below Lower")) self.cDirectionComboBox.setItemText(7, _translate("MainWindow", "Rising Lower")) self.cDirectionComboBox.setItemText(8, _translate("MainWindow", "Falling Lower")) self.cDirectionComboBox.setItemText(9, _translate("MainWindow", "Positive Runt")) self.cDirectionComboBox.setItemText(10, _translate("MainWindow", "Negative Runt")) self.aDirectionComboBox.setItemText(0, _translate("MainWindow", "Above")) self.aDirectionComboBox.setItemText(1, _translate("MainWindow", "Below")) self.aDirectionComboBox.setItemText(2, _translate("MainWindow", "Rising")) self.aDirectionComboBox.setItemText(3, _translate("MainWindow", "Falling")) self.aDirectionComboBox.setItemText(4, _translate("MainWindow", "Rising or Falling")) self.aDirectionComboBox.setItemText(5, _translate("MainWindow", "Above Lower")) self.aDirectionComboBox.setItemText(6, _translate("MainWindow", "Below Lower")) self.aDirectionComboBox.setItemText(7, _translate("MainWindow", "Rising Lower")) self.aDirectionComboBox.setItemText(8, _translate("MainWindow", "Falling Lower")) self.aDirectionComboBox.setItemText(9, _translate("MainWindow", "Positive Runt")) self.aDirectionComboBox.setItemText(10, _translate("MainWindow", "Negative Runt")) self.dThresholdModeComboBox.setItemText(0, _translate("MainWindow", "Level")) self.dThresholdModeComboBox.setItemText(1, _translate("MainWindow", "Window")) self.bThresholdModeComboBox.setItemText(0, _translate("MainWindow", "Level")) self.bThresholdModeComboBox.setItemText(1, _translate("MainWindow", "Window")) self.extThresholdModeComboBox.setItemText(0, _translate("MainWindow", "Level")) self.extThresholdModeComboBox.setItemText(1, _translate("MainWindow", "Window")) self.cThresholdModeComboBox.setItemText(0, _translate("MainWindow", "Level")) self.cThresholdModeComboBox.setItemText(1, _translate("MainWindow", "Window")) self.runButton.setText(_translate("MainWindow", "Run")) self.runsLabel.setText(_translate("MainWindow", "Runs")) self.tabWidget.setTabText(self.tabWidget.indexOf(runList['runTab'][-1]), _translate("MainWindow", "Run 1")) self.menuPreset.setTitle(_translate("MainWindow", "Presets")) self.actionLoad_Preset.setText(_translate("MainWindow", "Load Preset")) self.actionLoad_Preset.setShortcut(_translate("MainWindow", "Ctrl+O")) self.actionSave_Preset.setText(_translate("MainWindow", "Save Preset")) self.actionSave_Preset.setShortcut(_translate("MainWindow", "Ctrl+S")) #Defaults self.outFileNameLineEdit.setEnabled(False) self.cCheck.setEnabled(False) self.dCheck.setEnabled(False) self.cRangeComboBox.setEnabled(False) self.dRangeComboBox.setEnabled(False) self.cOffsetSpinBox.setEnabled(False) self.dOffsetSpinBox.setEnabled(False) self.cCouplingComboBox.setEnabled(False) self.dCouplingComboBox.setEnabled(False) self.cTriggerCheck.setEnabled(False) self.dTriggerCheck.setEnabled(False) self.extTriggerCheck.setEnabled(False) self.cUpperThresholdSpinBox.setEnabled(False) self.dUpperThresholdSpinBox.setEnabled(False) self.extUpperThresholdSpinBox.setEnabled(False) self.cUpperHysteresisSpinBox.setEnabled(False) self.dUpperHysteresisSpinBox.setEnabled(False) self.extUpperHysteresisSpinBox.setEnabled(False) self.cLowerThresholdSpinBox.setEnabled(False) self.dLowerThresholdSpinBox.setEnabled(False) self.extLowerThresholdSpinBox.setEnabled(False) self.cLowerHysteresisSpinBox.setEnabled(False) self.dLowerHysteresisSpinBox.setEnabled(False) self.extLowerHysteresisSpinBox.setEnabled(False) conditionList['cStateComboBox'][-1].setEnabled(False) conditionList['dStateComboBox'][-1].setEnabled(False) conditionList['extStateComboBox'][-1].setEnabled(False) self.cDirectionComboBox.setEnabled(False) self.dDirectionComboBox.setEnabled(False) self.extDirectionComboBox.setEnabled(False) self.cThresholdModeComboBox.setEnabled(False) self.dThresholdModeComboBox.setEnabled(False) self.extThresholdModeComboBox.setEnabled(False) self.totalRuntimeSpinBox.setEnabled(False) self.timeUnitsComboBox.setEnabled(False) self.segmentsSpinBox.setEnabled(False) self.capturesSpinBox.setEnabled(False) self.samplesPerBufferSpinBox.setEnabled(False) self.aUpperHysteresisSpinBox.setEnabled(False) self.bUpperHysteresisSpinBox.setEnabled(False) self.cUpperHysteresisSpinBox.setEnabled(False) self.dUpperHysteresisSpinBox.setEnabled(False) self.aLowerThresholdSpinBox.setEnabled(False) self.bLowerThresholdSpinBox.setEnabled(False) self.cLowerThresholdSpinBox.setEnabled(False) self.dLowerThresholdSpinBox.setEnabled(False) self.aLowerHysteresisSpinBox.setEnabled(False) self.bLowerHysteresisSpinBox.setEnabled(False) self.cLowerHysteresisSpinBox.setEnabled(False) self.dLowerHysteresisSpinBox.setEnabled(False) self.aThresholdModeComboBox.setEnabled(False) self.bThresholdModeComboBox.setEnabled(False) self.cThresholdModeComboBox.setEnabled(False) self.dThresholdModeComboBox.setEnabled(False) conditionList['aStateComboBox'][-1].setEnabled(False) conditionList['bStateComboBox'][-1].setEnabled(False) self.newConditionButton.setEnabled(False) self.deleteConditionButton.setEnabled(False) self.aRangeComboBox.model().item(0).setEnabled(False) self.aRangeComboBox.model().item(11).setEnabled(False) self.bRangeComboBox.model().item(0).setEnabled(False) self.bRangeComboBox.model().item(11).setEnabled(False) self.aRangeComboBox.setCurrentIndex(1) self.bRangeComboBox.setCurrentIndex(1) self.timeUnitsComboBox.setCurrentText('ns') self.aAutotriggerSpinBox.setValue(0) self.runsSpinBox.setMinimum(1) self.timebaseSpinBox.setMinimum(1) self.segmentsSpinBox.setMinimum(1) self.capturesSpinBox.setMinimum(1) self.totalRuntimeSpinBox.setMinimum(1) self.preTriggerSamplesSpinBox.setMinimum(0) self.postTriggerSamplesSpinBox.setMinimum(0) self.samplesPerBufferSpinBox.setMinimum(1) self.aUpperThresholdSpinBox.setMinimum(-32512) self.aUpperHysteresisSpinBox.setMinimum(-32512) self.aLowerThresholdSpinBox.setMinimum(-32512) self.aLowerHysteresisSpinBox.setMinimum(-32512) self.bUpperThresholdSpinBox.setMinimum(-32512) self.bUpperHysteresisSpinBox.setMinimum(-32512) self.bLowerThresholdSpinBox.setMinimum(-32512) self.bLowerHysteresisSpinBox.setMinimum(-32512) self.cUpperThresholdSpinBox.setMinimum(-32512) self.cUpperHysteresisSpinBox.setMinimum(-32512) self.cLowerThresholdSpinBox.setMinimum(-32512) self.cLowerHysteresisSpinBox.setMinimum(-32512) self.dUpperThresholdSpinBox.setMinimum(-32512) self.dUpperHysteresisSpinBox.setMinimum(-32512) self.dLowerThresholdSpinBox.setMinimum(-32512) self.dLowerHysteresisSpinBox.setMinimum(-32512) self.extUpperThresholdSpinBox.setMinimum(-32767) self.extUpperHysteresisSpinBox.setMinimum(-32767) self.extLowerThresholdSpinBox.setMinimum(-32767) self.extLowerHysteresisSpinBox.setMinimum(-32767) self.pageNumLineEdit.setText('1') self.pageNumLineEdit.setAlignment(QtCore.Qt.AlignCenter) self.nextPushButton.setText(_translate("MainWindow", "Next")) self.nextPushButton.setEnabled(False) self.previousPushButton.setText(_translate("MainWindow", "Previous")) self.previousPushButton.setEnabled(False) self.graphCheck.setText(_translate("MainWindow", "Graphing")) self.graphCheck.setChecked(True) f = open('driver.log', 'r') self.driverLineEdit.setText(f.readline().replace('\n', '')) f.close() self.driverChannelCheck() dir = os.path.join('.', 'presets') if not os.path.exists(dir): os.mkdir(dir) presetList = os.listdir('./presets') for i in range(len(presetList)): if presetList[i].split('.')[1] =='prst': f = open('./presets/'+presetList[i], 'r') driver = f.readline().replace('\n', '') if self.driverLineEdit.text() != driver: continue f.close() self.presetComboBox.addItem(presetList[i].split('.')[0]) #Actions self.outFileCheckBox.clicked.connect(self.fileOutCheck) self.modeComboBox.currentTextChanged.connect(self.captureModeCheck) self.triggerTypeComboBox.currentTextChanged.connect(self.triggerTypeCheck) self.newConditionButton.clicked.connect(self.newCondition) self.deleteConditionButton.clicked.connect(self.deleteCondition) self.actionSave_Preset.triggered.connect(self.savePreset) self.actionLoad_Preset.triggered.connect(self.loadPreset) self.presetComboBox.currentTextChanged.connect(self.loadDetectedPreset) self.runButton.clicked.connect(self.run) self.aTriggerCheck.clicked.connect(self.simpleTriggerCheck) self.bTriggerCheck.clicked.connect(self.simpleTriggerCheck) self.cTriggerCheck.clicked.connect(self.simpleTriggerCheck) self.dTriggerCheck.clicked.connect(self.simpleTriggerCheck) self.extTriggerCheck.clicked.connect(self.simpleTriggerCheck) self.nextPushButton.clicked.connect(self.nextPage) self.pageNumLineEdit.textChanged.connect(self.pageChangeCheck) self.previousPushButton.clicked.connect(self.previousPage) self.tabWidget.currentChanged.connect(self.runTabChange) self.graphCheck.clicked.connect(self.graphing) def graphing(self): self.tabWidget.setEnabled(int(self.graphCheck.checkState())) def nextPage(self): self.pageNumLineEdit.setText(str(int(self.pageNumLineEdit.text())+1)) def previousPage(self): self.pageNumLineEdit.setText(str(int(self.pageNumLineEdit.text())-1)) def pageChangeCheck(self): try: self.pageNumLineEdit.setText(str(int(float(self.pageNumLineEdit.text())))) if int(float(self.pageNumLineEdit.text())) > len(runList['captureTab'][self.tabWidget.currentIndex()]): self.pageNumLineEdit.setText(str(len(runList['captureTab'][self.tabWidget.currentIndex()]))) elif int(float(self.pageNumLineEdit.text())) < 1: self.pageNumLineEdit.setText('1') if int(float(self.pageNumLineEdit.text())) == len(runList['captureTab'][self.tabWidget.currentIndex()]): self.nextPushButton.setEnabled(False) else: self.nextPushButton.setEnabled(True) if int(float(self.pageNumLineEdit.text())) == 1: self.previousPushButton.setEnabled(False) else: self.previousPushButton.setEnabled(True) runList['stackedWidget'][self.tabWidget.currentIndex()].setCurrentIndex(int(float(self.pageNumLineEdit.text()))-1) except: pass def runTabChange(self): self.pageNumLineEdit.setText(str(runList['stackedWidget'][self.tabWidget.currentIndex()].currentIndex()+1)) def fileOutCheck(self): if self.outFileCheckBox.isChecked(): self.outFileNameLineEdit.setEnabled(True) else: self.outFileNameLineEdit.setText('') self.outFileNameLineEdit.setEnabled(False) def driverChannelCheck(self): driver_replacement(self.driverLineEdit.text()) if str(self.driverLineEdit.text()) == 'ps2000a': self.cCheck.setEnabled(False) self.cCheck.setChecked(False) self.dCheck.setEnabled(False) self.dCheck.setChecked(False) self.cRangeComboBox.setEnabled(False) self.dRangeComboBox.setEnabled(False) self.cOffsetSpinBox.setEnabled(False) self.dOffsetSpinBox.setEnabled(False) self.cCouplingComboBox.setEnabled(False) self.dCouplingComboBox.setEnabled(False) self.aTriggerCheck.setEnabled(True) self.bTriggerCheck.setEnabled(True) self.cTriggerCheck.setEnabled(False) self.cTriggerCheck.setChecked(False) self.dTriggerCheck.setEnabled(False) self.dTriggerCheck.setChecked(False) self.extTriggerCheck.setEnabled(False) self.extTriggerCheck.setChecked(False) self.aUpperThresholdSpinBox.setEnabled(True) self.bUpperThresholdSpinBox.setEnabled(True) self.cUpperThresholdSpinBox.setEnabled(False) self.dUpperThresholdSpinBox.setEnabled(False) self.extUpperThresholdSpinBox.setEnabled(False) self.cUpperHysteresisSpinBox.setEnabled(False) self.dUpperHysteresisSpinBox.setEnabled(False) self.extUpperHysteresisSpinBox.setEnabled(False) self.cLowerThresholdSpinBox.setEnabled(False) self.dLowerThresholdSpinBox.setEnabled(False) self.extLowerThresholdSpinBox.setEnabled(False) self.cLowerHysteresisSpinBox.setEnabled(False) self.dLowerHysteresisSpinBox.setEnabled(False) self.extLowerHysteresisSpinBox.setEnabled(False) for i in range(len(conditionList['aStateComboBox'])): conditionList['cStateComboBox'][i].setEnabled(False) conditionList['dStateComboBox'][i].setEnabled(False) conditionList['extStateComboBox'][i].setEnabled(False) self.aDirectionComboBox.setEnabled(True) self.bDirectionComboBox.setEnabled(True) self.cDirectionComboBox.setEnabled(False) self.dDirectionComboBox.setEnabled(False) self.extDirectionComboBox.setEnabled(False) self.cThresholdModeComboBox.setEnabled(False) self.dThresholdModeComboBox.setEnabled(False) self.extThresholdModeComboBox.setEnabled(False) self.aRangeComboBox.model().item(0).setEnabled(False) self.aRangeComboBox.model().item(11).setEnabled(False) self.bRangeComboBox.model().item(0).setEnabled(False) self.bRangeComboBox.model().item(11).setEnabled(False) elif str(self.driverLineEdit.text()) == 'ps3000a': self.cCheck.setEnabled(True) self.dCheck.setEnabled(True) self.cRangeComboBox.setEnabled(True) self.dRangeComboBox.setEnabled(True) self.cOffsetSpinBox.setEnabled(True) self.dOffsetSpinBox.setEnabled(True) self.cCouplingComboBox.setEnabled(True) self.dCouplingComboBox.setEnabled(True) self.aRangeComboBox.model().item(0).setEnabled(True) self.aRangeComboBox.model().item(11).setEnabled(True) self.bRangeComboBox.model().item(0).setEnabled(True) self.bRangeComboBox.model().item(11).setEnabled(True) if (str(self.triggerTypeComboBox.currentText()) == 'Simple' and not (self.aTriggerCheck.isChecked() or self.bTriggerCheck.isChecked())) or str(self.triggerTypeComboBox.currentText()) == 'Complex': self.cTriggerCheck.setEnabled(True) self.dTriggerCheck.setEnabled(True) self.extTriggerCheck.setEnabled(True) self.cUpperThresholdSpinBox.setEnabled(True) self.dUpperThresholdSpinBox.setEnabled(True) self.extUpperThresholdSpinBox.setEnabled(True) self.cDirectionComboBox.setEnabled(True) self.dDirectionComboBox.setEnabled(True) self.extDirectionComboBox.setEnabled(True) if str(self.triggerTypeComboBox.currentText()) == 'Complex': self.cUpperHysteresisSpinBox.setEnabled(True) self.dUpperHysteresisSpinBox.setEnabled(True) self.extUpperHysteresisSpinBox.setEnabled(True) self.cLowerThresholdSpinBox.setEnabled(True) self.dLowerThresholdSpinBox.setEnabled(True) self.extLowerThresholdSpinBox.setEnabled(True) self.cLowerHysteresisSpinBox.setEnabled(True) self.dLowerHysteresisSpinBox.setEnabled(True) self.extLowerHysteresisSpinBox.setEnabled(True) for i in range(len(conditionList['aStateComboBox'])): conditionList['cStateComboBox'][i].setEnabled(True) conditionList['dStateComboBox'][i].setEnabled(True) conditionList['extStateComboBox'][i].setEnabled(True) self.cThresholdModeComboBox.setEnabled(True) self.dThresholdModeComboBox.setEnabled(True) self.extThresholdModeComboBox.setEnabled(True) def captureModeCheck(self): if str(self.modeComboBox.currentText()) == 'Block': self.timebaseSpinBox.setEnabled(True) self.totalRuntimeSpinBox.setEnabled(False) self.totalRuntimeSpinBox.setValue(1) self.timeUnitsComboBox.setEnabled(False) self.timeUnitsComboBox.setCurrentText('ns') self.capturesSpinBox.setEnabled(False) self.capturesSpinBox.setValue(1) self.samplesPerBufferSpinBox.setEnabled(False) self.samplesPerBufferSpinBox.setValue(1) self.segmentsSpinBox.setEnabled(False) self.segmentsSpinBox.setValue(1) elif str(self.modeComboBox.currentText()) == 'Rapid Block': self.timebaseSpinBox.setEnabled(True) self.totalRuntimeSpinBox.setEnabled(False) self.totalRuntimeSpinBox.setValue(1) self.timeUnitsComboBox.setEnabled(False) self.timeUnitsComboBox.setCurrentText('ns') self.capturesSpinBox.setEnabled(True) self.samplesPerBufferSpinBox.setEnabled(False) self.samplesPerBufferSpinBox.setValue(1) self.segmentsSpinBox.setEnabled(True) elif str(self.modeComboBox.currentText()) == 'Streaming': self.timebaseSpinBox.setEnabled(False) self.timebaseSpinBox.setValue(1) self.totalRuntimeSpinBox.setEnabled(True) self.timeUnitsComboBox.setEnabled(True) self.capturesSpinBox.setEnabled(False) self.capturesSpinBox.setValue(1) self.samplesPerBufferSpinBox.setEnabled(True) self.segmentsSpinBox.setEnabled(True) def triggerTypeCheck(self): if str(self.triggerTypeComboBox.currentText()) == 'Simple': self.simpleTriggerCheck() checkCount = 0 if bool(int(self.aTriggerCheck.checkState())) and str(self.driverLineEdit.text()) == 'ps2000a': checkCount += 1 self.aTriggerCheck.setEnabled(True) self.aUpperThresholdSpinBox.setEnabled(True) self.aDirectionComboBox.setEnabled(True) if bool(int(self.bTriggerCheck.checkState())) and str(self.driverLineEdit.text()) == 'ps2000a': checkCount += 1 self.bTriggerCheck.setEnabled(True) self.bUpperThresholdSpinBox.setEnabled(True) self.bDirectionComboBox.setEnabled(True) if bool(int(self.cTriggerCheck.checkState())) and str(self.driverLineEdit.text()) == 'ps3000a': checkCount += 1 self.cTriggerCheck.setEnabled(True) self.cUpperThresholdSpinBox.setEnabled(True) self.cDirectionComboBox.setEnabled(True) if bool(int(self.dTriggerCheck.checkState())) and str(self.driverLineEdit.text()) == 'ps3000a': checkCount += 1 self.dTriggerCheck.setEnabled(True) self.dUpperThresholdSpinBox.setEnabled(True) self.dDirectionComboBox.setEnabled(True) if bool(int(self.extTriggerCheck.checkState())) and str(self.driverLineEdit.text()) == 'ps3000a': checkCount += 1 self.extTriggerCheck.setEnabled(True) self.extUpperThresholdSpinBox.setEnabled(True) self.extDirectionComboBox.setEnabled(True) if checkCount > 1: self.aTriggerCheck.setChecked(False) self.bTriggerCheck.setChecked(False) self.cTriggerCheck.setChecked(False) self.dTriggerCheck.setChecked(False) self.extTriggerCheck.setChecked(False) self.aUpperHysteresisSpinBox.setEnabled(False) self.bUpperHysteresisSpinBox.setEnabled(False) self.cUpperHysteresisSpinBox.setEnabled(False) self.dUpperHysteresisSpinBox.setEnabled(False) self.extUpperHysteresisSpinBox.setEnabled(False) self.aLowerThresholdSpinBox.setEnabled(False) self.bLowerThresholdSpinBox.setEnabled(False) self.cLowerThresholdSpinBox.setEnabled(False) self.dLowerThresholdSpinBox.setEnabled(False) self.extLowerThresholdSpinBox.setEnabled(False) self.aLowerHysteresisSpinBox.setEnabled(False) self.bLowerHysteresisSpinBox.setEnabled(False) self.cLowerHysteresisSpinBox.setEnabled(False) self.dLowerHysteresisSpinBox.setEnabled(False) self.extLowerHysteresisSpinBox.setEnabled(False) self.aThresholdModeComboBox.setEnabled(False) self.bThresholdModeComboBox.setEnabled(False) self.cThresholdModeComboBox.setEnabled(False) self.dThresholdModeComboBox.setEnabled(False) self.extThresholdModeComboBox.setEnabled(False) for i in range(len(conditionList['aStateComboBox'])): conditionList['aStateComboBox'][i].setEnabled(False) conditionList['bStateComboBox'][i].setEnabled(False) conditionList['cStateComboBox'][i].setEnabled(False) conditionList['dStateComboBox'][i].setEnabled(False) conditionList['extStateComboBox'][i].setEnabled(False) self.newConditionButton.setEnabled(False) self.deleteConditionButton.setEnabled(False) elif str(self.triggerTypeComboBox.currentText()) == 'Complex': self.aTriggerCheck.setEnabled(True) self.bTriggerCheck.setEnabled(True) self.aUpperThresholdSpinBox.setEnabled(True) self.bUpperThresholdSpinBox.setEnabled(True) self.aUpperHysteresisSpinBox.setEnabled(True) self.bUpperHysteresisSpinBox.setEnabled(True) self.aLowerThresholdSpinBox.setEnabled(True) self.bLowerThresholdSpinBox.setEnabled(True) self.aLowerHysteresisSpinBox.setEnabled(True) self.bLowerHysteresisSpinBox.setEnabled(True) self.aThresholdModeComboBox.setEnabled(True) self.bThresholdModeComboBox.setEnabled(True) self.aDirectionComboBox.setEnabled(True) self.bDirectionComboBox.setEnabled(True) for i in range(len(conditionList['aStateComboBox'])): conditionList['aStateComboBox'][i].setEnabled(True) conditionList['bStateComboBox'][i].setEnabled(True) self.newConditionButton.setEnabled(True) self.deleteConditionButton.setEnabled(True) if str(self.driverLineEdit.text()) == 'ps3000a': self.cTriggerCheck.setEnabled(True) self.dTriggerCheck.setEnabled(True) self.extTriggerCheck.setEnabled(True) self.cUpperThresholdSpinBox.setEnabled(True) self.dUpperThresholdSpinBox.setEnabled(True) self.extUpperThresholdSpinBox.setEnabled(True) self.cUpperHysteresisSpinBox.setEnabled(True) self.dUpperHysteresisSpinBox.setEnabled(True) self.extUpperHysteresisSpinBox.setEnabled(True) self.cLowerThresholdSpinBox.setEnabled(True) self.dLowerThresholdSpinBox.setEnabled(True) self.extLowerThresholdSpinBox.setEnabled(True) self.cLowerHysteresisSpinBox.setEnabled(True) self.dLowerHysteresisSpinBox.setEnabled(True) self.extLowerHysteresisSpinBox.setEnabled(True) self.cThresholdModeComboBox.setEnabled(True) self.dThresholdModeComboBox.setEnabled(True) self.extThresholdModeComboBox.setEnabled(True) self.cDirectionComboBox.setEnabled(True) self.dDirectionComboBox.setEnabled(True) self.extDirectionComboBox.setEnabled(True) for i in range(len(conditionList['aStateComboBox'])): conditionList['cStateComboBox'][i].setEnabled(True) conditionList['dStateComboBox'][i].setEnabled(True) conditionList['extStateComboBox'][i].setEnabled(True) def newCondition(self): _translate = QtCore.QCoreApplication.translate conditionList['conditionTab'].append(QtWidgets.QWidget()) conditionList['conditionTab'][-1].setObjectName("condition"+str(len(conditionList['conditionTab']))+"Tab") conditionList['extConditionLabel'].append(QtWidgets.QLabel(conditionList['conditionTab'][-1])) conditionList['extConditionLabel'][-1].setGeometry(QtCore.QRect(10*widthRatio, 100*heightRatio, 16*widthRatio, 16*heightRatio)) conditionList['extConditionLabel'][-1].setObjectName("extConditionLabel") conditionList['aConditionLabel'].append(QtWidgets.QLabel(conditionList['conditionTab'][-1])) conditionList['aConditionLabel'][-1].setGeometry(QtCore.QRect(10*widthRatio, 20*heightRatio, 16*widthRatio, 16*heightRatio)) conditionList['aConditionLabel'][-1].setObjectName("aConditionLabel") conditionList['bConditionLabel'].append(QtWidgets.QLabel(conditionList['conditionTab'][-1])) conditionList['bConditionLabel'][-1].setGeometry(QtCore.QRect(10*widthRatio, 40*heightRatio, 16*widthRatio, 16*heightRatio)) conditionList['bConditionLabel'][-1].setObjectName("bConditionLabel") conditionList['cConditionLabel'].append(QtWidgets.QLabel(conditionList['conditionTab'][-1])) conditionList['cConditionLabel'][-1].setGeometry(QtCore.QRect(10*widthRatio, 60*heightRatio, 16*widthRatio, 16*heightRatio)) conditionList['cConditionLabel'][-1].setObjectName("cConditionLabel") conditionList['dConditionLabel'].append(QtWidgets.QLabel(conditionList['conditionTab'][-1])) conditionList['dConditionLabel'][-1].setGeometry(QtCore.QRect(10*widthRatio, 80*heightRatio, 16*widthRatio, 16*heightRatio)) conditionList['dConditionLabel'][-1].setObjectName("dConditionLabel") conditionList['aStateComboBox'].append(QtWidgets.QComboBox(conditionList['conditionTab'][-1])) conditionList['aStateComboBox'][-1].setGeometry(QtCore.QRect(30*widthRatio, 20*heightRatio, 81*widthRatio, 16*heightRatio)) conditionList['aStateComboBox'][-1].setObjectName("aStateComboBox") conditionList['aStateComboBox'][-1].addItem("") conditionList['aStateComboBox'][-1].addItem("") conditionList['aStateComboBox'][-1].addItem("") conditionList['bStateComboBox'].append(QtWidgets.QComboBox(conditionList['conditionTab'][-1])) conditionList['bStateComboBox'][-1].setGeometry(QtCore.QRect(30*widthRatio, 40*heightRatio, 81*widthRatio, 16*heightRatio)) conditionList['bStateComboBox'][-1].setObjectName("bStateComboBox") conditionList['bStateComboBox'][-1].addItem("") conditionList['bStateComboBox'][-1].addItem("") conditionList['bStateComboBox'][-1].addItem("") conditionList['cStateComboBox'].append(QtWidgets.QComboBox(conditionList['conditionTab'][-1])) conditionList['cStateComboBox'][-1].setGeometry(QtCore.QRect(30*widthRatio, 60*heightRatio, 81*widthRatio, 16*heightRatio)) conditionList['cStateComboBox'][-1].setObjectName("cStateComboBox") conditionList['cStateComboBox'][-1].addItem("") conditionList['cStateComboBox'][-1].addItem("") conditionList['cStateComboBox'][-1].addItem("") conditionList['dStateComboBox'].append(QtWidgets.QComboBox(conditionList['conditionTab'][-1])) conditionList['dStateComboBox'][-1].setGeometry(QtCore.QRect(30*widthRatio, 80*heightRatio, 81*widthRatio, 16*heightRatio)) conditionList['dStateComboBox'][-1].setObjectName("dStateComboBox") conditionList['dStateComboBox'][-1].addItem("") conditionList['dStateComboBox'][-1].addItem("") conditionList['dStateComboBox'][-1].addItem("") conditionList['extStateComboBox'].append(QtWidgets.QComboBox(conditionList['conditionTab'][-1])) conditionList['extStateComboBox'][-1].setGeometry(QtCore.QRect(30*widthRatio, 100*heightRatio, 81*widthRatio, 16*heightRatio)) conditionList['extStateComboBox'][-1].setObjectName("extStateComboBox") conditionList['extStateComboBox'][-1].addItem("") conditionList['extStateComboBox'][-1].addItem("") conditionList['extStateComboBox'][-1].addItem("") conditionList['stateLabel'].append(QtWidgets.QLabel(conditionList['conditionTab'][-1])) conditionList['stateLabel'][-1].setGeometry(QtCore.QRect(30*widthRatio, 0*heightRatio, 81*widthRatio, 16*heightRatio)) conditionList['stateLabel'][-1].setObjectName("stateLabel") self.conditionsTabWidget.addTab(conditionList['conditionTab'][-1], "") conditionList['extConditionLabel'][-1].setText(_translate("MainWindow", "Ext")) conditionList['aConditionLabel'][-1].setText(_translate("MainWindow", "A")) conditionList['bConditionLabel'][-1].setText(_translate("MainWindow", "B")) conditionList['cConditionLabel'][-1].setText(_translate("MainWindow", "C")) conditionList['dConditionLabel'][-1].setText(_translate("MainWindow", "D")) conditionList['aStateComboBox'][-1].setItemText(0, _translate("MainWindow", "Don\'t Care")) conditionList['aStateComboBox'][-1].setItemText(1, _translate("MainWindow", "True")) conditionList['aStateComboBox'][-1].setItemText(2, _translate("MainWindow", "False")) conditionList['bStateComboBox'][-1].setItemText(0, _translate("MainWindow", "Don\'t Care")) conditionList['bStateComboBox'][-1].setItemText(1, _translate("MainWindow", "True")) conditionList['bStateComboBox'][-1].setItemText(2, _translate("MainWindow", "False")) conditionList['cStateComboBox'][-1].setItemText(0, _translate("MainWindow", "Don\'t Care")) conditionList['cStateComboBox'][-1].setItemText(1, _translate("MainWindow", "True")) conditionList['cStateComboBox'][-1].setItemText(2, _translate("MainWindow", "False")) conditionList['dStateComboBox'][-1].setItemText(0, _translate("MainWindow", "Don\'t Care")) conditionList['dStateComboBox'][-1].setItemText(1, _translate("MainWindow", "True")) conditionList['dStateComboBox'][-1].setItemText(2, _translate("MainWindow", "False")) conditionList['extStateComboBox'][-1].setItemText(0, _translate("MainWindow", "Don\'t Care")) conditionList['extStateComboBox'][-1].setItemText(1, _translate("MainWindow", "True")) conditionList['extStateComboBox'][-1].setItemText(2, _translate("MainWindow", "False")) conditionList['stateLabel'][-1].setText(_translate("MainWindow", "State Condition")) self.conditionsTabWidget.setTabText(self.conditionsTabWidget.indexOf(conditionList['conditionTab'][-1]), _translate("MainWindow", str(len(conditionList['conditionTab'])))) conditionList['aStateComboBox'][-1].setEnabled(False) conditionList['bStateComboBox'][-1].setEnabled(False) conditionList['cStateComboBox'][-1].setEnabled(False) conditionList['dStateComboBox'][-1].setEnabled(False) conditionList['extStateComboBox'][-1].setEnabled(False) self.triggerTypeCheck() def deleteCondition(self): _translate = QtCore.QCoreApplication.translate indx = self.conditionsTabWidget.currentIndex() self.conditionsTabWidget.removeTab(indx) if len(conditionList['aStateComboBox']) == 0: return 0 for name in conditionList: conditionList[name].pop(indx) for i in range(indx, len(conditionList['aStateComboBox'])): self.conditionsTabWidget.setTabText(self.conditionsTabWidget.indexOf(conditionList['conditionTab'][i]), _translate("MainWindow", str(i+1))) def savePreset(self): _translate = QtCore.QCoreApplication.translate if self.presetComboBox.currentText() == 'Manual': presetFileName, ok = QtWidgets.QInputDialog().getText(MainWindow, 'New Preset', 'New Preset File Name:', QtWidgets.QLineEdit.Normal, QtCore.QDir().home().dirName()) else: presetFileName = self.presetComboBox.currentText() if presetFileName == '': return 0 f = open('presets/'+presetFileName+'.prst', 'w') f.write(self.driverLineEdit.text()+'\n') f.write(str(self.outFileCheckBox.checkState())+'\n') f.write(self.outFileNameLineEdit.text()+'\n') f.write(self.runsSpinBox.text()+'\n') f.write(str(self.aCheck.checkState())+'\n') f.write(str(self.bCheck.checkState())+'\n') f.write(str(self.cCheck.checkState())+'\n') f.write(str(self.dCheck.checkState())+'\n') f.write(self.aRangeComboBox.currentText()+'\n') f.write(self.bRangeComboBox.currentText()+'\n') f.write(self.cRangeComboBox.currentText()+'\n') f.write(self.dRangeComboBox.currentText()+'\n') f.write(self.aOffsetSpinBox.text()+'\n') f.write(self.bOffsetSpinBox.text()+'\n') f.write(self.cOffsetSpinBox.text()+'\n') f.write(self.dOffsetSpinBox.text()+'\n') f.write(self.modeComboBox.currentText()+'\n') f.write(self.timebaseSpinBox.text()+'\n') f.write(self.segmentsSpinBox.text()+'\n') f.write(self.capturesSpinBox.text()+'\n') f.write(self.totalRuntimeSpinBox.text()+'\n') f.write(self.timeUnitsComboBox.currentText()+'\n') f.write(self.preTriggerSamplesSpinBox.text()+'\n') f.write(self.postTriggerSamplesSpinBox.text()+'\n') f.write(self.samplesPerBufferSpinBox.text()+'\n') f.write(self.triggerTypeComboBox.currentText()+'\n') f.write(self.aAutotriggerSpinBox.text()+'\n') f.write(self.aDelaySpinBox.text()+'\n') f.write(str(self.aTriggerCheck.checkState())+'\n') f.write(str(self.bTriggerCheck.checkState())+'\n') f.write(str(self.cTriggerCheck.checkState())+'\n') f.write(str(self.dTriggerCheck.checkState())+'\n') f.write(str(self.extTriggerCheck.checkState())+'\n') f.write(self.aUpperThresholdSpinBox.text()+'\n') f.write(self.bUpperThresholdSpinBox.text()+'\n') f.write(self.cUpperThresholdSpinBox.text()+'\n') f.write(self.dUpperThresholdSpinBox.text()+'\n') f.write(self.extUpperThresholdSpinBox.text()+'\n') f.write(self.aUpperHysteresisSpinBox.text()+'\n') f.write(self.bUpperHysteresisSpinBox.text()+'\n') f.write(self.cUpperHysteresisSpinBox.text()+'\n') f.write(self.dUpperHysteresisSpinBox.text()+'\n') f.write(self.extUpperHysteresisSpinBox.text()+'\n') f.write(self.aLowerThresholdSpinBox.text()+'\n') f.write(self.bLowerThresholdSpinBox.text()+'\n') f.write(self.cLowerThresholdSpinBox.text()+'\n') f.write(self.dLowerThresholdSpinBox.text()+'\n') f.write(self.extLowerThresholdSpinBox.text()+'\n') f.write(self.aLowerHysteresisSpinBox.text()+'\n') f.write(self.bLowerHysteresisSpinBox.text()+'\n') f.write(self.cLowerHysteresisSpinBox.text()+'\n') f.write(self.dLowerHysteresisSpinBox.text()+'\n') f.write(self.extLowerHysteresisSpinBox.text()+'\n') f.write(self.aDirectionComboBox.currentText()+'\n') f.write(self.bDirectionComboBox.currentText()+'\n') f.write(self.cDirectionComboBox.currentText()+'\n') f.write(self.dDirectionComboBox.currentText()+'\n') f.write(self.extDirectionComboBox.currentText()+'\n') f.write(self.aThresholdModeComboBox.currentText()+'\n') f.write(self.bThresholdModeComboBox.currentText()+'\n') f.write(self.cThresholdModeComboBox.currentText()+'\n') f.write(self.dThresholdModeComboBox.currentText()+'\n') f.write(self.extThresholdModeComboBox.currentText()+'\n') f.write(str(len(conditionList['aStateComboBox']))+'\n') for name in conditionList: if name in ['conditionTab', 'extConditionLabel', 'aConditionLabel', 'bConditionLabel', 'cConditionLabel', 'dConditionLabel', 'stateLabel']: continue for element in conditionList[name]: f.write(element.currentText()+'\n') f.close() self.presetComboBox.addItem(presetFileName) self.presetComboBox.setCurrentText(presetFileName) def loadPreset(self): presetFilePath = QtWidgets.QFileDialog.getOpenFileName(MainWindow, 'Find Preset File', '.') if presetFilePath[0] == '': return 0 f = open(presetFilePath[0], 'r') driver = f.readline().replace('\n', '') if self.driverLineEdit.text() != driver: self.error = QtWidgets.QMessageBox() self.error.setWindowTitle('Error') icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(".\\icon.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.error.setWindowIcon(icon) self.error.setText('Incompatible Driver Preset') self.error.setIcon(QtWidgets.QMessageBox.Information) ok = self.error.exec_() return 0 self.outFileCheckBox.setCheckState(int(f.readline().replace('\n', ''))) self.outFileNameLineEdit.setText(f.readline().replace('\n', '')) self.runsSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.aCheck.setCheckState(int(f.readline().replace('\n', ''))) self.bCheck.setCheckState(int(f.readline().replace('\n', ''))) self.cCheck.setCheckState(int(f.readline().replace('\n', ''))) self.dCheck.setCheckState(int(f.readline().replace('\n', ''))) self.aRangeComboBox.setCurrentText(f.readline().replace('\n', '')) self.bRangeComboBox.setCurrentText(f.readline().replace('\n', '')) self.cRangeComboBox.setCurrentText(f.readline().replace('\n', '')) self.dRangeComboBox.setCurrentText(f.readline().replace('\n', '')) self.aOffsetSpinBox.setValue(float(f.readline().replace('\n', ''))) self.bOffsetSpinBox.setValue(float(f.readline().replace('\n', ''))) self.cOffsetSpinBox.setValue(float(f.readline().replace('\n', ''))) self.dOffsetSpinBox.setValue(float(f.readline().replace('\n', ''))) self.modeComboBox.setCurrentText(f.readline().replace('\n', '')) self.timebaseSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.segmentsSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.capturesSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.totalRuntimeSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.timeUnitsComboBox.setCurrentText(f.readline().replace('\n', '')) self.preTriggerSamplesSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.postTriggerSamplesSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.samplesPerBufferSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.triggerTypeComboBox.setCurrentText(f.readline().replace('\n', '')) self.aAutotriggerSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.aDelaySpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.aTriggerCheck.setCheckState(int(f.readline().replace('\n', ''))) self.bTriggerCheck.setCheckState(int(f.readline().replace('\n', ''))) self.cTriggerCheck.setCheckState(int(f.readline().replace('\n', ''))) self.dTriggerCheck.setCheckState(int(f.readline().replace('\n', ''))) self.extTriggerCheck.setCheckState(int(f.readline().replace('\n', ''))) self.aUpperThresholdSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.bUpperThresholdSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.cUpperThresholdSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.dUpperThresholdSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.extUpperThresholdSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.aUpperHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.bUpperHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.cUpperHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.dUpperHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.extUpperHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.aLowerThresholdSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.bLowerThresholdSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.cLowerThresholdSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.dLowerThresholdSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.extLowerThresholdSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.aLowerHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.bLowerHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.cLowerHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.dLowerHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.extLowerHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.aDirectionComboBox.setCurrentText(f.readline().replace('\n', '')) self.bDirectionComboBox.setCurrentText(f.readline().replace('\n', '')) self.cDirectionComboBox.setCurrentText(f.readline().replace('\n', '')) self.dDirectionComboBox.setCurrentText(f.readline().replace('\n', '')) self.extDirectionComboBox.setCurrentText(f.readline().replace('\n', '')) self.aThresholdModeComboBox.setCurrentText(f.readline().replace('\n', '')) self.bThresholdModeComboBox.setCurrentText(f.readline().replace('\n', '')) self.cThresholdModeComboBox.setCurrentText(f.readline().replace('\n', '')) self.dThresholdModeComboBox.setCurrentText(f.readline().replace('\n', '')) self.extThresholdModeComboBox.setCurrentText(f.readline().replace('\n', '')) for i in range(len(conditionList['aStateComboBox'])): self.deleteCondition() conditionNum = int(f.readline().replace('\n', '')) for i in range(conditionNum): self.newCondition() for name in conditionList: if name in ['conditionTab', 'extConditionLabel', 'aConditionLabel', 'bConditionLabel', 'cConditionLabel', 'dConditionLabel', 'stateLabel']: continue for i in range(conditionNum): conditionList[name][i].setCurrentText(f.readline().replace('\n', '')) f.close() self.presetComboBox.setCurrentText(str(os.path.basename(presetFilePath[0])).split('.')[0]) def loadDetectedPreset(self): if self.presetComboBox.currentText() == 'Manual': return 0 presetFilePath = ['./presets/'+str(self.presetComboBox.currentText())+'.prst'] f = open(presetFilePath[0], 'r') self.driverLineEdit.setText(f.readline().replace('\n', '')) self.outFileCheckBox.setCheckState(int(f.readline().replace('\n', ''))) self.outFileNameLineEdit.setText(f.readline().replace('\n', '')) self.runsSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.aCheck.setCheckState(int(f.readline().replace('\n', ''))) self.bCheck.setCheckState(int(f.readline().replace('\n', ''))) self.cCheck.setCheckState(int(f.readline().replace('\n', ''))) self.dCheck.setCheckState(int(f.readline().replace('\n', ''))) self.aRangeComboBox.setCurrentText(f.readline().replace('\n', '')) self.bRangeComboBox.setCurrentText(f.readline().replace('\n', '')) self.cRangeComboBox.setCurrentText(f.readline().replace('\n', '')) self.dRangeComboBox.setCurrentText(f.readline().replace('\n', '')) self.aOffsetSpinBox.setValue(float(f.readline().replace('\n', ''))) self.bOffsetSpinBox.setValue(float(f.readline().replace('\n', ''))) self.cOffsetSpinBox.setValue(float(f.readline().replace('\n', ''))) self.dOffsetSpinBox.setValue(float(f.readline().replace('\n', ''))) self.modeComboBox.setCurrentText(f.readline().replace('\n', '')) self.timebaseSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.segmentsSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.capturesSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.totalRuntimeSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.timeUnitsComboBox.setCurrentText(f.readline().replace('\n', '')) self.preTriggerSamplesSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.postTriggerSamplesSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.samplesPerBufferSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.triggerTypeComboBox.setCurrentText(f.readline().replace('\n', '')) self.aAutotriggerSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.aDelaySpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.aTriggerCheck.setCheckState(int(f.readline().replace('\n', ''))) self.bTriggerCheck.setCheckState(int(f.readline().replace('\n', ''))) self.cTriggerCheck.setCheckState(int(f.readline().replace('\n', ''))) self.dTriggerCheck.setCheckState(int(f.readline().replace('\n', ''))) self.extTriggerCheck.setCheckState(int(f.readline().replace('\n', ''))) self.aUpperThresholdSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.bUpperThresholdSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.cUpperThresholdSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.dUpperThresholdSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.extUpperThresholdSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.aUpperHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.bUpperHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.cUpperHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.dUpperHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.extUpperHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.aLowerThresholdSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.bLowerThresholdSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.cLowerThresholdSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.dLowerThresholdSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.extLowerThresholdSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.aLowerHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.bLowerHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.cLowerHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.dLowerHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.extLowerHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', '')))) self.aDirectionComboBox.setCurrentText(f.readline().replace('\n', '')) self.bDirectionComboBox.setCurrentText(f.readline().replace('\n', '')) self.cDirectionComboBox.setCurrentText(f.readline().replace('\n', '')) self.dDirectionComboBox.setCurrentText(f.readline().replace('\n', '')) self.extDirectionComboBox.setCurrentText(f.readline().replace('\n', '')) self.aThresholdModeComboBox.setCurrentText(f.readline().replace('\n', '')) self.bThresholdModeComboBox.setCurrentText(f.readline().replace('\n', '')) self.cThresholdModeComboBox.setCurrentText(f.readline().replace('\n', '')) self.dThresholdModeComboBox.setCurrentText(f.readline().replace('\n', '')) self.extThresholdModeComboBox.setCurrentText(f.readline().replace('\n', '')) for i in range(len(conditionList['aStateComboBox'])): self.deleteCondition() conditionNum = int(f.readline().replace('\n', '')) for i in range(conditionNum): self.newCondition() for name in conditionList: if name in ['conditionTab', 'extConditionLabel', 'aConditionLabel', 'bConditionLabel', 'cConditionLabel', 'dConditionLabel', 'stateLabel']: continue for i in range(conditionNum): conditionList[name][i].setCurrentText(f.readline().replace('\n', '')) f.close() def autodetect(self): self.driverLineEdit.setText(driver_autodetect()) def simpleTriggerCheck(self): if self.triggerTypeComboBox.currentText() == 'Simple': if bool(int(self.aTriggerCheck.checkState())): self.bTriggerCheck.setEnabled(False) self.cTriggerCheck.setEnabled(False) self.dTriggerCheck.setEnabled(False) self.extTriggerCheck.setEnabled(False) self.bUpperThresholdSpinBox.setEnabled(False) self.cUpperThresholdSpinBox.setEnabled(False) self.dUpperThresholdSpinBox.setEnabled(False) self.extUpperThresholdSpinBox.setEnabled(False) self.bDirectionComboBox.setEnabled(False) self.cDirectionComboBox.setEnabled(False) self.dDirectionComboBox.setEnabled(False) self.extDirectionComboBox.setEnabled(False) elif bool(int(self.bTriggerCheck.checkState())): self.aTriggerCheck.setEnabled(False) self.cTriggerCheck.setEnabled(False) self.dTriggerCheck.setEnabled(False) self.extTriggerCheck.setEnabled(False) self.aUpperThresholdSpinBox.setEnabled(False) self.cUpperThresholdSpinBox.setEnabled(False) self.dUpperThresholdSpinBox.setEnabled(False) self.extUpperThresholdSpinBox.setEnabled(False) self.aDirectionComboBox.setEnabled(False) self.cDirectionComboBox.setEnabled(False) self.dDirectionComboBox.setEnabled(False) self.extDirectionComboBox.setEnabled(False) elif bool(int(self.cTriggerCheck.checkState())): self.aTriggerCheck.setEnabled(False) self.bTriggerCheck.setEnabled(False) self.dTriggerCheck.setEnabled(False) self.extTriggerCheck.setEnabled(False) self.aUpperThresholdSpinBox.setEnabled(False) self.bUpperThresholdSpinBox.setEnabled(False) self.dUpperThresholdSpinBox.setEnabled(False) self.extUpperThresholdSpinBox.setEnabled(False) self.aDirectionComboBox.setEnabled(False) self.bDirectionComboBox.setEnabled(False) self.dDirectionComboBox.setEnabled(False) self.extDirectionComboBox.setEnabled(False) elif bool(int(self.dTriggerCheck.checkState())): self.aTriggerCheck.setEnabled(False) self.bTriggerCheck.setEnabled(False) self.cTriggerCheck.setEnabled(False) self.extTriggerCheck.setEnabled(False) self.aUpperThresholdSpinBox.setEnabled(False) self.bUpperThresholdSpinBox.setEnabled(False) self.cUpperThresholdSpinBox.setEnabled(False) self.extUpperThresholdSpinBox.setEnabled(False) self.aDirectionComboBox.setEnabled(False) self.bDirectionComboBox.setEnabled(False) self.cDirectionComboBox.setEnabled(False) self.extDirectionComboBox.setEnabled(False) elif bool(int(self.extTriggerCheck.checkState())): self.aTriggerCheck.setEnabled(False) self.bTriggerCheck.setEnabled(False) self.cTriggerCheck.setEnabled(False) self.dTriggerCheck.setEnabled(False) self.aUpperThresholdSpinBox.setEnabled(False) self.bUpperThresholdSpinBox.setEnabled(False) self.cUpperThresholdSpinBox.setEnabled(False) self.dUpperThresholdSpinBox.setEnabled(False) self.aDirectionComboBox.setEnabled(False) self.bDirectionComboBox.setEnabled(False) self.cDirectionComboBox.setEnabled(False) self.dDirectionComboBox.setEnabled(False) else: if self.driverLineEdit.text() == 'ps2000a': self.aTriggerCheck.setEnabled(True) self.bTriggerCheck.setEnabled(True) self.aUpperThresholdSpinBox.setEnabled(True) self.bUpperThresholdSpinBox.setEnabled(True) self.aDirectionComboBox.setEnabled(True) self.bDirectionComboBox.setEnabled(True) else: self.aTriggerCheck.setEnabled(True) self.bTriggerCheck.setEnabled(True) self.cTriggerCheck.setEnabled(True) self.dTriggerCheck.setEnabled(True) self.extTriggerCheck.setEnabled(True) self.aUpperThresholdSpinBox.setEnabled(True) self.bUpperThresholdSpinBox.setEnabled(True) self.cUpperThresholdSpinBox.setEnabled(True) self.dUpperThresholdSpinBox.setEnabled(True) self.extUpperThresholdSpinBox.setEnabled(True) self.aDirectionComboBox.setEnabled(True) self.bDirectionComboBox.setEnabled(True) self.cDirectionComboBox.setEnabled(True) self.dDirectionComboBox.setEnabled(True) self.extDirectionComboBox.setEnabled(True) def run(self): _translate = QtCore.QCoreApplication.translate global runList #Reset self.tabWidget.clear() runList = {'runTab': [], 'stackedWidget': [], 'captureTab': []} chandle = ctypes.c_int16() status = {} start_scope([chandle, status]) #Channel Configuration channels_ = [] couplings_ = [] cranges_ = [] offsets_ = [] if bool(int(self.aCheck.checkState())): channels_.append(0) couplings_.append(self.aCouplingComboBox.currentIndex()) cranges_.append(self.aRangeComboBox.currentIndex()) offsets_.append(float(self.aOffsetSpinBox.text())) if bool(int(self.bCheck.checkState())): channels_.append(1) couplings_.append(self.bCouplingComboBox.currentIndex()) cranges_.append(self.bRangeComboBox.currentIndex()) offsets_.append(float(self.bOffsetSpinBox.text())) if bool(int(self.cCheck.checkState())): channels_.append(2) couplings_.append(self.cCouplingComboBox.currentIndex()) cranges_.append(self.cRangeComboBox.currentIndex()) offsets_.append(float(self.cOffsetSpinBox.text())) if bool(int(self.dCheck.checkState())): channels_.append(3) couplings_.append(self.dCouplingComboBox.currentIndex()) cranges_.append(self.dRangeComboBox.currentIndex()) offsets_.append(float(self.dOffsetSpinBox.text())) channel_config(chandle, status, 1, channels_, couplings_, cranges_, offsets_) #Trigger Configuration trigChannel = 0 #Default Value trigAdcCounts = 0 trigDirection = 0 if self.triggerTypeComboBox.currentText() == 'Simple': if bool(int(self.aTriggerCheck.checkState())): trigChannel = 0 trigAdcCounts = int(self.aUpperThresholdSpinBox.text()) trigDirection = int(self.aDirectionComboBox.currentIndex()) elif bool(int(self.bTriggerCheck.checkState())): trigChannel = 1 trigAdcCounts = int(self.bUpperThresholdSpinBox.text()) trigDirection = int(self.bDirectionComboBox.currentIndex()) elif bool(int(self.cTriggerCheck.checkState())): trigChannel = 2 trigAdcCounts = int(self.cUpperThresholdSpinBox.text()) trigDirection = int(self.cDirectionComboBox.currentIndex()) elif bool(int(self.dTriggerCheck.checkState())): trigChannel = 3 trigAdcCounts = int(self.dUpperThresholdSpinBox.text()) trigDirection = int(self.dDirectionComboBox.currentIndex()) elif bool(int(self.extTriggerCheck.checkState())): trigChannel = 4 trigAdcCounts = int(self.extUpperThresholdSpinBox.text()) trigDirection = int(self.extDirectionComboBox.currentIndex()) trig_simple_config(chandle, status, 1, trigChannel, trigAdcCounts, trigDirection, int(self.aDelaySpinBox.text()), int(self.aAutotriggerSpinBox.text())) #Setup a simple trigger elif self.triggerTypeComboBox.currentText() == 'Complex': trigCond_ = [] for i in range(len(conditionList['conditionTab'])): trigCond_.append([conditionList['aStateComboBox'][i].currentIndex(), conditionList['bStateComboBox'][i].currentIndex(), conditionList['cStateComboBox'][i].currentIndex(), conditionList['dStateComboBox'][i].currentIndex(), conditionList['extStateComboBox'][i].currentIndex(), 0, 0, 0]) trigChannelConf_ = [] if bool(int(self.aTriggerCheck.checkState())): trigChannelConf_.append([int(self.aUpperThresholdSpinBox.text()), int(self.aUpperHysteresisSpinBox.text()), int(self.aLowerThresholdSpinBox.text()), int(self.aLowerHysteresisSpinBox.text()), 0 ,int(self.aThresholdModeComboBox.currentIndex())]) if bool(int(self.bTriggerCheck.checkState())): trigChannelConf_.append([int(self.bUpperThresholdSpinBox.text()), int(self.bUpperHysteresisSpinBox.text()), int(self.bLowerThresholdSpinBox.text()), int(self.bLowerHysteresisSpinBox.text()), 1 ,int(self.bThresholdModeComboBox.currentIndex())]) if bool(int(self.cTriggerCheck.checkState())): trigChannelConf_.append([int(self.cUpperThresholdSpinBox.text()), int(self.cUpperHysteresisSpinBox.text()), int(self.cLowerThresholdSpinBox.text()), int(self.cLowerHysteresisSpinBox.text()), 2 ,int(self.cThresholdModeComboBox.currentIndex())]) if bool(int(self.dTriggerCheck.checkState())): trigChannelConf_.append([int(self.dUpperThresholdSpinBox.text()), int(self.dUpperHysteresisSpinBox.text()), int(self.dLowerThresholdSpinBox.text()), int(self.dLowerHysteresisSpinBox.text()), 3 ,int(self.dThresholdModeComboBox.currentIndex())]) if bool(int(self.extTriggerCheck.checkState())): trigChannelConf_.append([int(self.extUpperThresholdSpinBox.text()), int(self.extUpperHysteresisSpinBox.text()), int(self.extLowerThresholdSpinBox.text()), int(self.extLowerHysteresisSpinBox.text()), 4 ,int(self.extThresholdModeComboBox.currentIndex())]) print(chandle, status, trigCond_, [self.aDirectionComboBox.currentIndex(), self.bDirectionComboBox.currentIndex(), self.cDirectionComboBox.currentIndex(), self.dDirectionComboBox.currentIndex(), self.extDirectionComboBox.currentIndex(), self.aDirectionComboBox.currentIndex()], trigChannelConf_, int(self.aAutotriggerSpinBox.text())) trig_logic_config(chandle, status, trigCond_, [self.aDirectionComboBox.currentIndex(), self.bDirectionComboBox.currentIndex(), self.cDirectionComboBox.currentIndex(), self.dDirectionComboBox.currentIndex(), self.extDirectionComboBox.currentIndex(), self.aDirectionComboBox.currentIndex()], trigChannelConf_, int(self.aAutotriggerSpinBox.text())) #Capture Configuration buffFileName = 'buffer_swap.txt' buff = open(buffFileName, 'w') buff.close() if self.modeComboBox.currentText() == 'Block': preTriggerSamples = int(self.preTriggerSamplesSpinBox.text()) postTriggerSamples = int(self.postTriggerSamplesSpinBox.text()) timebase = int(self.timebaseSpinBox.text()) totalSamples = preTriggerSamples+postTriggerSamples segments = int(self.segmentsSpinBox.text()) captures = int(self.capturesSpinBox.text()) time_ = timebase_block_config(chandle, status, timebase, totalSamples) #Setup timebase and time axis buffersMax, buffersMin = buffer_block_config(chandle, status, channels_, totalSamples, segments, 0) #Setup buffer and segments buff = open(buffFileName, 'a') if bool(int(self.outFileCheckBox.checkState())): clear_file(self.outFileNameLineEdit.text()) for i in range(int(self.runsSpinBox.text())): data_block(chandle, status, preTriggerSamples, postTriggerSamples, timebase, 0, 0) #Get data for chann in buffersMax: for segm in chann: for j in segm: buff.write(str(j)+',') buff.write('\n\n') buff.write('/\n') buff.write('//\n') elif self.modeComboBox.currentText() == 'Rapid Block': preTriggerSamples = int(self.preTriggerSamplesSpinBox.text()) postTriggerSamples = int(self.postTriggerSamplesSpinBox.text()) timebase = int(self.timebaseSpinBox.text()) totalSamples = preTriggerSamples+postTriggerSamples segments = int(self.segmentsSpinBox.text()) captures = int(self.capturesSpinBox.text()) time_ = timebase_block_config(chandle, status, timebase, totalSamples) #Setup timebase and time axis segment_capture_config(chandle, status, segments, captures, totalSamples) #Setup memory segmentation & capture configuration buffersMax, buffersMin = buffer_block_config(chandle, status, channels_, totalSamples, segments, 0) #Setup buffer and segments buff = open(buffFileName, 'a') if bool(int(self.outFileCheckBox.checkState())): clear_file(self.outFileNameLineEdit.text()) for i in range(int(self.runsSpinBox.text())): data_rapid_block(chandle, status, preTriggerSamples, postTriggerSamples, timebase, segments, captures, 0, 0) #Get data for chann in buffersMax: for segm in chann: for j in segm: buff.write(str(j)+',') buff.write('\n\n') buff.write('/\n') buff.write('//\n') elif self.modeComboBox.currentText() == 'Streaming': preTriggerSamples = int(self.preTriggerSamplesSpinBox.text()) postTriggerSamples = int(self.postTriggerSamplesSpinBox.text()) totalSamples = preTriggerSamples+postTriggerSamples sizeOfOneBuffer = int(self.samplesPerBufferSpinBox.text()) totalRuntime = int(self.totalRuntimeSpinBox.text()) sampleInterval = int(totalRuntime/totalSamples) sampleUnits = int(self.timeUnitsComboBox.currentIndex()) segments = int(self.segmentsSpinBox.text()) captures = int(self.capturesSpinBox.text()) time_ = timebase_stream_config(totalSamples, sampleInterval, sampleUnits) #Setup timebase and time axis buffersComplete, buffersMax, buffersMin = buffer_stream_config(chandle, status, channels_, totalSamples, sizeOfOneBuffer, segments, 0) #Setup buffers buff = open(buffFileName, 'a') if bool(int(self.outFileCheckBox.checkState())): clear_file(self.outFileNameLineEdit.text()) for i in range(int(self.runsSpinBox.text())): data_streaming(chandle, status, sampleInterval, 0, buffersComplete, buffersMax, sizeOfOneBuffer, sampleUnits, preTriggerSamples, postTriggerSamples, 0, 1) #Get data for chann in buffersMax: for segm in chann: for j in segm: buff.write(str(j)+',') buff.write('\n\n') buff.write('/\n') buff.write('//\n') buff.write('F') #EOF character buff.close() #Data Processing tabMax = 7 capturesMax = 7 indx = 0 buff = open(buffFileName, 'r') temp = buff.readline().replace('\n', '') while temp != 'F': indx += 1 run = [] while temp != '//': chann = [] while temp != '/': segm = [] while temp != '': data = '' for char in temp: if char == ',': segm.append(int(data)) data = '' else: data += char temp = buff.readline().replace('\n', '') chann.append(segm) temp = buff.readline().replace('\n', '') run.append(chann) temp = buff.readline().replace('\n', '') #print(run) run = run_to_mV(chandle, status, run, channels_, cranges_, totalSamples, segments) if bool(int(self.graphCheck.checkState())) and len(runList['runTab']) < tabMax: runList['runTab'].append(QtWidgets.QWidget()) runList['runTab'][-1].setObjectName("run_"+str(indx)) runList['stackedWidget'].append(QtWidgets.QStackedWidget(runList['runTab'][-1])) runList['stackedWidget'][-1].setGeometry(QtCore.QRect(0*widthRatio, 0*heightRatio, 461*widthRatio, 361*heightRatio)) runList['stackedWidget'][-1].setObjectName("stackedWidget_"+str(indx)) runList['captureTab'].append([]) self.tabWidget.addTab(runList['runTab'][-1], "") self.tabWidget.setTabText(self.tabWidget.indexOf(runList['runTab'][-1]), _translate("MainWindow", "Run "+str(indx))) for i in range(captures): if i >= capturesMax: break runList['captureTab'][-1].append(Canvas(self, width=4.61*widthRatio, height=3.61*heightRatio, dpi=100)) for j in range(len(channels_)): run_channel_capture = run[j][i] runList['captureTab'][-1][-1].axes.plot(time_, run_channel_capture) runList['captureTab'][-1][-1].axes.set(xlabel = 'Time ('+self.timeUnitsComboBox.currentText()+')', ylabel = 'Voltage (mV)', title = 'Capture '+str(i+1)) runList['stackedWidget'][-1].addWidget(runList['captureTab'][-1][i]) self.pageChangeCheck() else: plt.close('all') if bool(int(self.outFileCheckBox.checkState())): #True for file writing run_to_file(time_, self.timeUnitsComboBox.currentText(), run, channels_, segments, indx, self.outFileNameLineEdit.text()) temp = buff.readline().replace('\n', '') stop_scope([chandle, status]) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())
122,321
38,537
import cgroup_parser def test_interface(): cgroup_parser.get_max_procs() cgroup_parser.get_cpu_usage() cgroup_parser.get_memory_limit() cgroup_parser.get_memory_usage()
187
68
# Copyright 2022 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== import pytest import mindspore.dataset as ds from mindspore.dataset.transforms import c_transforms from mindspore.dataset.transforms import py_transforms import mindspore.dataset.vision.c_transforms as c_vision import mindspore.dataset.vision.py_transforms as py_vision DATA_DIR = "../data/dataset/testPK/data" def test_map_c_transform_exception(): """ Feature: test c error op def Description: op defined like c_vision.HWC2CHW Expectation: success """ data_set = ds.ImageFolderDataset(DATA_DIR, num_parallel_workers=1, shuffle=True) train_image_size = 224 mean = [0.485 * 255, 0.456 * 255, 0.406 * 255] std = [0.229 * 255, 0.224 * 255, 0.225 * 255] # define map operations random_crop_decode_resize_op = c_vision.RandomCropDecodeResize(train_image_size, scale=(0.08, 1.0), ratio=(0.75, 1.333)) random_horizontal_flip_op = c_vision.RandomHorizontalFlip(prob=0.5) normalize_op = c_vision.Normalize(mean=mean, std=std) hwc2chw_op = c_vision.HWC2CHW # exception data_set = data_set.map(operations=random_crop_decode_resize_op, input_columns="image", num_parallel_workers=1) data_set = data_set.map(operations=random_horizontal_flip_op, input_columns="image", num_parallel_workers=1) data_set = data_set.map(operations=normalize_op, input_columns="image", num_parallel_workers=1) with pytest.raises(ValueError) as info: data_set = data_set.map(operations=hwc2chw_op, input_columns="image", num_parallel_workers=1) assert "Parameter operations's element of method map should be a " in str(info.value) # compose exception with pytest.raises(ValueError) as info: c_transforms.Compose([ c_vision.RandomCropDecodeResize(train_image_size, scale=(0.08, 1.0), ratio=(0.75, 1.333)), c_vision.RandomHorizontalFlip, c_vision.Normalize(mean=mean, std=std), c_vision.HWC2CHW()]) assert " should be a " in str(info.value) # randomapply exception with pytest.raises(ValueError) as info: c_transforms.RandomApply([ c_vision.RandomCropDecodeResize, c_vision.RandomHorizontalFlip(prob=0.5), c_vision.Normalize(mean=mean, std=std), c_vision.HWC2CHW()]) assert " should be a " in str(info.value) # randomchoice exception with pytest.raises(ValueError) as info: c_transforms.RandomChoice([ c_vision.RandomCropDecodeResize(train_image_size, scale=(0.08, 1.0), ratio=(0.75, 1.333)), c_vision.RandomHorizontalFlip(prob=0.5), c_vision.Normalize, c_vision.HWC2CHW()]) assert " should be a " in str(info.value) def test_map_py_transform_exception(): """ Feature: test python error op def Description: op defined like py_vision.RandomHorizontalFlip Expectation: success """ data_set = ds.ImageFolderDataset(DATA_DIR, num_parallel_workers=1, shuffle=True) # define map operations decode_op = py_vision.Decode() random_horizontal_flip_op = py_vision.RandomHorizontalFlip # exception to_tensor_op = py_vision.ToTensor() trans = [decode_op, random_horizontal_flip_op, to_tensor_op] with pytest.raises(ValueError) as info: data_set = data_set.map(operations=trans, input_columns="image", num_parallel_workers=1) assert "Parameter operations's element of method map should be a " in str(info.value) # compose exception with pytest.raises(ValueError) as info: py_transforms.Compose([ py_vision.Decode, py_vision.RandomHorizontalFlip(), py_vision.ToTensor()]) assert " should be a " in str(info.value) # randomapply exception with pytest.raises(ValueError) as info: py_transforms.RandomApply([ py_vision.Decode(), py_vision.RandomHorizontalFlip, py_vision.ToTensor()]) assert " should be a " in str(info.value) # randomchoice exception with pytest.raises(ValueError) as info: py_transforms.RandomChoice([ py_vision.Decode(), py_vision.RandomHorizontalFlip(), py_vision.ToTensor]) assert " should be a " in str(info.value) if __name__ == '__main__': test_map_c_transform_exception() test_map_py_transform_exception()
5,123
1,678
# -*- coding: utf-8 -*- # ******************************************************** # Author and developer: Aleksandr Suvorov # -------------------------------------------------------- # Licensed: BSD 3-Clause License (see LICENSE for details) # -------------------------------------------------------- # Url: https://github.com/smartlegion/ # -------------------------------------------------------- # Donate: https://smartlegion.github.io/donate # -------------------------------------------------------- # Copyright © 2021 Aleksandr Suvorov # ======================================================== class TestImageProxy: def test_draw(self, image_proxy, capfd): image_proxy.draw(0, 0, 'green') image_proxy.draw(0, 1, 'green') assert len(image_proxy.operations) == 2 def test_fill(self, image_proxy): image_proxy.fill('gray') assert len(image_proxy.operations) == 1 def test_save(self, image_proxy, capfd): image_proxy.fill('gray') image_proxy.draw(0, 0, 'green') image_proxy.draw(0, 1, 'green') image_proxy.draw(1, 0, 'green') image_proxy.draw(1, 1, 'green') image_proxy.save('image.png') out, _ = capfd.readouterr() assert 'Saves the image to a file: image.png\n' in out
1,295
387
from hallo.events import EventMessage, EventMode from hallo.server import Server from hallo.test.server_mock import ServerMock def test_deop_not_irc(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = "NOT_IRC" test_hallo.add_server(serv1) chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") user1 = serv1.get_user_by_address("test_user1".lower(), "test_user1") chan1.add_user(user1) chan1.add_user( serv1.get_user_by_address(serv1.get_nick().lower(), serv1.get_nick()) ) try: test_hallo.function_dispatcher.dispatch(EventMessage(serv1, chan1, user1, "deop")) data = serv1.get_send_data(1, chan1, EventMessage) assert "error" in data[0].text.lower() assert "only available for irc" in data[0].text.lower() finally: test_hallo.remove_server(serv1) def test_deop_0_privmsg(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = Server.TYPE_IRC test_hallo.add_server(serv1) chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") user1 = serv1.get_user_by_address("test_user1", "test_user1") chan1.add_user(user1) chan1.add_user( serv1.get_user_by_address(serv1.get_nick().lower(), serv1.get_nick()) ) try: test_hallo.function_dispatcher.dispatch(EventMessage(serv1, None, user1, "deop")) data = serv1.get_send_data(1, user1, EventMessage) assert "error" in data[0].text.lower() assert "in a private message" in data[0].text.lower() finally: test_hallo.remove_server(serv1) def test_deop_0_no_power(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = Server.TYPE_IRC test_hallo.add_server(serv1) chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") chan1.in_channel = True user1 = serv1.get_user_by_address("test_user1", "test_user1") chan1.add_user(user1) chan1.add_user( serv1.get_user_by_address(serv1.get_nick().lower(), serv1.get_nick()) ) try: test_hallo.function_dispatcher.dispatch(EventMessage(serv1, chan1, user1, "deop")) data = serv1.get_send_data(1, chan1, EventMessage) assert "error" in data[0].text.lower() assert "don't have power" in data[0].text.lower() finally: test_hallo.remove_server(serv1) def test_deop_0_not_op(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = Server.TYPE_IRC test_hallo.add_server(serv1) chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") chan1.in_channel = True user1 = serv1.get_user_by_address("test_user1", "test_user1") user_hallo = serv1.get_user_by_address(serv1.get_nick().lower(), serv1.get_nick()) chan1.add_user(user1) chan1.add_user(user_hallo) chan1_user1 = chan1.get_membership_by_user(user1) chan1_user1.is_op = False chan1_hallo = chan1.get_membership_by_user(user_hallo) chan1_hallo.is_op = True try: test_hallo.function_dispatcher.dispatch(EventMessage(serv1, chan1, user1, "deop")) data = serv1.get_send_data(1, chan1, EventMessage) assert "error" in data[0].text.lower() assert "doesn't have op" in data[0].text.lower() finally: test_hallo.remove_server(serv1) def test_deop_0(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = Server.TYPE_IRC test_hallo.add_server(serv1) chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") chan1.in_channel = True user1 = serv1.get_user_by_address("test_user1", "test_user1") user_hallo = serv1.get_user_by_address(serv1.get_nick().lower(), serv1.get_nick()) chan1.add_user(user1) chan1.add_user(user_hallo) chan1_user1 = chan1.get_membership_by_user(user1) chan1_user1.is_op = True chan1_hallo = chan1.get_membership_by_user(user_hallo) chan1_hallo.is_op = True try: test_hallo.function_dispatcher.dispatch(EventMessage(serv1, chan1, user1, "deop")) data = serv1.get_send_data(2) assert "error" not in data[1].text.lower() assert data[0].channel == chan1 assert data[1].channel == chan1 assert data[0].__class__ == EventMode assert data[1].__class__ == EventMessage assert "-o " + user1.name in data[0].mode_changes assert "status taken" in data[1].text.lower() finally: test_hallo.remove_server(serv1) def test_deop_1priv_channel_not_known(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = Server.TYPE_IRC test_hallo.add_server(serv1) chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") user1 = serv1.get_user_by_address("test_user1".lower(), "test_user1") user_hallo = serv1.get_user_by_address(serv1.get_nick().lower(), serv1.get_nick()) chan1.add_user(user1) chan1.add_user(user_hallo) chan1_user1 = chan1.get_membership_by_user(user1) chan1_user1.is_op = False chan1_hallo = chan1.get_membership_by_user(user_hallo) chan1_hallo.is_op = True try: test_hallo.function_dispatcher.dispatch( EventMessage(serv1, None, user1, "deop other_channel") ) data = serv1.get_send_data(1, user1, EventMessage) assert "error" in data[0].text.lower() assert "other_channel is not known" in data[0].text.lower() finally: test_hallo.remove_server(serv1) def test_deop_1priv_not_in_channel(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = Server.TYPE_IRC test_hallo.add_server(serv1) chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") user1 = serv1.get_user_by_address("test_user1".lower(), "test_user1") user_hallo = serv1.get_user_by_address(serv1.get_nick().lower(), serv1.get_nick()) chan1.add_user(user1) chan1.add_user(user_hallo) serv1.get_channel_by_address("test_chan2".lower(), "test_chan2") chan1_user1 = chan1.get_membership_by_user(user1) chan1_user1.is_op = False chan1_hallo = chan1.get_membership_by_user(user_hallo) chan1_hallo.is_op = True try: test_hallo.function_dispatcher.dispatch( EventMessage(serv1, None, user1, "deop test_chan2") ) data = serv1.get_send_data(1, user1, EventMessage) assert "error" in data[0].text.lower() assert "not in that channel" in data[0].text.lower() finally: test_hallo.remove_server(serv1) def test_deop_1priv_user_not_there(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = Server.TYPE_IRC test_hallo.add_server(serv1) chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") chan1.in_channel = True user1 = serv1.get_user_by_address("test_user1".lower(), "test_user1") user_hallo = serv1.get_user_by_address(serv1.get_nick().lower(), serv1.get_nick()) chan1.add_user(user_hallo) chan1_hallo = chan1.get_membership_by_user(user_hallo) chan1_hallo.is_op = True try: test_hallo.function_dispatcher.dispatch( EventMessage(serv1, None, user1, "deop test_chan1") ) data = serv1.get_send_data(1, user1, EventMessage) assert "error" in data[0].text.lower() assert "test_user1 is not in test_chan1" in data[0].text.lower() finally: test_hallo.remove_server(serv1) def test_deop_1priv_no_power(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = Server.TYPE_IRC test_hallo.add_server(serv1) chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") chan1.in_channel = True user1 = serv1.get_user_by_address("test_user1".lower(), "test_user1") user_hallo = serv1.get_user_by_address(serv1.get_nick().lower(), serv1.get_nick()) chan1.add_user(user1) chan1.add_user(user_hallo) chan1_user1 = chan1.get_membership_by_user(user1) chan1_user1.is_op = False chan1_hallo = chan1.get_membership_by_user(user_hallo) chan1_hallo.is_op = False try: test_hallo.function_dispatcher.dispatch( EventMessage(serv1, None, user1, "deop test_chan1") ) data = serv1.get_send_data(1, user1, EventMessage) assert "error" in data[0].text.lower() assert "don't have power" in data[0].text.lower() finally: test_hallo.remove_server(serv1) def test_deop_1priv_not_op(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = Server.TYPE_IRC test_hallo.add_server(serv1) chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") chan1.in_channel = True user1 = serv1.get_user_by_address("test_user1".lower(), "test_user1") user_hallo = serv1.get_user_by_address(serv1.get_nick().lower(), serv1.get_nick()) chan1.add_user(user1) chan1.add_user(user_hallo) chan1_user1 = chan1.get_membership_by_user(user1) chan1_user1.is_op = False chan1_hallo = chan1.get_membership_by_user(user_hallo) chan1_hallo.is_op = True try: test_hallo.function_dispatcher.dispatch( EventMessage(serv1, None, user1, "deop test_chan1") ) data = serv1.get_send_data(1, user1, EventMessage) assert "error" in data[0].text.lower() assert "doesn't have op" in data[0].text.lower() finally: test_hallo.remove_server(serv1) def test_deop_1priv(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = Server.TYPE_IRC test_hallo.add_server(serv1) chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") chan1.in_channel = True user1 = serv1.get_user_by_address("test_user1".lower(), "test_user1") user_hallo = serv1.get_user_by_address(serv1.get_nick().lower(), serv1.get_nick()) chan1.add_user(user1) chan1.add_user(user_hallo) chan1_user1 = chan1.get_membership_by_user(user1) chan1_user1.is_op = True chan1_hallo = chan1.get_membership_by_user(user_hallo) chan1_hallo.is_op = True try: test_hallo.function_dispatcher.dispatch( EventMessage(serv1, None, user1, "deop test_chan1") ) data = serv1.get_send_data(2) assert "error" not in data[1].text.lower() assert data[0].channel == chan1 assert data[1].user == user1 assert data[0].__class__ == EventMode assert data[1].__class__ == EventMessage assert "-o " + user1.name in data[0].mode_changes assert "status taken" in data[1].text.lower() finally: test_hallo.remove_server(serv1) def test_deop_1_chan_user_not_there(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = Server.TYPE_IRC test_hallo.add_server(serv1) chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") chan1.in_channel = True chan2 = serv1.get_channel_by_address("test_chan2".lower(), "test_chan2") chan2.in_channel = True user1 = serv1.get_user_by_address("test_user1".lower(), "test_user1") user2 = serv1.get_user_by_address("test_user2".lower(), "test_user2") user_hallo = serv1.get_user_by_address(serv1.get_nick().lower(), serv1.get_nick()) chan1.add_user(user1) chan1.add_user(user_hallo) chan2.add_user(user2) chan2.add_user(user_hallo) chan1_user1 = chan1.get_membership_by_user(user1) chan1_user1.is_op = False chan1_hallo = chan1.get_membership_by_user(user_hallo) chan1_hallo.is_op = True chan2_user2 = chan2.get_membership_by_user(user2) chan2_user2.is_op = False chan2_hallo = chan2.get_membership_by_user(user_hallo) chan2_hallo.is_op = True try: test_hallo.function_dispatcher.dispatch( EventMessage(serv1, chan1, user1, "deop test_chan2") ) data = serv1.get_send_data(1, chan1, EventMessage) assert "error" in data[0].text.lower() assert "test_user1 is not in test_chan2" in data[0].text.lower() finally: test_hallo.remove_server(serv1) def test_deop_1_chan_no_power(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = Server.TYPE_IRC test_hallo.add_server(serv1) chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") chan1.in_channel = True chan2 = serv1.get_channel_by_address("test_chan2".lower(), "test_chan2") chan2.in_channel = True user1 = serv1.get_user_by_address("test_user1".lower(), "test_user1") user2 = serv1.get_user_by_address("test_user2".lower(), "test_user2") user_hallo = serv1.get_user_by_address(serv1.get_nick().lower(), serv1.get_nick()) chan1.add_user(user1) chan1.add_user(user_hallo) chan2.add_user(user1) chan2.add_user(user_hallo) chan1_user1 = chan1.get_membership_by_user(user1) chan1_user1.is_op = False chan1_hallo = chan1.get_membership_by_user(user_hallo) chan1_hallo.is_op = True chan2_user1 = chan2.get_membership_by_user(user1) chan2_user1.is_op = False chan2_hallo = chan2.get_membership_by_user(user_hallo) chan2_hallo.is_op = False try: test_hallo.function_dispatcher.dispatch( EventMessage(serv1, chan1, user1, "deop test_chan2") ) data = serv1.get_send_data(1, chan1, EventMessage) assert "error" in data[0].text.lower() assert "don't have power" in data[0].text.lower() finally: test_hallo.remove_server(serv1) def test_deop_1_chan_not_op(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = Server.TYPE_IRC test_hallo.add_server(serv1) chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") chan1.in_channel = True chan2 = serv1.get_channel_by_address("test_chan2".lower(), "test_chan2") chan2.in_channel = True user1 = serv1.get_user_by_address("test_user1".lower(), "test_user1") user2 = serv1.get_user_by_address("test_user2".lower(), "test_user2") user_hallo = serv1.get_user_by_address(serv1.get_nick().lower(), serv1.get_nick()) chan1.add_user(user1) chan1.add_user(user_hallo) chan2.add_user(user1) chan2.add_user(user_hallo) chan1_user1 = chan1.get_membership_by_user(user1) chan1_user1.is_op = False chan1_hallo = chan1.get_membership_by_user(user_hallo) chan1_hallo.is_op = True chan2_user1 = chan2.get_membership_by_user(user1) chan2_user1.is_op = False chan2_hallo = chan2.get_membership_by_user(user_hallo) chan2_hallo.is_op = True try: test_hallo.function_dispatcher.dispatch( EventMessage(serv1, chan1, user1, "deop test_chan2") ) data = serv1.get_send_data(1, chan1, EventMessage) assert "error" in data[0].text.lower() assert "doesn't have op" in data[0].text.lower() finally: test_hallo.remove_server(serv1) def test_deop_1_chan(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = Server.TYPE_IRC test_hallo.add_server(serv1) chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") chan1.in_channel = True chan2 = serv1.get_channel_by_address("test_chan2".lower(), "test_chan2") chan2.in_channel = True user1 = serv1.get_user_by_address("test_user1".lower(), "test_user1") user2 = serv1.get_user_by_address("test_user2".lower(), "test_user2") user_hallo = serv1.get_user_by_address(serv1.get_nick().lower(), serv1.get_nick()) chan1.add_user(user1) chan1.add_user(user_hallo) chan2.add_user(user1) chan2.add_user(user_hallo) chan1_user1 = chan1.get_membership_by_user(user1) chan1_user1.is_op = False chan1_hallo = chan1.get_membership_by_user(user_hallo) chan1_hallo.is_op = True chan2_user1 = chan2.get_membership_by_user(user1) chan2_user1.is_op = True chan2_hallo = chan2.get_membership_by_user(user_hallo) chan2_hallo.is_op = True try: test_hallo.function_dispatcher.dispatch( EventMessage(serv1, chan1, user1, "deop test_chan2") ) data = serv1.get_send_data(2) assert "error" not in data[1].text.lower() assert data[0].channel == chan2 assert data[1].channel == chan1 assert data[0].__class__ == EventMode assert data[1].__class__ == EventMessage assert "-o " + user1.name in data[0].mode_changes assert "status taken" in data[1].text.lower() finally: test_hallo.remove_server(serv1) def test_deop_1_user_not_here(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = Server.TYPE_IRC test_hallo.add_server(serv1) chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") chan1.in_channel = True user1 = serv1.get_user_by_address("test_user1".lower(), "test_user1") user2 = serv1.get_user_by_address("test_user2".lower(), "test_user2") user_hallo = serv1.get_user_by_address(serv1.get_nick().lower(), serv1.get_nick()) chan1.add_user(user1) chan1_user1 = chan1.get_membership_by_user(user1) chan1_user1.is_op = False chan1.add_user(user_hallo) chan1_hallo = chan1.get_membership_by_user(user_hallo) chan1_hallo.is_op = True try: test_hallo.function_dispatcher.dispatch( EventMessage(serv1, chan1, user1, "deop test_user2") ) data = serv1.get_send_data(1, chan1, EventMessage) assert "error" in data[0].text.lower() assert "test_user2 is not in test_chan1" in data[0].text.lower() finally: test_hallo.remove_server(serv1) def test_deop_1_user_no_power(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = Server.TYPE_IRC test_hallo.add_server(serv1) chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") chan1.in_channel = True user1 = serv1.get_user_by_address("test_user1".lower(), "test_user1") user2 = serv1.get_user_by_address("test_user2".lower(), "test_user2") user_hallo = serv1.get_user_by_address(serv1.get_nick().lower(), serv1.get_nick()) chan1.add_user(user1) chan1_user1 = chan1.get_membership_by_user(user1) chan1_user1.is_op = False chan1.add_user(user_hallo) chan1_hallo = chan1.get_membership_by_user(user_hallo) chan1_hallo.is_op = False chan1.add_user(user2) chan1_user2 = chan1.get_membership_by_user(user2) chan1_user2.is_op = False try: test_hallo.function_dispatcher.dispatch( EventMessage(serv1, chan1, user1, "deop test_user2") ) data = serv1.get_send_data(1, chan1, EventMessage) assert "error" in data[0].text.lower() assert "don't have power" in data[0].text.lower() finally: test_hallo.remove_server(serv1) def test_deop_1_user_not_op(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = Server.TYPE_IRC test_hallo.add_server(serv1) chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") chan1.in_channel = True user1 = serv1.get_user_by_address("test_user1".lower(), "test_user1") user2 = serv1.get_user_by_address("test_user2".lower(), "test_user2") user_hallo = serv1.get_user_by_address(serv1.get_nick().lower(), serv1.get_nick()) chan1.add_user(user1) chan1_user1 = chan1.get_membership_by_user(user1) chan1_user1.is_op = False chan1.add_user(user_hallo) chan1_hallo = chan1.get_membership_by_user(user_hallo) chan1_hallo.is_op = True chan1.add_user(user2) chan1_user2 = chan1.get_membership_by_user(user2) chan1_user2.is_op = False try: test_hallo.function_dispatcher.dispatch( EventMessage(serv1, chan1, user1, "deop test_user2") ) data = serv1.get_send_data(1, chan1, EventMessage) assert "error" in data[0].text.lower() assert "doesn't have op" in data[0].text.lower() finally: test_hallo.remove_server(serv1) def test_deop_1_user(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = Server.TYPE_IRC test_hallo.add_server(serv1) chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") chan1.in_channel = True user1 = serv1.get_user_by_address("test_user1".lower(), "test_user1") user2 = serv1.get_user_by_address("test_user2".lower(), "test_user2") user_hallo = serv1.get_user_by_address(serv1.get_nick().lower(), serv1.get_nick()) chan1.add_user(user1) chan1_user1 = chan1.get_membership_by_user(user1) chan1_user1.is_op = False chan1.add_user(user_hallo) chan1_hallo = chan1.get_membership_by_user(user_hallo) chan1_hallo.is_op = True chan1.add_user(user2) chan1_user2 = chan1.get_membership_by_user(user2) chan1_user2.is_op = True try: test_hallo.function_dispatcher.dispatch( EventMessage(serv1, chan1, user1, "deop test_user2") ) data = serv1.get_send_data(2) assert "error" not in data[1].text.lower() assert data[0].channel == chan1 assert data[1].channel == chan1 assert data[0].__class__ == EventMode assert data[1].__class__ == EventMessage assert "-o " + user2.name in data[0].mode_changes assert "status taken" in data[1].text.lower() finally: test_hallo.remove_server(serv1) def test_deop_2_chan_user_not_known(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = Server.TYPE_IRC test_hallo.add_server(serv1) chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") chan1.in_channel = True chan2 = serv1.get_channel_by_address("test_chan2".lower(), "test_chan2") chan2.in_channel = True user1 = serv1.get_user_by_address("test_user1".lower(), "test_user1") user2 = serv1.get_user_by_address("test_user2".lower(), "test_user2") user_hallo = serv1.get_user_by_address(serv1.get_nick().lower(), serv1.get_nick()) chan1.add_user(user1) chan1_user1 = chan1.get_membership_by_user(user1) chan1_user1.is_op = False chan1.add_user(user_hallo) chan1_hallo = chan1.get_membership_by_user(user_hallo) chan1_hallo.is_op = True chan2.add_user(user2) chan2_user1 = chan2.get_membership_by_user(user2) chan2_user1.is_op = False chan2.add_user(user_hallo) chan2_hallo = chan2.get_membership_by_user(user_hallo) chan2_hallo.is_op = True try: test_hallo.function_dispatcher.dispatch( EventMessage(serv1, chan1, user1, "deop test_chan2 test_user3") ) data = serv1.get_send_data(1, chan1, EventMessage) assert "error" in data[0].text.lower() assert "test_user3 is not known" in data[0].text.lower() finally: test_hallo.remove_server(serv1) def test_deop_2_chan_user_not_there(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = Server.TYPE_IRC test_hallo.add_server(serv1) chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") chan1.in_channel = True chan2 = serv1.get_channel_by_address("test_chan2".lower(), "test_chan2") chan2.in_channel = True user1 = serv1.get_user_by_address("test_user1".lower(), "test_user1") user2 = serv1.get_user_by_address("test_user2".lower(), "test_user2") serv1.get_user_by_address("test_user3".lower(), "test_user3") user_hallo = serv1.get_user_by_address(serv1.get_nick().lower(), serv1.get_nick()) chan1.add_user(user1) chan1_user1 = chan1.get_membership_by_user(user1) chan1_user1.is_op = False chan1.add_user(user_hallo) chan1_hallo = chan1.get_membership_by_user(user_hallo) chan1_hallo.is_op = True chan2.add_user(user2) chan2_user1 = chan2.get_membership_by_user(user2) chan2_user1.is_op = False chan2.add_user(user_hallo) chan2_hallo = chan2.get_membership_by_user(user_hallo) chan2_hallo.is_op = True try: test_hallo.function_dispatcher.dispatch( EventMessage(serv1, chan1, user1, "deop test_chan2 test_user3") ) data = serv1.get_send_data(1, chan1, EventMessage) assert "error" in data[0].text.lower() assert "test_user3 is not in test_chan2" in data[0].text.lower() finally: test_hallo.remove_server(serv1) def test_deop_2_chan_no_power(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = Server.TYPE_IRC test_hallo.add_server(serv1) chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") chan1.in_channel = True chan2 = serv1.get_channel_by_address("test_chan2".lower(), "test_chan2") chan2.in_channel = True user1 = serv1.get_user_by_address("test_user1".lower(), "test_user1") user2 = serv1.get_user_by_address("test_user2".lower(), "test_user2") user_hallo = serv1.get_user_by_address(serv1.get_nick().lower(), serv1.get_nick()) chan1.add_user(user1) chan1_user1 = chan1.get_membership_by_user(user1) chan1_user1.is_op = False chan1.add_user(user_hallo) chan1_hallo = chan1.get_membership_by_user(user_hallo) chan1_hallo.is_op = True chan2.add_user(user2) chan2_user1 = chan2.get_membership_by_user(user2) chan2_user1.is_op = False chan2.add_user(user_hallo) chan2_hallo = chan2.get_membership_by_user(user_hallo) chan2_hallo.is_op = False try: test_hallo.function_dispatcher.dispatch( EventMessage(serv1, chan1, user1, "deop test_chan2 test_user2") ) data = serv1.get_send_data(1, chan1, EventMessage) assert "error" in data[0].text.lower() assert "don't have power" in data[0].text.lower() finally: test_hallo.remove_server(serv1) def test_deop_2_chan_not_op(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = Server.TYPE_IRC test_hallo.add_server(serv1) chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") chan1.in_channel = True chan2 = serv1.get_channel_by_address("test_chan2".lower(), "test_chan2") chan2.in_channel = True user1 = serv1.get_user_by_address("test_user1".lower(), "test_user1") user2 = serv1.get_user_by_address("test_user2".lower(), "test_user2") user_hallo = serv1.get_user_by_address(serv1.get_nick().lower(), serv1.get_nick()) chan1.add_user(user1) chan1_user1 = chan1.get_membership_by_user(user1) chan1_user1.is_op = False chan1.add_user(user_hallo) chan1_hallo = chan1.get_membership_by_user(user_hallo) chan1_hallo.is_op = True chan2.add_user(user2) chan2_user2 = chan2.get_membership_by_user(user2) chan2_user2.is_op = False chan2.add_user(user_hallo) chan2_hallo = chan2.get_membership_by_user(user_hallo) chan2_hallo.is_op = True try: test_hallo.function_dispatcher.dispatch( EventMessage(serv1, chan1, user1, "deop test_chan2 test_user2") ) data = serv1.get_send_data(1, chan1, EventMessage) assert "error" in data[0].text.lower() assert "doesn't have op" in data[0].text.lower() finally: test_hallo.remove_server(serv1) def test_deop_2_chan(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = Server.TYPE_IRC test_hallo.add_server(serv1) chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") chan1.in_channel = True chan2 = serv1.get_channel_by_address("test_chan2".lower(), "test_chan2") chan2.in_channel = True user1 = serv1.get_user_by_address("test_user1".lower(), "test_user1") user2 = serv1.get_user_by_address("test_user2".lower(), "test_user2") user_hallo = serv1.get_user_by_address(serv1.get_nick().lower(), serv1.get_nick()) chan1.add_user(user1) chan1_user1 = chan1.get_membership_by_user(user1) chan1_user1.is_op = False chan1.add_user(user_hallo) chan1_hallo = chan1.get_membership_by_user(user_hallo) chan1_hallo.is_op = True chan2.add_user(user2) chan2_user2 = chan2.get_membership_by_user(user2) chan2_user2.is_op = True chan2.add_user(user_hallo) chan2_hallo = chan2.get_membership_by_user(user_hallo) chan2_hallo.is_op = True try: test_hallo.function_dispatcher.dispatch( EventMessage(serv1, chan1, user1, "deop test_chan2 test_user2") ) data = serv1.get_send_data(2) assert "error" not in data[1].text.lower() assert data[0].channel == chan2 assert data[1].channel == chan1 assert data[0].__class__ == EventMode assert data[1].__class__ == EventMessage assert "-o " + user2.name in data[0].mode_changes assert "status taken" in data[1].text.lower() finally: test_hallo.remove_server(serv1) def test_deop_2_user_not_in_channel(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = Server.TYPE_IRC test_hallo.add_server(serv1) chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") chan1.in_channel = True chan2 = serv1.get_channel_by_address("test_chan2".lower(), "test_chan2") chan2.in_channel = False user1 = serv1.get_user_by_address("test_user1".lower(), "test_user1") user2 = serv1.get_user_by_address("test_user2".lower(), "test_user2") user_hallo = serv1.get_user_by_address(serv1.get_nick().lower(), serv1.get_nick()) chan1.add_user(user1) chan1_user1 = chan1.get_membership_by_user(user1) chan1_user1.is_op = False chan1.add_user(user_hallo) chan1_hallo = chan1.get_membership_by_user(user_hallo) chan1_hallo.is_op = True chan2.add_user(user2) chan2_user1 = chan2.get_membership_by_user(user2) chan2_user1.is_op = False try: test_hallo.function_dispatcher.dispatch( EventMessage(serv1, chan1, user1, "deop test_user2 test_chan2") ) data = serv1.get_send_data(1, chan1, EventMessage) assert "error" in data[0].text.lower() assert "i'm not in that channel" in data[0].text.lower() finally: test_hallo.remove_server(serv1) def test_deop_2_user_user_not_known(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = Server.TYPE_IRC test_hallo.add_server(serv1) chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") chan1.in_channel = True chan2 = serv1.get_channel_by_address("test_chan2".lower(), "test_chan2") chan2.in_channel = True user1 = serv1.get_user_by_address("test_user1".lower(), "test_user1") user2 = serv1.get_user_by_address("test_user2".lower(), "test_user2") user_hallo = serv1.get_user_by_address(serv1.get_nick().lower(), serv1.get_nick()) chan1.add_user(user1) chan1_user1 = chan1.get_membership_by_user(user1) chan1_user1.is_op = False chan1.add_user(user_hallo) chan1_hallo = chan1.get_membership_by_user(user_hallo) chan1_hallo.is_op = True chan2.add_user(user2) chan2_user1 = chan2.get_membership_by_user(user2) chan2_user1.is_op = False chan2.add_user(user_hallo) chan2_hallo = chan2.get_membership_by_user(user_hallo) chan2_hallo.is_op = True try: test_hallo.function_dispatcher.dispatch( EventMessage(serv1, chan1, user1, "deop test_user3 test_chan2") ) data = serv1.get_send_data(1, chan1, EventMessage) assert "error" in data[0].text.lower() assert "test_user3 is not known" in data[0].text.lower() finally: test_hallo.remove_server(serv1) def test_deop_2_user_user_not_there(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = Server.TYPE_IRC test_hallo.add_server(serv1) chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") chan1.in_channel = True chan2 = serv1.get_channel_by_address("test_chan2".lower(), "test_chan2") chan2.in_channel = True user1 = serv1.get_user_by_address("test_user1".lower(), "test_user1") user2 = serv1.get_user_by_address("test_user2".lower(), "test_user2") serv1.get_user_by_address("test_user3".lower(), "test_user3") user_hallo = serv1.get_user_by_address(serv1.get_nick().lower(), serv1.get_nick()) chan1.add_user(user1) chan1_user1 = chan1.get_membership_by_user(user1) chan1_user1.is_op = False chan1.add_user(user_hallo) chan1_hallo = chan1.get_membership_by_user(user_hallo) chan1_hallo.is_op = True chan2.add_user(user2) chan2_user1 = chan2.get_membership_by_user(user2) chan2_user1.is_op = False chan2.add_user(user_hallo) chan2_hallo = chan2.get_membership_by_user(user_hallo) chan2_hallo.is_op = True try: test_hallo.function_dispatcher.dispatch( EventMessage(serv1, chan1, user1, "deop test_user3 test_chan2") ) data = serv1.get_send_data(1, chan1, EventMessage) assert "error" in data[0].text.lower() assert "test_user3 is not in test_chan2" in data[0].text.lower() finally: test_hallo.remove_server(serv1) def test_deop_2_user_no_power(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = Server.TYPE_IRC test_hallo.add_server(serv1) chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") chan1.in_channel = True chan2 = serv1.get_channel_by_address("test_chan2".lower(), "test_chan2") chan2.in_channel = True user1 = serv1.get_user_by_address("test_user1".lower(), "test_user1") user2 = serv1.get_user_by_address("test_user2".lower(), "test_user2") user_hallo = serv1.get_user_by_address(serv1.get_nick().lower(), serv1.get_nick()) chan1.add_user(user1) chan1_user1 = chan1.get_membership_by_user(user1) chan1_user1.is_op = False chan1.add_user(user_hallo) chan1_hallo = chan1.get_membership_by_user(user_hallo) chan1_hallo.is_op = True chan2.add_user(user2) chan2_user1 = chan2.get_membership_by_user(user2) chan2_user1.is_op = False chan2.add_user(user_hallo) chan2_hallo = chan2.get_membership_by_user(user_hallo) chan2_hallo.is_op = False try: test_hallo.function_dispatcher.dispatch( EventMessage(serv1, chan1, user1, "deop test_user2 test_chan2") ) data = serv1.get_send_data(1, chan1, EventMessage) assert "error" in data[0].text.lower() assert "don't have power" in data[0].text.lower() finally: test_hallo.remove_server(serv1) def test_deop_2_user_not_op(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = Server.TYPE_IRC test_hallo.add_server(serv1) chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") chan1.in_channel = True chan2 = serv1.get_channel_by_address("test_chan2".lower(), "test_chan2") chan2.in_channel = True user1 = serv1.get_user_by_address("test_user1".lower(), "test_user1") user2 = serv1.get_user_by_address("test_user2".lower(), "test_user2") user_hallo = serv1.get_user_by_address(serv1.get_nick().lower(), serv1.get_nick()) chan1.add_user(user1) chan1_user1 = chan1.get_membership_by_user(user1) chan1_user1.is_op = False chan1.add_user(user_hallo) chan1_hallo = chan1.get_membership_by_user(user_hallo) chan1_hallo.is_op = True chan2.add_user(user2) chan2_user2 = chan2.get_membership_by_user(user2) chan2_user2.is_op = False chan2.add_user(user_hallo) chan2_hallo = chan2.get_membership_by_user(user_hallo) chan2_hallo.is_op = True try: test_hallo.function_dispatcher.dispatch( EventMessage(serv1, chan1, user1, "deop test_user2 test_chan2") ) data = serv1.get_send_data(1, chan1, EventMessage) assert "error" in data[0].text.lower() assert "doesn't have op" in data[0].text.lower() finally: test_hallo.remove_server(serv1) def test_deop_2_user(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = Server.TYPE_IRC test_hallo.add_server(serv1) chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") chan1.in_channel = True chan2 = serv1.get_channel_by_address("test_chan2".lower(), "test_chan2") chan2.in_channel = True user1 = serv1.get_user_by_address("test_user1".lower(), "test_user1") user2 = serv1.get_user_by_address("test_user2".lower(), "test_user2") user_hallo = serv1.get_user_by_address(serv1.get_nick().lower(), serv1.get_nick()) chan1.add_user(user1) chan1_user1 = chan1.get_membership_by_user(user1) chan1_user1.is_op = False chan1.add_user(user_hallo) chan1_hallo = chan1.get_membership_by_user(user_hallo) chan1_hallo.is_op = True chan2.add_user(user2) chan2_user2 = chan2.get_membership_by_user(user2) chan2_user2.is_op = True chan2.add_user(user_hallo) chan2_hallo = chan2.get_membership_by_user(user_hallo) chan2_hallo.is_op = True try: test_hallo.function_dispatcher.dispatch( EventMessage(serv1, chan1, user1, "deop test_user2 test_chan2") ) data = serv1.get_send_data(2) assert "error" not in data[1].text.lower() assert data[0].channel == chan2 assert data[1].channel == chan1 assert data[0].__class__ == EventMode assert data[1].__class__ == EventMessage assert "-o " + user2.name in data[0].mode_changes assert "status taken" in data[1].text.lower() finally: test_hallo.remove_server(serv1)
39,647
15,821
from base64 import b64encode from flask import Flask, jsonify, request from functools import reduce from gevent import subprocess, pywsgi, queue, socket, spawn, lock from gevent.subprocess import CalledProcessError from hashlib import sha512 from pathlib import Path from tempfile import mkstemp import json import os import subprocess import toml import requests import asyncio import websockets PROFILES_TOML_PATH = '/etc/nixos/hpos-admin-features.toml' app = Flask(__name__) rebuild_queue = queue.PriorityQueue() state_lock = lock.Semaphore() def rebuild_worker(): while True: (_, cmd) = rebuild_queue.get() rebuild_queue.queue.clear() subprocess.run(cmd) def rebuild(priority, args): rebuild_queue.put((priority, ['nixos-rebuild', 'switch'] + args)) def get_state_path(): hpos_config_file_symlink = os.getenv('HPOS_CONFIG_PATH') hpos_config_file = os.path.realpath(hpos_config_file_symlink) return hpos_config_file def get_state_data(): with open(get_state_path(), 'r') as f: return json.loads(f.read()) def cas_hash(data): dump = json.dumps(data, separators=(',', ':'), sort_keys=True) return b64encode(sha512(dump.encode()).digest()).decode() @app.route('/config', methods=['GET']) def get_settings(): return jsonify(get_state_data()['v1']['settings']) def replace_file_contents(path, data): fd, tmp_path = mkstemp(dir=os.path.dirname(path)) with open(fd, 'w') as f: f.write(data) os.rename(tmp_path, path) @app.route('/config', methods=['PUT']) def put_settings(): with state_lock: state = get_state_data() expected_cas = cas_hash(state['v1']['settings']) received_cas = request.headers.get('x-hpos-admin-cas') if received_cas != expected_cas: app.logger.warning('CAS mismatch: {} != {}'.format(received_cas, expected_cas)) return '', 409 state['v1']['settings'] = request.get_json(force=True) state_json = json.dumps(state, indent=2) try: subprocess.run(['hpos-config-is-valid'], check=True, input=state_json, text=True) except CalledProcessError: return '', 400 replace_file_contents(get_state_path(), state_json) # FIXME: see next FIXME # rebuild(priority=5, args=[]) return '', 200 # Toggling HPOS features def read_profiles(): if Path(PROFILES_TOML_PATH).is_file(): return toml.load(PROFILES_TOML_PATH) else: return {} def write_profiles(profiles): with open(PROFILES_TOML_PATH, 'w') as f: f.write(toml.dumps(profiles)) def set_feature_state(profile, feature, enable = True): profiles = read_profiles() profiles.update({ profile: { 'features': { feature: { 'enable': enable } } } }) write_profiles(profiles) return jsonify({ 'enabled': enable }) @app.route('/profiles', methods=['GET']) def get_profiles(): return jsonify({ 'profiles': read_profiles() }) @app.route('/profiles/<profile>/features/<feature>', methods=['GET']) def get_feature_state(profile, feature): profiles = read_profiles() keys = [profile, 'features', feature, 'enable'] enabled = reduce(lambda d, key: d.get(key) if d else None, keys, profiles) or False return jsonify({ 'enabled': enabled }) @app.route('/profiles/<profile>/features/<feature>', methods=['PUT']) def enable_feature(profile, feature): return set_feature_state(profile, feature, True) @app.route('/profiles/<profile>/features/<feature>', methods=['DELETE']) def disable_feature(profile, feature): return set_feature_state(profile, feature, False) def hosted_happs(): conductor_config = toml.load('/var/lib/holochain-conductor/conductor-config.toml') return [dna for dna in conductor_config['dnas'] if dna['holo-hosted']] def hosted_instances(): conductor_config = toml.load('/var/lib/holochain-conductor/conductor-config.toml') return [instance for instance in conductor_config['instances'] if instance['holo-hosted']] async def hc_call(method, params): uri = "ws://localhost:42222" m = { 'jsonrpc': '2.0', 'id': '0', 'method': method, 'params': params } data = json.dumps(m, indent=2) async with websockets.connect(uri) as websocket: await websocket.send(bytes(data,encoding="utf-8")) response = await websocket.recv() return json.loads(response) TRAFFIC_NULL_STATE = {'start_date': None, 'total_zome_calls':0, 'value': []} def get_traffic_service_logger_call(instance_id): response = asyncio.get_event_loop().run_until_complete(hc_call('call', { "instance_id": instance_id ,"zome": "service", "function": "get_traffic", "args": {"filter": "DAY"} })) if 'result' in response: return json.loads(response['result'])['Ok'] else: return TRAFFIC_NULL_STATE @app.route('/hosted_happs', methods=['GET']) def get_hosted_happs(): hosted_happs_list = hosted_happs() hosted_instances_list = hosted_instances() if len(hosted_happs_list) > 0: for hosted_happ in hosted_happs_list: if len(hosted_instances_list) > 0: num_instances = sum(hosted_happ['id'] in hosted_instance['id'] for hosted_instance in hosted_instances_list) hosted_happ['stats'] = {"traffic": get_traffic_service_logger_call(hosted_happ['id']+"::servicelogger")} else: num_instances = 0 hosted_happ['stats'] = {"traffic": TRAFFIC_NULL_STATE} hosted_happ['number_instances'] = num_instances return jsonify({ 'hosted_happs': hosted_happs_list }) def hydra_channel(): with open('/root/.nix-channels') as f: channel_url = f.read() return channel_url.split('/')[6] def hydra_revision(): channel = hydra_channel() eval_url = 'https://hydra.holo.host/jobset/holo-nixpkgs/' + channel + '/latest-eval' headers = { 'Content-Type': 'application/json', 'Accept': 'application/json' } eval_summary = requests.get(eval_url, headers=headers).json() return eval_summary['jobsetevalinputs']['holo-nixpkgs']['revision'] def local_revision(): try: with open('/root/.nix-revision') as f: local_revision = f.read() except: local_revision = 'unversioned' return local_revision def zerotier_info(): proc = subprocess.run(['zerotier-cli', '-j', 'info'], capture_output=True, check=True) return json.loads(proc.stdout) @app.route('/status', methods=['GET']) def status(): return jsonify({ 'holo_nixpkgs':{ 'channel': { 'name': hydra_channel(), 'rev': hydra_revision() }, 'current_system': { 'rev': local_revision() } }, 'zerotier': zerotier_info() }) @app.route('/upgrade', methods=['POST']) def upgrade(): # FIXME: calling nixos-rebuild fails # rebuild(priority=1, args=['--upgrade']) return '', 503 # service unavailable @app.route('/reset', methods=['POST']) def reset(): try: subprocess.run(['hpos-reset'], check=True) except CalledProcessError: return '', 500 def unix_socket(path): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) if os.path.exists(path): os.remove(path) sock.bind(path) sock.listen() return sock if __name__ == '__main__': spawn(rebuild_worker) pywsgi.WSGIServer(unix_socket('/run/hpos-admin.sock'), app).serve_forever()
7,685
2,583
import datetime import math import random import time from ..users.models import User def generate_random_time(): min_time = datetime.datetime(year=2021, month=1, day=1) max_time = datetime.datetime(year=2021, month=3, day=31) min_time_ts = int(time.mktime(min_time.timetuple())) max_time_ts = int(time.mktime(max_time.timetuple())) random_ts = random.randint(min_time_ts, max_time_ts) return datetime.datetime.fromtimestamp(random_ts) def generate_random_location(x0=55.7541, y0=37.62082, radius=17_500): radius_in_degrees = radius / (111.32 * 1000 * math.cos(x0 * (math.pi / 180))) u = random.uniform(0, 1) v = random.uniform(0, 1) w = radius_in_degrees * math.sqrt(u) t = 2 * math.pi * v x = w * math.cos(t) y = w * math.sin(t) return [x / math.cos(math.radians(y0)) + x0, y + y0] def get_random_size(): sizes = ["XS", "S", "M", "L", "XL"] + [str(x) for x in range(6, 12)] return random.choice(sizes) def get_random_user(): return random.choice(User.query.all()).id
1,050
446
import dataclasses import enum import typing from vkmodels.bases.object import ObjectBase class Fields(str, enum.Enum): ID = "id" TITLE = "title" ADDRESS = "address" ADDITIONAL_ADDRESS = "additional_address" COUNTRY_ID = "country_id" CITY_ID = "city_id" METRO_STATION_ID = "metro_station_id" LATITUDE = "latitude" LONGITUDE = "longitude" DISTANCE = "distance" WORK_INFO_STATUS = "work_info_status" TIMETABLE = "timetable" PHONE = "phone" TIME_OFFSET = "time_offset"
525
204
import curifactory as cf import json import os import pytest from stages.cache_stages import filerefcacher_stage, filerefcacher_stage_multifile # TODO: necessary? configured_test_manager already does this @pytest.fixture() def clear_stage_run(configured_test_manager): ran_path = os.path.join(configured_test_manager.cache_path, "stage_ran") try: os.remove(ran_path) except FileNotFoundError: pass yield try: os.remove(ran_path) except FileNotFoundError: pass def test_filerefcacher_stores_multiple_paths(configured_test_manager, clear_stage_run): """FileReferenceCacher should correctly store a list of files in the saved json.""" r = cf.Record(configured_test_manager, cf.ExperimentArgs(name="test")) filerefcacher_stage_multifile(r) argshash = r.args.hash expected_list = [ os.path.join( configured_test_manager.cache_path, f"test_{argshash}_filerefcacher_stage_multifile_my_files/thing{i}", ) for i in range(5) ] with open( os.path.join( configured_test_manager.cache_path, f"test_{argshash}_filerefcacher_stage_multifile_output_paths.json", ), "r", ) as infile: filelist = json.load(infile) assert filelist == expected_list for filename in filelist: assert os.path.exists(filename) def test_filerefcacher_stores_single_path(configured_test_manager, clear_stage_run): r = cf.Record(configured_test_manager, cf.ExperimentArgs(name="test")) filerefcacher_stage(r) argshash = r.args.hash expected_path = os.path.join( configured_test_manager.cache_path, f"test_{argshash}_filerefcacher_stage_my_file", ) with open( os.path.join( configured_test_manager.cache_path, f"test_{argshash}_filerefcacher_stage_output_path.json", ), "r", ) as infile: filelist = json.load(infile) assert filelist == expected_path def test_filerefcacher_shortcircuits(configured_test_manager, clear_stage_run): """FileReferenceCacher should short-circuit if all files in the filelist already exist.""" r0 = cf.Record(configured_test_manager, cf.ExperimentArgs(name="test")) filerefcacher_stage_multifile(r0) ran_path = os.path.join(configured_test_manager.cache_path, "stage_ran") assert os.path.exists(ran_path) os.remove(ran_path) r1 = cf.Record(configured_test_manager, cf.ExperimentArgs(name="test")) filerefcacher_stage_multifile(r1) assert not os.path.exists(ran_path) def test_filerefcacher_runs_when_file_missing(configured_test_manager, clear_stage_run): """FileReferenceCacher should _not_ short-circuit if any of the files in the filelist are missing.""" r0 = cf.Record(configured_test_manager, cf.ExperimentArgs(name="test")) filerefcacher_stage_multifile(r0) ran_path = os.path.join(configured_test_manager.cache_path, "stage_ran") assert os.path.exists(ran_path) os.remove(ran_path) os.remove( os.path.join( configured_test_manager.cache_path, f"test_{r0.args.hash}_filerefcacher_stage_multifile_my_files/thing1", ) ) r1 = cf.Record(configured_test_manager, cf.ExperimentArgs(name="test")) filerefcacher_stage_multifile(r1) assert os.path.exists(ran_path)
3,413
1,147
import urllib import time from multiprocessing.dummy import Pool as ThreadPool excelFolder = 'F://SecExcelDownload2/' compListUrl = 'C://Users/l1111/Desktop/AlphaCapture/downloadFileUrl.txt' successFile = excelFolder+'/success.txt' failFile = excelFolder+'/fail.txt' logFile = excelFolder+'/log.txt' def getAlreadyDownload(): lineList = [] count = 0 with open(successFile) as f: for line in f: line = line.strip() lineList.append(line) return lineList downloadedList = getAlreadyDownload() def downloadFile(line): compName = line.split(',')[0] cik = line.split(',')[1] doc = line.split(',')[2] url = line.split(',')[3] if url in downloadedList: return 0 fileURLOpener = urllib.URLopener() try: fileURLOpener.retrieve(url,excelFolder+compName+'-'+cik+'-'+doc+'.xlsx' ) with open(successFile, "a") as myfile: myfile.write(url+'\n') except: print('Error: not a xlsx file. Downloading xls file') try: fileURLOpener.retrieve(url.replace('.xlsx','.xls'), excelFolder+compName+'-'+cik+'-'+doc+'.xls') with open(successFile, "a") as myfile: myfile.write(url+'\n') except: print('Error: download failed') with open(failFile, "a") as myfile: myfile.write(url+'\n') def slowSingleThread(): lineList = [] count = 0 with open(compListUrl) as f: for line in f: line = line.strip() lineList.append(line) # downloadFile(line) # break # print(len(lineList)) # total = len(lineList) # with open(compListUrl) as f: # for line in f: # line = line.strip() # with open(logFile, "a") as myfile: # myfile.write(str(count)+'/'+str(total)+':'+line+'\n') # count+=1 # downloadFile(line) for line in lineList: downloadFile(line) def fastMultiThread(): lineList = [] count = 0 with open(compListUrl) as f: for line in f: line = line.strip() lineList.append(line) # make the Pool of workers pool = ThreadPool(10) # open the urls in their own threads # and return the results results = pool.map(downloadFile, lineList) # close the pool and wait for the work to finish pool.close() pool.join() fastMultiThread() # slowSingleThread()
2,471
786
#/* # * Copyright 2016 -- 2021 IBM Corporation # * # * 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 the License is distributed on an "AS IS" BASIS, # * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # * See the License for the specific language governing permissions and # * limitations under the License. # * # ***************************************************************************** # * @file : tc_TcpEcho.py # * @brief : A multi-threaded script to send and receive traffic on the # * TCP connection of an FPGA module. # * # * System: : cloudFPGA # * Component : cFp_BringUp/ROLE # * Language : Python 3 # * # ***************************************************************************** # ### REQUIRED PYTHON PACKAGES ################################################ import argparse import datetime import errno import filecmp import socket import threading import time # ### REQUIRED TESTCASE MODULES ############################################### from tc_utils import * # ### GLOBAL VARIABLES ######################################################## gEchoRxPath = './echoRx.dat' gEchoTxPath = './echoTx.dat' def tcp_tx(sock, message, count, verbose=False): """TCP Tx Thread. :param sock, the socket to send to. :param message, the random string to sent. :param count, the number of segments to send. :param verbose, enables verbosity. :return None""" if verbose: print("The following message of %d bytes will be sent out %d times:\n Message=%s\n" % (len(message), count, message.decode('ascii'))) # Create a Tx Reference File echoTxFile = open(gEchoTxPath, 'w') if count <= 1000: loop = 0 while loop < count: echoTxFile.write(message.decode('ascii')) loop += 1 # Start Data Transmission loop = 0 startTime = datetime.datetime.now() while loop < count: try: sock.sendall(message) finally: pass loop += 1 endTime = datetime.datetime.now() elapseTime = endTime - startTime; bandwidth = len(message) * 8 * count * 1.0 / (elapseTime.total_seconds() * 1024 * 1024) print("##################################################") print("#### TCP TX DONE with bandwidth = %6.1f Mb/s ####" % bandwidth) print("##################################################") print() # Close the Tx Reference File echoTxFile.close() # Push a few more bytes to force the FPGA to flush its buffers try: sock.sendall(message) finally: pass def tcp_rx(sock, message, count, verbose): """TCP Rx Thread. :param sock, the socket to receive from. :param message, the expected string message to be received. :param count, the number of segment to receive. :param verbose, enables verbosity. :return None""" # Create an Rx Test File echoRxFile = open(gEchoRxPath, 'w') # Start Data Reception loop = 0 rxBytes = 0 expectedBytes = count*len(message) startTime = datetime.datetime.now() while rxBytes < expectedBytes: try: data = sock.recv(expectedBytes - rxBytes) rxBytes += len(data) if count <= 1000: echoRxFile.write(data.decode('ascii')) except socket.error as exc: print("[EXCEPTION] Socket error while receiving :: %s" % exc) else: if verbose: print("Loop=%d | RxBytes=%d" % (loop, rxBytes)) loop += 1 endTime = datetime.datetime.now() elapseTime = endTime - startTime bandwidth = len(message) * 8 * count * 1.0 / (elapseTime.total_seconds() * 1024 * 1024) print("##################################################") print("#### TCP RX DONE with bandwidth = %6.1f Mb/s ####" % bandwidth) print("##################################################") print() # Close the Rx Test File echoRxFile.close() def waitUntilSocketPairCanBeReused(ipFpga, portFpga): """Check and wait until the a socket pair can be reused. [INFO] When a client or a server initiates an active close, then the same destination socket (i.e. the same IP address / TCP port number) cannot be re-used immediately because of security issues. Therefore, a closed connection must linger in a 'TIME_WAIT' or 'FIN_WAIT' state for as long as 2xMSL (Maximum Segment Lifetime), which corresponds to twice the time a TCP segment might exist in the internet system. The MSL is arbitrarily defined to be 2 minutes long. :param ipFpga: the IP address of FPGA. :param portFpga: the TCP port of the FPGA. :return: nothing """ wait = True # NETSTAT example: rc = os.system("netstat | grep '10.12.200.163:8803' | grep TIME_WAIT") cmdStr = "netstat | grep \'" + str(ipFpga) + ":" + str(portFpga) + "\' | grep \'TIME_WAIT\|FIN_WAIT\' " while wait: rc = os.system(cmdStr) if rc == 0: print("[INFO] Cannot reuse this socket as long as it is in the \'TIME_WAIT\' or \'FIN_WAIT\' state.") print(" Let's sleep for 5 sec...") time.sleep(5) else: wait = False def tcp_txrx_loop(sock, message, count, verbose=False): """TCP Tx-Rx Single-Thread Loop. :param sock The socket to send/receive to/from. :param message The message string to sent. :param count The number of segments send. :param verbose Enables verbosity. :return None""" if verbose: print("[INFO] The following message of %d bytes will be sent out %d times:\n Message=%s\n" % (len(message), count, message.decode('ascii'))) nrErr = 0 txMssgCnt = 0 rxMssgCnt = 0 rxByteCnt = 0 txStream = "" rxStream = "" # Init the Tx reference stream for i in range(count): txStream = txStream + message.decode('ascii') startTime = datetime.datetime.now() while rxByteCnt < (count * len(message)): if txMssgCnt < count: # Send a new message # ------------------------ try: tcpSock.sendall(message) txMssgCnt += 1 finally: pass # Receive a segment # -------------------- try: data = tcpSock.recv(len(message)) rxByteCnt += len(data) rxMssgCnt += 1 if verbose: print("%d:%s" % (rxMssgCnt, data.decode('ascii'))) except IOError as e: # On non blocking connections - when there are no incoming data, error is going to be # raised. Some operating systems will indicate that using AGAIN, and some using # WOULDBLOCK error code. We are going to check for both - if one of them - that's # expected, means no incoming data, continue as normal. If we got different error code, # something happened if e.errno != errno.EAGAIN and e.errno != errno.EWOULDBLOCK: print('[ERROR] Socket reading error: {}'.format(str(e))) exit(1) # We just did not receive anything continue except socket.error as exc: # Any other exception print("[EXCEPTION] Socket error while receiving :: %s" % exc) # exit(1) finally: pass rxStream = rxStream + data.decode('ascii') endTime = datetime.datetime.now() if verbose: print("\n") # Compare Tx and Rx stream if rxStream != txStream: print(" KO | Received stream = %s" % data.decode('ascii')) print(" | Expected stream = %s" % rxStream) nrErr += 1 elif verbose: print(" OK | Received %d bytes in %d messages." % (rxByteCnt, rxMssgCnt)) elapseTime = endTime - startTime; bandwidth = len(message) * 8 * count * 1.0 / (elapseTime.total_seconds() * 1024 * 1024) print("[INFO] Transferred a total of %d bytes." % rxByteCnt) print("#####################################################") print("#### TCP Tx/Rx DONE with bandwidth = %6.1f Mb/s ####" % bandwidth) print("#####################################################") print() def tcp_txrx_ramp(sock, message, count, verbose=False): """TCP Tx-Rx Single-Thread Ramp. :param sock The socket to send/receive to/from. :param message The message string to sent. :param count The number of segments to send. :param verbose Enables verbosity. :return None""" if verbose: print("[INFO] The following message of %d bytes will be sent out incrementally %d times:\n Message=%s\n" % (len(message), count, message.decode('ascii'))) nrErr = 0 loop = 0 rxByteCnt = 0 startTime = datetime.datetime.now() while loop < count: i = 1 while i <= len(message): subMsg = message[0:i] # Send datagram # ------------------- try: tcpSock.sendall(subMsg) finally: pass # Receive datagram # ------------------- try: data = tcpSock.recv(len(subMsg)) rxByteCnt += len(data) if data == subMsg: if verbose: print("Loop=%d | RxBytes=%d" % (loop, len(data))) else: print("Loop=%d | RxBytes=%d" % (loop, len(data))) print(" KO | Received Message=%s" % data.decode('ascii')) print(" | Expecting Message=%s" % subMsg) nrErr += 1 except IOError as e: # On non blocking connections - when there are no incoming data, error is going to be raised # Some operating systems will indicate that using AGAIN, and some using WOULDBLOCK error code # We are going to check for both - if one of them - that's expected, means no incoming data, # continue as normal. If we got different error code - something happened if e.errno != errno.EAGAIN and e.errno != errno.EWOULDBLOCK: print('[ERROR] Socket reading error: {}'.format(str(e))) exit(1) # We just did not receive anything continue except socket.error as exc: # Any other exception print("[EXCEPTION] Socket error while receiving :: %s" % exc) # exit(1) finally: pass i += 1 loop += 1 endTime = datetime.datetime.now() elapseTime = endTime - startTime bandwidth = (rxByteCnt * 8 * count * 1.0) / (elapseTime.total_seconds() * 1024 * 1024) megaBytes = (rxByteCnt * 1.0) / (1024 * 1024 * 1.0) print("[INFO] Transferred a total of %.1f MB." % megaBytes) print("#####################################################") print("#### TCP Tx/Rx DONE with bandwidth = %6.1f Mb/s ####" % bandwidth) print("#####################################################") print() ############################################################################### # # # MAIN # # # ############################################################################### rc = 0 # STEP-1: Parse the command line strings into Python objects # ----------------------------------------------------------------------------- parser = argparse.ArgumentParser(description='A script to send/receive TCP data to/from an FPGA module.') parser.add_argument('-fi', '--fpga_ipv4', type=str, default='', help='The destination IPv4 address of the FPGA (a.k.a image_ip / e.g. 10.12.200.163)') parser.add_argument('-fp', '--fpga_port', type=int, default=8803, help='The TCP destination port of the FPGA (default is 8803)') parser.add_argument('-ii', '--inst_id', type=int, default=0, help='The instance ID assigned by the cloudFPGA Resource Manager (range is 1-32)') parser.add_argument('-lc', '--loop_count', type=int, default=10, help='The number of times to run run the test (default is 10)') parser.add_argument('-mi', '--mngr_ipv4', type=str, default='10.12.0.132', help='The IP address of the cloudFPGA Resource Manager (default is 10.12.0.132)') parser.add_argument('-mp', '--mngr_port', type=int, default=8080, help='The TCP port of the cloudFPGA Resource Manager (default is 8080)') parser.add_argument('-mt', '--multi_threading', action="store_true", help='Enable multi_threading') parser.add_argument('-sd', '--seed', type=int, default=-1, help='The initial number to seed the pseudo-random number generator.') parser.add_argument('-sz', '--size', type=int, default=-1, help='The size of the segment to generate.') parser.add_argument('-un', '--user_name', type=str, default='', help='A user name as used to log in ZYC2 (.e.g \'fab\')') parser.add_argument('-up', '--user_passwd', type=str, default='', help='The ZYC2 password attached to the user name') parser.add_argument('-v', '--verbose', action="store_true", help='Enable verbosity') args = parser.parse_args() if args.user_name == '' or args.user_passwd == '': print("\nWARNING: You must provide a ZYC2 user name and the corresponding password for this script to execute.\n") exit(1) # STEP-2a: Retrieve the IP address of the FPGA module (this will be the SERVER) # ------------------------------------------------------------------------------ ipFpga = getFpgaIpv4(args) # STEP-2b: Retrieve the instance Id assigned by the cloudFPGA Resource Manager # ----------------------------------------------------------------------------- instId = getInstanceId(args) # STEP-2c: Retrieve the IP address of the cF Resource Manager # ----------------------------------------------------------------------------- ipResMngr = getResourceManagerIpv4(args) # STEP-3a: Retrieve the TCP port of the FPGA server # ----------------------------------------------------------------------------- portFpga = getFpgaPort(args) # STEP-3b: Retrieve the TCP port of the cloudFPGA Resource Manager # ----------------------------------------------------------------------------- portResMngr = getResourceManagerPort(args) # STEP-?: Configure the application registers # ----------------------------------------------------------------------------- # TODO print("\nNow: Configuring the application registers.") # TODO tcpEchoPathThruMode = (0x0 << 4) # See DIAG_CTRL_2 register # STEP-4: Trigger the FPGA role to restart (i.e. perform SW reset of the role) # ----------------------------------------------------------------------------- restartApp(instId, ipResMngr, portResMngr, args.user_name, args.user_passwd) # STEP-5: Ping the FPGA # ----------------------------------------------------------------------------- pingFpga(ipFpga) # STEP-6a: Set the FPGA socket association # ----------------------------------------------------------------------------- tcpDP = 8803 # 8803=0x2263 and 0x6322=25378 fpgaAssociation = (str(ipFpga), tcpDP) # STEP-6b: Set the HOST socket association (optional) # Info: Linux selects a source port from an ephemeral port range, which by # default is a set to range from 32768 to 61000. You can check it # with the command: # > cat /proc/sys/net/ipv4/ip_local_port_range # If we want to force the source port ourselves, we must use the # "bind before connect" trick. # ----------------------------------------------------------------------------- if 0: tcpSP = tcpDP + 49152 # 8803 + 0xC000 hostAssociation = (ipSaStr, tcpSP) # STEP-7: Wait until the current socket can be reused # ----------------------------------------------------------------------------- if 0: waitUntilSocketPairCanBeReused(ipFpga, portFpga) # STEP-8a: Create a TCP/IP socket for the TCP/IP connection # ----------------------------------------------------------------------------- try: tcpSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except Exception as exc: print("[EXCEPTION] %s" % exc) exit(1) # Step-8b: Allow this socket to be re-used and disable the Nagle's algorithm # ---------------------------------------------------------------------------- tcpSock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) tcpSock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True) # STEP-8c: Bind before connect (optional). # This trick enables us to ask the kernel to select a specific source IP and # source PORT by calling bind() before calling connect(). # ----------------------------------------------------------------------------- if 0: try: tcpSock.bind(hostAssociation) print('Binding the socket address of the HOST to {%s, %d}' % hostAssociation) except Exception as exc: print("[EXCEPTION] %s" % exc) exit(1) # STEP-9: Connect to the remote FPGA # ----------------------------------------------------------------------------- try: tcpSock.connect(fpgaAssociation) except Exception as exc: print("[EXCEPTION] %s" % exc) exit(1) else: print('\nSuccessful connection with socket address of FPGA at {%s, %d} \n' % fpgaAssociation) # STEP-10: Setup the test # ------------------------------- print("[INFO] Testcase `%s` is run with:" % (os.path.basename(__file__))) seed = args.seed if seed == -1: seed = random.randint(0, 100000) random.seed(seed) print("\t\t seed = %d" % seed) size = args.size if size == -1: size = random.randint(1, ZYC2_MSS) elif size > ZYC2_MSS: print('\nERROR: ') print("[ERROR] This test-case expects the transfer of segment which are less or equal to MSS (.i.e %d bytes).\n" % ZYC2_MSS) exit(1) print("\t\t size = %d" % size) count = args.loop_count print("\t\t loop = %d" % count) if seed % 1: message = str_static_gen(size) else: message = str_rand_gen(size) verbose = args.verbose print("[INFO] This testcase is sending traffic from HOST-to-FPGA and back from FPGA-to-HOST.") if args.multi_threading: print("[INFO] This run is executed in multi-threading mode.\n") # STEP-11: Create Rx and Tx threads # ---------------------------------- tx_thread = threading.Thread(target=tcp_tx, args=(tcpSock, message, count, args.verbose)) rx_thread = threading.Thread(target=tcp_rx, args=(tcpSock, message, count, args.verbose)) # STEP-12: Start the threads # --------------------------- tx_thread.start() rx_thread.start() # STEP-13: Wait for threads to terminate # ---------------------------------------- tx_thread.join() rx_thread.join() # STEP-14: Compare Rx and Tx files # ---------------------------------------- result = filecmp.cmp(gEchoTxPath, gEchoRxPath, shallow=False) if not result: print("\n[ERROR] Rx file \'%s\' differs from Tx file \'%s\'.\n" % (gEchoRxPath, gEchoTxPath)) rc = 1 else: os.remove(gEchoRxPath) os.remove(gEchoTxPath) else: print("[INFO] The run is executed in single-threading mode.\n") # STEP-11: Set the socket in non-blocking mode # ---------------------------------------------- tcpSock.setblocking(False) tcpSock.settimeout(5) if seed == 0: tcp_txrx_ramp(tcpSock, message, count, args.verbose) else: tcp_txrx_loop(tcpSock, message, count, args.verbose) # STEP-14: Close socket # ----------------------- time.sleep(2) tcpSock.close() exit(rc)
20,495
6,188
import json import re import random def stopfilter(word): if word[0] == '@' or word.startswith('http'): return False return True class NGram(object): __slots__ = ['wordindex', 'size', 'punct', 'chain'] def __init__(self, size=2): self.wordindex = {} self.chain = {} self.size = size self.punct = re.compile(r'["\!\^\(\)_\+\*=\{\}\[\]\|:;,<>\.\?]') def index(self, words): idx = 0 gram, pgram = '', '' words = words.replace('&amp;', '&') wlist = filter(stopfilter, re.sub(self.punct, '', words).split()) if len(wlist) < self.size: self.__add_gram__(words) wlen = len(wlist) - self.size for idx in range(0, wlen): tmpgram = [] for tmp in range(idx, idx + self.size): tmpgram.append(wlist[tmp]) gram = ' '.join(tmpgram) self.__add_gram__(gram) if pgram is not '': self.__add_chain__(pgram, gram) pgram = gram def random_gram(self): """ return a random ngram from the corpus """ return random.choice(self.wordindex.keys()) def gram_starts_with(self, prefix): """ given a prefix, return a (gram, chain) tuple that starts with prefix.""" if prefix in self.chain: return (prefix, self.chain[prefix]) for k, v in self.chain.iteritems(): # print "here: {0}".format(k) if k.startswith(prefix): return (k, v) return None def __add_gram__(self, gram): if gram in self.wordindex: self.wordindex[gram] += 1 else: self.wordindex[gram] = 1 def __add_chain__(self, pgram, gram): if pgram in self.chain: self.chain[pgram].add(gram) else: self.chain[pgram] = set([gram]) def gram_stats(self): wdata = [] for i in self.wordindex.iteritems(): wdata.append(i) if len(wdata) > 10: wdata = sorted(wdata, key=lambda x: x[1], reverse=True) wdata = wdata[0:10] return wdata if __name__ == "__main__": data, gramindex = {}, NGram() gramind3x = NGram(size=3) gram1ndex = NGram(size=1) with open('dump', 'r') as f: data = json.load(f) for tweet in data['tweet']: gramindex.index(tweet) gramind3x.index(tweet) gram1ndex.index(tweet) print gramindex.wordindex.keys()[0:10] print gramind3x.wordindex.keys()[0:10] print gram1ndex.wordindex.keys()[0:10] print gramindex.gram_stats() print gramind3x.gram_stats() print gram1ndex.gram_stats() print gramindex.chain.items()[0:10] print gramind3x.chain.items()[0:10] print gram1ndex.chain.items()[0:10] print gramindex.random_gram() print gramind3x.random_gram() print gram1ndex.random_gram()
2,961
1,008
import os from mir.scm.cmd import CmdScm from mir.tools.code import MirCode from mir.tools.errors import MirRuntimeError def Scm(root_dir: str, scm_executable: str = None) -> CmdScm: """Returns SCM instance that corresponds to a repo at the specified path. Args: root_dir (str): path to a root directory of the repo. scm_excutable(str): "git". Returns: mir.scm.cmd.BaseScm: SCM instance. """ if scm_executable not in ["git"]: raise MirRuntimeError(error_code=MirCode.RC_CMD_INVALID_ARGS, error_message=f"args error: expected git, not {scm_executable}") if not os.path.exists(root_dir): os.makedirs(root_dir) if not os.path.isdir(root_dir): raise MirRuntimeError(error_code=MirCode.RC_CMD_INVALID_ARGS, error_message=f"can not create dir: {root_dir}") return CmdScm(root_dir, scm_executable)
967
316
""" Software: LingFeat - Comprehensive Linguistic Features for Readability Assessment Page: utils.py License: CC-BY-SA 4.0 Original Author: Bruce W. Lee (이웅성) @brucewlee Affiliation 1: LXPER AI, Seoul, South Korea Affiliation 2: University of Pennsylvania, PA, USA Contributing Author: - Affiliation : - """ import re import math def division(x, y): try: result = x/y except: result = 0 return result def nan_check(result): for key in result: if math.isnan(float(result[key])): result[key] = 0 return result def count_syllables(word:str): return len( re.findall('(?!e$)[aeiouy]+', word, re.I) + re.findall('^[^aeiouy]*e$', word, re.I) )
724
269
# Generated by Django 3.2.8 on 2021-10-31 23:57 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("pretix_eventparts", "0006_alter_eventpart_name"), ] operations = [ migrations.AlterField( model_name="eventpart", name="category", field=models.CharField(default="", max_length=200), ), ]
416
141
# Usage: # python bwfilter.py --input=./data/test1.jpg import cv2 import numpy as np import argparse def parse_args(): parser = argparse.ArgumentParser(add_help=True, description='testing B&W filter') required_named = parser.add_argument_group('required named arguments') required_named.add_argument('-i', '--input', type=str, help='path of the input image', required=True) return parser.parse_args() def show_img(img): cv2.namedWindow("output", cv2.WINDOW_NORMAL) cv2.resizeWindow('output', 900, 900) cv2.imshow("output", img) cv2.waitKey(0) cv2.destroyAllWindows() def bwfilter(bwimg): # blur the image bwimg = cv2.GaussianBlur(bwimg,(7,7),7) cv2.imwrite('blur.png', bwimg) bwimg = cv2.bilateralFilter(bwimg,9,75,75) cv2.imwrite('bilat.png', bwimg) # adaptive threshholding bwimg = cv2.adaptiveThreshold(bwimg,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,2) cv2.imwrite('adaptth.png', bwimg) return bwimg if __name__=='__main__': args = parse_args() img = cv2.imread(args.input, 0) bwimg = bwfilter(img) show_img(bwimg) cv2.imwrite('bwimg.png', bwimg)
1,173
492
from networkx import DiGraph from pytest import fixture from resotolib.graph.graph_extensions import dependent_node_iterator @fixture def graph() -> DiGraph: g = DiGraph() for i in range(1, 14): g.add_node(i) g.add_edges_from([(1, 2), (1, 3), (2, 3)]) # island 1 g.add_edges_from([(4, 5), (4, 6), (6, 7)]) # island 2 g.add_edges_from( [(8, 9), (9, 10), (9, 11), (8, 12), (12, 11), (12, 13)] ) # island 3 return g def test_reversed_directed_traversal(graph: DiGraph): result = list(dependent_node_iterator(graph)) assert len(result) == 3 # 3 steps to complete assert result == [ [3, 5, 7, 10, 11, 13], # step 1 [2, 6, 9, 12], # step 2 [1, 4, 8], # step 3 ] def test_delete_nodes(graph: DiGraph): to_delete = graph.copy() for parallel in dependent_node_iterator(graph): for node in parallel: to_delete.remove_node(node) assert len(to_delete.nodes) == 0 def test_empty_graph(): assert list(dependent_node_iterator(DiGraph())) == []
1,065
439
from django.contrib.auth.models import AbstractUser from django.db import models from django.urls import reverse class User(AbstractUser): location = models.CharField(max_length=100, null=True) NOT_CHOSEN = 'N' MALE = 'M' FEMALE = 'F' GENDERS = ( (NOT_CHOSEN, 'Not Chosen'), (MALE, 'Male'), (FEMALE, 'Female'), ) gender = models.CharField( max_length=1, choices=GENDERS, default=NOT_CHOSEN, ) avatar_url = models.URLField(null=True) bio = models.CharField(max_length=200, null=True) def get_absolute_url(self): return reverse('user:profile', kwargs={ 'pk': self.id })
693
241
#!/usr/bin/env python3.4 import functools @functools.total_ordering class CrossSum: def __init__(self, digits, total=0, addends=''): self._digits = digits self._base = len(digits) self.total = total self.addends = addends def _convert_total(self): num_total = self.total total_digits = [] while num_total: total_digits.append(self._digits[num_total % self._base]) num_total //= self._base return ''.join(total_digits[::-1]) # This assumes that the new addend is larger than others in the sum def add_addend(self, addend): d = self._digits.index(addend) return CrossSum(self._digits, self.total + d, self.addends + addend) def has_total(self, total): if isinstance(total, str): total_str = total total = 0 for digit in total_str: total = total * self._base + self._digits.index(digit) return self.total == total def has_addends(self, addends): if not isinstance(addends, set): addends = set(addends) return set(self.addends).issuperset(addends) @property def num_addends(self): return len(self.addends) @staticmethod def _is_valid_operand(other): return hasattr(other, 'total') and hasattr(other, 'addends') def __eq__(self, other): if not self._is_valid_operand(other): return NotImplemented return (self.total, self.addends) == (other.total, other.addends) def __lt__(self, other): if not self._is_valid_operand(other): return NotImplemented return (self.total, self.addends) < (other.total, other.addends) def __repr__(self): return ("<CrossSum(digits='%s', total='%s', addends='%s'>" % (self._digits, self._convert_total(), self.addends)) def __str__(self): total_str = self._convert_total() return '%s = %s' % (total_str, ' + '.join(self.addends)) class CrossSums: def __init__(self, digits='0123456789', cross_sums=None): self._digits = digits self._base = len(digits) if cross_sums is None: cross_sums = [CrossSum(digits)] for digit in digits[1:]: cross_sums += [cs.add_addend(digit) for cs in cross_sums] cross_sums = [cs for cs in cross_sums if cs.num_addends > 1] self._cross_sums = sorted(cross_sums) def filter(self, total=None, num_addends=None, addends=None): cross_sums = self._cross_sums if total: cross_sums = [cs for cs in cross_sums if cs.has_total(total)] if num_addends: cross_sums = [cs for cs in cross_sums if cs.num_addends == num_addends] if addends: addends = set(addends) cross_sums = [cs for cs in cross_sums if cs.has_addends(addends)] return CrossSums(self._digits, cross_sums) @property def max_sum(self): return self._cross_sums[-1].total def __iter__(self): return self._cross_sums.__iter__() def __len__(self): return len(self._cross_sums) if __name__ == '__main__': doz_sums = CrossSums('0123456789XE') print('Sums totalling 15:') for ds in doz_sums.filter(total='15'): print(' ', ds) print('\nSums containing addends 3-X inclusive:') for ds in doz_sums.filter(addends='3456789X'): print(' ', ds) print('\nSums containing ten addends:') for ds in doz_sums.filter(num_addends=10): print(' ', ds) print('\nSums totaling 1X with five addends including 2 and 3:') for ds in doz_sums.filter(total='1X', num_addends=5, addends='23'): print(' ', ds)
3,806
1,297
import base64 import re def encode(text): return base64.b64encode(text.encode("ASCII")).decode() def enhanceText(text): text = text.replace('.', '.', text.count('.')).replace(',', ', ', text.count(',')) text = " ".join(text.split()).replace(" . ", ". ") return text def stylish_text(text): text = text.lower() style_text = list('𝗮𝗯𝗰𝗱𝗲𝗳𝗴𝗵𝗶𝗷𝗸𝗹𝗺𝗻𝗼𝗽𝗾𝗿𝘀𝘁𝘂𝘃𝘄𝘅𝘆𝘇') normal_text = list('abcdefghijklmnopqrstuvwxyz') result = [] for char in list(text): if char in normal_text: result.append(style_text[normal_text.index(char)]) else: result.append(char) return ''.join(result) def checkForURLs(string): regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))" url = re.findall(regex, string) return [x[0] for x in url] def replace_special_slash(text): characters = '!@#$%^&*()-+?_=,<>/".' + "''" new_string = "" for i in text: if i in characters: new_string += '\\' new_string += i return new_string
1,177
561
# may 30 20 def max_sub_array_of_size_k(k, arr): # TODO: Write your code here windowStart, currSum, maxSum = 0,0,0 for endIndex in range(len(arr)): currSum += arr[endIndex] if endIndex - windowStart + 1 > k: currSum -= arr[windowStart] windowStart+=1 # had this in while...most cases its below maxSum = max(maxSum, currSum) return maxSum
377
139
import xlwings as xw import random import pandas as pd @xw.func @xw.arg('num_periods', numbers=int) @xw.ret(expand='table') def n_random_normal(mean, stdev, num_periods, horizontal=False): random_values = [] for i in range(num_periods): num = random.normalvariate(mean, stdev) if not horizontal: num = [num] random_values.append(num) return random_values @xw.func @xw.arg('nper', numbers=int) @xw.ret(expand='horizontal') def n_random_uniform(bot, top, nper): nums = [] for i in range(nper): num = random.uniform(bot, top) nums.append(num) return nums def capm(risk_free, beta, market_ret, epsilon): return risk_free + beta * (market_ret - risk_free) + epsilon def capm_auto_epsilon(risk_free, beta, market_ret, epsilon_stdev): epsilon = random.normalvariate(0, epsilon_stdev) return capm(risk_free, beta, market_ret, epsilon) @xw.func @xw.arg('betas', expand='horizontal') @xw.arg('epsilon_stdevs', expand='horizontal') @xw.arg('market_rets', expand='vertical') @xw.arg('num_assets', numbers=int) @xw.ret(expand='table', index=False) def multi_capm(risk_free, betas, market_rets, epsilon_stdevs, num_assets): df = pd.DataFrame() for i in range(num_assets): beta = betas[i] epsilon_stdev = epsilon_stdevs[i] returns = [capm_auto_epsilon(risk_free, beta, market_ret, epsilon_stdev) for market_ret in market_rets] df[f'Asset {i + 1}'] = returns return df @xw.func @xw.arg('data', pd.DataFrame, expand='table', index=False) @xw.ret(expand='table') def correlations(data): return data.corr()
1,697
656
# -*- coding: UTF-8 -*- import ConfigParser import os import inspect class Settings(): __default_conf_name = 'example.conf' __conf = {} def __init__(self, filename=False): """ Create config object, read config data from file and make friendly format ot access to config data """ self.APP_DIR = os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]) + '/../' self.CONF_DIR = self.APP_DIR + 'conf/' if not filename: filename = self.__default_conf_name self.FILENAME = self.CONF_DIR + filename self.CONF_NAME = filename config = ConfigParser.ConfigParser() config.readfp(open(self.CONF_DIR + filename)) for section_name in config.sections(): data = {} for item in config.items(section_name): try: data.update({item[0]: str(config.get(section_name, item[0])).strip()}) except ConfigParser.NoOptionError: data.update({item[0]: None}) if data[item[0]].lower() == 'false': data[item[0]] = False self.__conf.update({ section_name: data }) def get(self, key=None): if not key: return self.__conf try: section, option = key.split(':') return self.__conf[section][option] except KeyError, e: raise Exception("Can't find config key in file: " + str(e))
1,547
440
from .detection import FDetector from .haar_detector import HaarDetector from .hog_detector import Hog_detector from .mtcnn_detector import MTCNNDetector from .dnn_detector import DnnDetector
192
66
import torchvision.datasets as datasets from torch.utils.data import Dataset from itertools import combinations import math import psutil class CombinationDataset(Dataset): def __init__(self, dataset): self.dataset = dataset self.comb = list(combinations(dataset, 2)) def __getitem__(self, index): img1, img2 = self.comb[index] return img1, img2 def __len__(self): return len(self.comb) def cut_dataset(self, index): self.comb = self.comb[index:] class ImageFolderWithPaths(datasets.ImageFolder): """Custom dataset that includes image file paths. Extends torchvision.datasets.ImageFolder """ # override the __getitem__ method. this is the method that dataloader calls def __getitem__(self, index): # this is what ImageFolder normally returns original_tuple = super(ImageFolderWithPaths, self).__getitem__(index) # the image file path path = self.imgs[index][0] # make a new tuple that includes original and the path tuple_with_path = original_tuple + (path,) return tuple_with_path class FeatureTensorDatasetWithImgName(Dataset): def __init__(self, feature_tensor, img_name_array): self.feature_tensor = feature_tensor self.imgnames = img_name_array def __getitem__(self, index): feat = self.feature_tensor[index, :] imgname = self.imgnames[index] return imgname, feat def __len__(self): return len(self.imgnames) class PermutationIndexDataset(Dataset): def __init__(self, datalen): self.datalen = datalen def __getitem__(self, index): idx1 = int(math.floor(index / self.datalen)) idx2 = index % self.datalen return idx1, idx2 class OriginalandPostProcessedPairsDataset(Dataset): def __init__(self, original_feat_dataset, postprocessed_feat_dataset): self.original = original_feat_dataset self.postprocessed = postprocessed_feat_dataset self.datalen = len(self.postprocessed) def __getitem__(self, index): idx1 = int(math.floor(index / self.datalen)) idx2 = index % self.datalen s1 = self.original[idx1] s2 = self.postprocessed[idx2] return (idx1, s1), (idx2, s2) def __len__(self): return len(self.original) ** 2 class PermutationPairsDataset(Dataset): def __init__(self, original_feat_dataset, postprocessed=None): self.original = original_feat_dataset self.datalen = len(self.original) self.postprocessed = postprocessed def __getitem__(self, index): idx1 = int(math.floor(index / self.datalen)) idx2 = index % self.datalen s1 = self.original[idx1] if self.postprocessed is not None: s2 = self.postprocessed[idx2] else: s2 = self.original[idx2] return (idx1, s1), (idx2, s2) def __len__(self): return len(self.original) ** 2 class HDFDataset(Dataset): def __init__(self, hdfstore, mem_usage=0.85): self.hdfstore = hdfstore self.datalen = len(self.hdfstore) self.pull_data_to_cache(mem_usage) if not self.all_in_cache: print("initializing placeholder cache list") self.cache_length = int( psutil.virtual_memory().available * 0.85 / self.hdfstore[0].nbytes ) self.in_cache_idx = [None] * self.cache_length self.in_cache = [None] * self.cache_length self.cache_counter = 0 def __getitem__(self, index): if not self.all_in_cache: if index in self.in_cache_idx: return self.in_cache[self.in_cache_idx.index(index)] else: self.in_cache_idx[self.cache_counter] = index data = self.hdfstore[index] self.in_cache[self.cache_counter] = data self.cache_counter += 1 self.cache_counter %= self.cache_length return data return self.hdfstore[index] def __len__(self): return self.datalen def pull_data_to_cache(self, mem_usage): single_row = self.hdfstore[0] if ( psutil.virtual_memory().available * mem_usage < single_row.nbytes * self.datalen ): print("Not enough memory to pull data to cache") self.all_in_cache = False else: print("Pulling data to cache") self.hdfstore = self.hdfstore[:] self.all_in_cache = True print("Done pulling data to cache")
4,635
1,423
# iaga.utils # Utility functions and helpers # # Author: Benjamin Bengfort <benjamin@bengfort.com> # Created: Wed Aug 08 12:00:44 2018 -0400 # # ID: utils.py [] benjamin@bengfort.com $ """ Utility functions and helpers """ ########################################################################## ## Imports ########################################################################## import time from functools import wraps ########################################################################## ## Decorators ########################################################################## def memoized(fget): """ Return a property attribute for new-style classes that only calls its getter on the first access. The result is stored and on subsequent accesses is returned, preventing the need to call the getter any more. Parameters ---------- fget: function The getter method to memoize for subsequent access. See also -------- python-memoized-property `python-memoized-property <https://github.com/estebistec/python-memoized-property>`_ """ attr_name = '_{0}'.format(fget.__name__) @wraps(fget) def fget_memoized(self): if not hasattr(self, attr_name): setattr(self, attr_name, fget(self)) return getattr(self, attr_name) return property(fget_memoized) ########################################################################## ## Timer Class ########################################################################## def human_readable_time(s): h, s = divmod(s, 3600) m, s = divmod(s, 60) return "{:>02.0f}:{:02.0f}:{:>07.4f}".format(h, m, s) class Timer: """ A context object timer. Usage: >>> with Timer() as timer: ... do_something() >>> print timer.interval """ def __init__(self): self.time = time.time def __enter__(self): self.start = self.time() return self def __exit__(self, *exc): self.finish = self.time() self.interval = self.finish - self.start def __str__(self): return human_readable_time(self.interval)
2,160
638
'''Faça um programa que receba dois números, compare e diga quem é maior. Mostrando a msn qual valor é maior ou menor. OU diga que os valores são iguais.''' print('=+=+=+=+=+=+=+=+='*3) titulo = 'COMPARANDO NÚMEROS MAIOR, MENOR E IGUAL' print('{:^51}'.format(titulo)) print('-----------------'*3) num1 = float(input('Digite o primeiro número: ')) num2 = float(input('Digite o segundo número: ')) if num1 == num2: print('Os números {} e {} são iguais.'.format(num1,num2)) elif num1 > num2: print('O número {} é \033[1;31mMAIOR\033[m que {}.'.format(num1, num2)) elif num1 < num2: print('O número {} é \033[1;34mMAIOR\033[m que {}.'.format(num2, num1)) else: print('Você precisa digitar um número. Tente novamente.') print('=+=+=+=+=+=+=+=+='*3)
760
313
def spam(): global eggs eggs = "spam" # this is the global var def bacon(): eggs = "bacon" # this is a local var def ham(): print(eggs) # this is the global var eggs = 42 # this is the global var spam() print(eggs)
234
86
# Copyright © 2017-2019 Cedric Legrand # # 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, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice (including the next # paragraph) shall be included in all copies or substantial portions of the # Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import logging from typing import Callable, cast, List, Sequence, Union from ehlit.parser.c_header import CDefine, CMacroFunction, CAnyType from ehlit.parser.ast import ( Alias, AnonymousArray, Array, ArrayAccess, Assignment, AST, BoolValue, Cast, Char, ClassMethod, ClassProperty, CompoundIdentifier, Condition, ControlStructure, DecimalNumber, Declaration, Dtor, EhClass, EhEnum, EhUnion, EnumField, Expression, ForDoLoop, FunctionCall, Function, FunctionType, HeapAlloc, HeapDealloc, Identifier, Include, Import, InitializationList, Namespace, Node, NullValue, Number, Operator, PrefixOperatorValue, ReferenceToType, ReferenceToValue, Return, Sizeof, Statement, String, Struct, SuffixOperatorValue, SwitchCase, SwitchCaseBody, SwitchCaseTest, Symbol, TemplatedIdentifier, VariableAssignment, VariableDeclaration ) IndentedFnType = Callable[['DumpWriter', Union[Node, str]], None] def indent(fn: IndentedFnType) -> Callable[..., None]: def fn_wrapper(cls: 'DumpWriter', node: Union[Node, str], is_next: bool = True) -> None: cls.increment_prefix(is_next) fn(cls, node) cls.decrement_prefix() return fn_wrapper class DumpWriter: def __init__(self, ast: AST) -> None: self.prefix: str = '' logging.debug('') logging.debug('--- AST ---') i: int = 0 count: int = len(ast) self.prev_have_next: bool = count > 1 self.upd_prefix: bool = False while i < count: self.print_node(ast[i], i < count - 1) i += 1 def dump(self, string: str) -> None: logging.debug('%s%s', self.prefix, string) def decrement_prefix(self) -> None: self.prefix = self.prefix[:-3] self.upd_prefix = False def increment_prefix(self, is_next: bool) -> None: if self.upd_prefix: self.prefix = self.prefix[:-3] if self.prev_have_next: self.prefix += '\u2502 ' else: self.prefix += ' ' self.upd_prefix = False self.prev_have_next = is_next if is_next: self.prefix += '\u251c' + '\u2500 ' else: self.prefix += '\u2514' + '\u2500 ' self.upd_prefix = True def print_node(self, node: Node, is_next: bool = True) -> None: func = getattr(self, 'dump' + type(node).__name__) func(node, is_next) def print_node_list(self, string: str, lst: Sequence[Node], is_next: bool = True) -> None: self.increment_prefix(is_next) self.dump(string) i: int = 0 cnt: int = len(lst) while i < cnt: self.print_node(lst[i], i < cnt - 1) i += 1 self.decrement_prefix() @indent def print_str(self, s: Union[Node, str]) -> None: s = cast(str, s) self.dump(s) @indent def dumpInclude(self, inc: Union[Node, str]) -> None: inc = cast(Include, inc) self.dump('Include') self.print_str('Path: {}'.format(inc.lib)) self.print_node_list('Symbols found', inc.syms, False) @indent def dumpImport(self, node: Union[Node, str]) -> None: node = cast(Import, node) self.dump('Import') self.print_str('Path: {}'.format(node.lib)) self.print_node_list('Symbols found', node.syms, False) def dump_declaration(self, decl: Union[Node, str], is_next: bool = True) -> None: decl = cast(Declaration, decl) self.print_node(decl.typ_src, decl.sym is not None or is_next) if decl.sym is not None: self.print_node(decl.sym, is_next) def dump_variable_declaration(self, cls_name: str, decl: VariableDeclaration) -> None: self.dump(cls_name) if decl.private: self.print_str('Modifiers: private') if decl.static: self.print_str('Modifiers: static') if decl.assign is not None: self.dump_declaration(decl) self.print_node(decl.assign, False) else: self.dump_declaration(decl, False) @indent def dumpVariableDeclaration(self, decl: Union[Node, str]) -> None: decl = cast(VariableDeclaration, decl) self.dump_variable_declaration('VariableDeclaration', decl) def dump_function(self, cls_name: str, fun: Function) -> None: self.dump(cls_name) if fun.body_str is None: self.print_str('Declaration') if fun.sym is not None: self.print_node(fun.sym) self.dump_qualifiers(fun) self.print_node(fun.typ, fun.body_str is not None) if fun.body_str is not None: self.print_node_list('Body', fun.body, False) @indent def dumpFunction(self, fun: Union[Node, str]) -> None: fun = cast(Function, fun) self.dump_function('Function', fun) @indent def dumpStatement(self, stmt: Union[Node, str]) -> None: stmt = cast(Statement, stmt) self.dump('Statement') self.print_node(stmt.expr, False) def dumpExpression(self, expr: Union[Node, str], is_next: bool) -> None: expr = cast(Expression, expr) self.print_node_list('Expression', expr.contents, is_next) def dumpInitializationList(self, node: Union[Node, str], is_next: bool) -> None: node = cast(InitializationList, node) self.print_node_list('InitializerList', node.contents, is_next) @indent def dumpCast(self, node: Union[Node, str]) -> None: node = cast(Cast, node) self.dump('Cast') self.print_node(node.types[0]) self.print_node(node.arg, False) @indent def dumpFunctionCall(self, call: Union[Node, str]) -> None: call = cast(FunctionCall, call) self.dump('FunctionCall') self.print_node(call.sym) if call.cast: self.increment_prefix(True) self.dump('Automatic cast') self.print_node(call.cast, False) self.decrement_prefix() self.print_node_list('Arguments', call.args, False) @indent def dumpArrayAccess(self, arr: Union[Node, str]) -> None: arr = cast(ArrayAccess, arr) self.dump('ArrayAccess') self.print_node(arr.idx) self.print_node(arr.child, False) @indent def dumpVariableAssignment(self, assign: Union[Node, str]) -> None: assign = cast(VariableAssignment, assign) self.dump('VariableAssignment') self.print_node(assign.var) self.print_node(assign.assign, False) @indent def dumpAssignment(self, assign: Union[Node, str]) -> None: assign = cast(Assignment, assign) self.dump('Assignment') if assign.operator is not None: self.print_node(assign.operator) self.print_node(assign.expr, False) @indent def dumpControlStructure(self, struct: Union[Node, str]) -> None: struct = cast(ControlStructure, struct) self.dump('ControlStructure: ' + struct.name) if struct.cond is not None: self.print_node(struct.cond) self.print_node_list("ControlStructureBody", struct.body, False) def dumpDoWhileLoop(self, node: Union[Node, str], is_next: bool) -> None: self.dumpControlStructure(node, is_next) @indent def dumpForDoLoop(self, node: Union[Node, str]) -> None: node = cast(ForDoLoop, node) self.dump('ControlStructure: ' + node.name) self.print_node(node.cond) self.print_node_list("Initializers", node.initializers) self.print_node_list("Actions", node.actions) self.print_node_list("ControlStructureBody", node.body, False) def dumpCondition(self, cond: Union[Node, str], is_next: bool) -> None: cond = cast(Condition, cond) self.print_node_list("ConditionBranches", cond.branches, is_next) @indent def dumpSwitchCase(self, node: Union[Node, str]) -> None: node = cast(SwitchCase, node) self.dump('Case') self.print_node_list('Tests', node.cases) self.print_node(node.body, False) def dumpSwitchCaseTest(self, node: Union[Node, str], is_next: bool) -> None: node = cast(SwitchCaseTest, node) if node.test is not None: self.print_node(node.test, is_next) else: self.print_str('default', is_next) def dumpSwitchCaseBody(self, node: Union[Node, str], _: bool) -> None: node = cast(SwitchCaseBody, node) self.print_str('Falls through: ' + ('yes' if node.fallthrough else 'no')) self.print_node_list('Body', node.body, False) @indent def dumpReturn(self, ret: Union[Node, str]) -> None: ret = cast(Return, ret) self.dump('Return') if ret.expr is not None: self.print_node(ret.expr, False) def dump_qualifiers(self, node: Union[Symbol, Function]) -> None: qualifiers: List[str] = [] if node.qualifiers.is_const: qualifiers.append('const') if node.qualifiers.is_volatile: qualifiers.append('volatile') if node.qualifiers.is_restricted: qualifiers.append('restrict') if node.qualifiers.is_inline: qualifiers.append('inline') if node.qualifiers.is_private: qualifiers.append('private') if len(qualifiers) != 0: self.print_str('Modifiers: {}'.format(', '.join(qualifiers))) @indent def dumpReferenceToType(self, ref: Union[Node, str]) -> None: ref = cast(ReferenceToType, ref) self.dump('Reference') self.dump_qualifiers(ref) self.print_node(ref.child, False) @indent def dumpReferenceToValue(self, ref: Union[Node, str]) -> None: ref = cast(ReferenceToValue, ref) self.dump('Reference') self.print_node(ref.child, False) @indent def dumpOperator(self, op: Union[Node, str]) -> None: op = cast(Operator, op) self.dump('Operator: ' + op.op) @indent def dumpArray(self, arr: Union[Node, str]) -> None: arr = cast(Array, arr) self.dump('Array') if arr.length is not None: self.print_str('Sub-type:') self.increment_prefix(True) self.print_node(arr.child, False) if arr.length is not None: self.decrement_prefix() self.print_str('Length:', False) self.increment_prefix(False) self.print_node(arr.length, False) self.decrement_prefix() @indent def dumpFunctionType(self, node: Union[Node, str]) -> None: node = cast(FunctionType, node) self.dump('FunctionType') self.print_node(node.ret, len(node.args) != 0 or node.is_variadic) if len(node.args) != 0: self.print_node_list('Arguments:', node.args, node.is_variadic) if node.is_variadic: if node.variadic_type is None: self.print_str('Variadic (C)', False) else: self.print_str('Variadic:', False) self.increment_prefix(False) self.print_node(node.variadic_type, False) self.decrement_prefix() def dumpCompoundIdentifier(self, node: Union[Node, str], is_next: bool) -> None: node = cast(CompoundIdentifier, node) self.increment_prefix(is_next) self.dump('CompoundIdentifier') self.dump_qualifiers(node) i = 0 while i < len(node.elems): self.print_node(node.elems[i], i < len(node.elems) - 1) i += 1 self.decrement_prefix() @indent def dumpIdentifier(self, node: Union[Node, str]) -> None: node = cast(Identifier, node) self.dump('Identifier: ' + node.name) @indent def dumpTemplatedIdentifier(self, node: Union[Node, str]) -> None: node = cast(TemplatedIdentifier, node) self.dump('TemplatedIdentifier: ' + node.name) self.print_node_list('Types', node.types, False) @indent def dumpHeapAlloc(self, node: Union[Node, str]) -> None: node = cast(HeapAlloc, node) self.dump('HeapAlloc') self.print_node(node.sym) self.print_node_list('Arguments', node.args, False) @indent def dumpHeapDealloc(self, node: Union[Node, str]) -> None: node = cast(HeapDealloc, node) self.dump('HeapDealloc') self.print_node(node.sym) @indent def dumpNumber(self, num: Union[Node, str]) -> None: num = cast(Number, num) self.dump('Number: ' + num.num) @indent def dumpDecimalNumber(self, node: Union[Node, str]) -> None: node = cast(DecimalNumber, node) self.dump('DecimalNumber: ' + node.num) @indent def dumpChar(self, char: Union[Node, str]) -> None: char = cast(Char, char) self.dump('Character: ' + char.char) @indent def dumpString(self, string: Union[Node, str]) -> None: string = cast(String, string) self.dump('String: ' + string.string) @indent def dumpNullValue(self, stmt: Union[Node, str]) -> None: stmt = cast(NullValue, stmt) self.dump('NullValue') @indent def dumpBoolValue(self, node: Union[Node, str]) -> None: node = cast(BoolValue, node) self.dump('BoolValue: ' + 'true' if node.val is True else 'false') @indent def dumpPrefixOperatorValue(self, val: Union[Node, str]) -> None: val = cast(PrefixOperatorValue, val) self.dump('PrefixOperatorValue') self.print_str('Operator: %s' % val.op) self.print_node(val.val, False) @indent def dumpSuffixOperatorValue(self, val: Union[Node, str]) -> None: val = cast(SuffixOperatorValue, val) self.dump('SuffixOperatorValue') self.print_str('Operator: %s' % val.op) self.print_node(val.val, False) @indent def dumpAnonymousArray(self, node: Union[Node, str]) -> None: node = cast(AnonymousArray, node) self.dump('AnonymousArray') self.print_node_list('Contents:', node.contents, False) @indent def dumpSizeof(self, node: Union[Node, str]) -> None: node = cast(Sizeof, node) self.dump('Sizeof') self.print_node(node.sz_typ, False) @indent def dumpAlias(self, node: Union[Node, str]) -> None: node = cast(Alias, node) self.dump('Alias') self.print_str('From:') self.increment_prefix(True) self.print_node(node.src_sym, False) self.decrement_prefix() self.print_str('To:', False) self.increment_prefix(False) self.print_node(node.dst, False) self.decrement_prefix() @indent def dumpStruct(self, node: Union[Node, str]) -> None: node = cast(Struct, node) self.dump('Struct') self.print_node(node.sym) if node.fields is None: self.print_str('Forward declaration', False) else: self.print_node_list('Fields', node.fields, False) @indent def dumpEhUnion(self, node: Union[Node, str]) -> None: node = cast(EhUnion, node) self.dump('Union') self.print_node(node.sym) if node.fields is None: self.print_str('Forward declaration', False) else: self.print_node_list('Fields', node.fields, False) @indent def dumpClassMethod(self, node: Union[Node, str]) -> None: node = cast(ClassMethod, node) self.dump_function('ClassMethod', node) @indent def dumpCtor(self, node: Union[Node, str]) -> None: node = cast(ClassMethod, node) self.dump('Constructor') self.dump_qualifiers(node) assert isinstance(node.typ, FunctionType) if len(node.typ.args) != 0: self.print_node_list('Arguments:', node.typ.args) if node.typ.is_variadic: self.print_str('Variadic:') self.increment_prefix(False) assert node.typ.variadic_type is not None self.print_node(node.typ.variadic_type, False) self.decrement_prefix() self.print_node_list('Body', node.body, False) @indent def dumpDtor(self, node: Union[Node, str]) -> None: node = cast(Dtor, node) self.dump('Destructor') self.dump_qualifiers(node) self.print_node_list('Body', node.body, False) @indent def dumpClassProperty(self, node: Union[Node, str]) -> None: node = cast(ClassProperty, node) self.dump_variable_declaration('ClassProperty', node) @indent def dumpEhClass(self, node: Union[Node, str]) -> None: node = cast(EhClass, node) self.dump('Class') self.print_node(node.sym) if node.contents is None: self.print_str('Forward declaration', False) else: self.print_node_list('Properties', node.properties) self.print_node_list('Methods', node.methods, len(node.ctors) != 0) for ctor in node.ctors: self.print_node(ctor, ctor != node.ctors[-1] or node.dtor is not None) if node.dtor is not None: self.print_node(node.dtor, False) @indent def dumpEhEnum(self, node: Union[Node, str]) -> None: node = cast(EhEnum, node) self.dump('Enum') self.print_node(node.sym) if node.fields is None: self.print_str('Forward declaration', False) else: self.print_node_list('Fields', node.fields, False) @indent def dumpEnumField(self, node: Union[Node, str]) -> None: node = cast(EnumField, node) self.dump(node.name) @indent def dumpNamespace(self, node: Union[Node, str]) -> None: node = cast(Namespace, node) self.dump('Namespace') self.print_node(node.sym) self.print_node_list('Contents', node.contents, False) @indent def dumpCDefine(self, node: Union[Node, str]) -> None: node = cast(CDefine, node) self.dump('C define') if node.sym is not None: self.print_node(node.sym, False) @indent def dumpCMacroFunction(self, node: Union[Node, str]) -> None: node = cast(CMacroFunction, node) self.dump('C function macro') if node.sym is not None: self.print_node(node.sym) assert isinstance(node.typ, FunctionType) self.print_str('Arg count: {}'.format(len(node.typ.args)), False) @indent def dumpCAnyType(self, node: Union[Node, str]) -> None: node = cast(CAnyType, node) self.dump('No type')
19,761
6,227
# -*- coding: utf-8 -*- """ 04_Tutorial_Boolean """ # In this tutorial we learn how to do boolean operations between groups of # polygons # Let's import basic stuff import samplemaker.layout as smlay # used for layout import samplemaker.makers as sm # used for drawing # Create a simple mask layout themask = smlay.Mask("04_Tutorial_Boolean") # Empty geometry geomE = sm.GeomGroup() # Let's make a large box box0 = sm.make_rect(0,0,100,100,layer=1) # And some text, because text is complex polygons! text0 = sm.make_text(0, 0, "DIFF", 10, 2,angle=30,to_poly=True,layer=1) # Let's take the boolean difference box-text bdiff = box0.copy() # Note that boolean operations alter the original element so we need to make a copy first bdiff.boolean_difference(text0, 1, 1) # The first integer is the layer from which you should subtract and the second is the subtracted layer # Now bdiff is box-text geomE+=bdiff # Now let's try intersection (AND operation) # Let's use two overlapping texts, slighlty larger text1 = sm.make_text(0,0,"DIFF",11,3,angle=30,to_poly=True,layer=1) text1.boolean_intersection(text0, 1, 1) text1.translate(100, 0) geomE+=text1 # XOR is also quite useful, only keeps parts that are not in both text2 = sm.make_text(50,0,"XOR",10,1,angle=0,to_poly=True,layer=1) text2.boolean_xor(box0, 1, 1) text2.translate(200, 0) geomE+=text2 # Trapezoid slicing, useful for some e-beam export trapz = text2.copy() trapz.trapezoids(1) trapz.translate(150, 0) geomE+=trapz # Union, we could re-unite all trapezoids in the previous uni1 = trapz.copy() uni1.boolean_union(1) uni1.translate(150, 0) geomE+=uni1 # Just for fun, outlining the last result out1 = uni1.copy() out1.poly_outlining(1, 1) out1.translate(150, 0) geomE+=out1 # Let's add all to main cell themask.addToMainCell(geomE) # Export to GDS themask.exportGDS() # Finished!
1,859
743
from tabulate import tabulate def make_table(series_data): table = tabulate(series_data, headers='keys', tablefmt='github') return table def make_data_table_footer(series_metadata): table = tabulate(series_metadata, headers='keys') return table
265
79
"""Test cvejob.version.BenevolentVersion.""" from cvejob.version import BenevolentVersion def test_version_basic(): """Test basic behavior.""" assert BenevolentVersion('1') == BenevolentVersion('1') assert BenevolentVersion('1') != BenevolentVersion('2') assert BenevolentVersion('1') < BenevolentVersion('2') assert BenevolentVersion('1') <= BenevolentVersion('2') assert BenevolentVersion('1') > BenevolentVersion('0') assert BenevolentVersion('1') >= BenevolentVersion('0') assert BenevolentVersion(None) != BenevolentVersion('') assert BenevolentVersion(None) == BenevolentVersion(None) assert BenevolentVersion('0') != BenevolentVersion('') assert BenevolentVersion('') == BenevolentVersion('') assert BenevolentVersion(1) == BenevolentVersion(1) assert BenevolentVersion('Final.RELEASE') == BenevolentVersion('Final.RELEASE') def test_version_trailing_zeros(): """Test with trailing zeros.""" assert BenevolentVersion('1.0.0.0.0') == BenevolentVersion('1.0') assert BenevolentVersion('1.0.1') != BenevolentVersion('1.0.0') assert BenevolentVersion('1.1.0') < BenevolentVersion('1.2.0') assert BenevolentVersion('1.1.0') <= BenevolentVersion('1.2.0') assert BenevolentVersion('1.2.1.1') > BenevolentVersion('1.2.0') assert BenevolentVersion('1.2.1.1') >= BenevolentVersion('1.2.1.0') def test_version_complex(): """More complex tests.""" assert BenevolentVersion('0.3m') == BenevolentVersion('0.3.0') assert BenevolentVersion('0.3m1') == BenevolentVersion('0.3') assert BenevolentVersion('0.3-SNAPSHOT-1') == BenevolentVersion('0.3') assert BenevolentVersion('1.2.Final') == BenevolentVersion('1.2.0') assert BenevolentVersion('1.2.Final.RELEASE') == BenevolentVersion('1.2.0') def test_version_exact(): """Test exact version.""" assert '1.5.0.RELEASE-1' == BenevolentVersion('1.5.0.RELEASE-1').exact def test_version_loose(): """Test loose version.""" assert '1.5' == BenevolentVersion('1.5.0.RELEASE-1').loose def test_hash(): """Test hashing.""" s = { BenevolentVersion('1.0'), BenevolentVersion('1'), BenevolentVersion(None) } assert len(s) == 2 def test_repr(): """Basic test for the __repr__ method.""" v = BenevolentVersion('1.0') assert v.__repr__() == "BenevolentVersion('1.0')" v = BenevolentVersion('1.2.3') assert v.__repr__() == "BenevolentVersion('1.2.3')"
2,472
912
#!/bin/python3 import math import os import random import re import sys import string if __name__ == '__main__': try: t = int(input().strip()) except: print('Invalid input.') if t>=1 and t<=10: for a0 in range(t): s = input().strip() index = 0 if len(s)>=2 and len(s)<=10000: while index<len(s): #Loop should quit when it reaches the last character, which has an index of (length-1) if index<2: odd = s[index] even = s[index + 1] elif index>=2: odd = odd + s[index] #If string length is an odd number loop should stop at the even index #Trying to add another character will give an IndexError if index<len(s)-1: even = even + s[index + 1] index = index + 2 print(odd + ' ' + even) else: print('Constraint error. String is either too long or too short.') a0 = a0 + 1 else: print('Constraint error.')
1,211
326
import sublime, sublime_plugin import os import json class FindAndReplaceByProjectWithExclusions(sublime_plugin.TextCommand): print('reloading FindAndReplaceByProjectWithExclusions') def run(self, edit, from_current_file_path=None): # Текущее окно сублайма window = self.view.window() # В окне - проект, берём его настройки dict_project = window.project_data() # Определим exclusions - безопасным извлечением интересуемой настройки из многоуровнего словаря # через get. exclusions_list = dict_project.get('settings', {}).get("find_and_replace_by_project_with_exclusions") exclusions = None if exclusions_list is not None: exclusions = ', '.join('-' + exclusion for exclusion in exclusions_list) # Определим project_path - первый путь из прикреплённых папок в файле # проекта. sublime_project_file_path = window.project_file_name() is_project = sublime_project_file_path is not None project_path = None if is_project and dict_project is not None and 'folders' in dict_project and dict_project['folders'][0] is not None: relative_first_folder_path = dict_project['folders'][0]['path'] if relative_first_folder_path == '.' or relative_first_folder_path == './': relative_first_folder_path = '' project_path = os.path.join(os.path.dirname(sublime_project_file_path), relative_first_folder_path) # Определим dir_path - путь к директории текущего открытого файла (если # таковой открыт). dir_path = None file_path = self.view.file_name() if file_path is not None: dir_path = os.path.dirname(file_path) # Бизнес логика # Определение пути поиска по исходным данным search_path = "" if from_current_file_path == True and dir_path is not None: search_path = dir_path elif is_project and project_path is not None: search_path = project_path elif is_project: search_path = "<project>" # Дополнение пути поиска исключенем where_string = search_path if exclusions is not None: where_string = search_path + ", " + exclusions # Аргументы для открытия панели panel_args = { "panel": "find_in_files", "regex": False, "where": where_string } # Показываем панель с настройками в panel_args self.view.window().run_command( "show_panel", panel_args )
2,377
781
# Schnell Nautilus Extension # # Place me in ~/.local/share/nautilus-python/extensions/, # ensure you have python-nautilus package, restrart Nautilus, and enjoy :) from gi import require_version require_version('Gtk', '3.0') require_version('Nautilus', '3.0') from gi.repository import Nautilus, GObject from subprocess import call import os # path to schnell schnell = 'schnell' # what name do you want to see in the context menu? schnellname = 'Schnell' # always create new window? NEWWINDOW = False class SchnellExtension(GObject.GObject, Nautilus.MenuProvider): def schnellname(self, menu, files): safepaths = '' for file in files: filepath = file.get_location().get_path() safepaths += '"' + filepath + '" ' # If one of the files we are trying to open is a folder # create a new instance of schnell call(schnell + ' ' + safepaths + '&', shell=True) def get_file_items(self, window, files): item = Nautilus.MenuItem( name='SchnellOpen', label='Open In ' + schnellname, tip='Opens the selected files with Schnell' ) item.connect('activate', self.schnellname, files) return [item] def get_background_items(self, window, file_): item = Nautilus.MenuItem( name='SchnellOpenBackground', label='Open in ' + schnellname, tip='Opens Schnell in the current directory' ) item.connect('activate', self.schnellname, [file_]) return [item]
1,566
474
# Generated by the pRPC protocol buffer compiler plugin. DO NOT EDIT! # source: service.proto import base64 from google.protobuf import descriptor_pb2 # Includes description of the service.proto and all of its transitive # dependencies. Includes source code info. FILE_DESCRIPTOR_SET = descriptor_pb2.FileDescriptorSet() FILE_DESCRIPTOR_SET.ParseFromString(base64.b64decode( 'Co8J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vIHRoZSBpZGVudGlmaWVkIG9mZnNldC4gVGhlIGVuZCBvZmZzZXQgc2hvdWxkIGJl' 'IG9uZSBwYXN0CiB0aGUgbGFzdCByZWxldmFudCBieXRlIChzbyB0aGUgbGVuZ3RoIG9mIHRoZS' 'B0ZXh0ID0gZW5kIC0gYmVnaW4pLgoKFQgECBMIAwgACAIIAwgEELcGEAQQDAoVCAQIEwgDCAAI' 'AggDCAUQtwYQDRASChUIBAgTCAMIAAgCCAMIARC3BhATEBYKFQgECBMIAwgACAIIAwgDELcGEB' 'kQGg==')) _INDEX = { f.name: { 'descriptor': f, 'services': {s.name: s for s in f.service}, } for f in FILE_DESCRIPTOR_SET.file } DiscoveryServiceDescription = { 'file_descriptor_set': FILE_DESCRIPTOR_SET, 'file_descriptor': _INDEX[u'service.proto']['descriptor'], 'service_descriptor': _INDEX[u'service.proto']['services'][u'Discovery'], }
74,548
54,993
from pymongo import MongoClient import random as r import os client = MongoClient(os.environ["MONGO_LAB"]) db = client.get_database("hetmanbot") collection = db['data_base'] class StaticMethods(): @staticmethod def push_record(name, txt, number): records = collection.find_one({"document_id": number}) for i in records[name]: if txt[10:] == str(list(i.values()))[2:-2]: return "Ten cytat już istnieje" else: size = len(records[name]) print(records[name]) collection.update({"document_id": number}, {'$push': {name: {str(size): txt[10:]}}}) print("Dodano nowy cytat") return "Dodano nowy cytat" @staticmethod def get_random_record(name, number): records = collection.find_one({"document_id": number}) for i in records[name]: str(list(i.values()))[2:-2] return str(list(r.choice(records[name]).values())) @staticmethod def get_specific_record(name, number, r_number): records = collection.find_one({"document_id": number}) return str(list(records[name][r_number].values())) @staticmethod def number_of_quotes(name, number): records = collection.find_one({"document_id": number}) size = len(records[name]) return size @staticmethod def replace(string): collection.update({"document_id": 3}, {'$set' : {"plan": string}}) @staticmethod def getPlan(): record = collection.find_one({"document_id": 3}) return record["plan"] @staticmethod def getGame(): record = collection.find_one({"document_id":3}) return record["game"] @staticmethod def setGame(string): collection.update({"document_id": 3},{'$set': {"game": string}})
1,891
566
from django.contrib import admin # Register your models here. from . import models from .models import Article, Comment class ArticleAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['id']}), (None, {'fields': ['title', 'content', 'status']}) ] list_display = ( ['expire_time', 'diary_type', 'square_open', 'add_date', 'mod_date', 'id', 'title', 'content', 'status', 'author_id']) # title = title, # content = content, # square_open = square_open, # expire_time = expire_time, # status = status, # author_id_id = user_id, # diary_type = diary_type, # admin.site.register(Article, ArticleAdmin) admin.site.register(Comment) admin.site.register(Article)
702
234
# - * - coding: utf-8 - * - import numpy as np import pandas as pd import matplotlib.pyplot as plt import scipy.signal from ..signal import signal_smooth from ..signal import signal_zerocrossings def ecg_findpeaks(ecg_cleaned, sampling_rate=1000, method="neurokit", show=False): """Find R-peaks in an ECG signal. Low-level function used by `ecg_peaks()` to identify R-peaks in an ECG signal using a different set of algorithms. See `ecg_peaks()` for details. Parameters ---------- ecg_cleaned : list, array or Series The cleaned ECG channel as returned by `ecg_clean()`. sampling_rate : int The sampling frequency of `ecg_signal` (in Hz, i.e., samples/second). Defaults to 1000. method : string The algorithm to be used for R-peak detection. Can be one of 'neurokit' (default), 'pamtompkins1985', 'hamilton2002', 'christov2004', 'gamboa2008', 'elgendi2010', 'engzeemod2012', 'kalidas2017', 'martinez2003' or 'rodrigues2020'. show : bool If True, will return a plot to visualizing the thresholds used in the algorithm. Useful for debugging. Returns ------- info : dict A dictionary containing additional information, in this case the samples at which R-peaks occur, accessible with the key "ECG_R_Peaks". See Also -------- ecg_clean, signal_fixpeaks, ecg_peaks, ecg_rate, ecg_process, ecg_plot Examples -------- >>> import neurokit2 as nk >>> >>> ecg = nk.ecg_simulate(duration=10, sampling_rate=1000) >>> cleaned = nk.ecg_clean(ecg, sampling_rate=1000) >>> info = nk.ecg_findpeaks(cleaned) >>> nk.events_plot(info["ECG_R_Peaks"], cleaned) >>> >>> # Different methods >>> neurokit = nk.ecg_findpeaks(nk.ecg_clean(ecg, method="neurokit"), method="neurokit") >>> pantompkins1985 = nk.ecg_findpeaks(nk.ecg_clean(ecg, method="pantompkins1985"), method="pantompkins1985") >>> hamilton2002 = nk.ecg_findpeaks(nk.ecg_clean(ecg, method="hamilton2002"), method="hamilton2002") >>> christov2004 = nk.ecg_findpeaks(cleaned, method="christov2004") >>> gamboa2008 = nk.ecg_findpeaks(nk.ecg_clean(ecg, method="gamboa2008"), method="gamboa2008") >>> elgendi2010 = nk.ecg_findpeaks(nk.ecg_clean(ecg, method="elgendi2010"), method="elgendi2010") >>> engzeemod2012 = nk.ecg_findpeaks(nk.ecg_clean(ecg, method="engzeemod2012"), method="engzeemod2012") >>> kalidas2017 = nk.ecg_findpeaks(nk.ecg_clean(ecg, method="kalidas2017"), method="kalidas2017") >>> martinez2003 = nk.ecg_findpeaks(cleaned, method="martinez2003") >>> >>> # Visualize >>> nk.events_plot([neurokit["ECG_R_Peaks"], pantompkins1985["ECG_R_Peaks"], hamilton2002["ECG_R_Peaks"], christov2004["ECG_R_Peaks"], gamboa2008["ECG_R_Peaks"], elgendi2010["ECG_R_Peaks"], engzeemod2012["ECG_R_Peaks"], kalidas2017["ECG_R_Peaks"]], martinez2003["ECG_R_Peaks"]], cleaned) References -------------- - Gamboa, H. (2008). Multi-modal behavioral biometrics based on hci and electrophysiology. PhD ThesisUniversidade. - W. Zong, T. Heldt, G.B. Moody, and R.G. Mark. An open-source algorithm to detect onset of arterial blood pressure pulses. In Computers in Cardiology, 2003, pages 259–262, 2003. - Hamilton, Open Source ECG Analysis Software Documentation, E.P.Limited, 2002. - Jiapu Pan and Willis J. Tompkins. A Real-Time QRS Detection Algorithm. In: IEEE Transactions on Biomedical Engineering BME-32.3 (1985), pp. 230–236. - C. Zeelenberg, A single scan algorithm for QRS detection and feature extraction, IEEE Comp. in Cardiology, vol. 6, pp. 37-42, 1979 - A. Lourenco, H. Silva, P. Leite, R. Lourenco and A. Fred, "Real Time Electrocardiogram Segmentation for Finger Based ECG Biometrics", BIOSIGNALS 2012, pp. 49-54, 2012. """ # Try retrieving right column if isinstance(ecg_cleaned, pd.DataFrame): try: ecg_cleaned = ecg_cleaned["ECG_Clean"] except NameError: try: ecg_cleaned = ecg_cleaned["ECG_Raw"] except NameError: ecg_cleaned = ecg_cleaned["ECG"] method = method.lower() # remove capitalised letters # Run peak detection algorithm if method in ["nk", "nk2", "neurokit", "neurokit2"]: rpeaks = _ecg_findpeaks_neurokit(ecg_cleaned, sampling_rate, show=show) elif method in ["pantompkins", "pantompkins1985"]: rpeaks = _ecg_findpeaks_pantompkins(ecg_cleaned, sampling_rate) elif method in ["gamboa2008", "gamboa"]: rpeaks = _ecg_findpeaks_gamboa(ecg_cleaned, sampling_rate) elif method in ["ssf", "slopesumfunction", "zong", "zong2003"]: rpeaks = _ecg_findpeaks_ssf(ecg_cleaned, sampling_rate) elif method in ["hamilton", "hamilton2002"]: rpeaks = _ecg_findpeaks_hamilton(ecg_cleaned, sampling_rate) elif method in ["christov", "christov2004"]: rpeaks = _ecg_findpeaks_christov(ecg_cleaned, sampling_rate) elif method in ["engzee", "engzee2012", "engzeemod", "engzeemod2012"]: rpeaks = _ecg_findpeaks_engzee(ecg_cleaned, sampling_rate) elif method in ["elgendi", "elgendi2010"]: rpeaks = _ecg_findpeaks_elgendi(ecg_cleaned, sampling_rate) elif method in ["kalidas2017", "swt", "kalidas", "kalidastamil", "kalidastamil2017"]: rpeaks = _ecg_findpeaks_kalidas(ecg_cleaned, sampling_rate) elif method in ["martinez2003", "martinez"]: rpeaks = _ecg_findpeaks_WT(ecg_cleaned, sampling_rate) elif method in ["rodrigues2020", "rodrigues", "asi"]: rpeaks = _ecg_findpeaks_rodrigues(ecg_cleaned, sampling_rate) else: raise ValueError("NeuroKit error: ecg_findpeaks(): 'method' should be " "one of 'neurokit' or 'pamtompkins'.") # Prepare output. info = {"ECG_R_Peaks": rpeaks} return info # ============================================================================= # NeuroKit # ============================================================================= def _ecg_findpeaks_neurokit(signal, sampling_rate=1000, smoothwindow=.1, avgwindow=.75, gradthreshweight=1.5, minlenweight=0.4, mindelay=0.3, show=False): """ All tune-able parameters are specified as keyword arguments. The `signal` must be the highpass-filtered raw ECG with a lowcut of .5 Hz. """ if show is True: fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, sharex=True) # Compute the ECG's gradient as well as the gradient threshold. Run with # show=True in order to get an idea of the threshold. grad = np.gradient(signal) absgrad = np.abs(grad) smooth_kernel = int(np.rint(smoothwindow * sampling_rate)) avg_kernel = int(np.rint(avgwindow * sampling_rate)) smoothgrad = signal_smooth(absgrad, kernel="boxcar", size=smooth_kernel) avggrad = signal_smooth(smoothgrad, kernel="boxcar", size=avg_kernel) gradthreshold = gradthreshweight * avggrad mindelay = int(np.rint(sampling_rate * mindelay)) if show is True: ax1.plot(signal) ax2.plot(smoothgrad) ax2.plot(gradthreshold) # Identify start and end of QRS complexes. qrs = smoothgrad > gradthreshold beg_qrs = np.where(np.logical_and(np.logical_not(qrs[0:-1]), qrs[1:]))[0] end_qrs = np.where(np.logical_and(qrs[0:-1], np.logical_not(qrs[1:])))[0] # Throw out QRS-ends that precede first QRS-start. end_qrs = end_qrs[end_qrs > beg_qrs[0]] # Identify R-peaks within QRS (ignore QRS that are too short). num_qrs = min(beg_qrs.size, end_qrs.size) min_len = np.mean(end_qrs[:num_qrs] - beg_qrs[:num_qrs]) * minlenweight peaks = [0] for i in range(num_qrs): beg = beg_qrs[i] end = end_qrs[i] len_qrs = end - beg if len_qrs < min_len: continue if show is True: ax2.axvspan(beg, end, facecolor="m", alpha=0.5) # Find local maxima and their prominence within QRS. data = signal[beg:end] locmax, props = scipy.signal.find_peaks(data, prominence=(None, None)) if locmax.size > 0: # Identify most prominent local maximum. peak = beg + locmax[np.argmax(props["prominences"])] # Enforce minimum delay between peaks. if peak - peaks[-1] > mindelay: peaks.append(peak) peaks.pop(0) if show is True: ax1.scatter(peaks, signal[peaks], c="r") peaks = np.asarray(peaks).astype(int) # Convert to int return peaks # ============================================================================= # Pan & Tompkins (1985) # ============================================================================= def _ecg_findpeaks_pantompkins(signal, sampling_rate=1000): """ From https://github.com/berndporr/py-ecg-detectors/ - Jiapu Pan and Willis J. Tompkins. A Real-Time QRS Detection Algorithm. In: IEEE Transactions on Biomedical Engineering BME-32.3 (1985), pp. 230–236. """ diff = np.diff(signal) squared = diff * diff N = int(0.12 * sampling_rate) mwa = _ecg_findpeaks_MWA(squared, N) mwa[:int(0.2 * sampling_rate)] = 0 mwa_peaks = _ecg_findpeaks_peakdetect(mwa, sampling_rate) mwa_peaks = np.array(mwa_peaks, dtype='int') return mwa_peaks # ============================================================================= # Hamilton (2002) # ============================================================================= def _ecg_findpeaks_hamilton(signal, sampling_rate=1000): """ From https://github.com/berndporr/py-ecg-detectors/ - Hamilton, Open Source ECG Analysis Software Documentation, E.P.Limited, 2002. """ diff = abs(np.diff(signal)) b = np.ones(int(0.08 * sampling_rate)) b = b/int(0.08 * sampling_rate) a = [1] ma = scipy.signal.lfilter(b, a, diff) ma[0:len(b) * 2] = 0 n_pks = [] n_pks_ave = 0.0 s_pks = [] s_pks_ave = 0.0 QRS = [0] RR = [] RR_ave = 0.0 th = 0.0 i = 0 idx = [] peaks = [] for i in range(len(ma)): if i > 0 and i < len(ma) - 1: if ma[i-1] < ma[i] and ma[i + 1] < ma[i]: peak = i peaks.append(i) if ma[peak] > th and (peak-QRS[-1]) > 0.3 * sampling_rate: QRS.append(peak) idx.append(i) s_pks.append(ma[peak]) if len(n_pks) > 8: s_pks.pop(0) s_pks_ave = np.mean(s_pks) if RR_ave != 0.0: if QRS[-1]-QRS[-2] > 1.5 * RR_ave: missed_peaks = peaks[idx[-2] + 1:idx[-1]] for missed_peak in missed_peaks: if missed_peak - peaks[idx[-2]] > int(0.360 * sampling_rate) and ma[missed_peak] > 0.5 * th: QRS.append(missed_peak) QRS.sort() break if len(QRS) > 2: RR.append(QRS[-1]-QRS[-2]) if len(RR) > 8: RR.pop(0) RR_ave = int(np.mean(RR)) else: n_pks.append(ma[peak]) if len(n_pks) > 8: n_pks.pop(0) n_pks_ave = np.mean(n_pks) th = n_pks_ave + 0.45 * (s_pks_ave-n_pks_ave) i += 1 QRS.pop(0) QRS = np.array(QRS, dtype='int') return QRS # ============================================================================= # Slope Sum Function (SSF) - Zong et al. (2003) # ============================================================================= def _ecg_findpeaks_ssf(signal, sampling_rate=1000, threshold=20, before=0.03, after=0.01): """ From https://github.com/PIA-Group/BioSPPy/blob/e65da30f6379852ecb98f8e2e0c9b4b5175416c3/biosppy/signals/ecg.py#L448 - W. Zong, T. Heldt, G.B. Moody, and R.G. Mark. An open-source algorithm to detect onset of arterial blood pressure pulses. In Computers in Cardiology, 2003, pages 259–262, 2003. """ # TODO: Doesn't really seems to work # convert to samples winB = int(before * sampling_rate) winA = int(after * sampling_rate) Rset = set() length = len(signal) # diff dx = np.diff(signal) dx[dx >= 0] = 0 dx = dx ** 2 # detection idx, = np.nonzero(dx > threshold) idx0 = np.hstack(([0], idx)) didx = np.diff(idx0) # search sidx = idx[didx > 1] for item in sidx: a = item - winB if a < 0: a = 0 b = item + winA if b > length: continue r = np.argmax(signal[a:b]) + a Rset.add(r) # output rpeaks = list(Rset) rpeaks.sort() rpeaks = np.array(rpeaks, dtype='int') return rpeaks # ============================================================================= # Christov (2004) # ============================================================================= def _ecg_findpeaks_christov(signal, sampling_rate=1000): """ From https://github.com/berndporr/py-ecg-detectors/ - Ivaylo I. Christov, Real time electrocardiogram QRS detection using combined adaptive threshold, BioMedical Engineering OnLine 2004, vol. 3:28, 2004. """ total_taps = 0 b = np.ones(int(0.02 * sampling_rate)) b = b/int(0.02 * sampling_rate) total_taps += len(b) a = [1] MA1 = scipy.signal.lfilter(b, a, signal) b = np.ones(int(0.028 * sampling_rate)) b = b/int(0.028 * sampling_rate) total_taps += len(b) a = [1] MA2 = scipy.signal.lfilter(b, a, MA1) Y = [] for i in range(1, len(MA2)-1): diff = abs(MA2[i + 1]-MA2[i-1]) Y.append(diff) b = np.ones(int(0.040 * sampling_rate)) b = b/int(0.040 * sampling_rate) total_taps += len(b) a = [1] MA3 = scipy.signal.lfilter(b, a, Y) MA3[0:total_taps] = 0 ms50 = int(0.05 * sampling_rate) ms200 = int(0.2 * sampling_rate) ms1200 = int(1.2 * sampling_rate) ms350 = int(0.35 * sampling_rate) M = 0 newM5 = 0 M_list = [] MM = [] M_slope = np.linspace(1.0, 0.6, ms1200-ms200) F = 0 F_list = [] R = 0 RR = [] Rm = 0 R_list = [] MFR = 0 MFR_list = [] QRS = [] for i in range(len(MA3)): # M if i < 5 * sampling_rate: M = 0.6 * np.max(MA3[:i + 1]) MM.append(M) if len(MM) > 5: MM.pop(0) elif QRS and i < QRS[-1] + ms200: newM5 = 0.6 * np.max(MA3[QRS[-1]:i]) if newM5 > 1.5 * MM[-1]: newM5 = 1.1 * MM[-1] elif QRS and i == QRS[-1] + ms200: if newM5 == 0: newM5 = MM[-1] MM.append(newM5) if len(MM) > 5: MM.pop(0) M = np.mean(MM) elif QRS and i > QRS[-1] + ms200 and i < QRS[-1] + ms1200: M = np.mean(MM) * M_slope[i-(QRS[-1] + ms200)] elif QRS and i > QRS[-1] + ms1200: M = 0.6 * np.mean(MM) # F if i > ms350: F_section = MA3[i-ms350:i] max_latest = np.max(F_section[-ms50:]) max_earliest = np.max(F_section[:ms50]) F = F + ((max_latest-max_earliest)/150.0) # R if QRS and i < QRS[-1] + int((2.0/3.0 * Rm)): R = 0 elif QRS and i > QRS[-1] + int((2.0/3.0 * Rm)) and i < QRS[-1] + Rm: dec = (M-np.mean(MM))/1.4 R = 0 + dec MFR = M + F + R M_list.append(M) F_list.append(F) R_list.append(R) MFR_list.append(MFR) if not QRS and MA3[i] > MFR: QRS.append(i) elif QRS and i > QRS[-1] + ms200 and MA3[i] > MFR: QRS.append(i) if len(QRS) > 2: RR.append(QRS[-1] - QRS[-2]) if len(RR) > 5: RR.pop(0) Rm = int(np.mean(RR)) QRS.pop(0) QRS = np.array(QRS, dtype='int') return QRS # ============================================================================= # Gamboa (2008) # ============================================================================= def _ecg_findpeaks_gamboa(signal, sampling_rate=1000, tol=0.002): """ From https://github.com/PIA-Group/BioSPPy/blob/e65da30f6379852ecb98f8e2e0c9b4b5175416c3/biosppy/signals/ecg.py#L834 - Gamboa, H. (2008). Multi-modal behavioral biometrics based on hci and electrophysiology. PhD ThesisUniversidade. """ # convert to samples v_100ms = int(0.1 * sampling_rate) v_300ms = int(0.3 * sampling_rate) hist, edges = np.histogram(signal, 100, density=True) TH = 0.01 F = np.cumsum(hist) v0 = edges[np.nonzero(F > TH)[0][0]] v1 = edges[np.nonzero(F < (1 - TH))[0][-1]] nrm = max([abs(v0), abs(v1)]) norm_signal = signal / float(nrm) d2 = np.diff(norm_signal, 2) b = np.nonzero((np.diff(np.sign(np.diff(-d2)))) == -2)[0] + 2 b = np.intersect1d(b, np.nonzero(-d2 > tol)[0]) if len(b) < 3: rpeaks = [] else: b = b.astype('float') rpeaks = [] previous = b[0] for i in b[1:]: if i - previous > v_300ms: previous = i rpeaks.append(np.argmax(signal[int(i):int(i + v_100ms)]) + i) rpeaks = sorted(list(set(rpeaks))) rpeaks = np.array(rpeaks, dtype='int') return rpeaks # ============================================================================= # Engzee Modified (2012) # ============================================================================= def _ecg_findpeaks_engzee(signal, sampling_rate=1000): """ From https://github.com/berndporr/py-ecg-detectors/ - C. Zeelenberg, A single scan algorithm for QRS detection and feature extraction, IEEE Comp. in Cardiology, vol. 6, pp. 37-42, 1979 - A. Lourenco, H. Silva, P. Leite, R. Lourenco and A. Fred, "Real Time Electrocardiogram Segmentation for Finger Based ECG Biometrics", BIOSIGNALS 2012, pp. 49-54, 2012. """ engzee_fake_delay = 0 diff = np.zeros(len(signal)) for i in range(4, len(diff)): diff[i] = signal[i]-signal[i-4] ci = [1, 4, 6, 4, 1] low_pass = scipy.signal.lfilter(ci, 1, diff) low_pass[:int(0.2 * sampling_rate)] = 0 ms200 = int(0.2 * sampling_rate) ms1200 = int(1.2 * sampling_rate) ms160 = int(0.16 * sampling_rate) neg_threshold = int(0.01 * sampling_rate) M = 0 M_list = [] neg_m = [] MM = [] M_slope = np.linspace(1.0, 0.6, ms1200-ms200) QRS = [] r_peaks = [] counter = 0 thi_list = [] thi = False thf_list = [] thf = False for i in range(len(low_pass)): # M if i < 5 * sampling_rate: M = 0.6 * np.max(low_pass[:i + 1]) MM.append(M) if len(MM) > 5: MM.pop(0) elif QRS and i < QRS[-1] + ms200: newM5 = 0.6 * np.max(low_pass[QRS[-1]:i]) if newM5 > 1.5 * MM[-1]: newM5 = 1.1 * MM[-1] elif QRS and i == QRS[-1] + ms200: MM.append(newM5) if len(MM) > 5: MM.pop(0) M = np.mean(MM) elif QRS and i > QRS[-1] + ms200 and i < QRS[-1] + ms1200: M = np.mean(MM) * M_slope[i-(QRS[-1] + ms200)] elif QRS and i > QRS[-1] + ms1200: M = 0.6 * np.mean(MM) M_list.append(M) neg_m.append(-M) if not QRS and low_pass[i] > M: QRS.append(i) thi_list.append(i) thi = True elif QRS and i > QRS[-1] + ms200 and low_pass[i] > M: QRS.append(i) thi_list.append(i) thi = True if thi and i < thi_list[-1] + ms160: if low_pass[i] < -M and low_pass[i-1] > -M: # thf_list.append(i) thf = True if thf and low_pass[i] < -M: thf_list.append(i) counter += 1 elif low_pass[i] > -M and thf: counter = 0 thi = False thf = False elif thi and i > thi_list[-1] + ms160: counter = 0 thi = False thf = False if counter > neg_threshold: unfiltered_section = signal[thi_list[-1] - int(0.01 * sampling_rate):i] r_peaks.append(engzee_fake_delay + np.argmax(unfiltered_section) + thi_list[-1] - int(0.01 * sampling_rate)) counter = 0 thi = False thf = False r_peaks = np.array(r_peaks, dtype='int') return r_peaks # ============================================================================= # Stationary Wavelet Transform (SWT) - Kalidas and Tamil (2017) # ============================================================================= def _ecg_findpeaks_kalidas(signal, sampling_rate=1000): """ From https://github.com/berndporr/py-ecg-detectors/ - Vignesh Kalidas and Lakshman Tamil (2017). Real-time QRS detector using Stationary Wavelet Transform for Automated ECG Analysis. In: 2017 IEEE 17th International Conference on Bioinformatics and Bioengineering (BIBE). Uses the Pan and Tompkins thresolding. """ # Try loading pywt try: import pywt except ImportError: raise ImportError("NeuroKit error: ecg_findpeaks(): the 'PyWavelets' " "module is required for this method to run. ", "Please install it first (`pip install PyWavelets`).") swt_level = 3 padding = -1 for i in range(1000): if (len(signal) + i) % 2 ** swt_level == 0: padding = i break if padding > 0: signal = np.pad(signal, (0, padding), 'edge') elif padding == -1: print("Padding greater than 1000 required\n") swt_ecg = pywt.swt(signal, 'db3', level=swt_level) swt_ecg = np.array(swt_ecg) swt_ecg = swt_ecg[0, 1, :] squared = swt_ecg * swt_ecg f1 = 0.01/sampling_rate f2 = 10/sampling_rate b, a = scipy.signal.butter(3, [f1 * 2, f2 * 2], btype='bandpass') filtered_squared = scipy.signal.lfilter(b, a, squared) filt_peaks = _ecg_findpeaks_peakdetect(filtered_squared, sampling_rate) filt_peaks = np.array(filt_peaks, dtype='int') return filt_peaks # ============================================================================= # Elgendi et al. (2010) # ============================================================================= def _ecg_findpeaks_elgendi(signal, sampling_rate=1000): """ From https://github.com/berndporr/py-ecg-detectors/ - Elgendi, Mohamed & Jonkman, Mirjam & De Boer, Friso. (2010). Frequency Bands Effects on QRS Detection. The 3rd International Conference on Bio-inspired Systems and Signal Processing (BIOSIGNALS2010). 428-431. """ window1 = int(0.12 * sampling_rate) mwa_qrs = _ecg_findpeaks_MWA(abs(signal), window1) window2 = int(0.6 * sampling_rate) mwa_beat = _ecg_findpeaks_MWA(abs(signal), window2) blocks = np.zeros(len(signal)) block_height = np.max(signal) for i in range(len(mwa_qrs)): if mwa_qrs[i] > mwa_beat[i]: blocks[i] = block_height else: blocks[i] = 0 QRS = [] for i in range(1, len(blocks)): if blocks[i-1] == 0 and blocks[i] == block_height: start = i elif blocks[i-1] == block_height and blocks[i] == 0: end = i-1 if end-start > int(0.08 * sampling_rate): detection = np.argmax(signal[start:end + 1]) + start if QRS: if detection-QRS[-1] > int(0.3 * sampling_rate): QRS.append(detection) else: QRS.append(detection) QRS = np.array(QRS, dtype='int') return QRS # ============================================================================= # Continuous Wavelet Transform (CWT) - Martinez et al. (2003) # ============================================================================= # def _ecg_findpeaks_WT(signal, sampling_rate=1000): # Try loading pywt try: import pywt except ImportError: raise ImportError("NeuroKit error: ecg_delineator(): the 'PyWavelets' " "module is required for this method to run. ", "Please install it first (`pip install PyWavelets`).") # first derivative of the Gaissian signal scales = np.array([1, 2, 4, 8, 16]) cwtmatr, freqs = pywt.cwt(signal, scales, 'gaus1', sampling_period=1.0/sampling_rate) # For wt of scale 2^4 signal_4 = cwtmatr[4, :] epsilon_4 = np.sqrt(np.mean(np.square(signal_4))) peaks_4, _ = scipy.signal.find_peaks(np.abs(signal_4), height=epsilon_4) # For wt of scale 2^3 signal_3 = cwtmatr[3, :] epsilon_3 = np.sqrt(np.mean(np.square(signal_3))) peaks_3, _ = scipy.signal.find_peaks(np.abs(signal_3), height=epsilon_3) # Keep only peaks_3 that are nearest to peaks_4 peaks_3_keep = np.zeros_like(peaks_4) for i in range(len(peaks_4)): peaks_distance = abs(peaks_4[i] - peaks_3) peaks_3_keep[i] = peaks_3[np.argmin(peaks_distance)] # For wt of scale 2^2 signal_2 = cwtmatr[2, :] epsilon_2 = np.sqrt(np.mean(np.square(signal_2))) peaks_2, _ = scipy.signal.find_peaks(np.abs(signal_2), height=epsilon_2) # Keep only peaks_2 that are nearest to peaks_3 peaks_2_keep = np.zeros_like(peaks_4) for i in range(len(peaks_4)): peaks_distance = abs(peaks_3_keep[i] - peaks_2) peaks_2_keep[i] = peaks_2[np.argmin(peaks_distance)] # For wt of scale 2^1 signal_1 = cwtmatr[1, :] epsilon_1 = np.sqrt(np.mean(np.square(signal_1))) peaks_1, _ = scipy.signal.find_peaks(np.abs(signal_1), height=epsilon_1) # Keep only peaks_1 that are nearest to peaks_2 peaks_1_keep = np.zeros_like(peaks_4) for i in range(len(peaks_4)): peaks_distance = abs(peaks_2_keep[i] - peaks_1) peaks_1_keep[i] = peaks_1[np.argmin(peaks_distance)] # Find R peaks max_R_peak_dist = int(0.1 * sampling_rate) rpeaks = [] for index_cur, index_next in zip(peaks_1_keep[:-1], peaks_1_keep[1:]): correct_sign = signal_1[index_cur] < 0 and signal_1[index_next] > 0 # limit 1 near = (index_next - index_cur) < max_R_peak_dist # limit 2 if near and correct_sign: rpeaks.append(signal_zerocrossings( signal_1[index_cur:index_next])[0] + index_cur) rpeaks = np.array(rpeaks, dtype='int') return rpeaks # ============================================================================= # ASI (FSM based 2020) # ============================================================================= def _ecg_findpeaks_rodrigues(signal, sampling_rate=1000): """ Segmenter by Tiago Rodrigues, inspired by on Gutierrez-Rivas (2015) and Sadhukhan (2012). References ---------- - Gutiérrez-Rivas, R., García, J. J., Marnane, W. P., & Hernández, A. (2015). Novel real-time low-complexity QRS complex detector based on adaptive thresholding. IEEE Sensors Journal, 15(10), 6036-6043. - Sadhukhan, D., & Mitra, M. (2012). R-peak detection algorithm for ECG using double difference and RR interval processing. Procedia Technology, 4, 873-877. """ N = int(np.round(3 * sampling_rate/128)) Nd = N-1 Pth = (0.7 * sampling_rate) / 128+2.7 # Pth = 3, optimal for fs = 250 Hz Rmin = 0.26 rpeaks = [] i = 1 tf = len(signal) Ramptotal = 0 # Double derivative squared diff_ecg = [signal[i] - signal[i - Nd] for i in range(Nd, len(signal))] ddiff_ecg = [diff_ecg[i] - diff_ecg[i - 1] for i in range(1, len(diff_ecg))] squar = np.square(ddiff_ecg) # Integrate moving window b = np.array(np.ones(N)) a = [1] processed_ecg = scipy.signal.lfilter(b, a, squar) # R-peak finder FSM while i < tf - sampling_rate: # ignore last second of recording # State 1: looking for maximum tf1 = np.round(i + Rmin*sampling_rate) Rpeakamp = 0 while i < tf1: # Rpeak amplitude and position if processed_ecg[i] > Rpeakamp: Rpeakamp = processed_ecg[i] rpeakpos = i + 1 i += 1 Ramptotal = (19 / 20) * Ramptotal + (1 / 20) * Rpeakamp rpeaks.append(rpeakpos) # State 2: waiting state d = tf1 - rpeakpos tf2 = i + np.round(0.2*2 - d) while i <= tf2: i += 1 # State 3: decreasing threshold Thr = Ramptotal while processed_ecg[i] < Thr: Thr = Thr * np.exp(-Pth / sampling_rate) i += 1 return rpeaks # ============================================================================= # Utilities # ============================================================================= def _ecg_findpeaks_MWA(signal, window_size): """ From https://github.com/berndporr/py-ecg-detectors/ """ mwa = np.zeros(len(signal)) sums = np.cumsum(signal) def get_mean(begin, end): if begin == 0: return sums[end - 1] / end dif = sums[end - 1] - sums[begin - 1] return dif / (end - begin) for i in range(len(signal)): if i < window_size: section = signal[0:i] else: section = get_mean(i - window_size, i) if i != 0: mwa[i] = np.mean(section) else: mwa[i] = signal[i] return mwa def _ecg_findpeaks_peakdetect(detection, sampling_rate=1000): """ From https://github.com/berndporr/py-ecg-detectors/ """ min_distance = int(0.25 * sampling_rate) signal_peaks = [0] noise_peaks = [] SPKI = 0.0 NPKI = 0.0 threshold_I1 = 0.0 threshold_I2 = 0.0 RR_missed = 0 index = 0 indexes = [] missed_peaks = [] peaks = [] for i in range(len(detection)): if i > 0 and i < len(detection) - 1: if detection[i-1] < detection[i] and detection[i + 1] < detection[i]: peak = i peaks.append(i) if detection[peak] > threshold_I1 and (peak - signal_peaks[-1]) > 0.3 * sampling_rate: signal_peaks.append(peak) indexes.append(index) SPKI = 0.125 * detection[signal_peaks[-1]] + 0.875 * SPKI if RR_missed != 0: if signal_peaks[-1] - signal_peaks[-2] > RR_missed: missed_section_peaks = peaks[indexes[-2] + 1:indexes[-1]] missed_section_peaks2 = [] for missed_peak in missed_section_peaks: if missed_peak - signal_peaks[-2] > min_distance and signal_peaks[-1] - missed_peak > min_distance and detection[missed_peak] > threshold_I2: missed_section_peaks2.append(missed_peak) if len(missed_section_peaks2) > 0: missed_peak = missed_section_peaks2[np.argmax(detection[missed_section_peaks2])] missed_peaks.append(missed_peak) signal_peaks.append(signal_peaks[-1]) signal_peaks[-2] = missed_peak else: noise_peaks.append(peak) NPKI = 0.125 * detection[noise_peaks[-1]] + 0.875 * NPKI threshold_I1 = NPKI + 0.25 * (SPKI - NPKI) threshold_I2 = 0.5 * threshold_I1 if len(signal_peaks) > 8: RR = np.diff(signal_peaks[-9:]) RR_ave = int(np.mean(RR)) RR_missed = int(1.66 * RR_ave) index = index + 1 signal_peaks.pop(0) return signal_peaks
32,545
12,299
import inspect import sys from enum import IntEnum from tflite.ActivationFunctionType import ActivationFunctionType from tflite.BuiltinOperator import BuiltinOperator # In Python 3.6, we cannot make ExtendedOperator derive from IntEnum if sys.version_info >= (3, 7): bases = (IntEnum, ) else: bases = () class _ExtendedOperatorBase(BuiltinOperator, *bases): INPUT_NODE = -1 OUTPUT_NODE = -2 CONSTANT_NODE = -3 BATCH_NORM = -10 GENERIC_CONV = -11 GENERIC_DECONV = -12 def type_name(self): return self.name.replace('_NODE', '') # In Python 3.6, the elements in the parent class are not collected in IntEnum, # so we have to do that dynamically. if sys.version_info >= (3, 7): ExtendedOperator = _ExtendedOperatorBase else: ExtendedOperator = IntEnum('ExtendedOperator', dict( filter(lambda x: not x[0].startswith('__'), inspect.getmembers(_ExtendedOperatorBase)))) FUSE_ACTIVATION_MAP = {BuiltinOperator.RELU: ActivationFunctionType.RELU, BuiltinOperator.RELU6: ActivationFunctionType.RELU6, BuiltinOperator.TANH: ActivationFunctionType.TANH}
1,157
387
PACKAGE_NAME = 'mkdocs_markmap' PROJECT_NAME = PACKAGE_NAME.replace('_', '-') PROJECT_VERSION = '2.1.3' OWNER = 'neatc0der' REPOSITORY_NAME = f'{OWNER}/{PROJECT_NAME}'
169
78
from django.conf.urls import url from rest_framework.routers import DefaultRouter from apps.homes import views urlpatterns = [ url(r'^areas/$', views.AreaAPIView.as_view()), # url(r'^houses/$', views.HouseAPIView.as_view()), # 我的房屋列表 url(r'^user/houses/$', views.HouseListView.as_view()), # 首页房屋模块 url(r'^houses/index/$', views.HouseIndexView.as_view()), # 房屋详情页面 url(r'^houses/(?P<house_id>\d+)/$', views.HouseDetailView.as_view()), ] router = DefaultRouter() # # 首页房屋推荐 # router.register(r'houses/index', views.HouseIndexViewSet, basename='index') # urlpatterns += router.urls # 发布房源 房屋数据搜索 router.register(r'houses', views.HouseAPIView, basename='houses') urlpatterns += router.urls # 上传房源图片 router.register(r'houses/(?P<house_id>\d+)/images', views.HouseImageView, basename='images') urlpatterns += router.urls
852
352
class Rules: def __init__(self): self.ONE_ONE_SCORE = 100 self.ONE_FIVE_SCORE = 50 self.STRAIGHT_SCORE = 1500 self.THREE_PAIR_SCORE = 1000 class Alternate(Rules): def __init__(self): self.STRAIGHT_SCORE = 2500 self.THREE_PAIR_SCORE = 2000
294
148
import socket import ssl import sys hostname = '127.0.0.1' if len(sys.argv) < 2: exit(0) inputfile = sys.argv[1] print('\tRead file %s' % inputfile) # msg = b"HEAD / HTTP /1.0\r\nHost: linuxfr.org\r\n\r\n" msg = open(inputfile).read() msg = bytes(msg.encode()) context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) context.load_verify_locations('rootCA.pem') with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock: with context.wrap_socket(sock, server_hostname=hostname) as ssock: ssock.connect((hostname, 8443)) # cert = ssock.getpeercert() ssock.sendall(msg) print('\tSent %s .+' % msg[:10])
646
261
class Solution: def removeDuplicates(self, s: str, k: int) -> str: """Stack. Running time: O(n) where n is the length of s. """ st = [['#', 0]] for c in s: if st[-1][0] == c: st[-1][1] += 1 if st[-1][1] == k: st.pop() else: st.append([c, 1]) return ''.join([i[0] * i[1] for i in st])
429
148
from typing import Callable class Item(Action): """ Items are Actions that can be transferred to another Player """ def __init__(self, name, function: Callable[[Player], None]): super().__init__(name, function) class Knife(Item): def __init__(self): super().__init__("Knife", lambda player: player.die())
345
101
import numpy as np from scipy.misc import imread, imsave from scipy import ndimage img = imread('doc1.bmp') def f(x): ret = x * 255 / 150 if ret > 255: ret = 255 return ret F = np.vectorize(f) treated_img = F(img) imsave('treated_doc.bmp', treated_img) mask = treated_img < treated_img.mean() label_im, nb_labels = ndimage.label(mask) sizes = ndimage.sum(mask, label_im, range(nb_labels + 1)) print(nb_labels) print(sum(sizes > 1)) print(sum(sizes > 2)) print(sum(sizes > 5)) print(sum(sizes > 10))
528
235
def connect(node1, node2): node1.connect(node2) node2.connect(node1)
72
30
import os from dotenv import load_dotenv import sqlite3 import psycopg2 from psycopg2.extras import execute_values load_dotenv() # looks inside the .env file for some env vars # passes env var values to python var DB_HOST = os.getenv("DB_HOST", default="OOPS") DB_NAME = os.getenv("DB_NAME", default="OOPS") DB_USER = os.getenv("DB_USER", default="OOPS") DB_PASSWORD = os.getenv("DB_PASSWORD", default="OOPS") # what is the filepath to connect to our sqlite database? DB_FILEPATH = os.path.join(os.path.dirname(__file__), "..", "module1-introduction-to-sql", "rpg_db.sqlite3") class SqliteService_thief(): def __init__(self, db_filepath=DB_FILEPATH): self.connection = sqlite3.connect(db_filepath) self.cursor = self.connection.cursor() def fetch_characters_thief(self): return self.cursor.execute("SELECT * FROM charactercreator_thief;").fetchall() class ElephantSQLService_thief(): def __init__(self): self.connection = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASSWORD, host=DB_HOST) self.cursor = self.connection.cursor() def create_characters_thief_table(self): create_query = """ DROP TABLE IF EXISTS characters_thief; -- allows this to be run idempotently, avoids psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "characters_thief_pkey" DETAIL: Key (character_id)=(1) already exists. CREATE TABLE IF NOT EXISTS characters_thief ( character_ptr_id INT, is_sneaking INT, energy INT ); """ print(create_query) self.cursor.execute(create_query) self.connection.commit() def insert_characters_thief(self, characters_thief): """ Param characters_thief needs to be a list of tuples, each representing a row to insert (each should have each column) """ insertion_query = """ INSERT INTO characters_thief (character_ptr_id, is_sneaking, energy) VALUES %s """ execute_values(self.cursor, insertion_query, characters_thief) self.connection.commit() if __name__ == "__main__": # # EXTRACT (AND MAYBE TRANSFORM IF NECESSARY) # sqlite_service = SqliteService_thief() characters_thief = sqlite_service.fetch_characters_thief() print(type(characters_thief), len(characters_thief)) print(type(characters_thief[0]), characters_thief[0]) # # LOAD # pg_service = ElephantSQLService_thief() pg_service.create_characters_thief_table() pg_service.insert_characters_thief(characters_thief)
2,617
825
#: L23 Port Transceiver Commands from dataclasses import dataclass import typing from ..protocol.command_builders import ( build_get_request, build_set_request ) from .. import interfaces from ..transporter.token import Token from ..protocol.fields.data_types import * from ..protocol.fields.field import XmpField from ..registry import register_command from .enums import * @register_command @dataclass class PX_RW: """ Provides access to the register interface supported by the port transceiver. It is possible to both read and write register values. """ code: typing.ClassVar[int] = 501 pushed: typing.ClassVar[bool] = False _connection: "interfaces.IConnection" _module: int _port: int _page_xindex: int _register_xaddress: int @dataclass(frozen=True) class SetDataAttr: value: XmpField[XmpHex4] = XmpField(XmpHex4) # 4 hex bytes, register value of the port transceiver @dataclass(frozen=True) class GetDataAttr: value: XmpField[XmpHex4] = XmpField(XmpHex4) # 4 hex bytes, register value of the port transceiver def get(self) -> "Token[GetDataAttr]": """Get the register value of a transceiver. :return: the register value of a transceiver :rtype: PX_RW.GetDataAttr """ return Token(self._connection, build_get_request(self, module=self._module, port=self._port, indices=[self._page_xindex, self._register_xaddress])) def set(self, value: str) -> "Token": """Set the register value of a transceiver. :param value: register value of a transceiver :type value: str """ return Token(self._connection, build_set_request(self, module=self._module, port=self._port, indices=[self._page_xindex, self._register_xaddress], value=value)) @register_command @dataclass class PX_MII: """Provides access to the register interface supported by the media-independent interface (MII) transceiver. It is possible to both read and write register values.""" code: typing.ClassVar[int] = 537 pushed: typing.ClassVar[bool] = False _connection: "interfaces.IConnection" _module: int _port: int _register_xaddress: int @dataclass(frozen=True) class SetDataAttr: value: XmpField[XmpHex2] = XmpField(XmpHex2) # 2 hex bytes, register value of the transceiver @dataclass(frozen=True) class GetDataAttr: value: XmpField[XmpHex2] = XmpField(XmpHex2) # 2 hex bytes, register value of the transceiver def get(self) -> "Token[GetDataAttr]": """Get the register value of a transceiver. :return: the register value of a transceiver :rtype: PX_MII.GetDataAttr """ return Token(self._connection, build_get_request(self, module=self._module, port=self._port, indices=[self._register_xaddress])) def set(self, value: str) -> "Token": """Set the register value of a transceiver. :param value: register value of a transceiver :type value: str """ return Token(self._connection, build_set_request(self, module=self._module, port=self._port, indices=[self._register_xaddress], value=value)) @register_command @dataclass class PX_TEMPERATURE: """ Transceiver temperature in degrees Celsius. """ code: typing.ClassVar[int] = 538 pushed: typing.ClassVar[bool] = True _connection: "interfaces.IConnection" _module: int _port: int @dataclass(frozen=True) class GetDataAttr: temperature_msb: XmpField[XmpByte] = XmpField(XmpByte) # byte, temperature value before the decimal digit. temperature_decimal_fraction: XmpField[XmpByte] = XmpField(XmpByte) # byte, 1/256th of a degree Celsius after the decimal digit. def get(self) -> "Token[GetDataAttr]": """Get transceiver temperature in degrees Celsius. :return: temperature value before the decimal digit, and 1/256th of a degree Celsius after the decimal digit. :rtype: PX_TEMPERATURE.GetDataAttr """ return Token(self._connection, build_get_request(self, module=self._module, port=self._port))
4,161
1,316
# Copyright (c) 2020, NVIDIA CORPORATION. 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 applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: nvidia/clara/platform/node-monitor/metrics.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from nvidia_clara.grpc import common_pb2 as nvidia_dot_clara_dot_platform_dot_common__pb2 from nvidia_clara.grpc.common_pb2 import * DESCRIPTOR = _descriptor.FileDescriptor( name='nvidia/clara/platform/node-monitor/metrics.proto', package='nvidia.clara.platform.node_monitor', syntax='proto3', serialized_options=_b('\n%com.nvidia.clara.platform.nodemonitorZ\004apis\252\002&Nvidia.Clara.Platform.NodeMonitor.Grpc'), serialized_pb=_b('\n0nvidia/clara/platform/node-monitor/metrics.proto\x12\"nvidia.clara.platform.node_monitor\x1a\"nvidia/clara/platform/common.proto\"\xbb\x02\n\nGpuDetails\x12\x11\n\tdevice_id\x18\x01 \x01(\x05\x12G\n\x04\x64\x61ta\x18\x02 \x01(\x0b\x32\x39.nvidia.clara.platform.node_monitor.GpuDetails.GpuMetrics\x12\x33\n\ttimestamp\x18\x03 \x01(\x0b\x32 .nvidia.clara.platform.Timestamp\x1a\x9b\x01\n\nGpuMetrics\x12\x1a\n\x12memory_utilization\x18\x01 \x01(\x02\x12\x17\n\x0fgpu_utilization\x18\x02 \x01(\x02\x12\x12\n\nfree_bar_1\x18\x03 \x01(\x03\x12\x12\n\nused_bar_1\x18\x04 \x01(\x03\x12\x17\n\x0f\x66ree_gpu_memory\x18\x05 \x01(\x03\x12\x17\n\x0fused_gpu_memory\x18\x06 \x01(\x03\"P\n\x18MonitorGpuMetricsRequest\x12\x34\n\x06header\x18\x01 \x01(\x0b\x32$.nvidia.clara.platform.RequestHeader\"\x97\x01\n\x19MonitorGpuMetricsResponse\x12\x35\n\x06header\x18\x01 \x01(\x0b\x32%.nvidia.clara.platform.ResponseHeader\x12\x43\n\x0bgpu_details\x18\x02 \x03(\x0b\x32..nvidia.clara.platform.node_monitor.GpuDetails2\x97\x01\n\x07Monitor\x12\x8b\x01\n\nGpuMetrics\x12<.nvidia.clara.platform.node_monitor.MonitorGpuMetricsRequest\x1a=.nvidia.clara.platform.node_monitor.MonitorGpuMetricsResponse0\x01\x42V\n%com.nvidia.clara.platform.nodemonitorZ\x04\x61pis\xaa\x02&Nvidia.Clara.Platform.NodeMonitor.GrpcP\x00\x62\x06proto3') , dependencies=[nvidia_dot_clara_dot_platform_dot_common__pb2.DESCRIPTOR,], public_dependencies=[nvidia_dot_clara_dot_platform_dot_common__pb2.DESCRIPTOR,]) _GPUDETAILS_GPUMETRICS = _descriptor.Descriptor( name='GpuMetrics', full_name='nvidia.clara.platform.node_monitor.GpuDetails.GpuMetrics', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='memory_utilization', full_name='nvidia.clara.platform.node_monitor.GpuDetails.GpuMetrics.memory_utilization', index=0, number=1, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='gpu_utilization', full_name='nvidia.clara.platform.node_monitor.GpuDetails.GpuMetrics.gpu_utilization', index=1, number=2, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='free_bar_1', full_name='nvidia.clara.platform.node_monitor.GpuDetails.GpuMetrics.free_bar_1', index=2, number=3, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='used_bar_1', full_name='nvidia.clara.platform.node_monitor.GpuDetails.GpuMetrics.used_bar_1', index=3, number=4, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='free_gpu_memory', full_name='nvidia.clara.platform.node_monitor.GpuDetails.GpuMetrics.free_gpu_memory', index=4, number=5, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='used_gpu_memory', full_name='nvidia.clara.platform.node_monitor.GpuDetails.GpuMetrics.used_gpu_memory', index=5, number=6, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=285, serialized_end=440, ) _GPUDETAILS = _descriptor.Descriptor( name='GpuDetails', full_name='nvidia.clara.platform.node_monitor.GpuDetails', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='device_id', full_name='nvidia.clara.platform.node_monitor.GpuDetails.device_id', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data', full_name='nvidia.clara.platform.node_monitor.GpuDetails.data', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='timestamp', full_name='nvidia.clara.platform.node_monitor.GpuDetails.timestamp', index=2, number=3, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[_GPUDETAILS_GPUMETRICS, ], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=125, serialized_end=440, ) _MONITORGPUMETRICSREQUEST = _descriptor.Descriptor( name='MonitorGpuMetricsRequest', full_name='nvidia.clara.platform.node_monitor.MonitorGpuMetricsRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='header', full_name='nvidia.clara.platform.node_monitor.MonitorGpuMetricsRequest.header', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=442, serialized_end=522, ) _MONITORGPUMETRICSRESPONSE = _descriptor.Descriptor( name='MonitorGpuMetricsResponse', full_name='nvidia.clara.platform.node_monitor.MonitorGpuMetricsResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='header', full_name='nvidia.clara.platform.node_monitor.MonitorGpuMetricsResponse.header', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='gpu_details', full_name='nvidia.clara.platform.node_monitor.MonitorGpuMetricsResponse.gpu_details', index=1, number=2, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=525, serialized_end=676, ) _GPUDETAILS_GPUMETRICS.containing_type = _GPUDETAILS _GPUDETAILS.fields_by_name['data'].message_type = _GPUDETAILS_GPUMETRICS _GPUDETAILS.fields_by_name['timestamp'].message_type = nvidia_dot_clara_dot_platform_dot_common__pb2._TIMESTAMP _MONITORGPUMETRICSREQUEST.fields_by_name['header'].message_type = nvidia_dot_clara_dot_platform_dot_common__pb2._REQUESTHEADER _MONITORGPUMETRICSRESPONSE.fields_by_name['header'].message_type = nvidia_dot_clara_dot_platform_dot_common__pb2._RESPONSEHEADER _MONITORGPUMETRICSRESPONSE.fields_by_name['gpu_details'].message_type = _GPUDETAILS DESCRIPTOR.message_types_by_name['GpuDetails'] = _GPUDETAILS DESCRIPTOR.message_types_by_name['MonitorGpuMetricsRequest'] = _MONITORGPUMETRICSREQUEST DESCRIPTOR.message_types_by_name['MonitorGpuMetricsResponse'] = _MONITORGPUMETRICSRESPONSE _sym_db.RegisterFileDescriptor(DESCRIPTOR) GpuDetails = _reflection.GeneratedProtocolMessageType('GpuDetails', (_message.Message,), dict( GpuMetrics = _reflection.GeneratedProtocolMessageType('GpuMetrics', (_message.Message,), dict( DESCRIPTOR = _GPUDETAILS_GPUMETRICS, __module__ = 'nvidia.clara.platform.node_monitor.metrics_pb2' # @@protoc_insertion_point(class_scope:nvidia.clara.platform.node_monitor.GpuDetails.GpuMetrics) )) , DESCRIPTOR = _GPUDETAILS, __module__ = 'nvidia.clara.platform.node_monitor.metrics_pb2' # @@protoc_insertion_point(class_scope:nvidia.clara.platform.node_monitor.GpuDetails) )) _sym_db.RegisterMessage(GpuDetails) _sym_db.RegisterMessage(GpuDetails.GpuMetrics) MonitorGpuMetricsRequest = _reflection.GeneratedProtocolMessageType('MonitorGpuMetricsRequest', (_message.Message,), dict( DESCRIPTOR = _MONITORGPUMETRICSREQUEST, __module__ = 'nvidia.clara.platform.node_monitor.metrics_pb2' # @@protoc_insertion_point(class_scope:nvidia.clara.platform.node_monitor.MonitorGpuMetricsRequest) )) _sym_db.RegisterMessage(MonitorGpuMetricsRequest) MonitorGpuMetricsResponse = _reflection.GeneratedProtocolMessageType('MonitorGpuMetricsResponse', (_message.Message,), dict( DESCRIPTOR = _MONITORGPUMETRICSRESPONSE, __module__ = 'nvidia.clara.platform.node_monitor.metrics_pb2' # @@protoc_insertion_point(class_scope:nvidia.clara.platform.node_monitor.MonitorGpuMetricsResponse) )) _sym_db.RegisterMessage(MonitorGpuMetricsResponse) DESCRIPTOR._options = None _MONITOR = _descriptor.ServiceDescriptor( name='Monitor', full_name='nvidia.clara.platform.node_monitor.Monitor', file=DESCRIPTOR, index=0, serialized_options=None, serialized_start=679, serialized_end=830, methods=[ _descriptor.MethodDescriptor( name='GpuMetrics', full_name='nvidia.clara.platform.node_monitor.Monitor.GpuMetrics', index=0, containing_service=None, input_type=_MONITORGPUMETRICSREQUEST, output_type=_MONITORGPUMETRICSRESPONSE, serialized_options=None, ), ]) _sym_db.RegisterServiceDescriptor(_MONITOR) DESCRIPTOR.services_by_name['Monitor'] = _MONITOR # @@protoc_insertion_point(module_scope)
12,991
5,072
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy class YunqiBookListItem(scrapy.Item): novelId = scrapy.Field() novelName = scrapy.Field() novelLink = scrapy.Field() novelAuthor = scrapy.Field() novelType = scrapy.Field() novelStatus = scrapy.Field() novelUpdateTime = scrapy.Field() novelWords = scrapy.Field() novelImageUrl = scrapy.Field() class YunqiBookDetailItem(scrapy.Item): novelId = scrapy.Field() novelLabel =scrapy.Field() novelAllClick = scrapy.Field() novelMonthClick = scrapy.Field() novelWeekClick = scrapy.Field() novelAllPopular = scrapy.Field() novelMonthPopular = scrapy.Field() novelWeekPopular = scrapy.Field() novelCommentNum = scrapy.Field() novelAllComm = scrapy.Field() novelMonthComm = scrapy.Field() novelWeekComm = scrapy.Field()
964
321
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.model_selection import StratifiedKFold, KFold def cv_index(n_fold, feature, label): skf = KFold(n_fold, shuffle=True, random_state=7840) index_list = [] for i, j in skf.split(feature, label): index_list.append((i, j)) return index_list def data_selector(data_name): if data_name == 'cmc': return x_train_cmc, x_test_cmc, y_train_cmc, y_test_cmc, index_cmc elif data_name == 'setap': return x_train_setap, x_test_setap, y_train_setap, y_test_setap, index_setap elif data_name == 'audit': return x_train_audit, x_test_audit, y_train_audit, y_test_audit, index_audit elif data_name == 'titanic': return x_train_tt, x_test_tt, y_train_tt, y_test_tt, index_tt elif data_name == 'dota': return x_train_dota, x_test_dota, y_train_dota, y_test_dota, index_dota no_of_folds = 3 # Dataset cmc data_cmc = pd.read_csv("data/cmc.data", header=None) data_cmc[9] = np.where(data_cmc[9] == 1, 0, 1) data_cmc_label = data_cmc.pop(9) x_train_cmc, x_test_cmc, y_train_cmc, y_test_cmc = train_test_split(data_cmc, data_cmc_label, random_state=7840, test_size=0.25) index_cmc = cv_index(no_of_folds, x_train_cmc, y_train_cmc) # Dataset SETAP data_setap = pd.read_csv("data/setap.csv") data_setap['label'] = np.where(data_setap['label'] == 'A', 0, 1) data_setap_label = data_setap.pop('label') x_train_setap, x_test_setap, y_train_setap, y_test_setap = train_test_split(data_setap, data_setap_label, random_state=7840, test_size=0.25) index_setap = cv_index(no_of_folds, x_train_setap, y_train_setap) # Dataset audit data_audit = pd.read_csv("data/audit_risk.csv") data_audit['LOCATION_ID'] = pd.to_numeric(data_audit['LOCATION_ID'], errors='coerce') data_audit['LOCATION_ID'] = data_audit['LOCATION_ID'].fillna(data_audit['LOCATION_ID'].mode()[0]) data_audit['Money_Value'] = data_audit['Money_Value'].fillna(data_audit['Money_Value'].mean()) data_audit_label = data_audit.pop('Risk') x_train_audit, x_test_audit, y_train_audit, y_test_audit = train_test_split(data_audit, data_audit_label, random_state=7840, test_size=0.25,) index_audit = cv_index(no_of_folds, x_train_audit, y_train_audit) # Dataset titanic data_tt = pd.read_csv("data/titanic_train.csv") data_tt['Age'] = data_tt['Age'].fillna(data_tt['Age'].mean()) data_tt['Embarked'] = data_tt['Embarked'].fillna(data_tt['Embarked'].mode()[0]) data_tt['Pclass'] = data_tt['Pclass'].apply(str) for col in data_tt.dtypes[data_tt.dtypes == 'object'].index: for_dummy = data_tt.pop(col) data_tt = pd.concat([data_tt, pd.get_dummies(for_dummy, prefix=col)], axis=1) data_tt_labels = data_tt.pop('Survived') x_train_tt, x_test_tt, y_train_tt, y_test_tt = train_test_split(data_tt, data_tt_labels, random_state=7840, test_size=0.25) index_tt = cv_index(no_of_folds, x_train_tt, y_train_tt) # Dataset DotA2 x_train_dota = pd.read_csv("data/dota2Train.csv", header=None) x_train_dota[0] = np.where(x_train_dota[0] == 1, 1, 0) y_train_dota = x_train_dota.pop(0) x_test_dota = pd.read_csv("data/dota2Test.csv", header=None) x_test_dota[0] = np.where(x_test_dota[0] == 1, 1, 0) y_test_dota = x_test_dota.pop(0) index_dota = cv_index(no_of_folds, x_train_dota, y_train_dota) # for train_index, test_index in skf.split(x_train, y_train): # train_feature, test_feature = x_train.iloc[train_index], x_train.iloc[test_index] # train_label, test_label = y_train.iloc[train_index], y_train.iloc[test_index] # print(train_gbm(train_feature, train_label, test_feature, test_label)) # skf = KFold(5) # train_index = [] # test_index = [] # index_list = [] # for i, j in skf.split(x_train_cmc, y_train_cmc): # index_list.append((i, j))
4,626
1,723
# coding: utf-8 from flask.ext import wtf import flask import wtforms import auth import config import model import util from main import app ############################################################################### # Admin Stuff ############################################################################### @app.route('/admin/') @auth.admin_required def admin(): return flask.render_template( 'admin/dashboard/dashboard.html', title='Admin', html_class='admin', )
502
128
from datetime import datetime from django.views.generic.base import TemplateView from django.shortcuts import get_object_or_404, render from django.urls import reverse from .models import MONTH_DICT, MONTH_LIST, YEARS,CARRIER_LIST from .forms import BSfilterForm from .main import _init_SCRAPER class HomePageView(TemplateView): template_name = "base.html" class IndexView(TemplateView): template_name = 'scrape/index.html' class VesselRouteView(IndexView): template_name = 'scrape/vesselroute.html' def index(request): return render(request, 'scrape/index.html') def blanksailing(request): inital_data = { 'monthF':datetime.now().month, 'monthT':datetime.now().month } form = BSfilterForm(request.GET or None, initial=inital_data) if request.method =='POST': form = BSfilterForm(request.POST) if form.is_valid(): data = form.cleaned_data _init_SCRAPER(data) # print(data) else: print(form.errors) context = { 'form':form, 'months':MONTH_DICT } return render(request,'scrape/blanksailing.html',context) def vesselroute(request): return render(request,'scrape/vesselroute.html') def filter(request): form = BSfilterForm(request.POST or None) if form.is_valid(): form.save() context = {'form':form} return render(request,'scrape/filter.html',context) # class BlankSailingView(ListView): # blanksailing() # template_name = 'scrape/blanksailing.html'
1,564
520
import argparse import importlib import logging import sys logger = logging.getLogger() COMMAND_MODULES = ( 'ncdoublescrape.scrape', ) def main(): parser = argparse.ArgumentParser('ncds', description='A janky NCAA scraper') subparsers = parser.add_subparsers(dest='subcommand') subcommands = {} for module in COMMAND_MODULES: try: command = importlib.import_module(module).Command(subparsers) except ImportError as e: logger.error('exception "%s" prevented loading of %s module', e, module) else: subcommands[command.name] = command args, other = parser.parse_known_args() if not args.subcommand: parser.print_help() else: try: subcommands[args.subcommand].handle(args, other) except Exception as e: logger.critical(str(e)) sys.exit(1) if __name__ == '__main__': main()
935
288
class ElektraConstants: pass
33
11
#!/usr/bin/env python ############################################################################ # # # Copyright 2014 Prelert Ltd # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################ ''' Delete all the jobs in the Engine API. Request a list of jobs configured in the API then delete them one at a time using the job id. Be careful with this one you can't change your mind afterwards. ''' import argparse import sys import json import logging import time from prelert.engineApiClient import EngineApiClient # defaults HOST = 'localhost' PORT = 8080 BASE_URL = 'engine/v2' def parseArguments(): parser = argparse.ArgumentParser() parser.add_argument("--host", help="The Prelert Engine API host defaults to " + HOST, default=HOST) parser.add_argument("--port", help="The Prelert Engine API port defaults to " + str(PORT), default=PORT) return parser.parse_args() def main(): args = parseArguments() host = args.host port = args.port # Create the REST API client engine_client = EngineApiClient(host, BASE_URL, port) while True: (http_status_code, response) = engine_client.getJobs() if http_status_code != 200: print (http_status_code, json.dumps(response)) break jobs = response['documents'] if (len(jobs) == 0): print "Deleted all jobs" break print "Deleting %d jobs" % (len(jobs)), for job in jobs: (http_status_code, response) = engine_client.delete(job['id']) if http_status_code != 200: print (http_status_code, json.dumps(response)) else: sys.stdout.write('.') sys.stdout.flush() print if __name__ == "__main__": main()
2,971
738
# Python3 from solution1 import twoTeams as f qa = [ ([1, 11, 13, 6, 14], 11), ([3, 4], -1), ([16, 14, 79, 8, 71, 72, 71, 10, 80, 76, 83, 70, 57, 29, 31], 209), ([23, 72, 54, 4, 88, 91, 8, 44], -38), ([23, 74, 57, 33, 61, 99, 19, 12, 19, 38, 77, 70, 20], -50) ] for *q, a in qa: for i, e in enumerate(q): print('input{0}: {1}'.format(i + 1, e)) ans = f(*q) if ans != a: print(' [failed]') print(' output:', ans) print(' expected:', a) else: print(' [ok]') print(' output:', ans) print()
614
340
from __future__ import print_function import boto3 from decimal import Decimal import json import urllib from botocore.vendored import requests print('Loading function') rekognition = boto3.client('rekognition') s3 = boto3.resource("s3") # --------------- Helper Functions to call Rekognition APIs ------------------ def detect_faces(bucket, key): response = rekognition.detect_faces(Image={"S3Object": {"Bucket": bucket, "Name": key}}) return response def detect_labels(bucket, key): response = rekognition.detect_labels(Image={"S3Object": {"Bucket": bucket, "Name": key}}) # Sample code to write response to DynamoDB table 'MyTable' with 'PK' as Primary Key. # Note: role used for executing this Lambda function should have write access to the table. #table = boto3.resource('dynamodb').Table('MyTable') #labels = [{'Confidence': Decimal(str(label_prediction['Confidence'])), 'Name': label_prediction['Name']} for label_prediction in response['Labels']] #table.put_item(Item={'PK': key, 'Labels': labels}) return response def index_faces(bucket, key): # Note: Collection has to be created upfront. Use CreateCollection API to create a collecion. #rekognition.create_collection(CollectionId='BLUEPRINT_COLLECTION') response = rekognition.index_faces(Image={"S3Object": {"Bucket": bucket, "Name": key}}, CollectionId="BLUEPRINT_COLLECTION") return response def find_recipes(ingredients): payload = { 'ingredients': ingredients, 'number': 2, 'ranking': '1', 'apiKey': '8bce36150747496f98b2c81860545458' } recipes = requests.get('https://api.spoonacular.com/recipes/findByIngredients', params=payload) return recipes.json() # --------------- Main handler ------------------ def lambda_handler(event, context): '''Demonstrates S3 trigger that uses Rekognition APIs to detect faces, labels and index faces in S3 Object. ''' print("Received event: " + json.dumps(event, indent=2)) # Get the object from the event bucket = event['Records'][0]['s3']['bucket']['name'] key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key'].encode('utf8')) try: # Calls rekognition DetectFaces API to detect faces in S3 object #response = detect_faces(bucket, key) # Calls rekognition DetectLabels API to detect labels in S3 object response = detect_labels(bucket, key) # Calls rekognition IndexFaces API to detect faces in S3 object and index faces into specified collection #response = index_faces(bucket, key) # Print response to console. print('Detected labels for ' + key) print() ingredients = "" for label in response['Labels']: encodedName = label['Name'].encode('utf-8') if len(ingredients): ingredients = ingredients + ", " + encodedName else: ingredients = encodedName # print ("Label: " + label['Name']) # print ("Confidence: " + str(label['Confidence'])) # print ("Instances:") #for instance in label['Instances']: # print (" Bounding box") # print (" Top: " + str(instance['BoundingBox']['Top'])) # print (" Left: " + str(instance['BoundingBox']['Left'])) # print (" Width: " + str(instance['BoundingBox']['Width'])) # print (" Height: " + str(instance['BoundingBox']['Height'])) # print (" Confidence: " + str(instance['Confidence'])) # print() # print ("Parents:") # for parent in label['Parents']: # print (" " + parent['Name']) # print ("----------") # print () recipes = find_recipes(ingredients) #return recipes #print(ingredients) #print(recipes) recipeResponse = [] for recipe in recipes: recipeIngredients = [] for usedIngredient in recipe['usedIngredients']: recipeIngredients.append({ 'name': usedIngredient['name'], 'servingSize': str(usedIngredient['amount']) + ' ' + usedIngredient['unit'] }) recipeResponse.append({ 'title': recipe['title'], 'image': recipe['image'], 'ingredients': recipeIngredients }) responseData = { 'ingredients': ingredients, 'recipes': recipeResponse } if responseData: print(s3) obj = s3.Object('groupneuralnetworkrecipebucket1','recipes.json') obj.put(Body=json.dumps(responseData)) return responseData except Exception as e: print(e) print("Error processing object {} from bucket {}. ".format(key, bucket) + "Make sure your object and bucket exist and your bucket is in the same region as this function.") raise e
5,037
1,464
import socket import sqlite3 def Main(): port = 4000 s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) print(socket.gethostbyaddr(socket.gethostname())) s.bind((socket.gethostbyaddr(),port)) print("Server started") while True: reg_db = sqlite3.connect("reg_db.db") reg_db_cur = reg_db.cursor() unp_db = sqlite3.connect("unp_db.db") unp_db_cur = unp_db.cursor() '''first quadrant table : f_q_table second quadrant table : s_q_table third quadrant table : t_q_table fourth quadrant table : fourth_q_table''' data, addr = s.recvfrom(1024) data = data.decode('utf-8') data = eval(data) if data[0] == "acc": data.remove(data[0]) username = data[0].lower() email = data[1].lower() email = email.replace("@","_") password = data[2].lower() success = None unp_db_cur.execute("SELECT email FROM accounts where email = "+"'"+email+"'") res = unp_db_cur.fetchall() if len(res) == 0: try: unp_db_cur.execute("INSERT INTO accounts values("+"'"+email+"',"+" '"+username+"', "+"'"+password+"')") unp_db.commit() unp_db_cur.execute("SELECT * FROM accounts") print(unp_db_cur.fetchall()) s.sendto("ACCOUNT CREATED".encode("utf-8"),addr) except: print("DATABASE REGISTRATION ERROR") elif len(res) ==1: print("email associated with account already exist") elif data[1] == "ch_acc_cred": email_ch = data[0][0].replace("@","_") name_ch = data[0][1] pw_ch = data[0][2] unp_db_cur.execute("SELECT * FROM accounts WHERE email ="+"'"+email_ch+"'") ch_res = unp_db_cur.fetchall() if ch_res == [] : print("no accounts associated with the email") s.sendto("error_lia".encode("utf-8"), addr) elif ch_res[0][2]== pw_ch: print("Login success") s.sendto(str(["verified",ch_res[0][1]]).encode("utf-8"),addr) elif data[0] == "tr_reg": lat = data[1][0] lon = data[1][1] if lon >= 0 and lat >= 0: print("INSERT INTO f_q_table values('"+str(lon)+"', '"+str(lat)+")") reg_db_cur.execute("INSERT INTO f_q_table values('"+str(lon)+"', '"+str(lat)+"')") else: print("message from : ", addr) print("message : ",data) temp = data # the data from the client is of the form [[lo,lo*],[la,la*]] lo = temp[0][0] lo_p = temp[0][1] la = temp[1][0] la_p = temp[1][1] text = "" if lo >= 0 and la >=0: text = "FIRST QUADRANT" print(text) reg_db_cur.execute("SELECT DISTINCT * FROM f_q_table WHERE lon > %s AND lon < %s AND lat > %s AND lat < %s"%(lo,lo_p,la,la_p)) coordinates = reg_db_cur.fetchall() coordinates = str(coordinates) print("sending : ", coordinates) s.sendto(coordinates.encode('utf-8'), addr) elif lo_p < 0 and la >= 0: text = "SECOND QUADRANT" print(text) elif lo_p < 0 and la_p < 0: text = "THIRD QUADRANT" print(text) elif lo >= 0 and la_p < 0: text = "FOURTH QUADRANT" print(text) else: text = "unidentified... but will find tomorrow" if __name__ == "__main__": Main().run()
3,836
1,232
from typing import Any class Stack: def __init__(self) -> None: self.stack = [] def stack_size(self) -> int: return len(self.stack) def is_empty(self) -> bool: return self.stack == [] # O(1) running time def push(self, data: Any) -> None: self.stack.append(data) # O(1) running time def pop(self) -> Any: if self.stack.is_empty(): return data = self.stack[-1] del self.stack[-1] return data # O(1) running time def peek(self) -> Any: return self.stack[-1] # There is no point implementing a stack with a linkedlist # since we'd majorly be interacting with the topmost item # in the stakc -- this is what arrays are optimized for
759
242
import collections import os from pathlib import Path def setter(f): return property(None, f) enum = enumerate def esorted(l): return enum(sorted(l)) def cn(o): return o.__class__.__name__ def strcmp(s1, s2, ignore_case=False): if ignore_case: return s1.lower() == s2.lower() return s1 == s2 def inv_map(d): return {v: k for k, v in d.items()} def num2str(num): return str(num) def isblank(s): return len(s.replace(' ', '').replace('\t', '').replace('\n', '').replace('\r', '')) == 0 def notblank(s): return not isblank(s) def isblankstr(s): return isstr(s) and isblank(s) def composed(*decs): # https://stackoverflow.com/questions/5409450/can-i-combine-two-decorators-into-a-single-one-in-python def deco(f): for dec in reversed(decs): f = dec(f) return f return deco def listkeys(d): from mlib.boot.stream import li return li(d.keys()) def listvalues(d): from mlib.boot.stream import li return li(d.values()) def all_or_break(li, lamb): for o in li: if not lamb(o): return False return True def strrep(s, s1, s2): return s.replace(s1, s2) def classname(o): return o.__class__.__name__ def simple_classname(o): return classname(o).split('.')[-1] def isa(o, name): return classname(o) == name def isnumber(o): import numpy as np return isinstsafe(o, int) or isinstsafe(o, float) or isinstsafe(o, np.long) def will_break_numpy(o): return not isnumber(o) and not isstr(o) and not isbool(o) and not islist(o) def isinstsafe(o, c): from mlib.inspect import all_superclasses return isinstance(o, c) or c in all_superclasses(o.__class__) def isslice(v): return isinstance(v, slice) def isint(v): import numpy as np return isinstance(v, int) or isinstance(v, np.int64) def isdict(v): return isinstance(v, dict) def isdictsafe(v): return isinstance(v, collections.Mapping) def islistsafe(v): return isinstance(v, collections.Sequence) def iscls(v): return isinstance(v, type) def isfun(v): return callable(v) and not iscls(v) def isdigit(s): return s.isdigit() def isstr(v): from mlib.str import StringExtension return isinstance(v, str) or isinstance(v, StringExtension) def istuple(v): return isinstance(v, tuple) def islist(v): return isinstance(v, list) def isbool(v): return isinstance(v, bool) def isitr(v): import typing return isinstance(v, collections.Iterable) or isinstance(v, typing.Iterable) # not sure if I need both def is_non_str_itr(o): return isitr(o) and not isstr(o) def addpath(p): import sys sys.path.append(p) def ismac(): import platform return platform.system() == 'Darwin' def islinux(): import platform return platform.system() == 'Linux' def pwd(): return os.getcwd() HOME = str(Path.home()) DESKTOP = os.path.join(HOME, 'Desktop') DEBUG = True NORMAL = False
2,967
1,090
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime from .common import Base, session_scope from .team import Team class Division(Base): __tablename__ = 'divisions' __autoload__ = True HUMAN_READABLE = 'division' def __init__(self, name, season, teams, conference=None): self.division_name = name self.season = season self.teams = list() for t in teams: self.teams.append(t.team_id) self.conference = conference @classmethod def get_divisions_and_teams(cls, season=None): if season is None: now = datetime.datetime.now() season = now.year - 1 if now.month <= 6 else now.year division_dict = dict() with session_scope() as session: divs = session.query(Division).filter( Division.season == season).all() for d in divs: teams = list() for team_id in d.teams: team = Team.find_by_id(team_id) teams.append(team) division_dict[d.division_name] = teams return division_dict def __str__(self): if self.conference: base_information_str = "%s Division (%s Conference) %s:" % ( self.division_name, self.conference, self.season) else: base_information_str = "%s Division %s:" % ( self.division_name, self.season) team_information_str = "\n\t+ ".join( sorted([Team.find_by_id(team_id).name for team_id in self.teams])) return "\n\t+ ".join((base_information_str, team_information_str)) def __gt__(self, other): if None in (self.conference, other.conference): return self.division_name > other.division_name else: return ( self.conference, self.division_name ) > ( other.conference, other.division_name) def __lt__(self, other): if None in (self.conference, other.conference): return self.division_name < other.division_name else: return ( self.conference, self.division_name ) < ( other.conference, other.division_name)
2,274
664
import pytest from ruamel import yaml from runthis.server.config import Config, get_config_from_yaml @pytest.fixture def config_obj(tmpdir): return Config( tty_server="ttyd", command="xonsh", docker=False, docker_image="myimage", keyfile="/path/to/privkey.pem", ) def test_fields(config_obj): assert config_obj.tty_server == "ttyd" assert config_obj.command == "xonsh" assert not config_obj.docker assert config_obj.docker_image == "myimage" assert config_obj.keyfile == "/path/to/privkey.pem" DICT_CONFIG_CONTENT = dict( tty_server="tty-server", command="myshell", docker=True, docker_image="img", host="8.8.8.8", certfile="/path/to/cert.pem", ) @pytest.mark.parametrize( "config_content", [DICT_CONFIG_CONTENT, {"runthis": DICT_CONFIG_CONTENT}] ) def test_populate_config_by_yaml(config_content, tmpdir): yaml_path = tmpdir.join("TEST.yaml") yaml_path.write(yaml.dump(config_content)) config_obj = get_config_from_yaml(str(yaml_path)) assert config_obj.tty_server == "tty-server" assert config_obj.command == "myshell" assert config_obj.docker assert config_obj.docker_image == "img" assert config_obj.host == "8.8.8.8" assert config_obj.certfile == "/path/to/cert.pem"
1,338
472
# DISCLAIMER TO CONTEST TEAMS : DO NOT MAKE CHANGES IN THIS FILE. classes = { "Tasit": 0, "Insan": 1, "UAP": 2, "UAI": 3, } landing_statuses = { "Inilebilir": "1", "Inilemez": "0", "Inis Alani Degil": "-1" } base_url = "http://192.168.1.10:3000"
290
143