id
stringlengths 1
8
| text
stringlengths 6
1.05M
| dataset_id
stringclasses 1
value |
---|---|---|
6475224
|
<filename>setup.py
import sys
from setuptools import setup
VERSION = '0.0.1'
DESCRIPTION = 'WRITE SOMETHING INTELLIGENT HERE!'
CLASSIFIERS = ['Development status :: 3 - Alpha',
'Intended Audience :: Ay250 grader',
'Topic :: Software Development :: Libraries :: Python Modules',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 3.9']
setup(name='calcalc',
version=VERSION,
description=DESCRIPTION,
long_description=DESCRIPTION,
long_description_content_type='text/x-rst',
classifiers=CLASSIFIERS,
author='<NAME>',
author_email='<EMAIL>',
url='http://github.com/caseylam/calcalc',
python_requires='>=3',
license='BSD',
keywords='homework',
packages=['calcalc'],
platforms=['any'],
setup_requires=['pytest_runner'],
tests_require=['pytest'])
|
StarcoderdataPython
|
3213904
|
<reponame>tencentmusic/fab
# 如果安装torndb,记得要替换/usr/local/lib/python3.6/dist-packages文件夹下的torndb.py文件,内容同utils/torndb-python3.py
import queue,threading,torndb
# mysql异步线程池
class MysqlConnPool(object):
def __init__(self, host, database, user, pwd, max_conns=30):
self.idle_conn = queue.Queue()
self.pool_size = 0
self.max_conns = max_conns
self.conn_params = (host, database, user, pwd)
self.poll_size_mutex = threading.Lock()
def _get_conn_from_pool(self):
if self.idle_conn.empty() and self.pool_size < self.max_conns:
conn = torndb.Connection(*self.conn_params, time_zone="+8:00")
self.poll_size_mutex.acquire()
self.pool_size += 1
self.poll_size_mutex.release()
return conn
return self.idle_conn.get()
# 查询函数
def query(self, sqlcommand,*args, **kwargs):
conn = self._get_conn_from_pool()
res = conn.query(sqlcommand,*args, **kwargs)
self.idle_conn.put(conn)
return res
# 执行+查询函数
def execute(self,sqlcommand, *args, **kwargs):
conn = self._get_conn_from_pool()
res = conn.execute(sqlcommand,*args, **kwargs)
self.idle_conn.put(conn)
return res
# 提交函数
def commit(self):
pass
if __name__=="__main__":
import time,random,pymysql
mysqlpool=MysqlConnPool('192.168.11.127:32001','vesionbook','root','admin')
result = mysqlpool.query('select id from capture order by id desc limit 1')
print(result)
feature_arr = bytearray([random.randint(1,244) for x in range(0,2068)])
result = mysqlpool.execute('insert into capture (feature,image_id,device_id,create_time) values(%s,%s,%s,%s)',*(feature_arr,'12312312312', '1000', int(time.time())))
print(result)
|
StarcoderdataPython
|
160790
|
<filename>env/Lib/site-packages/plotly/validators/layout/smith/imaginaryaxis/__init__.py
import sys
if sys.version_info < (3, 7):
from ._visible import VisibleValidator
from ._tickwidth import TickwidthValidator
from ._tickvalssrc import TickvalssrcValidator
from ._tickvals import TickvalsValidator
from ._ticksuffix import TicksuffixValidator
from ._ticks import TicksValidator
from ._tickprefix import TickprefixValidator
from ._ticklen import TicklenValidator
from ._tickformat import TickformatValidator
from ._tickfont import TickfontValidator
from ._tickcolor import TickcolorValidator
from ._showticksuffix import ShowticksuffixValidator
from ._showtickprefix import ShowtickprefixValidator
from ._showticklabels import ShowticklabelsValidator
from ._showline import ShowlineValidator
from ._showgrid import ShowgridValidator
from ._linewidth import LinewidthValidator
from ._linecolor import LinecolorValidator
from ._layer import LayerValidator
from ._hoverformat import HoverformatValidator
from ._gridwidth import GridwidthValidator
from ._gridcolor import GridcolorValidator
from ._color import ColorValidator
else:
from _plotly_utils.importers import relative_import
__all__, __getattr__, __dir__ = relative_import(
__name__,
[],
[
"._visible.VisibleValidator",
"._tickwidth.TickwidthValidator",
"._tickvalssrc.TickvalssrcValidator",
"._tickvals.TickvalsValidator",
"._ticksuffix.TicksuffixValidator",
"._ticks.TicksValidator",
"._tickprefix.TickprefixValidator",
"._ticklen.TicklenValidator",
"._tickformat.TickformatValidator",
"._tickfont.TickfontValidator",
"._tickcolor.TickcolorValidator",
"._showticksuffix.ShowticksuffixValidator",
"._showtickprefix.ShowtickprefixValidator",
"._showticklabels.ShowticklabelsValidator",
"._showline.ShowlineValidator",
"._showgrid.ShowgridValidator",
"._linewidth.LinewidthValidator",
"._linecolor.LinecolorValidator",
"._layer.LayerValidator",
"._hoverformat.HoverformatValidator",
"._gridwidth.GridwidthValidator",
"._gridcolor.GridcolorValidator",
"._color.ColorValidator",
],
)
|
StarcoderdataPython
|
1611984
|
def is_valid(number):
min_number = 2
max_number = 10
results = [x for x in range(min_number, max_number + 1) if number % x == 0]
return True if results else False
n = int(input())
m = int(input())
result = [x for x in range(n, m + 1) if is_valid(x)]
print(result)
|
StarcoderdataPython
|
1884286
|
#!/usr/bin/env python3
# See LICENSE for licensing information.
#
# Copyright (c) 2016-2021 Regents of the University of California
# All rights reserved.
#
"""
This type of setup script should be placed in the setup_scripts directory in
the trunk
"""
import os
TECHNOLOGY = "sky130"
os.environ["MGC_TMPDIR"] = "/tmp"
###########################
# OpenRAM Paths
# OpenPDK needed for magicrc, tech file and spice models of transistors
if 'PDK_ROOT' in os.environ:
open_pdks = os.path.join(os.environ['PDK_ROOT'], 'sky130A', 'libs.tech')
else:
raise SystemError("Unable to find open_pdks tech file. Set PDK_ROOT.")
spice_model_dir = os.path.join(open_pdks, "SIMULATOR",)
sky130_lib_ngspice = os.path.join(open_pdks, "ngspice", "sky130.lib.spice")
# We may end up using Xyce but check if at least ngspice exists
if not os.path.exists(sky130_lib_ngspice):
raise SystemError("Did not find {} under {}".format(sky130_lib_ngspice, open_pdks))
os.environ["SPICE_MODEL_DIR"] = spice_model_dir
open_pdks = os.path.abspath(open_pdks)
sky130_magicrc = os.path.join(open_pdks, 'magic', "sky130A.magicrc")
if not os.path.exists(sky130_magicrc):
raise SystemError("Did not find {} under {}".format(sky130_magicrc, open_pdks))
os.environ["OPENRAM_MAGICRC"] = sky130_magicrc
sky130_netgenrc = os.path.join(open_pdks, 'netgen', "setup.tcl")
if not os.path.exists(sky130_netgenrc):
raise SystemError("Did not find {} under {}".format(sky130_netgenrc, open_pdks))
os.environ["OPENRAM_NETGENRC"] = sky130_netgenrc
try:
DRCLVS_HOME = os.path.abspath(os.environ.get("DRCLVS_HOME"))
except:
DRCLVS_HOME= "not-found"
os.environ["DRCLVS_HOME"] = DRCLVS_HOME
|
StarcoderdataPython
|
11280326
|
import mysql.connector
cnx = mysql.connector.connect(user='testing', password='<PASSWORD>',
host='192.168.2.102',
database='testing')
cursor = cnx.cursor()
add_statistike = ("INSERT INTO meteo_uslovi ( temperatura_1, temperatura_2, pritisak, vlaznost_vazduha) "
"VALUES (%s, %s, %s, %s)")
podaci = (50,49,1000,60)
cursor.execute(add_statistike,podaci)
cnx.commit()
cursor.close()
cnx.close()
|
StarcoderdataPython
|
8045682
|
class InfrastructureEntity:
def __init__(self):
self.sinks = list()
self.states = list()
self.visualizations = list()
self.hourly_days = None
self.warning_zone = None
def load_state(self, state: dict):
self.sinks = state['sinks']
self.states = state['states']
self.visualizations = state['visualizations']
self.hourly_days = state['hourly_days']
self.warning_zone = state.get('warning_zone', 0)
|
StarcoderdataPython
|
6585104
|
<filename>creational-patterns/abstract_factory.py<gh_stars>0
"""
https://sourcemaking.com/design_patterns/abstract_factory
https://medium.com/datadriveninvestor/usage-of-singleton-pattern-in-multithreaded-applications-ec0cc4c8805e
"""
from abc import ABC, abstractmethod
class Tv(ABC):
pass
class Phone(ABC):
pass
class AbstractFactory(ABC):
@abstractmethod
def create_tv(self) -> Tv:
pass
@abstractmethod
def create_phone(self) -> Phone:
pass
# region samsung
class RU7099Tv(Tv):
def __str__(self):
return "Samsung RU7099"
class GalaxyS10Phone(Phone):
def __str__(self):
return "Samsung Galaxy S10"
class SamsungFactory(AbstractFactory):
def create_tv(self) -> Tv:
return RU7099Tv()
def create_phone(self) -> Phone:
return GalaxyS10Phone()
# endregion
# region sony
class BraviaTv(Tv):
def __str__(self):
return "Sony Bravia"
class Xperia10Phone(Phone):
def __str__(self):
return "Sony Xperia 10"
class SonyFactory(AbstractFactory):
def create_tv(self) -> Tv:
return BraviaTv()
def create_phone(self) -> Phone:
return Xperia10Phone()
# endregion
# region usage
if __name__ == "__main__":
samsung_factory = SamsungFactory()
sony_factory = SonyFactory()
print(samsung_factory.create_phone())
print(samsung_factory.create_tv())
print(sony_factory.create_phone())
print(sony_factory.create_tv())
# endregion
|
StarcoderdataPython
|
151151
|
<reponame>Philoso-Fish/CARLA<filename>carla/__init__.py<gh_stars>0
# flake8: noqa
from .evaluation import distances
|
StarcoderdataPython
|
238815
|
<reponame>NGoetz/TorchPS
import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="torchps",
version="1.0.1",
author="<NAME>",
author_email="<EMAIL>",
description="Phase Space Sampling with PyTorch",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/NGoetz/TorchPS",
project_urls={
"Bug Tracker": "https://github.com/NGoetz/TorchPS/issues",
},
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
package_dir={"": "src"},
packages=setuptools.find_packages(where="src"),
python_requires=">=3.6",
install_requires = ['torch==1.6', 'numpy==1.19.1','python-dateutil']
)
|
StarcoderdataPython
|
11277513
|
#!/usr/bin/env python
from os.path import exists
from setuptools import setup
setup(name='castra',
version='0.1.8',
description='On-disk partitioned store',
url='http://github.com/blaze/Castra/',
maintainer='<NAME>',
maintainer_email='<EMAIL>',
license='BSD',
keywords='',
packages=['castra'],
package_data={'castra': ['tests/*.py']},
install_requires=list(open('requirements.txt').read().strip().split('\n')),
long_description=(open('README.rst').read() if exists('README.rst')
else ''),
zip_safe=False)
|
StarcoderdataPython
|
126587
|
<reponame>barnabemonnot/eth2.0-specs
from eth2spec.phase0 import spec as spec_phase0
from eth2spec.altair import spec as spec_altair
from eth2spec.phase1 import spec as spec_phase1
from eth2spec.test.context import PHASE0, PHASE1, ALTAIR
from eth2spec.gen_helpers.gen_from_tests.gen import run_state_test_generators
specs = (spec_phase0, spec_altair, spec_phase1)
if __name__ == "__main__":
phase_0_mods = {key: 'eth2spec.test.phase0.sanity.test_' + key for key in [
'blocks',
'slots',
]}
altair_mods = {**{key: 'eth2spec.test.altair.sanity.test_' + key for key in [
'blocks',
]}, **phase_0_mods} # also run the previous phase 0 tests
phase_1_mods = {**{key: 'eth2spec.test.phase1.sanity.test_' + key for key in [
'blocks', # more phase 1 specific block tests
'shard_blocks',
]}, **phase_0_mods} # also run the previous phase 0 tests (but against phase 1 spec)
all_mods = {
PHASE0: phase_0_mods,
ALTAIR: altair_mods,
PHASE1: phase_1_mods,
}
run_state_test_generators(runner_name="sanity", specs=specs, all_mods=all_mods)
|
StarcoderdataPython
|
11240393
|
from morph2vec.api import Morph2Vec
__version__ = '1.0.0'
|
StarcoderdataPython
|
4989334
|
import warnings
import plac
import spacy
import srsly
from wasabi import msg
from spacy_crfsuite.crf_extractor import CRFExtractor
from spacy_crfsuite.tokenizer import SpacyTokenizer
from spacy_crfsuite.train import gold_example_to_crf_tokens
from spacy_crfsuite.utils import read_file
warnings.simplefilter(action="ignore", category=FutureWarning)
@plac.annotations(
in_file=("Path to input file (either .json, .md or .conll)", "positional", None, str),
model_file=("Path to model file", "option", "m", str),
config_file=("Path to config file (.json format)", "option", "c", str),
spacy_model=("Name of spaCy model to use", "option", "lm", str),
)
def main(in_file, model_file=None, config_file=None, spacy_model=None):
"""Train CRF entity tagger."""
if config_file:
msg.info(f"Loading config: {config_file}")
component_config = srsly.read_json(config_file)
else:
component_config = None
model_file = model_file or "model.pkl"
msg.info("Loading model from file", model_file)
crf_extractor = CRFExtractor(component_config=component_config).from_disk(model_file)
msg.good("Successfully loaded CRF tagger", crf_extractor)
msg.info("Loading dev dataset from file", in_file)
dev_examples = read_file(in_file)
msg.good(f"Successfully loaded {len(dev_examples)} dev examples.")
if spacy_model is not None:
nlp = spacy.load(spacy_model)
msg.info(f"Using spaCy model: {spacy_model}")
else:
nlp = spacy.blank("en")
msg.info(f"Using spaCy blank: 'en'")
tokenizer = SpacyTokenizer(nlp=nlp)
use_dense_features = crf_extractor.use_dense_features()
dev_crf_examples = [
gold_example_to_crf_tokens(
ex, tokenizer=tokenizer, use_dense_features=use_dense_features
)
for ex in dev_examples
]
f1_score, classification_report = crf_extractor.eval(dev_crf_examples)
msg.warn(f"f1 score: {f1_score}")
print(classification_report)
if __name__ == "__main__":
plac.call(main)
|
StarcoderdataPython
|
143087
|
<filename>gpaw/setup/customize-mahti.py
"""User provided customizations.
Here one changes the default arguments for compiling _gpaw.so (serial)
and gpaw-python (parallel).
Here are all the lists that can be modified:
* libraries
* library_dirs
* include_dirs
* extra_link_args
* extra_compile_args
* runtime_library_dirs
* extra_objects
* define_macros
* mpi_libraries
* mpi_library_dirs
* mpi_include_dirs
* mpi_runtime_library_dirs
* mpi_define_macros
To override use the form:
libraries = ['somelib', 'otherlib']
To append use the form
libraries += ['somelib', 'otherlib']
"""
parallel_python_interpreter = True
# compiler
compiler = os.environ['CC']
mpicompiler = 'mpicc'
mpilinker = 'mpicc'
extra_compile_args = ['-std=c99', '-O3', '-fopenmp-simd', '-march=native',
'-mtune=native', '-mavx2']
#extra_link_args = ['-fno-lto']
# libz
libraries = ['z']
# libxc
library_dirs += [os.environ['LIBXCDIR'] + '/lib']
include_dirs += [os.environ['LIBXCDIR'] + '/include']
libraries += ['xc']
# MKL
# libraries += ['mkl_core', 'mkl_intel_lp64' ,'mkl_sequential']
libraries += os.environ['BLAS_LIBS'].split()
# use ScaLAPACK and HDF5
scalapack = True
if scalapack:
libraries += os.environ['SCALAPACK_LIBS'].split()
# hdf5 = True
# GPAW defines
define_macros += [('GPAW_NO_UNDERSCORE_CBLACS', '1')]
define_macros += [('GPAW_NO_UNDERSCORE_CSCALAPACK', '1')]
define_macros += [("GPAW_ASYNC",1)]
define_macros += [("GPAW_MPI2",1)]
|
StarcoderdataPython
|
5061040
|
series = {
'row': lambda cell: tuple(board[cell[0]][col] for col in range(cell[1],min(7,cell[1]+4))),
'col': lambda cell: tuple(board[row][cell[1]] for row in range(cell[0],min(6,cell[0]+4))),
'primary_diagonal': lambda cell: tuple(board[cell[0]+i][cell[1]+i] for i in (0,1,2,3) if cell[0]+i < 6 and cell[1]+i < 7),
'secondary_diagonal': lambda cell: tuple(board[cell[0]+i][cell[1]-i] for i in (0,1,2,3) if cell[0]+i < 6 and cell[1]-i >= 0),
}
def play_move(player):
global board
while True:
column = input(f'Player {player}, please choose a column (1-7): ')
if column.isnumeric():
column = int(column)
if 0 < column < 8 and board[0][column-1] == ' ':
break
else:
print('Invalid choice.')
for row in range(5,-1,-1):
if board[row][column-1] == ' ':
break
board[row][column-1] = player
def won_game(player):
for row in range(6):
for col in range(7):
if board[row][col] == player:
for key in series.keys():
test_tuple = series[key]((row,col))
if test_tuple:
if test_tuple.count(player) == 4:
return True
return False
def print_board():
print('\n')
for row in board:
print('|', ' | '.join([str(el) for el in row]), '|')
print('-'*29)
print('\n')
board = [[' ']*7 for _ in range(6)]
play_id, next_id = 1, 2
print("Let's start!\n")
print_board()
while True:
play_move(play_id)
print_board()
if won_game(play_id):
print(f'The winner is player {play_id}!')
break
play_id, next_id = next_id, play_id
|
StarcoderdataPython
|
6694549
|
"""Support for loading picture from Neato."""
from datetime import timedelta
import logging
from homeassistant.components.camera import Camera
from . import NEATO_LOGIN, NEATO_MAP_DATA, NEATO_ROBOTS
_LOGGER = logging.getLogger(__name__)
SCAN_INTERVAL = timedelta(minutes=10)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Neato Camera."""
dev = []
for robot in hass.data[NEATO_ROBOTS]:
if 'maps' in robot.traits:
dev.append(NeatoCleaningMap(hass, robot))
_LOGGER.debug("Adding robots for cleaning maps %s", dev)
add_entities(dev, True)
class NeatoCleaningMap(Camera):
"""Neato cleaning map for last clean."""
def __init__(self, hass, robot):
"""Initialize Neato cleaning map."""
super().__init__()
self.robot = robot
self._robot_name = '{} {}'.format(self.robot.name, 'Cleaning Map')
self._robot_serial = self.robot.serial
self.neato = hass.data[NEATO_LOGIN]
self._image_url = None
self._image = None
def camera_image(self):
"""Return image response."""
self.update()
return self._image
def update(self):
"""Check the contents of the map list."""
self.neato.update_robots()
image_url = None
map_data = self.hass.data[NEATO_MAP_DATA]
image_url = map_data[self._robot_serial]['maps'][0]['url']
if image_url == self._image_url:
_LOGGER.debug("The map image_url is the same as old")
return
image = self.neato.download_map(image_url)
self._image = image.read()
self._image_url = image_url
@property
def name(self):
"""Return the name of this camera."""
return self._robot_name
@property
def unique_id(self):
"""Return unique ID."""
return self._robot_serial
|
StarcoderdataPython
|
4928479
|
from petisco.legacy import LogMessage
from petisco.legacy.logger.interface_logger import ILogger
class FakeLogger(ILogger):
def __init__(self):
self.logging_messages = []
def log(self, logging_level, log_message: LogMessage):
self.logging_messages.append((logging_level, log_message.to_dict()))
def get_logging_messages(self):
return self.logging_messages
|
StarcoderdataPython
|
6699303
|
# -*- coding: utf-8 -*-
"""
Test ramlient.core module
"""
import types
import pytest
from ramlient.core import Node, ParameterizedNode
from ramlient.errors import UnsupportedResourceMethodError, UnsupportedQueryParameter
@pytest.mark.parametrize('example_client', [
'simple'
], indirect=['example_client'])
def test_creating_client_from_raml_url(example_client):
"""
Test creating client from a RAML file per URL
"""
assert example_client.raml.title == 'Example API'
@pytest.mark.parametrize('example_client', [
'simple'
], indirect=['example_client'])
def test_accessing_first_level_resource(example_client):
"""
Test accessing first level resource
"""
# given & when
resource = example_client.resource
# then
assert isinstance(resource, Node)
assert resource.path == '/resource'
assert resource.resource.display_name == 'First One'
@pytest.mark.parametrize('example_client', [
'github'
], indirect=['example_client'])
def test_accessing_second_level_resource(example_client):
"""
Test accessing second level resource
"""
# given & when
resource = example_client.search.repositories
# then
assert isinstance(resource, Node)
assert resource.path == '/search/repositories'
@pytest.mark.parametrize('example_client', [
'simple'
], indirect=['example_client'])
def test_accessing_dynamic_resource(example_client):
"""
Test accessing dynamic resource
"""
# given & when
resource = example_client.resource.resourceId(5)
# then
assert isinstance(resource, ParameterizedNode)
assert resource.resource.path == '/resource/{resourceId}'
assert resource.parameter == {"resourceId": 5}
assert resource.path == '/resource/5'
@pytest.mark.parametrize('example_client', [
'simple'
], indirect=['example_client'])
def test_getting_request_method_from_resource(example_client):
"""
Test getting request method from resource
"""
assert isinstance(example_client.resource.get, types.FunctionType)
assert isinstance(example_client.resource.put, types.FunctionType)
assert isinstance(example_client.resource.delete, types.FunctionType)
assert isinstance(example_client.resource.patch, types.FunctionType)
assert isinstance(example_client.resource.options, types.FunctionType)
assert isinstance(example_client.resource.trace, types.FunctionType)
assert isinstance(example_client.resource.connect, types.FunctionType)
# when
with pytest.raises(UnsupportedResourceMethodError) as exc:
example_client.resource.post # noqa
# then
assert str(exc.value) == "Resource '/resource' does not support method 'post'"
# then
assert isinstance(example_client.resource.resourceId(5).get, types.FunctionType)
assert isinstance(example_client.resource.resourceId(5).post, types.FunctionType)
# when
with pytest.raises(UnsupportedResourceMethodError) as exc:
example_client.resource.resourceId(5).delete # noqa
# then
assert str(exc.value) == "Resource '/resource/{resourceId}' does not support method 'delete'"
@pytest.mark.parametrize('example_client', [
'simple'
], indirect=['example_client'])
def test_passing_query_parameter_to_resource(example_client):
"""
Test passing query parameter to resource
"""
# when
with pytest.raises(UnsupportedQueryParameter) as exc:
example_client.resource.resourceId(5).get(foo=42)
# then
assert str(exc.value) == "Resource '/resource/{resourceId}' does " \
"not support Query Parameter 'foo'"
@pytest.mark.parametrize('example_client', [
'simple'
], indirect=['example_client'])
def test_passing_wrong_typed_query_parameter_to_resource(example_client):
"""
Test passing wrong typed query parameter to resource
"""
# when
with pytest.raises(TypeError) as exc:
example_client.resource.resourceId(5).get(filter=42)
# then
assert str(exc.value) == "Resource Query Parameter has type 'int' but expected type 'string'"
|
StarcoderdataPython
|
11385709
|
import re
from itertools import count
from .tools import process_path
_conversions = {'atomicint': 'counter',
'str': 'text',
'bool': 'boolean',
'decimal': 'decimal',
'float': 'float',
'int': 'int',
'tuple': 'tuple',
'list': 'list',
'generator': 'list',
'frozenset': 'set',
'set': 'set',
'dict': 'map',
'long': 'bigint',
'buffer': 'blob',
'bytearray': 'blob',
'counter': 'counter',
'double': 'double',
'StorageDict': 'dict',
'ndarray': 'hecuba.hnumpy.StorageNumpy',
'numpy.ndarray': 'hecuba.hnumpy.StorageNumpy',
'date': 'date',
'time': 'time',
'datetime': 'timestamp'}
class Parser(object):
args_names = ["type_parser"]
split_dtypes_regex = re.compile('^(tuple|set)<(.*)>$')
def _append_values_to_list_after_replace(self, vals):
"""
Receives a list of data types. Strips the outermost data type.
Returns:
typev: list of the outer data types, with the keyword "simple" if not found
finalvars: list of the corresponding internal data types
"""
typev = []
finalvars = []
for var in vals:
res = self.split_dtypes_regex.search(var)
if res:
typev.append(res.group(1))
finalvars.append(res.group(2))
else:
typev.append("simple")
finalvars.append(var)
return typev, finalvars
def _get_elements(self, s):
"""
Args:
s is a string with a type specification containing one or more types
Returns a list of type_specifications
Example:
k1:tuple<int,int>,k2:tuple<int,str>,str
-->
'k1:tuple<int,int>' 'k2:tuple<int,str>' 'str'
"""
elements=[]
n_brackets = 0
pos = 0
lastpos = 0
for pos, c in enumerate(s):
if c == '<':
n_brackets = n_brackets + 1
elif c == '>':
n_brackets = n_brackets - 1
elif c == ',':
if n_brackets == 0: # a new element found
elements.append( s[lastpos:pos] )
lastpos = pos + 1 # skip ','
if lastpos < pos: #add last element
elements.append( s[lastpos:] )
return elements
def _get_name_and_type(self, k):
"""
Args:
k is a string with a single type specification "name:value"
Return:
name and type, or None and type if ":" is not present
Raises Syntax Error in cases: "n:", ":v" , ":"
"""
s = k.split(":")
if len(s) == 2: # case "name:value"
if len(s[0]) > 0 and len(s[1]) > 0:
return s
elif len(s) == 1: # case "value" only
if len(s[0]) > 0: # case ":"
return None, s[0]
raise SyntaxError("Error parsing Type Specification. Trying to parse: '{}'".format(k))
def _get_str_primary_keys_values(self, pk):
"""
Args:
pk is a string with a dict specification "dict<<key_specification>, value_specification>"
Return:
Six lists:
- keys' names,
- values' names,
- keys' types (simple, tuple or set),
- values' types (simple, tuple or set),
- keys' types (int, float, ...),
- values' types (int, float, ...),
"""
pk = pk.replace("dict", "", 1).strip()
# Find point to split keys from values
n_brackets = 0
pos = 0
for pos, c in enumerate(pk):
if c == '<':
n_brackets = n_brackets + 1
elif c == '>':
n_brackets = n_brackets - 1
if n_brackets == 1:
break
keys = pk[2:pos]
values = pk[pos + 2:len(pk) - 1]
if not keys:
raise SyntaxError("Can't detect the keys in the TypeSpec")
# We get the variables
keyList = self._get_elements(keys)
valueList = self._get_elements(values)
# Parse Keys...
keyNamesList = []
keyTypesList = []
for i,k in enumerate(keyList):
myname,mytype = self._get_name_and_type(k)
if not myname: # Generate name "key_0","key_1",...,"key_N"
myname = "key_" + str(i)
keyNamesList.append(myname)
keyTypesList.append(mytype)
# Parse Values...
valueNamesList = []
valueTypesList = []
offset = len(keyNamesList)
for i,v in enumerate(valueList):
myname,mytype = self._get_name_and_type(v)
if not myname: # Generate name "val_N+1","valN+2",...
myname = "val_" + str(i + offset)
valueNamesList.append(myname)
valueTypesList.append(mytype)
# for each type we store if its a 'simple' or a 'tuple/set' type
# (finalvarksk and finalvarsv)
# and for 'set' or 'tuple' types, the type specification is replaced by
# the type of its elements (typek and typev)
#TODO: review if this can be improved
typevk, finalvarsk = self._append_values_to_list_after_replace(keyTypesList)
typevv, finalvarsv = self._append_values_to_list_after_replace(valueTypesList)
return keyNamesList, valueNamesList, finalvarsk, finalvarsv, typevk, typevv
def _set_or_tuple(self, type, pk_col, t, t1):
string_str = ""
t = t.split(',')
converted_primary_keys = ", ".join([_conversions.get(w, w) for w in t])
converted_primary_keys = converted_primary_keys.split(',')
converted_primary_keys = [w.replace(' ', '') for w in converted_primary_keys]
aux_list = [] # stores ((var_1, val),(var_2, val),...)
if len(converted_primary_keys) > 1:
counter = count(0)
for type_val in converted_primary_keys:
if type == "set":
aux_list.append((t1 + '_' + str(next(counter)), type_val))
else:
aux_list.append(type_val)
# string_str = ',{"name": "%s", "type": "%s", "%s": ["%s"]}' % (t1, type, pk_col, '","'.join(aux_list))
string_str = ',{"name": "%s", "type": "%s", "%s": %s}' % (t1, type, pk_col, aux_list)
else:
aux_list.append((t1, converted_primary_keys[0]))
string_str = ',{"name": "%s", "type": "%s", "%s": %s}' % (t1, type, pk_col, aux_list)
return string_str
def _get_dict_str(self, varsk, cleank, typek):
concatenated_keys = ""
values = ""
string_str = ""
for t, t1, t2 in zip(cleank, varsk, typek): # first keys
if t2 == 'set':
string_str = self._set_or_tuple('set', 'columns', t, t1)
elif t2 == 'tuple':
string_str = self._set_or_tuple('tuple', 'columns', t, t1)
else:
if t not in _conversions:
route = t
cname, module = process_path(route)
try:
mod = __import__(module, globals(), locals(), [cname], 0)
except (ImportError, ValueError) as ex:
if cname in _conversions:
raise Exception("Error parsing the TypeSpec. Maybe you forgot a comma between the columns.")
raise ImportError("Can't import class {} from module {}".format(cname, module))
string_str = ',("%s", "%s")' % (t1, t)
else:
type = _conversions[t]
string_str = ',("%s", "%s")' % (t1, type)
concatenated_keys = concatenated_keys + string_str
concatenated_keys = concatenated_keys[1:]
return concatenated_keys
def _parse_dict(self, line, this):
split_line = line.split()
if len(split_line) == 2:
pk = split_line[1]
table = None
else:
pk = split_line[2]
table = split_line[1]
varsk, varsv, cleank, cleanv, typek, typevv = self._get_str_primary_keys_values(pk)
pks = self._get_dict_str(varsk, cleank, typek)
values = self._get_dict_str(varsv, cleanv, typevv)
if table == None:
final_dict = '{"primary_keys": [%s], "columns": [%s], "type": "StorageDict"}' % (pks, values)
else:
final_dict = '{"%s": {"primary_keys": [%s], "columns": [%s], "type": "StorageDict"}}' % (table, pks, values)
final_dict = eval(final_dict)
aux = '{"primary_keys": [%s], "columns": [%s], "type": "StorageDict"}' % (pks, values)
if table in this:
this[table].update(eval(aux))
return this
return final_dict
def _parse_set_or_tuple(self, type, line, pk_or_col, this):
split_line = line.split()
table = split_line[1]
line = re.sub('[<>, ]', ' ', split_line[2].replace(str(type), ""))
primary_keys = line.split()
converted_primary_keys = ", ".join([_conversions.get(w, w) for w in primary_keys])
if len(primary_keys) == 1:
string_str = '{"%s":{"%s": "%s","type": "%s"}}' % (table, pk_or_col, converted_primary_keys, str(type))
final_string = eval(string_str)
aux = '{"%s": "%s","type": "%s"}' % (pk_or_col, converted_primary_keys, str(type))
else:
string_str = '{"%s":{"%s": "%s","type": "%s"}}' % (table, pk_or_col, converted_primary_keys, str(type))
final_string = eval(string_str)
aux = '{"%s": {"%s"},"type": "%s"}' % (pk_or_col, converted_primary_keys, str(type))
if table in this:
this[table].update(eval(aux))
return this
return final_string
def _parse_index(self, line, this):
'''Def: parses index declaration, checking for the introduced vars.
Returns: a dict structure with the parsed dict.'''
if self.type_parser == "TypeSpec":
table = "indexed_on"
atributes = line.split(' ', 2)
atributes = atributes[1].replace(" ", '')
else:
table = line.split()[1]
atributes = line.split(' ', 2)
atributes = atributes[2].replace(" ", '')
atributes = atributes.split(',')
converted_atributes = ", ".join([_conversions.get(w, w) for w in atributes])
converted_atributes = converted_atributes.split(',')
converted_atributes = [w.replace(" ", "") for w in converted_atributes]
if self.type_parser == "TypeSpec":
this[table] = converted_atributes
else:
if table in this:
this[table].update({'indexed_on': converted_atributes})
else:
this[table] = {'indexed_on': converted_atributes}
return this
def _parse_file(self, line, new):
'''Def: Checks if the file declaration is correct.
Returns: the file declaration with a dict structure'''
line = line.split(" ")
output = {}
table_name = line[1]
route = line[2]
cname, module = process_path(route)
try:
mod = __import__(module, globals(), locals(), [cname], 0)
except (ImportError, ValueError) as ex:
raise ImportError("Can't import class {} from module {}".format(cname, module))
output["type"] = str(route)
if table_name in new:
new[table_name].update(output)
else:
new[table_name] = output
return new
def _parse_set_tuple_list(self, line, this):
if line.count('set') > 0:
return self._parse_set_or_tuple('set', line, 'primary_keys', this)
elif line.count('tuple') > 0:
return self._parse_set_or_tuple('tuple', line, 'columns', this)
elif line.count('list') > 0:
return self._parse_set_or_tuple('list', line, 'columns', this)
def _parse_simple(self, line, this):
split_line = line.split()
table = split_line[1]
try:
type = _conversions[split_line[2]]
except KeyError as ex:
raise Exception(f"Type '{split_line[2]}' not identified.")
simple = '{"%s":{"type":"%s"}}' % (table, type)
simple = eval(simple)
if table in this:
this[table].update(simple)
return simple
def _input_type(self, line, this):
if line.count('<') == 1: # is tuple, set, list
aux = self._parse_set_tuple_list(line, this)
elif line.count('<') == 0 and line.count('Index_on') == 0 and line.count('.') == 0 or (
line.count('numpy.ndarray') and line.count(' dict') == 0): # is simple type
aux = self._parse_simple(line, this)
elif line.count('Index_on') == 1:
aux = self._parse_index(line, this)
elif line.count('.') > 0 and line.count(' dict') == 0:
aux = self._parse_file(line, this)
else: # is dict
aux = self._parse_dict(line, this)
return aux
def _remove_spaces_from_line(self, line):
'''Def: Remove all the spaces of the line splitted from comments
Returns: same line with no spaces.'''
line = re.sub(' +', '*', line)
if line.find('@Index_on') == -1:
line = line[line.find(self.type_parser):]
if line.count('tuple') == 1 and line.count('dict') == 0:
pos = re.search(r'\b(tuple)\b', line)
pos = pos.start()
elif line.count('set') == 1 and line.count('dict') == 0:
pos = re.search(r'\b(set)\b', line)
pos = pos.start()
elif line.count('@Index_on') == 1:
pos = line.find('@Index_on')
line = line[pos:]
return line.replace('*', ' ')
elif line.count('*dict') > 0:
pos = re.search(r'\b(dict)\b', line)
pos = pos.start()
elif line.count('list') > 0:
pos = re.search(r'\b(list)\b', line)
pos = pos.start()
else:
return line.replace('*', ' ')
line = line[0:pos].replace('*', ' ') + line[pos:].replace("*", '')
return line
def _parse_comments(self, comments):
'''Def: Parses the comments param to a ClassField or TypeSpec type and checks if the comments are in the correct
format.
Returns: an structure with all the parsed comments.'''
this = {}
'''Erasing first and last line'''
str_splitted = comments.split('\n', 1)[-1]
lines = str_splitted.rsplit('\n', 1)[0]
''''''
self.detect_errors_before(lines, self.type_parser)
if self.type_parser == "TypeSpec":
for line in lines.split('\n'):
this = self._input_type(self._remove_spaces_from_line(line), this)
if self.type_parser == "ClassField":
for line in lines.split('\n'):
this.update(self._input_type(self._remove_spaces_from_line(line), this))
self.detect_errors_after(this, self.type_parser)
return this
@staticmethod
def detect_errors_before(lines, type_parser):
bad_characters = (";", "&", "(", ")", "[", "]", "=", "?", "¿", "!", "¡")
# re.escape will escape '|' too, but it shouldn't be escaped, so 'a' is a replacement
bad_characters = re.escape("a".join(bad_characters)).replace("a", "|")
bad_found = re.findall(bad_characters, lines)
if len(bad_found) > 0:
raise Exception(f"One or more bad character detected: [{', '.join(bad_found)}].")
if type_parser == "TypeSpec":
if len(lines.split("\n")) != 1:
raise Exception("StorageDicts should only have one TypeSpec line.")
if lines.count("<") < 2 or lines.count(">") < 2:
raise Exception("The TypeSpec should have at least two '<' and two '>'. Format: "
"@TypeSpec dict<<key:type>, value:type>.")
elif type_parser == "ClassField":
for line in lines.split("\n"):
if ":" in line and "dict" not in line:
line_error = line.replace(" ", "")
raise Exception(
f"The ClassField {line_error} should only have the character ':' if it is in a dict.")
@staticmethod
def detect_errors_after(output, type_parser):
if type_parser == "TypeSpec":
if "primary_keys" not in output:
raise Exception("No detected keys. Maybe you forgot to set a primary key or "
"there is a missing 'dict' after the TypeSpec.")
elif "columns" not in output:
raise Exception("No detected non-key columns.")
elif type_parser == "ClassField":
pass
def __init__(self, type_parser):
'''Initializes the Parser class with the type_parser that can be @ClassField or @TypeSpec.'''
self.type_parser = type_parser
|
StarcoderdataPython
|
3426654
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
"""
Graph node unit tests.
"""
# pylint: disable=no-self-use
import abc
import pytest
from forml.flow import task, error
from forml.flow.graph import node as grnode, port
class Atomic(metaclass=abc.ABCMeta):
"""Base class for node tests."""
@staticmethod
@abc.abstractmethod
def node(spec: task.Spec) -> grnode.Atomic:
"""Node fixture."""
def test_copy(self, node: grnode.Atomic):
"""Test for node copy method."""
assert isinstance(node.fork(), grnode.Atomic)
def test_subscribe(self, node: grnode.Atomic, simple: grnode.Worker):
"""Test node subscribing."""
simple[0].subscribe(node[0])
assert any(simple is s.node and s.port == port.Apply(0) for s in node.output[0])
assert port.Apply(0) in simple.input
with pytest.raises(error.Topology): # self subscription
simple[0].subscribe(node[0])
def test_publish(self, node: grnode.Atomic, simple: grnode.Worker):
"""Test node publishing."""
node[0].publish(simple, port.Train())
assert any(simple is s.node and s.port is port.Train() for s in node.output[0])
assert port.Train() in simple.input
with pytest.raises(error.Topology): # already subscribed
node[0].publish(simple, port.Train())
with pytest.raises(error.Topology): # self subscription
node[0].publish(node, port.Apply(0))
with pytest.raises(error.Topology): # apply-train collision
node[0].publish(simple, port.Apply(0))
with pytest.raises(error.Topology): # trained node publishing
node[0].subscribe(simple[0])
class TestWorker(Atomic):
"""Specific tests for the worker node."""
@staticmethod
@pytest.fixture(scope='function')
def node(spec: task.Spec) -> grnode.Worker:
"""Node fixture."""
return grnode.Worker(spec, 1, 1)
def test_train(self, node: grnode.Worker, simple: grnode.Worker, multi: grnode.Worker):
"""Test train subscription"""
node.train(multi[0], multi[1])
assert any(node is s.node and s.port == port.Train() for s in multi.output[0])
assert any(node is s.node and s.port == port.Label() for s in multi.output[1])
assert node.trained
with pytest.raises(error.Topology): # train-apply collision
node[0].subscribe(simple[0])
with pytest.raises(error.Topology): # publishing node trained
multi.train(node[0], node[0])
def test_fork(self, node: grnode.Worker, multi: grnode.Worker):
"""Testing node creation."""
fork = node.fork()
assert {node, fork} == node.group
node.train(multi[0], multi[1])
with pytest.raises(error.Topology): # Fork train non-exclusive
fork.train(multi[0], multi[1])
def test_stateful(self, node: grnode.Worker):
"""Test the node statefulness."""
assert node.stateful
def test_spec(self, node: grnode.Worker, spec: task.Spec):
"""Test the node spec."""
assert node.spec is spec
class TestFuture(Atomic):
"""Specific tests for the future node."""
@staticmethod
@pytest.fixture(scope='function')
def node(spec: task.Spec) -> grnode.Future:
"""Node fixture."""
return grnode.Future()
def test_future(self, node: grnode.Future, simple: grnode.Worker, multi: grnode.Worker):
"""Test future publishing."""
node[0].subscribe(simple[0])
node[0].publish(multi, port.Train())
assert any(multi is s.node and s.port == port.Train() for s in simple.output[0])
def test_invalid(self, node: grnode.Future, multi: grnode.Worker):
"""Testing invalid future subscriptions."""
node[0].publish(multi, port.Train())
with pytest.raises(error.Topology): # trained node publishing
node[0].subscribe(multi[0])
|
StarcoderdataPython
|
1685775
|
from kokoropy.controller import Crud_Controller
from ..models._all import Third_Party_Authenticator
class Third_Party_Authenticator_Controller(Crud_Controller):
__model__ = Third_Party_Authenticator
Third_Party_Authenticator_Controller.publish_route()
|
StarcoderdataPython
|
272511
|
<reponame>daijingjing/tornado_web_base
# -*- encoding: utf-8 -*-
from modules.index.IndexHandler import IndexHandler
urls = [
(r'/index', IndexHandler),
]
|
StarcoderdataPython
|
113170
|
<reponame>andrade-stats/DisjunctSupportSpikeAndSlab
import numpy
from SpikeAndSlabNonContinuous_ModelSearch_Proposed import SpikeAndSlabProposedModelSearch as SpikeAndSlabProposedModelSearch_NONCONT
import shared.idcHelper as idcHelper
MAX_INCREASE_IN_ERROR = 0.05
def select(maxIncreaseInError, allResultsForEachDelta, repId, variableNames = None):
bestSelectedVars = None
bestDelta = None
bestCorrespondingErrorIncrease = None
smallestIncreaseInError = numpy.inf
smallestIncreaseInErrorModel = None
for delta in SpikeAndSlabProposedModelSearch_NONCONT.allDelta:
if repId is not None:
selectedVars, estimatedSigmaSquareR_BMA, estimatedSigmaSquareR_reducedModel, sortedAssignmentsByFrequency = (allResultsForEachDelta[delta])[repId]
_, sigmaSquareR_trueEst, _, _ = (allResultsForEachDelta[0.0])[repId]
else:
selectedVars, estimatedSigmaSquareR_BMA, estimatedSigmaSquareR_reducedModel, sortedAssignmentsByFrequency = allResultsForEachDelta[delta]
_, sigmaSquareR_trueEst, _, _ = allResultsForEachDelta[0.0]
increaseInError = (estimatedSigmaSquareR_reducedModel / sigmaSquareR_trueEst) - 1.0
increaseInError = numpy.max([increaseInError, 0.0])
print("--")
print("delta = ", delta)
print("selectedVars = ", selectedVars)
if variableNames is not None:
idcHelper.showSelectedVariables(variableNames, selectedVars)
print("true MSE estimate = ", sigmaSquareR_trueEst)
print("MSE simplified model = ", estimatedSigmaSquareR_reducedModel)
print("increaseInError (in percent) = " + str(round(increaseInError * 100, 2)) + "\\%")
if increaseInError < maxIncreaseInError:
if (bestDelta is None) or (len(selectedVars) < len(bestSelectedVars)) or (len(selectedVars) == len(bestSelectedVars) and increaseInError < bestCorrespondingErrorIncrease):
bestSelectedVars = selectedVars
bestDelta = delta
bestCorrespondingErrorIncrease = increaseInError
# backup in case all models violate maxIncreaseInError
if increaseInError < smallestIncreaseInError:
smallestIncreaseInErrorModel = selectedVars
smallestIncreaseInError = increaseInError
assert(smallestIncreaseInErrorModel is not None)
if bestSelectedVars is None:
print("WARNING ALL MODELS FOUND VIOLATE MINIMUM INCREASE IN MSE REQUIREMENT")
bestSelectedVars = smallestIncreaseInErrorModel
print("===")
print("bestSelectedVars = ", bestSelectedVars)
if variableNames is not None:
idcHelper.showSelectedVariables(variableNames, bestSelectedVars)
if bestCorrespondingErrorIncrease is None:
print("no bestCorrespondingErrorIncrease available")
else:
print("bestCorrespondingErrorIncrease = ", bestCorrespondingErrorIncrease)
print("bestCorrespondingErrorIncrease (in percent) = " + str( round(bestCorrespondingErrorIncrease * 100.0,2) ) + "%")
return bestSelectedVars, bestDelta, bestCorrespondingErrorIncrease
|
StarcoderdataPython
|
1874889
|
"""
Copyright (c) 2004-Present Pivotal Software, Inc.
This program and the accompanying materials are made available under
the terms of the 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 inspect
import os
import re
from contextlib import closing
from datetime import datetime
from StringIO import StringIO
from unittest2.runner import _WritelnDecorator
import tinctest
from tinctest import TINCTestSuite
from tinctest.runner import TINCTestResultSet, TINCTextTestResult, TINCTestRunner
from tinctest.discovery import TINCDiscoveryQueryHandler
import unittest2 as unittest
"""
We cannot use TINC to test TINC because bugs in TINC may prevent us, during these checks,
from finding the bugs in TINC. Therefore, we must use the more basic unittest mechanisms to
test TINC.
"""
@unittest.skip('mock')
class MockTINCTestCase(tinctest.TINCTestCase):
""" Mock TINCTestCase used for below unittest TestCases """
def test_do_stuff(self):
self.assertTrue(True)
class TINCTestCaseTests(unittest.TestCase):
def test_sanity_metadata(self):
tinc_test_case = MockTINCTestCase('test_do_stuff')
self.assertEqual(tinc_test_case.name, 'MockTINCTestCase.test_do_stuff')
self.assertEqual(tinc_test_case.author, None)
self.assertEqual(tinc_test_case.description, '')
self.assertEqual(tinc_test_case.created_datetime, datetime.strptime('2000-01-01 00:00:00', '%Y-%m-%d %H:%M:%S'))
self.assertEqual(tinc_test_case.modified_datetime, datetime.strptime('2000-01-01 00:00:00', '%Y-%m-%d %H:%M:%S'))
self.assertEqual(len(tinc_test_case.tags), 0)
def test_sanity_run(self):
tinc_test_case = MockTINCTestCase('test_do_stuff')
tinc_test_case.run()
def test_name_attributes(self):
tinc_test_case = MockTINCTestCase('test_do_stuff')
self.assertEquals(tinc_test_case.name, 'MockTINCTestCase.test_do_stuff')
self.assertEquals(tinc_test_case.full_name, 'tinctest.test.test_core.MockTINCTestCase.test_do_stuff')
self.assertEquals(tinc_test_case.method_name, 'test_do_stuff')
self.assertEquals(tinc_test_case.class_name, 'MockTINCTestCase')
self.assertEquals(tinc_test_case.module_name, 'test_core')
self.assertEquals(tinc_test_case.package_name, 'tinctest.test')
class TINCTestSuiteTests(unittest.TestCase):
def test_sanity_run(self):
with closing(_WritelnDecorator(StringIO())) as buffer:
tinc_test_result = tinctest.TINCTextTestResult(buffer, True, 1)
tinc_test_suite = tinctest.TINCTestSuite()
tinc_test_suite.addTest(MockTINCTestCase('test_do_stuff'))
tinc_test_suite.run(tinc_test_result)
@unittest.skip('mock')
class MockTINCTestCaseWithMetadata(MockTINCTestCase):
"""
@maintainer prabhd
@description test case with metadata
@created 2012-07-05 12:00:00
@modified 2012-07-05 12:00:02
@tags orca hashagg
"""
def test_do_other_stuff(self):
"""
@maintainer prabhd
@description test *function* (within a class) with metadata
@created 2012-07-05 12:00:00
@modified 2012-07-05 12:00:02
@tags orca hashagg regression
"""
pass
def test_do_partially_defined_stuff(self):
"""
@description this is a new description
@created 2012-07-06 12:00:00
@modified 2012-07-06 12:00:02
"""
pass
class TINCTestCaseMetadataTests(unittest.TestCase):
def test_infer_metadata(self):
tinc_test_case = MockTINCTestCaseWithMetadata('test_do_stuff')
self.assertEqual(tinc_test_case.name, 'MockTINCTestCaseWithMetadata.test_do_stuff')
self.assertEqual(tinc_test_case.author, 'balasr3')
self.assertEqual(tinc_test_case.maintainer, 'prabhd')
self.assertEqual(tinc_test_case.description, 'test case with metadata')
self.assertEqual(tinc_test_case.created_datetime, datetime.strptime('2012-07-05 12:00:00', '%Y-%m-%d %H:%M:%S'))
self.assertEqual(tinc_test_case.modified_datetime, datetime.strptime('2012-07-05 12:00:02', '%Y-%m-%d %H:%M:%S'))
self.assertEqual(tinc_test_case.tags, set(['orca', 'hashagg']))
def test_infer_method_metadata(self):
tinc_test_case = MockTINCTestCaseWithMetadata('test_do_other_stuff')
self.assertEqual(tinc_test_case.name, 'MockTINCTestCaseWithMetadata.test_do_other_stuff')
self.assertEqual(tinc_test_case.author, 'kumara64')
self.assertEqual(tinc_test_case.maintainer, 'prabhd')
self.assertEqual(tinc_test_case.description,'test *function* (within a class) with metadata')
self.assertEqual(tinc_test_case.created_datetime, datetime.strptime('2012-07-05 12:00:00', '%Y-%m-%d %H:%M:%S'))
self.assertEqual(tinc_test_case.modified_datetime, datetime.strptime('2012-07-05 12:00:02', '%Y-%m-%d %H:%M:%S'))
self.assertEqual( tinc_test_case.tags, set(['orca', 'hashagg', 'regression']))
def test_infer_partial_method_metadata(self):
tinc_test_case = MockTINCTestCaseWithMetadata('test_do_partially_defined_stuff')
self.assertEqual(tinc_test_case.name, 'MockTINCTestCaseWithMetadata.test_do_partially_defined_stuff')
self.assertEqual(tinc_test_case.author, 'balasr3')
self.assertEqual(tinc_test_case.description, 'this is a new description')
self.assertEqual(tinc_test_case.created_datetime, datetime.strptime('2012-07-06 12:00:00', '%Y-%m-%d %H:%M:%S'))
self.assertEqual(tinc_test_case.modified_datetime, datetime.strptime('2012-07-06 12:00:02', '%Y-%m-%d %H:%M:%S'))
self.assertEqual(tinc_test_case.tags, set(['orca', 'hashagg']))
@unittest.skip('mock')
class MockTINCTestCaseForResults(tinctest.TINCTestCase):
def test_success(self):
self.assertTrue(True)
def test_failure(self):
self.assertTrue(False)
def test_error(self):
raise Exception()
def test_skip(self):
self.skipTest('i feel like it')
class TINCTextTestResultTests(unittest.TestCase):
def test_success(self):
tinc_test_case = MockTINCTestCaseForResults('test_success')
tinc_test_case.__class__.__unittest_skip__ = False
with closing(_WritelnDecorator(StringIO())) as buffer:
tinc_test_result = tinctest.TINCTextTestResult(buffer, True, 1)
tinc_test_case.run(tinc_test_result)
text = buffer.getvalue()
self.assertEqual(tinc_test_result.testsRun, 1)
self.assertEqual(len(tinc_test_result.failures), 0)
self.assertEqual(len(tinc_test_result.skipped), 0)
self.assertEqual(len(tinc_test_result.errors), 0)
self.assertRegexpMatches(text, 'MockTINCTestCaseForResults.test_success \.\.\. .* \.\.\. ok')
# same for failure
def test_failure(self):
tinc_test_case = MockTINCTestCaseForResults('test_failure')
tinc_test_case.__class__.__unittest_skip__ = False
with closing(_WritelnDecorator(StringIO())) as buffer:
tinc_test_result = tinctest.TINCTextTestResult(buffer, True, 1)
tinc_test_case.run(tinc_test_result)
text = buffer.getvalue()
self.assertEqual(tinc_test_result.testsRun, 1)
self.assertEqual(len(tinc_test_result.failures), 1)
self.assertEqual(len(tinc_test_result.skipped), 0)
self.assertEqual(len(tinc_test_result.errors), 0)
self.assertRegexpMatches(text, 'MockTINCTestCaseForResults.test_failure \.\.\. .* \.\.\. FAIL')
# same for error
def test_error(self):
tinc_test_case = MockTINCTestCaseForResults('test_error')
tinc_test_case.__class__.__unittest_skip__ = False
with closing(_WritelnDecorator(StringIO())) as buffer:
tinc_test_result = tinctest.TINCTextTestResult(buffer, True, 1)
tinc_test_case.run(tinc_test_result)
text = buffer.getvalue()
self.assertEqual(tinc_test_result.testsRun, 1)
self.assertEqual(len(tinc_test_result.failures), 0)
self.assertEqual(len(tinc_test_result.skipped), 0)
self.assertEqual(len(tinc_test_result.errors), 1)
self.assertRegexpMatches(text, 'MockTINCTestCaseForResults.test_error \.\.\. .* \.\.\. ERROR')
# same for skip
def test_skip(self):
tinc_test_case = MockTINCTestCaseForResults('test_skip')
tinc_test_case.__class__.__unittest_skip__ = False
with closing(_WritelnDecorator(StringIO())) as buffer:
tinc_test_result = tinctest.TINCTextTestResult(buffer, True, 1)
tinc_test_case.run(tinc_test_result)
text = buffer.getvalue()
self.assertEqual(tinc_test_result.testsRun, 1)
self.assertEqual(len(tinc_test_result.failures), 0)
self.assertEqual(len(tinc_test_result.skipped), 1)
self.assertEqual(len(tinc_test_result.errors), 0)
self.assertRegexpMatches(text, 'MockTINCTestCaseForResults.test_skip \.\.\. .* \.\.\. skipped .*')
def test_some_combination(self):
# some combinations of the previous 4, this will require building a test suite
# and running that test suite with the TINCTextTestResult
suite = tinctest.TINCTestSuite()
suite.addTest(MockTINCTestCaseForResults('test_success'))
suite.addTest(MockTINCTestCaseForResults('test_failure'))
suite.addTest(MockTINCTestCaseForResults('test_error'))
suite.addTest(MockTINCTestCaseForResults('test_skip'))
with closing(_WritelnDecorator(StringIO())) as buffer:
tinc_test_result = TINCTestResultSet(buffer, True, 1)
suite.run(tinc_test_result)
text = buffer.getvalue()
self.assertEqual(tinc_test_result.testsRun, 4)
self.assertEqual(len(tinc_test_result.failures), 1)
self.assertEqual(len(tinc_test_result.errors), 1)
self.assertEqual(len(tinc_test_result.skipped), 1)
self.assertRegexpMatches(text, 'MockTINCTestCaseForResults.test_success \.\.\. .* \.\.\. ok')
self.assertRegexpMatches(text, 'MockTINCTestCaseForResults.test_failure \.\.\. .* \.\.\. FAIL')
self.assertRegexpMatches(text, 'MockTINCTestCaseForResults.test_error \.\.\. .* \.\.\. ERROR')
self.assertRegexpMatches(text, 'MockTINCTestCaseForResults.test_skip \.\.\. .* \.\.\. skipped .*')
class TINCPulseIntegrationTests(unittest.TestCase):
p = re.compile('(.*) \((.*)\) \"(.*)\" \.\.\. (.*)\.\d\d ms \.\.\. (\w+)\s?(.*)')
def test_success(self):
tinc_test_case = MockTINCTestCaseForResults('test_success')
tinc_test_case.__class__.__unittest_skip__ = False
with closing(_WritelnDecorator(StringIO())) as buffer:
# Run tinc test with verbosity=2 similar to Pulse
tinc_test_result = tinctest.TINCTextTestResult(buffer, descriptions=True, verbosity=2)
tinc_test_case.run(tinc_test_result)
text = buffer.getvalue()
match_object = self.p.match(text)
self.assertEqual(match_object.group(1), 'MockTINCTestCaseForResults.test_success')
self.assertEqual(match_object.group(5), 'ok')
def test_failure(self):
tinc_test_case = MockTINCTestCaseForResults('test_failure')
tinc_test_case.__class__.__unittest_skip__ = False
with closing(_WritelnDecorator(StringIO())) as buffer:
# Run tinc test with verbosity=2 similar to Pulse
tinc_test_result = tinctest.TINCTextTestResult(buffer, descriptions=True, verbosity=2)
tinc_test_case.run(tinc_test_result)
text = buffer.getvalue()
match_object = self.p.match(text)
self.assertEqual(match_object.group(1), 'MockTINCTestCaseForResults.test_failure')
self.assertEqual(match_object.group(5), 'FAIL')
def test_error(self):
tinc_test_case = MockTINCTestCaseForResults('test_error')
tinc_test_case.__class__.__unittest_skip__ = False
with closing(_WritelnDecorator(StringIO())) as buffer:
# Run tinc test with verbosity=2 similar to Pulse
tinc_test_result = tinctest.TINCTextTestResult(buffer, descriptions=True, verbosity=2)
tinc_test_case.run(tinc_test_result)
text = buffer.getvalue()
match_object = self.p.match(text)
self.assertEqual(match_object.group(1), 'MockTINCTestCaseForResults.test_error')
self.assertEqual(match_object.group(5), 'ERROR')
def test_skip(self):
tinc_test_case = MockTINCTestCaseForResults('test_skip')
tinc_test_case.__class__.__unittest_skip__ = False
with closing(_WritelnDecorator(StringIO())) as buffer:
# Run tinc test with verbosity=2 similar to Pulse
tinc_test_result = tinctest.TINCTextTestResult(buffer, descriptions=True, verbosity=2)
tinc_test_case.run(tinc_test_result)
text = buffer.getvalue()
match_object = self.p.match(text)
self.assertEqual(match_object.group(1), 'MockTINCTestCaseForResults.test_skip')
self.assertEqual(match_object.group(5), 'skipped')
self.assertEqual(match_object.group(6), "'i feel like it'")
@unittest.skip('mock')
class MockTINCTestCaseForLoader(tinctest.TINCTestCase):
@classmethod
def setUpClass(cls):
pass
@classmethod
def loadTestsFromTestCase(cls):
"""
Custom load tests for this test case. Return the two tests
from this class and check that when we call loadTestsFromName
for this test case class , these methods will be executed twice
once that will be loaded by default the unit test loader
and once as a result of calling loadTestsfromTestCase from within
loadTestsFromTestCase in TINCTestLoader.
"""
tests = []
tests.append(MockTINCTestCaseForLoader('test_0'))
tests.append(MockTINCTestCaseForLoader('test_1'))
return tests
def test_0(self):
"""
@description test test case
@created 2012-07-05 12:00:00
@modified 2012-07-08 12:00:02
@tags tag1 tag2 tag3
"""
pass
def test_1(self):
"""
@description test test case
@created 2012-07-05 12:00:00
@modified 2012-07-08 12:00:02
@tags tag1 tag2 tag3
"""
pass
class TINCTestLoaderTests(unittest.TestCase):
def test_load_explicit_defined_test_from_name(self):
"""
Test loadTestsFromName for an already defined python test method
"""
test_loader = tinctest.TINCTestLoader()
test_suite = test_loader.loadTestsFromName('tinctest.test.test_core.MockTINCTestCaseForLoader.test_0')
test_case = test_suite._tests[0]
self.assertIsNotNone(test_case)
self.assertEqual(test_case.name, 'MockTINCTestCaseForLoader.test_0')
self.assertEqual(test_case.author, 'balasr3')
self.assertEqual(test_case.description, 'test test case')
self.assertEqual(test_case.created_datetime, datetime.strptime('2012-07-05 12:00:00', '%Y-%m-%d %H:%M:%S'))
self.assertEqual(test_case.modified_datetime, datetime.strptime('2012-07-08 12:00:02', '%Y-%m-%d %H:%M:%S'))
self.assertEqual(test_case.tags, set(['tag1', 'tag2', 'tag3']))
def test_load_tests_from_class_name(self):
"""
Test whether the loadTestsFromTestCase defined in the class above is called
when we provide a class name as an input to the loader's loadTestsFromName.
loadTestsFromName in TINCTestLoader will call loadTestsFromTestCase in TINCTestLoader
when the name is a class that can be imported which in turn will look for 'loadTestsFromTestCase'
in the class to do a custom loading of tests for the test case class.
Here we test that the above loadTestsFromTestCase in MockTINCTestCaseForLoader
will be called when we provide MockTINCTestCaseForLoader as an input to loadTestsFromName.
This should result in four tests loaded as a result of calling loadTestsFromName even though there
are only two tests in the above class because we are adding additional two tests in the loadTestsFromTestCase
implementation above.
"""
test_loader = tinctest.TINCTestLoader()
test_suite = test_loader.loadTestsFromName('tinctest.test.test_core.MockTINCTestCaseForLoader')
self.assertIsNotNone(test_suite)
self.assertEqual(len(test_suite._tests), 4)
def test_load_invalid_class_name(self):
test_loader = tinctest.TINCTestLoader()
with self.assertRaises(AttributeError) as cm:
test_suite = test_loader.loadTestsFromName('tinctest.test.test_core.blah')
the_exception = cm.exception
# Assert the right error message
expected_error_message = "module object 'tinctest.test.test_core' has no attribute 'blah'"
self.assertEqual(str(the_exception), expected_error_message)
# With invalid method
with self.assertRaises(AttributeError) as cm:
test_suite = test_loader.loadTestsFromName('tinctest.test.test_core.MockTINCTestCaseForLoader.blah')
the_exception = cm.exception
# Assert the right error message
expected_error_message = "type object 'MockTINCTestCaseForLoader' has no attribute 'blah'"
self.assertEqual(str(the_exception), expected_error_message)
@unittest.skip('mock')
class MockTINCTestCaseForLoaderDiscovery(tinctest.TINCTestCase):
def test_lacking_product_version(self):
"""
@maintainer balasr3
@description test stuff
@created 2012-07-05 12:00:00
@modified 2012-07-05 12:00:02
@tags storage executor
"""
pass
class TINCTestLoaderDiscoveryTests(unittest.TestCase):
def test_matching_author(self):
loader = tinctest.TINCTestLoader()
test_suite = loader.loadTestsFromName('tinctest.test.test_core.MockTINCTestCaseForLoaderDiscovery.test_lacking_product_version')
filtered_test_suite = loader._filter_and_expand(test_suite, TINCDiscoveryQueryHandler(['author=pedroc']))
self.assertEquals(len(filtered_test_suite._tests), 1)
filtered_test_suite = loader._filter_and_expand(test_suite, TINCDiscoveryQueryHandler(['author=kumara64']))
self.assertEquals(len(filtered_test_suite._tests), 0)
def test_matching_maintainer(self):
loader = tinctest.TINCTestLoader()
test_suite = loader.loadTestsFromName('tinctest.test.test_core.MockTINCTestCaseForLoaderDiscovery.test_lacking_product_version')
filtered_test_suite = loader._filter_and_expand(test_suite, TINCDiscoveryQueryHandler(['maintainer=balasr3']))
self.assertEquals(len(filtered_test_suite._tests), 1)
filtered_test_suite = loader._filter_and_expand(test_suite, TINCDiscoveryQueryHandler(['maintainer=kumara64']))
self.assertEquals(len(filtered_test_suite._tests), 0)
def test_matching_tags(self):
loader = tinctest.TINCTestLoader()
test_suite = loader.loadTestsFromName('tinctest.test.test_core.MockTINCTestCaseForLoaderDiscovery.test_lacking_product_version')
filtered_test_suite = loader._filter_and_expand(test_suite, TINCDiscoveryQueryHandler(['tags=storage']))
self.assertEquals(len(filtered_test_suite._tests), 1)
filtered_test_suite = loader._filter_and_expand(test_suite, TINCDiscoveryQueryHandler(['tags=kumara64']))
self.assertEquals(len(filtered_test_suite._tests), 0)
def test_matching_multiple_tags(self):
loader = tinctest.TINCTestLoader()
test_suite = loader.loadTestsFromName('tinctest.test.test_core.MockTINCTestCaseForLoaderDiscovery.test_lacking_product_version')
filtered_test_suite = loader._filter_and_expand(test_suite, TINCDiscoveryQueryHandler(['tags=storage', 'tags=executor']))
self.assertEquals(len(filtered_test_suite._tests), 1)
filtered_test_suite = loader._filter_and_expand(test_suite, TINCDiscoveryQueryHandler(['tags=storage', 'tags=optimizer']))
self.assertEquals(len(filtered_test_suite._tests), 0)
def test_discover_with_invalid_imports(self):
tinc_test_loader = tinctest.TINCTestLoader()
pwd = os.path.dirname(inspect.getfile(self.__class__))
test_dir = os.path.join(pwd, 'data_provider')
tinc_test_suite = tinc_test_loader.discover(start_dirs = [test_dir],
patterns = ['discover_invalid_imports.py'],
top_level_dir = test_dir)
self.assertEquals(len(tinc_test_suite._tests), 1)
with closing(_WritelnDecorator(StringIO())) as buffer:
tinc_test_result = tinctest.TINCTestResultSet(buffer, True, 1)
tinc_test_suite.run(tinc_test_result)
# This should have thrown a ModuleImportFailure error
self.assertTrue('ModuleImportFailure' in str(tinc_test_result.errors[0][0]))
def test_discover_multiple_folders(self):
tinc_test_loader = tinctest.TINCTestLoader()
pwd = os.path.dirname(inspect.getfile(self.__class__))
test_dir1 = os.path.join(pwd, 'folder1')
test_dir2 = os.path.join(pwd, 'folder2')
tinc_test_suite = tinc_test_loader.discover(start_dirs = [test_dir1, test_dir2],
patterns = ['test*', 'regress*'],
top_level_dir = None)
self.assertEquals(len(tinc_test_suite._tests), 4)
def test_discover_folder_failure(self):
tinc_test_loader = tinctest.TINCTestLoader()
pwd = os.path.dirname(inspect.getfile(self.__class__))
test_dir3 = os.path.join(pwd, 'folder3_failure')
tinc_test_suite = tinc_test_loader.discover(start_dirs = [test_dir3],
patterns = ['test*', 'regress*'],
top_level_dir = None,
query_handler = None)
# 2 tests for folder1, 2 tests for folder2
# 4 tests for folder3 test module and regress module from Pass classes
# 4 actual tests for folder3 test module and regress module from Fail classes shouldn't load, but
# 2 "tests" for load failure should be there
test_count = 0
load_failure_count = 0
for module in tinc_test_suite._tests:
for suite in module:
for test in suite._tests:
test_count += 1
if 'TINCTestCaseLoadFailure' in str(test):
load_failure_count += 1
self.assertEquals(test_count, 6)
self.assertEquals(load_failure_count, 2)
def test_all_tests_loaded(self):
tinc_test_loader = tinctest.TINCTestLoader()
pwd = os.path.dirname(inspect.getfile(self.__class__))
test_dir1 = os.path.join(pwd, 'dryrun/mocktests')
tinc_test_suite = tinc_test_loader.discover(start_dirs = [test_dir1],
patterns = ['dryrun_test_sample2.py'],
top_level_dir = None)
self.assertEquals(tinc_test_suite.countTestCases(), 3)
flat_test_suite = TINCTestSuite()
tinc_test_suite.flatten(flat_test_suite)
for test in flat_test_suite._tests:
self.assertTrue(test.__class__._all_tests_loaded)
test_dir1 = os.path.join(pwd, 'dryrun/mocktests')
tinc_test_suite = tinc_test_loader.discover(start_dirs = [test_dir1],
patterns = ['dryrun_test_sample2.py'],
top_level_dir = None,
query_handler = TINCDiscoveryQueryHandler('tags=hawq'))
self.assertEquals(tinc_test_suite.countTestCases(), 1)
for test in flat_test_suite._tests:
self.assertFalse(test.__class__._all_tests_loaded)
@unittest.skip('mock')
class MockTINCTestCaseWithCustomResult(tinctest.TINCTestCase):
""" Mock TINCTestCase that uses its own result
used for below unittest TestCases """
def test_success(self):
self.assertTrue(True)
def test_failure(self):
self.assertTrue(False)
def test_error(self):
raise Exception
@unittest.expectedFailure
def test_expectedfailure(self):
self.assertTrue(False)
@unittest.expectedFailure
def test_unexpectedsuccess(self):
self.assertTrue(True)
@unittest.skip('skipping')
def test_skip(self):
pass
def defaultTestResult(self, stream=None, descriptions=None, verbosity=None):
if stream and descriptions and verbosity:
return MockTINCTestCaseWithCustomResultResult(stream, descriptions, verbosity)
else:
return unittest.TestResult()
def run(self, result = None):
super(MockTINCTestCaseWithCustomResult, self).run(result)
self._my_result = result
class MockTINCTestCaseWithCustomResultResult(TINCTextTestResult):
""" The Result class that is used by the test case MockTINCTestCaseWithCustomResult"""
def __init__(self, stream, descriptions, verbosity):
self._my_errors = 0
self._my_pass = 0
self._my_expected_failure = 0
self._my_failure = 0
self._my_unexpected_success = 0
self._my_skip = 0
super(MockTINCTestCaseWithCustomResultResult, self).__init__(stream, descriptions, verbosity)
def startTest(self, test):
pass
def addError(self, test, err):
self._my_errors += 1
self.result_detail['errors'] = 'errors'
super(MockTINCTestCaseWithCustomResultResult, self).addError(test, err)
def addFailure(self, test, err):
self._my_failure += 1
self.result_detail['failures'] = 'failures'
super(MockTINCTestCaseWithCustomResultResult, self).addFailure(test, err)
def addSuccess(self, test):
self._my_pass += 1
self.result_detail['success'] = 'success'
super(MockTINCTestCaseWithCustomResultResult, self).addSuccess(test)
def addSkip(self, test, reason):
self._my_skip += 1
self.result_detail['skip'] = 'skip'
super(MockTINCTestCaseWithCustomResultResult, self).addSkip(test, reason)
def addExpectedFailure(self, test, err):
self._my_expected_failure += 1
self.result_detail['expected_failure'] = 'expected_failure'
super(MockTINCTestCaseWithCustomResultResult, self).addExpectedFailure(test, err)
def addUnexpectedSuccess(self, test):
self._my_unexpected_success += 1
self.result_detail['unexpected_success'] = 'unexpected_success'
super(MockTINCTestCaseWithCustomResultResult, self).addUnexpectedSuccess(test)
class TINCCustomResultTests(unittest.TestCase):
"""This tests if we construct the appropriate result object for each instance of MockTINCTestCaseWithCustomResult
when invoked through the runner. Note that to use a custom result object , we have to invoke the tests through
the runner which will call tinc_test_suite._wrapped_run that will call out to the test case specific defaultTestResult()
method.
"""
def test_custom_result_add_success(self):
test_loader = tinctest.TINCTestLoader()
tinc_test_suite = test_loader.loadTestsFromName('tinctest.test.test_core.MockTINCTestCaseWithCustomResult')
for test in tinc_test_suite._tests:
if not 'test_skip' in test.name:
test.__class__.__unittest_skip__ = False
with closing(_WritelnDecorator(StringIO())) as buffer:
tinc_test_runner = TINCTestRunner(stream = buffer, descriptions = True, verbosity = 1)
tinc_test_runner.run(tinc_test_suite)
count = 0
for test in tinc_test_suite._tests:
if 'test_success' in test.name:
self.assertEqual(test._my_result._my_pass, 1)
self.assertEqual(test._my_result._my_errors, 0)
self.assertEqual(test._my_result._my_failure, 0)
self.assertEqual(test._my_result._my_skip, 0)
self.assertEqual(test._my_result._my_expected_failure, 0)
self.assertEqual(test._my_result._my_unexpected_success, 0)
self.assertEqual(len(test._my_result.result_detail), 1)
self.assertTrue('success' in test._my_result.result_detail)
count += 1
if 'test_failure' in test.name:
self.assertEqual(test._my_result._my_pass, 0)
self.assertEqual(test._my_result._my_errors, 0)
self.assertEqual(test._my_result._my_failure, 1)
self.assertEqual(test._my_result._my_skip, 0)
self.assertEqual(test._my_result._my_expected_failure, 0)
self.assertEqual(test._my_result._my_unexpected_success, 0)
self.assertEqual(len(test._my_result.result_detail), 1)
self.assertTrue('failures' in test._my_result.result_detail)
count += 1
if 'test_error' in test.name:
self.assertEqual(test._my_result._my_pass, 0)
self.assertEqual(test._my_result._my_errors, 1)
self.assertEqual(test._my_result._my_failure, 0)
self.assertEqual(test._my_result._my_skip, 0)
self.assertEqual(test._my_result._my_expected_failure, 0)
self.assertEqual(test._my_result._my_unexpected_success, 0)
self.assertEqual(len(test._my_result.result_detail), 1)
self.assertTrue('errors' in test._my_result.result_detail)
count += 1
if 'test_expectedfailure' in test.name:
self.assertEqual(test._my_result._my_pass, 0)
self.assertEqual(test._my_result._my_errors, 0)
self.assertEqual(test._my_result._my_failure, 0)
self.assertEqual(test._my_result._my_skip, 0)
self.assertEqual(test._my_result._my_expected_failure, 1)
self.assertEqual(test._my_result._my_unexpected_success, 0)
self.assertEqual(len(test._my_result.result_detail), 1)
self.assertTrue('expected_failure' in test._my_result.result_detail)
count += 1
if 'test_error' in test.name:
self.assertEqual(test._my_result._my_pass, 0)
self.assertEqual(test._my_result._my_errors, 1)
self.assertEqual(test._my_result._my_failure, 0)
self.assertEqual(test._my_result._my_skip, 0)
self.assertEqual(test._my_result._my_expected_failure, 0)
self.assertEqual(test._my_result._my_unexpected_success, 0)
self.assertEqual(len(test._my_result.result_detail), 1)
self.assertTrue('errors' in test._my_result.result_detail)
count += 1
if 'test_skip' in test.name:
self.assertEqual(test._my_result._my_pass, 0)
self.assertEqual(test._my_result._my_errors, 0)
self.assertEqual(test._my_result._my_failure, 0)
self.assertEqual(test._my_result._my_skip, 1)
self.assertEqual(test._my_result._my_expected_failure, 0)
self.assertEqual(test._my_result._my_unexpected_success, 0)
count += 1
self.assertEqual(len(test._my_result.result_detail), 1)
self.assertTrue('skip' in test._my_result.result_detail)
self.assertEqual(count, 6)
|
StarcoderdataPython
|
1697131
|
<reponame>pamjesus/RotorHazard<gh_stars>1-10
'''
RotorHazard event manager
'''
import gevent
from monotonic import monotonic
class EventManager:
processEventObj = gevent.event.Event()
events = {}
eventOrder = {}
eventThreads = {}
def __init__(self):
pass
def on(self, event, name, handlerFn, defaultArgs=None, priority=200, unique=False):
if event not in self.events:
self.events[event] = {}
self.events[event][name] = {
"handlerFn": handlerFn,
"defaultArgs": defaultArgs,
"priority": priority,
"unique": unique
}
self.eventOrder[event] = sorted(self.events[event].items(), key=lambda x: x[1]['priority'])
return True
def trigger(self, event, evtArgs=None):
if event in self.events:
for handlerlist in self.eventOrder[event]:
for name in handlerlist:
handler = self.events[event][name]
args = handler['defaultArgs']
if evtArgs:
if args:
args.update(evtArgs)
else:
args = evtArgs
if handler['priority'] < 100:
# stop any threads with same name
if name in self.eventThreads:
if self.eventThreads[name] is not None:
self.eventThreads[name].kill()
self.eventThreads[name] = None
handler['handlerFn'](args)
else:
# restart thread with same name regardless of status
if name in self.eventThreads:
if self.eventThreads[name] is not None:
self.eventThreads[name].kill()
if handler['unique']:
token = monotonic()
self.eventThreads[name + str(token)] = gevent.spawn(handler['handlerFn'], args)
else:
self.eventThreads[name] = gevent.spawn(handler['handlerFn'], args)
return True
return False
class Evt:
# Program
STARTUP = 'startup'
SHUTDOWN = 'shutdown'
OPTION_SET = 'optionSet'
MESSAGE_STANDARD = 'messageStandard'
MESSAGE_INTERRUPT = 'messageInterrupt'
# Event setup
FREQUENCY_SET = 'frequencySet'
ENTER_AT_LEVEL_SET = 'enterAtLevelSet'
EXIT_AT_LEVEL_SET = 'exitAtLevelSet'
PROFILE_SET = 'profileSet'
PROFILE_ADD = 'profileAdd'
PROFILE_ALTER = 'profileAlter'
PROFILE_DELETE = 'profileDelete'
PILOT_ADD = 'pilotAdd'
PILOT_ALTER = 'pilotAlter'
PILOT_DELETE = 'pilotDelete'
HEAT_SET = 'heatSet'
HEAT_ADD = 'heatAdd'
HEAT_DUPLICATE = 'heatDuplicate'
HEAT_ALTER = 'heatAlter'
HEAT_DELETE = 'heatDelete'
HEAT_GENERATE = 'heatGenerate'
CLASS_ADD = 'classAdd'
CLASS_DUPLICATE = 'classDuplicate'
CLASS_ALTER = 'classAlter'
CLASS_DELETE = 'classDelete'
# Database
DATABASE_BACKUP = 'databaseBackup'
DATABASE_RESET = 'databaseReset'
DATABASE_INITIALIZE = 'databaseInitialize'
DATABASE_RECOVER = 'databaseRecover'
# Race setup
MIN_LAP_TIME_SET = 'minLapTimeSet'
MIN_LAP_BEHAVIOR_SET = 'minLapBehaviorSet'
RACE_FORMAT_SET = 'raceFormatSet'
RACE_FORMAT_ADD = 'raceFormatAdd'
RACE_FORMAT_ALTER = 'raceFormatAlter'
RACE_FORMAT_DELETE = 'raceFormatDelete'
# Race sequence
RACE_SCHEDULE = 'raceSchedule'
RACE_SCHEDULE_CANCEL = 'raceScheduleCancel'
RACE_STAGE = 'raceStage'
RACE_START = 'raceStart'
RACE_FINISH = 'raceFinish'
RACE_STOP = 'raceStop'
RACE_WIN = 'raceWin'
RACE_FIRST_PASS = 'raceFirstPass'
RACE_LAP_RECORDED = 'raceLapRecorded'
CROSSING_ENTER = 'crossingEnter'
CROSSING_EXIT = 'crossingExit'
# Race management
LAPS_SAVE = 'lapsSave'
LAPS_DISCARD = 'lapsDiscard'
LAPS_CLEAR = 'lapsClear'
LAPS_RESAVE = 'lapsResave'
LAP_DELETE = 'lapDelete'
# Results cache
CACHE_CLEAR = 'cacheClear'
CACHE_READY = 'cacheReady'
# CLUSTER
CLUSTER_JOIN = 'clusterJoin'
# LED
LED_EFFECT_SET = 'LedEffectSet'
LED_BRIGHTNESS_SET = 'LedBrightnessSet'
LED_MANUAL = 'LedManual'
# VRX Controller
VRX_DATA_RECEIVE = 'VrxDataRecieve'
|
StarcoderdataPython
|
12803521
|
import re
import struct
import ctypes
import itertools
def tokenize(string):
string_ = string
#print 'tokenizing: %s' % string
result = []
# pick off opcode
opcode = re.match(r'^(\w+)', string).group(1)
result.append(['OPC', opcode])
string = string[len(opcode):]
# pick off the rest
while string:
eat = 0
if string.startswith(' '):
eat = 1
elif re.match(r'^r\d+', string):
tmp = re.match(r'^(r\d+)', string).group(1) # eg: r0
result.append( ('GPR',int(tmp[1:])) )
eat = len(tmp)
elif re.match(r'^v\d+', string):
tmp = re.match(r'^(v\d+)', string).group(1) # eg: v0
result.append( ('VREG',int(tmp[1:])) )
eat = len(tmp)
elif len(string) >= 2 and string[0:2] in ['lt','gt','eq','so'] and \
(len(string)==2 or (re.match(r'[^\w]',string[2]))):
result.append( ('FLAG',string[0:2]) )
eat = 2
elif re.match(r'^cr\d+', string):
tmp = re.match(r'^(cr\d+)', string).group(1) # eg: cr1
result.append( ('CREG',int(tmp[2:])) )
eat = len(tmp)
elif re.match(r'^vs\d+', string):
tmp = re.match(r'^(vs\d+)', string).group(1) # eg: vs0
result.append( ('VSREG',int(tmp[2:])) )
eat = len(tmp)
elif re.match(r'^f\d+', string):
tmp = re.match(r'^(f\d+)', string).group(1) # eg: f0
result.append( ('FREG',int(tmp[1:])) )
eat = len(tmp)
elif re.match(r'^-?0x[a-fA-F0-9]+', string):
tmp = re.match(r'^(-?0x[a-fA-F0-9]+)', string).group(1)
result.append( ('NUM', int(tmp,16)) )
eat = len(tmp)
elif re.match(r'^-?\d+', string):
tmp = re.match(r'(^-?\d+)', string).group(1)
result.append( ('NUM', int(tmp)) )
eat = len(tmp)
elif string[0] in list('(),.*+-'):
result.append( (string[0],string[0]) )
eat = 1
else:
raise Exception('dunno what to do with: %s (original input: %s)' % (string, string_))
string = string[eat:]
return result
def tokenize_types(string):
tokens = tokenize(string)
types, values = zip(*tokens)
return ' '.join((values[0],) + types[1:])
(adapt, cbuf, ibuf) = (None, None, None)
def disasm(word):
global adapt, cbuf, ibuf
if not adapt:
adapt = ctypes.CDLL("gofer.so")
cbuf = ctypes.create_string_buffer(256)
ibuf = ctypes.create_string_buffer(4)
# form input buffer
data = struct.pack('<I', word)
# ask capstone
adapt.get_disasm_capstone(data, 4, ctypes.byref(cbuf))
return cbuf.value
def syntax_from_string(instr):
tokens = tokenize(instr)
syntax = tokens[0][1];
if tokens[1:]:
syntax += ' ' + ' '.join(map(lambda x: x[0], tokens[1:]))
return syntax
def syntax_from_insword(insword):
return syntax_from_string(disasm(insword))
# return all 32-bit values that have 4, 3, 2, 1 and 0 bits set
def fuzz4():
fuzz = [0]
for positions in itertools.combinations(range(32), 1):
mask = (1<<positions[0])
fuzz.append(mask)
for positions in itertools.combinations(range(32), 2):
mask = (1<<positions[0])|(1<<positions[1])
fuzz.append(mask)
for positions in itertools.combinations(range(32), 3):
mask = (1<<positions[0])|(1<<positions[1])|(1<<positions[2])
fuzz.append(mask)
for positions in itertools.combinations(range(32), 4):
mask = (1<<positions[0])|(1<<positions[1])|(1<<positions[2])|(1<<positions[3])
fuzz.append(mask)
# fuzz should have all 4-bit subsets, 3-bit subsets, 2-bit, 1-bit, 0-bit
assert len(fuzz) == 32*31*30*29/24 + 32*31*30/6 + 32*31/2 + 32 + 1
return fuzz
def fuzz5():
fuzz = fuzz4()
for positions in itertools.combinations(range(32), 5):
mask = (1<<positions[0])|(1<<positions[1])|(1<<positions[2])|(1<<positions[3])|(1<<positions[4])
fuzz.append(mask)
# fuzz should have all 4-bit subsets, 3-bit subsets, 2-bit, 1-bit, 0-bit
assert len(fuzz) == 32*31*30*29*28/120 + 32*31*30*29/24 + 32*31*30/6 + 32*31/2 + 32 + 1
return fuzz
def fuzz6():
fuzz = fuzz5()
for positions in itertools.combinations(range(32), 6):
mask = (1<<positions[0])|(1<<positions[1])|(1<<positions[2])|(1<<positions[3])|(1<<positions[4])|(1<<positions[5])
fuzz.append(mask)
# fuzz should have all 5-bit subets, 4-bit subsets, 3-bit subsets, 2-bit, 1-bit, 0-bit
assert len(fuzz) == 32*31*30*29*28*27/720 + 32*31*30*29*28/120 + 32*31*30*29/24 + 32*31*30/6 + 32*31/2 + 32 + 1
return fuzz
|
StarcoderdataPython
|
377121
|
<reponame>vectorcrumb/3D-face-tracker
import cv2
print(cv2.__version__)
if cv2.__version__ is '2.4.10':
print("Install working!")
exit(0)
|
StarcoderdataPython
|
1629849
|
<reponame>shaochangbin/chromium-crosswalk
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from benchmarks import silk_flags
from measurements import rasterize_and_record_micro
from telemetry import test
# RasterizeAndRecord disabled on mac because Chrome DCHECKS.
# TODO: Re-enable when unittests are happy: crbug.com/350684.
@test.Disabled('android', 'linux', 'mac')
class RasterizeAndRecordMicroTop25(test.Test):
"""Measures rasterize and record performance on the top 25 web pages.
http://www.chromium.org/developers/design-documents/rendering-benchmarks"""
test = rasterize_and_record_micro.RasterizeAndRecordMicro
page_set = 'page_sets/top_25.json'
@test.Disabled('mac')
class RasterizeAndRecordMicroKeyMobileSites(test.Test):
"""Measures rasterize and record performance on the key mobile sites.
http://www.chromium.org/developers/design-documents/rendering-benchmarks"""
test = rasterize_and_record_micro.RasterizeAndRecordMicro
page_set = 'page_sets/key_mobile_sites.json'
@test.Disabled('mac')
class RasterizeAndRecordMicroKeySilkCases(test.Test):
"""Measures rasterize and record performance on the silk sites.
http://www.chromium.org/developers/design-documents/rendering-benchmarks"""
test = rasterize_and_record_micro.RasterizeAndRecordMicro
page_set = 'page_sets/key_silk_cases.json'
@test.Disabled('mac')
class RasterizeAndRecordMicroFastPathKeySilkCases(test.Test):
"""Measures rasterize and record performance on the silk sites.
Uses bleeding edge rendering fast paths.
http://www.chromium.org/developers/design-documents/rendering-benchmarks"""
tag = 'fast_path'
test = rasterize_and_record_micro.RasterizeAndRecordMicro
page_set = 'page_sets/key_silk_cases.json'
def CustomizeBrowserOptions(self, options):
silk_flags.CustomizeBrowserOptionsForFastPath(options)
|
StarcoderdataPython
|
12809591
|
<reponame>misialq/qiime2<gh_stars>100-1000
# ----------------------------------------------------------------------------
# Copyright (c) 2016-2021, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ----------------------------------------------------------------------------
import os
import errno
import tempfile
import unittest
import unittest.mock as mock
import qiime2.util as util
EXDEV = OSError(errno.EXDEV, "Invalid cross-device link")
EPERM = PermissionError(errno.EPERM, "unsafe operation e.g. using link wrong")
EACCES = PermissionError(errno.EACCES, "insufficient r/w permissions")
SECRET = "this is a secret for testing, don't tell anyone!"
class TestDuplicate(unittest.TestCase):
def setUp(self):
self.test_dir = tempfile.TemporaryDirectory(prefix='qiime2-test-temp-')
self.dst1 = os.path.join(self.test_dir.name, 'dst1')
self.dst2 = os.path.join(self.test_dir.name, 'dst2')
self.dir = os.path.join(self.test_dir.name, 'dir')
with open(self.dst2, 'w') as fh:
fh.write("This is not the secret")
os.mkdir(self.dir)
self.src = os.path.join(self.test_dir.name, 'src')
self.missing = os.path.join(self.test_dir.name, 'missing')
with open(self.src, 'w') as fh:
fh.write(SECRET)
def tearDown(self):
self.test_dir.cleanup()
def test_src_not_exists(self):
with self.assertRaisesRegex(FileNotFoundError, self.missing):
util.duplicate(self.missing, self.dst1)
def test_src_dir(self):
with self.assertRaisesRegex(IsADirectoryError, self.dir):
util.duplicate(self.dir, self.dst1)
def test_dst_not_exists(self):
util.duplicate(self.src, self.dst1)
assert os.path.exists(self.dst1)
with open(self.dst1) as fh:
self.assertEqual(fh.read(), SECRET)
def test_dst_exists(self):
with self.assertRaisesRegex(FileExistsError, self.dst2):
util.duplicate(self.src, self.dst2)
def test_dst_dir(self):
with self.assertRaisesRegex(IsADirectoryError, self.dir):
util.duplicate(self.src, self.dir)
@mock.patch('qiime2.util.os.link', side_effect=EACCES)
def test_perm_error_EACCES(self, mocked_link):
with self.assertRaisesRegex(
PermissionError, "insufficient r/w permissions"):
util.duplicate(self.src, self.dst1)
assert mocked_link.called
@mock.patch('qiime2.util.os.link', side_effect=EPERM)
def test_perm_error_EPERM(self, mocked_link):
util.duplicate(self.src, self.dst1)
assert mocked_link.called
assert os.path.exists(self.dst1)
with open(self.dst1) as fh:
self.assertEqual(fh.read(), SECRET)
@mock.patch('qiime2.util.os.link', side_effect=EXDEV)
def test_cross_device_src_not_exists(self, mocked_link):
with self.assertRaisesRegex(FileNotFoundError, self.missing):
util.duplicate(self.missing, self.dst1)
@mock.patch('qiime2.util.os.link', side_effect=EXDEV)
def test_cross_device_src_dir(self, mocked_link):
with self.assertRaisesRegex(IsADirectoryError, self.dir):
util.duplicate(self.dir, self.dst1)
@mock.patch('qiime2.util.os.link', side_effect=EXDEV)
def test_cross_device_dst_not_exists(self, mocked_link):
util.duplicate(self.src, self.dst1)
assert mocked_link.called
assert os.path.exists(self.dst1)
with open(self.dst1) as fh:
self.assertEqual(fh.read(), SECRET)
@mock.patch('qiime2.util.os.link', side_effect=EXDEV)
def test_cross_device_dst_exists(self, mocked_link):
with self.assertRaisesRegex(FileExistsError, self.dst2):
util.duplicate(self.src, self.dst2)
@mock.patch('qiime2.util.os.link', side_effect=EXDEV)
def test_cross_device_dst_dir(self, mocked_link):
with self.assertRaisesRegex(IsADirectoryError, self.dir):
util.duplicate(self.src, self.dir)
@mock.patch('qiime2.util.os.link', side_effect=EXDEV)
@mock.patch('qiime2.util.shutil.copyfile', side_effect=EACCES)
def test_cross_device_perm_error(self, mocked_link, mocked_copyfile):
with self.assertRaisesRegex(
PermissionError, "insufficient r/w permissions"):
util.duplicate(self.src, self.dst1)
assert mocked_link.called
assert mocked_copyfile.called
if __name__ == '__main__':
unittest.main()
|
StarcoderdataPython
|
3232716
|
from setuptools import find_packages
from setuptools import setup
package_name = 'rclnodejs_pkg_creation_tool'
setup(
name=package_name,
version='0.0.1',
packages=find_packages(exclude=['test', 'scripts']),
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
],
install_requires=['ros2cli'],
zip_safe=True,
maintainer='<NAME>',
maintainer_email='<EMAIL>',
description='The pkg command for ROS 2 command line tools.',
long_description="""\
The package provides the pkg command for the ROS 2 command line tools.""",
license='Apache License, Version 2.0',
tests_require=['pytest'],
entry_points={
'ros2pkg.verb': [
'create_nodejs = rclnodejs_pkg_creation_tool.verb.create_nodejs_pkg:CreateROS2NodeJsPkgVerb',
]
},
package_data={
'rclnodejs_pkg_creation_tool': [
'resource/**/*', 'resource/**/**/*', 'resource/**/**/**/*',
],
},
)
|
StarcoderdataPython
|
4936556
|
<reponame>WeihaoTan/gym_cooking_env<gh_stars>0
import gym
import numpy as np
from gym import spaces
from env.items import Tomato, Lettuce, Plate, Knife, Delivery, Agent, Food
from env.render.game import Game
DIRECTION = [(0,1), (1,0), (0,-1), (-1,0)]
ITEMNAME = ["space", "counter", "agent", "tomato", "lettuce", "plate", "knife", "delivery"]
ITEMIDX= {"space": 0, "counter": 1, "agent": 2, "tomato": 3, "lettuce": 4, "plate": 5, "knife": 6, "delivery": 7}
AGENTCOLOR = ["blue", "magenta", "green", "yellow"]
TASKLIST = ["tomato salad", "lettuce salad", "tomato-lettuce salad"]
class Overcooked(gym.Env):
metadata = {
'render.modes': ['human', 'rgb_array'],
'video.frames_per_second' : 50
}
def __init__(self, grid_dim, map, task, rewardList, debug = False):
self.xlen, self.ylen = grid_dim
self.game = Game(self)
self.map = map
self.task = task
self.rewardList = rewardList
self.debug = debug
self.oneHotTask = []
for t in TASKLIST:
if t == self.task:
self.oneHotTask.append(1)
else:
self.oneHotTask.append(0)
self._createItems()
#action: move(up, down, left, right), stay
self.action_space = spaces.Discrete(5)
#Observation: agent(pos[x,y]) dim = 2
# knife(pos[x,y]) dim = 2
# delivery (pos[x,y]) dim = 2
# plate(pos[x,y]) dim = 2
# food(pos[x,y]/status) dim = 3
self.observation_space = spaces.Box(low=0, high=1, shape=(len(self._getObs()),), dtype=np.float32)
self.n_agent = len(self.agent)
def _createItems(self):
self.agent = []
self.knife = []
self.delivery = []
self.tomato = []
self.lettuce = []
self.plate = []
self.itemList = []
agent_idx = 0
for x in range(self.xlen):
for y in range(self.ylen):
if self.map[x][y] == ITEMIDX["agent"]:
self.agent.append(Agent(x, y, color = AGENTCOLOR[agent_idx]))
agent_idx += 1
elif self.map[x][y] == ITEMIDX["knife"]:
self.knife.append(Knife(x, y))
elif self.map[x][y] == ITEMIDX["delivery"]:
self.delivery.append(Delivery(x, y))
elif self.map[x][y] == ITEMIDX["tomato"]:
self.tomato.append(Tomato(x, y))
elif self.map[x][y] == ITEMIDX["lettuce"]:
self.lettuce.append(Lettuce(x, y))
elif self.map[x][y] == ITEMIDX["plate"]:
self.plate.append(Plate(x, y))
self.itemDic = {"agent": self.agent, "tomato": self.tomato, "lettuce": self.lettuce, "plate": self.plate, "knife": self.knife, "delivery": self.delivery}
for key in self.itemDic:
self.itemList += self.itemDic[key]
def _getObs(self):
obs = []
for item in self.itemList:
obs.append(item.x / self.xlen)
obs.append(item.y / self.ylen)
if isinstance(item, Food):
obs.append(item.cur_chopped_times / item.required_chopped_times)
obs += self.oneHotTask
return obs
def _findItem(self, x, y, itemName):
for item in self.itemDic[itemName]:
if item.x == x and item.y == y:
return item
@property
def obs_size(self):
return [self.observation_space.shape[0]] * self.n_agent
@property
def n_action(self):
return [a.n for a in self.action_spaces]
@property
def action_spaces(self):
return [self.action_space] * self.n_agent
def reset(self):
self._createItems()
return self._getObs()
def step(self, action):
reward = 0
done = False
info = {}
#action:move, stay
all_action_done = False
for agent in self.agent:
agent.moved = False
if self.debug:
print("in overcooked primitive actions:", action)
if action[0] < 4 and action[1] < 4:
new_agent0_x = self.agent[0].x + DIRECTION[action[0]][0]
new_agent0_y = self.agent[0].y + DIRECTION[action[0]][1]
new_agent1_x = self.agent[1].x + DIRECTION[action[1]][0]
new_agent1_y = self.agent[1].y + DIRECTION[action[1]][1]
if new_agent0_x == self.agent[1].x and new_agent0_y == self.agent[1].y\
and new_agent1_x == self.agent[0].x and new_agent1_y == self.agent[0].y:
self.agent[0].move(new_agent0_x, new_agent0_y)
self.agent[1].move(new_agent1_x, new_agent1_y)
if self.debug:
print("swap")
return self._getObs(), reward, done, info
while not all_action_done:
for idx, agent in enumerate(self.agent):
agent_action = action[idx]
agent.moved = True
if agent_action < 4:
target_x = agent.x + DIRECTION[agent_action][0]
target_y = agent.y + DIRECTION[agent_action][1]
target_name = ITEMNAME[self.map[target_x][target_y]]
if target_name == "agent":
target_agent = self._findItem(target_x, target_y, target_name)
if not target_agent.moved:
agent.moved = False
elif target_name == "space":
self.map[agent.x][agent.y] = ITEMIDX["space"]
agent.move(target_x, target_y)
self.map[target_x][target_y] = ITEMIDX["agent"]
#pickup and chop
elif not agent.holding:
if target_name == "tomato" or target_name == "lettuce" or target_name == "plate":
item = self._findItem(target_x, target_y, target_name)
agent.pickup(item)
self.map[target_x][target_y] = ITEMIDX["counter"]
elif target_name == "knife":
knife = self._findItem(target_x, target_y, target_name)
if isinstance(knife.holding, Plate):
item = knife.holding
knife.release()
agent.pickup(item)
elif isinstance(knife.holding, Food):
if knife.holding.chopped:
item = knife.holding
knife.release()
agent.pickup(item)
else:
knife.holding.chop()
if knife.holding.chopped:
if self.task == "tomato-lettuce salad"\
or (self.task == "tomato salad" and isinstance(knife.holding, Tomato)) \
or (self.task == "lettuce salad" and isinstance(knife.holding, Lettuce)):
reward += self.rewardList["subtask finished"]
#put down
elif agent.holding:
if target_name == "counter":
if isinstance(agent.holding, Tomato):
self.map[target_x][target_y] = ITEMIDX["tomato"]
elif isinstance(agent.holding, Lettuce):
self.map[target_x][target_y] = ITEMIDX["lettuce"]
elif isinstance(agent.holding, Plate):
self.map[target_x][target_y] = ITEMIDX["plate"]
agent.putdown(target_x, target_y)
elif target_name == "plate":
if isinstance(agent.holding, Food):
if agent.holding.chopped:
plate = self._findItem(target_x, target_y, target_name)
item = agent.holding
if self.task == "tomato-lettuce salad":
reward += self.rewardList["subtask finished"]
elif not plate.containing:
if (self.task == "tomato salad" and isinstance(item, Tomato)) \
or (self.task == "lettuce salad" and isinstance(item, Lettuce)):
reward += self.rewardList["subtask finished"]
agent.putdown(target_x, target_y)
plate.contain(item)
elif target_name == "knife":
knife = self._findItem(target_x, target_y, target_name)
if not knife.holding:
item = agent.holding
agent.putdown(target_x, target_y)
knife.hold(item)
elif isinstance(knife.holding, Food) and isinstance(agent.holding, Plate):
item = knife.holding
if item.chopped:
knife.release()
agent.holding.contain(item)
elif target_name == "delivery":
if isinstance(agent.holding, Plate):
if agent.holding.containing:
if len(agent.holding.containing) > 1 and self.task == "tomato-lettuce salad":
reward += self.rewardList["correct delivery"]
done = True
elif len(agent.holding.containing) == 1 and \
((agent.holding.containing[0].rawName == "tomato" and self.task == "tomato salad") \
or (agent.holding.containing[0].rawName == "lettuce" and self.task == "lettuce salad")):
reward += self.rewardList["correct delivery"]
done = True
else:
reward += self.rewardList["wrong delivery"]
item = agent.holding
agent.putdown(target_x, target_y)
food = item.containing
item.release()
item.refresh()
self.map[item.x][item.y] = ITEMIDX[item.name]
for f in food:
f.refresh()
self.map[f.x][f.y] = ITEMIDX[f.rawName]
elif target_name == "tomato" or target_name == "lettuce":
item = self._findItem(target_x, target_y, target_name)
if item.chopped and isinstance(agent.holding, Plate):
if self.task == "tomato-lettuce salad":
reward += self.rewardList["subtask finished"]
elif not agent.holding.containing:
if (self.task == "tomato salad" and target_name == "tomato") \
or (self.task == "lettuce salad" and target_name == "lettuce"):
reward += self.rewardList["subtask finished"]
agent.holding.contain(item)
self.map[target_x][target_y] = ITEMIDX["counter"]
any_agent_moved = False
for agent in self.agent:
if agent.moved == True:
any_agent_moved == True
if not any_agent_moved:
break
if done:
self.game.on_cleanup()
return self._getObs(), reward, done, info
def render(self, mode='human'):
return self.game.on_render()
|
StarcoderdataPython
|
8053411
|
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\interactions\jog_interaction.py
# Compiled at: 2020-07-22 05:56:20
# Size of source mod 2**32: 16676 bytes
from _math import Vector3
import itertools, random
from balloon.tunable_balloon import TunableBalloon
from element_utils import do_all
from event_testing.results import TestResult
from interactions import TargetType
from interactions.base.super_interaction import SuperInteraction
from interactions.constraints import Circle, ANYWHERE
from interactions.utils.routing import FollowPath, PlanRoute, get_route_element_for_path
from routing.walkstyle.walkstyle_request import WalkStyleRequest
from routing.waypoints.waypoint_generator_variant import TunableWaypointGeneratorVariant
from routing.waypoints.waypoint_stitching import WaypointStitchingVariant
from sims4 import random
from sims4.tuning.tunable import TunableRange, Tunable, OptionalTunable
from sims4.tuning.tunable_base import GroupNames
from sims4.utils import flexmethod
import element_utils, routing, sims4.log
logger = sims4.log.Logger('WaypointInteraction')
class _WaypointGeneratorRallyable:
def __init__(self, waypoint_info):
self._original_generator = waypoint_info
def get_start_constraint(self):
return self._original_generator.get_start_constraint()
def get_waypoint_constraints_gen(self, routing_agent, waypoint_count):
yield from self._original_generator.get_waypoint_constraints_gen(routing_agent, waypoint_count)
if False:
yield None
class WaypointInteraction(SuperInteraction):
INSTANCE_TUNABLES = {'waypoint_constraint':TunableWaypointGeneratorVariant(tuning_group=GroupNames.ROUTING),
'waypoint_count':TunableRange(description='\n The number of waypoints to select, from spawn points in the zone, to\n visit for a Jog prior to returning to the original location.\n ',
tunable_type=int,
default=2,
minimum=2,
tuning_group=GroupNames.ROUTING),
'waypoint_walk_style':WalkStyleRequest.TunableFactory(description='\n The walkstyle to use when routing between waypoints.\n ',
tuning_group=GroupNames.ROUTING),
'waypoint_stitching':WaypointStitchingVariant(tuning_group=GroupNames.ROUTING),
'waypoint_randomize_orientation':Tunable(description='\n Make Waypoint orientation random. Default is velocity aligned.\n ',
tunable_type=bool,
default=False,
tuning_group=GroupNames.ROUTING),
'waypoint_clear_locomotion_mask':Tunable(description='\n If enabled, override the locomotion queue mask. This mask controls\n which Animation Requests and XEvents get blocked during locomotion.\n By default, the mask blocks everything. If cleared, it blocks\n nothing. It also lowers the animation track used by locomotion to \n 9,999 from the default of 10,000. Use with care, ask your GPE.\n ',
tunable_type=bool,
default=False,
tuning_group=GroupNames.ROUTING),
'waypoint_override_agent_radius':OptionalTunable(description='\n If enabled, use the specified value as the agent radius when\n generating goals for the waypoints. The agent radius is restored\n for the actual route.\n ',
tunable=TunableRange(description='\n The value to use as the agent radius when generating goals. \n ',
tunable_type=float,
minimum=0,
maximum=1.0,
default=0.123),
tuning_group=GroupNames.ROUTING),
'waypoint_route_fail_balloon':OptionalTunable(description='\n Tuning for balloon to show when failing to plan a aroute for this waypoint interaction. \n ',
tunable=TunableBalloon(locked_args={'balloon_delay':0,
'balloon_delay_random_offset':0,
'balloon_chance':100}),
tuning_group=GroupNames.ROUTING)}
def __init__(self, aop, *args, waypoint_generator=None, **kwargs):
(super().__init__)(aop, *args, **kwargs)
waypoint_info = kwargs.get('waypoint_info')
if waypoint_info is not None:
self._waypoint_generator = _WaypointGeneratorRallyable(waypoint_info)
else:
if aop.target is None:
if self.target_type is TargetType.ACTOR:
target = self.sim
else:
target = aop.target
elif waypoint_generator is None:
self._waypoint_generator = self.waypoint_constraint(self.context, target)
else:
self._waypoint_generator = waypoint_generator
self._routing_infos = None
self._goal_size = 0.0
self.register_on_finishing_callback(self._clean_up_waypoint_generator)
@classmethod
def _test(cls, target, context, **interaction_parameters):
sim = context.sim
routing_master = sim.routing_master
if routing_master is not None:
if sim.parent is not routing_master:
return TestResult(False, '{} cannot run Waypoint interactions because they are following {}', sim, routing_master)
return (super()._test)(target, context, **interaction_parameters)
def _get_starting_constraint(self, *args, **kwargs):
constraint = ANYWHERE
target = self.target
if self._waypoint_generator.is_for_vehicle and target is not None and target.vehicle_component is not None:
constraint = target.is_in_inventory() or Circle((target.position), (target.vehicle_component.minimum_route_distance), routing_surface=(target.routing_surface))
constraint = constraint.intersect(self._waypoint_generator.get_water_constraint())
else:
constraint = self._waypoint_generator.get_start_constraint()
posture_constraint = self._waypoint_generator.get_posture_constraint()
if posture_constraint is not None:
constraint = constraint.intersect(posture_constraint)
return constraint
@flexmethod
def _constraint_gen(cls, inst, *args, **kwargs):
inst_or_cls = inst if inst is not None else cls
if inst is not None:
constraint = (inst._get_starting_constraint)(*args, **kwargs)
yield constraint
yield from (super(__class__, inst_or_cls)._constraint_gen)(*args, **kwargs)
def cancel(self, *args, **kwargs):
for sim_primitive in list(self.sim.primitives):
if isinstance(sim_primitive, FollowPath):
sim_primitive.detach()
return (super().cancel)(*args, **kwargs)
def _clean_up_waypoint_generator(self, _):
self._waypoint_generator.clean_up()
def _get_goals_for_constraint(self, constraint, routing_agent):
goals = []
handles = constraint.get_connectivity_handles(routing_agent)
for handle in handles:
goals.extend(handle.get_goals(always_reject_invalid_goals=True))
return goals
def _show_route_fail_balloon(self):
balloon_tuning = self.waypoint_route_fail_balloon
if balloon_tuning is None:
return
else:
return self.is_user_directed or None
balloon_requests = balloon_tuning(self)
if balloon_requests:
chosen_balloon = random.random.choice(balloon_requests)
if chosen_balloon is not None:
chosen_balloon.distribute()
def _run_interaction_gen(self, timeline):
all_sims = self.required_sims()
if not all_sims:
return
self._routing_infos = []
routing_agent = self.sim
for sim in all_sims:
routing_context = sim.routing_context
routing_agent = sim
vehicle = None if not sim.posture.is_vehicle else sim.parent
if vehicle is not None:
if vehicle.vehicle_component is not None:
routing_agent = vehicle
routing_context = vehicle.routing_component.pathplan_context
self._routing_infos.append((routing_agent, routing_context))
waypoints = []
default_agent_radius = None
if self.waypoint_override_agent_radius is not None:
if routing_agent.routing_component is not None:
default_agent_radius = routing_agent.routing_component._pathplan_context.agent_radius
routing_agent.routing_component._pathplan_context.agent_radius = self.waypoint_override_agent_radius
else:
try:
for constraint in self._waypoint_generator.get_waypoint_constraints_gen(routing_agent, self.waypoint_count):
goals = self._get_goals_for_constraint(constraint, routing_agent)
if not goals:
continue
if self.waypoint_randomize_orientation:
for goal in goals:
goal.orientation = sims4.math.angle_to_yaw_quaternion(random.uniform(0.0, sims4.math.TWO_PI))
waypoints.append(goals)
finally:
if default_agent_radius is not None:
routing_agent.routing_component._pathplan_context.agent_radius = default_agent_radius
return waypoints or False
self._goal_size = max((info[0].routing_component.get_routing_context().agent_goal_radius for info in self._routing_infos))
self._goal_size *= self._goal_size
if self.staging:
for route_waypoints in itertools.cycle(self.waypoint_stitching(waypoints, self._waypoint_generator.loops)):
result = yield from self._do_route_to_constraint_gen(route_waypoints, timeline)
if not result:
return result
else:
for route_waypoints in self.waypoint_stitching(waypoints, self._waypoint_generator.loops):
result = yield from self._do_route_to_constraint_gen(route_waypoints, timeline)
return result
return True
if False:
yield None
def _do_route_to_constraint_gen(self, waypoints, timeline):
if self.is_finishing:
return False
plan_primitives = []
for i, routing_info in enumerate(self._routing_infos):
routing_agent = routing_info[0]
routing_context = routing_info[1]
route = routing.Route((routing_agent.routing_location), (waypoints[(-1)]), waypoints=(waypoints[:-1]), routing_context=routing_context)
plan_primitive = PlanRoute(route, routing_agent, interaction=self)
result = yield from element_utils.run_child(timeline, plan_primitive)
if not result:
self._show_route_fail_balloon()
return False
plan_primitive.path.nodes and plan_primitive.path.nodes.plan_success or self._show_route_fail_balloon()
return False
plan_primitive.path.blended_orientation = self.waypoint_randomize_orientation
plan_primitives.append(plan_primitive)
if i == len(self._routing_infos) - 1:
continue
for node in plan_primitive.path.nodes:
position = Vector3(*node.position)
for goal in itertools.chain.from_iterable(waypoints):
if goal.routing_surface_id != node.routing_surface_id:
continue
dist_sq = (Vector3(*goal.position) - position).magnitude_2d_squared()
if dist_sq < self._goal_size:
goal.cost = routing.get_default_obstacle_cost()
route_primitives = []
track_override = None
mask_override = None
if self.waypoint_clear_locomotion_mask:
mask_override = 0
track_override = 9999
for plan_primitive in plan_primitives:
sequence = get_route_element_for_path((plan_primitive.sim), (plan_primitive.path), interaction=self,
force_follow_path=True,
track_override=track_override,
mask_override=mask_override)
walkstyle_request = self.waypoint_walk_style(plan_primitive.sim)
sequence = walkstyle_request(sequence=sequence)
route_primitives.append(sequence)
result = yield from element_utils.run_child(timeline, do_all(*route_primitives))
return result
if False:
yield None
@classmethod
def get_rallyable_aops_gen(cls, target, context, **kwargs):
key = 'waypoint_info'
if key not in kwargs:
waypoint_generator = cls.waypoint_constraint(context, target)
kwargs[key] = waypoint_generator
yield from (super().get_rallyable_aops_gen)(target, context, rally_constraint=waypoint_generator.get_start_constraint(), **kwargs)
if False:
yield None
|
StarcoderdataPython
|
4937575
|
class TestClass:
def reverse_string(self, str):
result = ""
i = len(str) - 1
while i >= 0:
result += str[i]
i -= 1
return result
def test_method(self):
print self.reverse_string("print value")
return "return value"
try:
TestClass().test_method()
except Exception as err:
print "Exception: " + err.message
|
StarcoderdataPython
|
3437712
|
<gh_stars>10-100
from discord.ext import commands
class Gateway(commands.Cog):
def __init__(self, bot):
self.bot = bot
db = self.bot.db()
self.collection = db["gateway"]
def setup(bot):
bot.add_cog(Gateway(bot))
|
StarcoderdataPython
|
11269792
|
<gh_stars>10-100
import time, datetime
from apscheduler.schedulers.blocking import BlockingScheduler
from src.sensors.sensors1_text import sonde1
from src.sensors.sensors2_piechart import sonde2
from src.sensors.sensors3_linechart import sonde3
from src.sensors.sensors4_cumulativeflow import sonde4
from src.sensors.sensors5_simplepercentage import sonde5
from src.sensors.sensors6_listing import sonde6
from src.sensors.sensors7_barchart import sonde7
from src.sensors.sensors9_bigvalue import sonde9
from src.sensors.sensors10_justvalue import sonde10
from src.sensors.sensors12_normchart import sonde12
from src.sensors.sensors14_radarchart import sonde14
from src.sensors.sensors15_polarchart import sonde15
from src.sensors.sensors16_dougnutchart import sonde16
from src.sensors.sensors17_halfdougnutchart import sonde17
from src.sensors.sensors18_gauge import sonde18
from src.sensors.sensors19_lineargauge import sonde19
from src.sensors.sensors20_radialgauge import sonde20
from src.sensors.sensors21_stream import sonde21 as sonde_stream
from src.sensors.sensors21_iframe import sonde21 as sonde_iframe
from src.sensors.sensors22_custom import sonde22
from src.sensors.utils import end
def addSchedule(scheduler, sonde, second=5, args=None):
scheduler.add_job(sonde, 'interval', seconds=second, args=args, next_run_time=datetime.datetime.now())
return 1
def test_sensors(tester):
sonde1(tester, 'txt_ex')
sonde2(tester, 'pie_chartjs_ex')
sonde3(tester, 'line_chart_ex')
sonde4(tester, 'cfjs_ex')
sonde5(tester, 'sp_ex')
sonde6(tester, 'listing_ex')
sonde7(tester, 'barjs_ex')
sonde7(tester, 'vbarjs_ex')
sonde9(tester, 'bv_ex')
sonde10(tester, 'jv_ex')
sonde12(tester, 'norm_chart')
sonde14(tester, 'radar_chart')
sonde15(tester, 'polararea_ex')
sonde16(tester, 'doughnut_ex')
sonde17(tester, 'half_doughnut_ex')
sonde18(tester, 'gauge_ex')
sonde19(tester, 'lgauge_ex')
sonde20(tester, 'rgauge_ex')
sonde_stream(tester, 'stream_ex')
sonde_iframe(tester, 'iframe_ex')
sonde22(tester, 'custom_ex ')
def scheduleYourSensors(scheduler=None, tester=None):
""" Schedule the script tu updates all tiles, rax is here to control by unit-test, that we test all tiles """
if scheduler is None:
scheduler = BlockingScheduler()
rax = 0
if not scheduler.running:
rax += addSchedule(scheduler, sonde1, args=[tester, 'txt_ex'])
rax += addSchedule(scheduler, sonde5, args=[tester, 'sp_ex'])
rax += addSchedule(scheduler, sonde6, args=[tester, 'listing_ex'])
rax += addSchedule(scheduler, sonde9, args=[tester, 'bv_ex'])
rax += addSchedule(scheduler, sonde10, args=[tester, 'jv_ex'])
rax += addSchedule(scheduler, sonde2, second=5, args=[tester, 'pie_chartjs_ex'])
rax += addSchedule(scheduler, sonde3, second=3, args=[tester, 'line_chartjs_ex'])
rax += addSchedule(scheduler, sonde4, second=19, args=[tester, 'cfjs_ex'])
rax += addSchedule(scheduler, sonde7, second=2, args=[tester, 'barjs_ex', True])
rax += addSchedule(scheduler, sonde7, second=2, args=[tester, 'vbarjs_ex3', False])
rax += addSchedule(scheduler, sonde12, second=45, args=[tester, 'normjs_ex'])
rax += addSchedule(scheduler, sonde14, second=2, args=[tester, 'radar_ex'])
rax += addSchedule(scheduler, sonde15, second=28, args=[tester, 'polararea_ex'])
rax += addSchedule(scheduler, sonde16, second=30, args=[tester, 'doughnut_ex'])
rax += addSchedule(scheduler, sonde17, second=30, args=[tester, 'half_doughnut_ex'])
rax += addSchedule(scheduler, sonde18, second=30, args=[tester, 'gauge_ex'])
rax += addSchedule(scheduler, sonde19, second=30, args=[tester, 'lgauge_ex'])
rax += addSchedule(scheduler, sonde20, second=30, args=[tester, 'rgauge_ex'])
rax += addSchedule(scheduler, sonde_stream, second=30, args=[tester, 'stream_ex'])
rax += addSchedule(scheduler, sonde_iframe, second=30, args=[tester, 'iframe_ex'])
rax += addSchedule(scheduler, sonde22, second=30, args=[tester, 'custom_ex'])
print("[DEBUG] Tipboard starting schedul task", flush=True)
scheduler.start()
return rax
def stopTheSensors(localScheduler):
if localScheduler is not None and localScheduler:
localScheduler.shutdown()
if __name__ == "__main__":
print("[DEBUG] Tipboard sensors initialisation", flush=True)
start_time = time.time()
scheduleYourSensors(BlockingScheduler()) # If you need actualized data :)
end(title="startUp", startTime=start_time)
|
StarcoderdataPython
|
9632601
|
<reponame>ardin/simple-django-login-and-register
BBBB BBBB
gettext(u'Your username is:')
|
StarcoderdataPython
|
1625953
|
import torch
import torch.nn.functional as F
from torch import nn
class PyramidPooling(nn.Module):
"""
Reference:
<NAME>, et al. *"Pyramid scene parsing network."*
"""
def __init__(self, in_channels, norm_layer, up_kwargs):
super(PyramidPooling, self).__init__()
self.pool1 = nn.AdaptiveAvgPool2d(1)
self.pool2 = nn.AdaptiveAvgPool2d(2)
self.pool3 = nn.AdaptiveAvgPool2d(3)
self.pool4 = nn.AdaptiveAvgPool2d(6)
out_channels = int(in_channels / 4)
self.conv1 = nn.Sequential(nn.Conv2d(in_channels, out_channels, 1, bias=False),
norm_layer(out_channels),
nn.ReLU(True))
self.conv2 = nn.Sequential(nn.Conv2d(in_channels, out_channels, 1, bias=False),
norm_layer(out_channels),
nn.ReLU(True))
self.conv3 = nn.Sequential(nn.Conv2d(in_channels, out_channels, 1, bias=False),
norm_layer(out_channels),
nn.ReLU(True))
self.conv4 = nn.Sequential(nn.Conv2d(in_channels, out_channels, 1, bias=False),
norm_layer(out_channels),
nn.ReLU(True))
# bilinear upsample options
self._up_kwargs = up_kwargs
def forward(self, x):
_, _, h, w = x.size()
feat1 = F.upsample(self.conv1(self.pool1(x)),
(h, w), **self._up_kwargs)
feat2 = F.upsample(self.conv2(self.pool2(x)),
(h, w), **self._up_kwargs)
feat3 = F.upsample(self.conv3(self.pool3(x)),
(h, w), **self._up_kwargs)
feat4 = F.upsample(self.conv4(self.pool4(x)),
(h, w), **self._up_kwargs)
return torch.cat((x, feat1, feat2, feat3, feat4), 1)
|
StarcoderdataPython
|
1874130
|
# Also, there's a timeout error which is managed by subprocess module.
class TIRCrashError(Exception):
pass
class IncorrectResult(Exception):
pass
class PerfDegradation(Exception):
pass
class RuntimeFailure(Exception):
pass
# Timeout...
class MaybeDeadLoop(Exception):
pass
|
StarcoderdataPython
|
9791092
|
<reponame>Ridhii/SyncdSim
#!/usr/bin/env python
import os
import sys
sys.path.append(os.path.join(os.environ["CONTECH_HOME"], "scripts"))
import util
import subprocess
import shutil
import time
import datetime
import glob
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib as matplotlib
import json
import math
import csv
def makeUnit(v):
unit = "B"
if (v > 10000):
v /= 1024
unit = "KB"
if (v > 10000):
v /= 1024
unit = "MB"
if (v > 10000):
v /= 1024
unit = "GB"
v = int(v)
return str(v) + unit
def main(arg):
if (len(arg)) == 1:
print "Usage: {0} input\n".format(arg[0])
exit()
p = 1
for harmony_in in arg[1:]:
# try:
with open(harmony_in, "r") as csvfile:
#sorry to use blah, but I blanked on a name for this latest temp
blah = csv.reader(csvfile)
rowNum = 0
meanSize = 0
totalAlloc = 0
sizeList = []
freqList = []
for row in blah:
if (rowNum == 0):
stats = []
for v in row[1:-1]:
stats.append(makeUnit(int(v)))
#stats = row[1:]
stats.append(str(100.0*float(row[-1])))
rowNum += 1
continue
if (len(row) < 3):
rowNum += 1
continue
r = map(int, row)
size = r[0]
numAlloc = r[1]
meanSize += size
totalAlloc += numAlloc
sizeList.append( size)
freqList.append(numAlloc)
if (rowNum == 0):
continue
if (totalAlloc > 0):
meanSize = meanSize / totalAlloc
medianNum = (totalAlloc + 1) / 2
pos = 0
count = 0
for a in sizeList:
count += freqList[pos]
if (count >= medianNum):
medianSize = a
break
pos += 1
harmony_l = harmony_in.split('/')
harmony_in = harmony_l[-1]
harmony_l = harmony_in.split('.')
harmony_in = harmony_l[-2]
pstr = harmony_in
pstats = ','.join(s for s in stats)
meanStr = makeUnit(meanSize)
medianStr = makeUnit(medianSize)
pstr = pstr + "," + pstats + ", {0}, {1}".format(meanStr, medianStr)
print pstr
if __name__ == "__main__":
main(sys.argv)
|
StarcoderdataPython
|
6618784
|
VERSION = (1, 0, 13)
|
StarcoderdataPython
|
8151378
|
import bisect
import cPickle as pickle
import re
from application.notification import IObserver, NotificationCenter
from application.python import Null
from application.python.types import Singleton
from datetime import date
from sipsimple.account import BonjourAccount
from sipsimple.threading import run_in_thread
from sipsimple.util import ISOTimestamp
from zope.interface import implements
from op2d.resources import ApplicationData
__all__ = ['HistoryManager']
class HistoryManager(object):
__metaclass__ = Singleton
implements(IObserver)
history_size = 20
def start(self):
try:
data = pickle.load(open(ApplicationData.get('calls_history')))
if not isinstance(data, list) or not all(isinstance(item, HistoryEntry) and item.text for item in data):
raise ValueError("invalid save data")
except Exception:
self.calls = []
else:
self.calls = data[-self.history_size:]
notification_center = NotificationCenter()
notification_center.add_observer(self, name='SIPSessionDidEnd')
notification_center.add_observer(self, name='SIPSessionDidFail')
def stop(self):
notification_center = NotificationCenter()
notification_center.remove_observer(self, name='SIPSessionDidEnd')
notification_center.remove_observer(self, name='SIPSessionDidFail')
@run_in_thread('file-io')
def save(self):
with open(ApplicationData.get('calls_history'), 'wb+') as history_file:
pickle.dump(self.calls, history_file)
def handle_notification(self, notification):
handler = getattr(self, '_NH_%s' % notification.name, Null)
handler(notification)
def _NH_SIPSessionDidEnd(self, notification):
if notification.sender.account is BonjourAccount():
return
session = notification.sender
entry = HistoryEntry.from_session(session)
bisect.insort(self.calls, entry)
self.calls = self.calls[-self.history_size:]
self.save()
def _NH_SIPSessionDidFail(self, notification):
if notification.sender.account is BonjourAccount():
return
session = notification.sender
entry = HistoryEntry.from_session(session)
if session.direction == 'incoming':
if notification.data.code != 487 or notification.data.failure_reason != 'Call completed elsewhere':
entry.failed = True
else:
if notification.data.code == 0:
entry.reason = 'Internal Error'
elif notification.data.code == 487:
entry.reason = 'Cancelled'
else:
entry.reason = notification.data.reason or notification.data.failure_reason
entry.failed = True
bisect.insort(self.calls, entry)
self.calls = self.calls[-self.history_size:]
self.save()
class HistoryEntry(object):
phone_number_re = re.compile(r'^(?P<number>(0|00|\+)[1-9]\d{7,14})@')
def __init__(self, direction, name, uri, account_id, call_time, duration, failed=False, reason=None):
self.direction = direction
self.name = name
self.uri = uri
self.account_id = account_id
self.call_time = call_time
self.duration = duration
self.failed = failed
self.reason = reason
self.text = self._generate_text()
def __reduce__(self):
return (self.__class__, (self.direction, self.name, self.uri, self.account_id, self.call_time, self.duration, self.failed, self.reason))
def __eq__(self, other):
return self is other
def __ne__(self, other):
return self is not other
def __lt__(self, other):
return self.call_time < other.call_time
def __le__(self, other):
return self.call_time <= other.call_time
def __gt__(self, other):
return self.call_time > other.call_time
def __ge__(self, other):
return self.call_time >= other.call_time
def _generate_text(self):
result = unicode(self.name or self.uri)
if self.call_time:
call_date = self.call_time.date()
today = date.today()
days = (today - call_date).days
if call_date == today:
result += self.call_time.strftime(" at %H:%M")
elif days == 1:
result += self.call_time.strftime(" Yesterday at %H:%M")
elif days < 7:
result += self.call_time.strftime(" on %A")
elif call_date.year == today.year:
result += self.call_time.strftime(" on %B %d")
else:
result += self.call_time.strftime(" on %Y-%m-%d")
if self.duration:
seconds = int(self.duration.total_seconds())
if seconds >= 3600:
result += """ (%dh%02d'%02d")""" % (seconds / 3600, (seconds % 3600) / 60, seconds % 60)
else:
result += """ (%d'%02d")""" % (seconds / 60, seconds % 60)
elif self.reason:
result += ' (%s)' % self.reason.title()
return result
@classmethod
def from_session(cls, session):
if session.start_time is None and session.end_time is not None:
# Session may have anded before it fully started
session.start_time = session.end_time
call_time = session.start_time or ISOTimestamp.now()
if session.start_time and session.end_time:
duration = session.end_time - session.start_time
else:
duration = None
remote_uri = '%s@%s' % (session.remote_identity.uri.user, session.remote_identity.uri.host)
match = cls.phone_number_re.match(remote_uri)
if match:
remote_uri = match.group('number')
display_name = session.remote_identity.display_name
return cls(session.direction, display_name, remote_uri, unicode(session.account.id), call_time, duration)
|
StarcoderdataPython
|
3237583
|
from colorama import Fore, init
init(autoreset=True)
def validaNumero(numero):
numero_real = input(numero)
while True:
if numero_real.isnumeric():
return int(numero_real)
break
else:
print(Fore.RED + 'ERRO! Digite um número válido!')
numero_real = input(numero)
n = validaNumero('Digite um número: ')
print(f' Você acabou de digitar o número {n}')
|
StarcoderdataPython
|
8124402
|
<filename>studies/event/gw151226_ias_points_no_m1m2_reweighting/plot_caches.py
from deep_gw_pe_followup.restricted_prior import RestrictedPrior
import matplotlib.pyplot as plt
from deep_gw_pe_followup import get_mpl_style
from deep_gw_pe_followup.plotting.hist2d import make_colormap_to_white, plot_heatmap
import os
from scipy.signal import savgol_filter
plt.style.use(get_mpl_style())
LAB_a1 = r"$\chi_1$"
LAB_cos1 = r"$\cos\theta_1$"
LAB_pa1 = r"$p(\chi_1|q,\chi_{\rm eff})$"
LAB_pc1 = r"$p(\cos\theta_1|\chi_1, q,\chi_{\rm eff})$"
LAB_pa1c1 = r"$p(\chi_1, \cos\theta_1| q,\chi_{\rm eff})$"
FSIZE = (3.2, 3.2)
COLOR = "C0"
def smooth(y):
return y
# return savgol_filter(y, window_length=21, polyorder=3)
def add_a1_line(ax, a1):
for i, a1i in enumerate(a1):
ax.axvline(a1i, color=f"C{i+1}", linestyle="dashed")
def plot_p_a1(p, basepth, a1=[]):
y = smooth(p['a_1'].yy)
fig, ax = plt.subplots(1, 1, figsize=FSIZE)
ax.set_xlabel(LAB_a1)
ax.set_ylabel(LAB_pa1)
ax.set_yticks([])
ax.set_xticks([0, 0.5, 1])
ax.set_ylim([min(y), max(y) * 1.1])
ax.set_xlim([0, 1])
ax.plot(p['a_1'].xx, y, color=COLOR)
if len(a1) > 0:
add_a1_line(ax, a1)
plt.minorticks_off()
plt.tight_layout()
plt.savefig(f"{basepth}/p_a1.png")
def plot_p_a1_cos1(p, basepth, a1=[]):
data = p.cached_cos1_data
fig, ax = plt.subplots(1, 1, figsize=FSIZE)
ax.set_xlabel(LAB_a1)
ax.set_ylabel(LAB_cos1)
ax.set_xticks([0.1, 0.5, 1])
ax.set_yticks([-1, 1])
cmap = make_colormap_to_white(COLOR)
plot_heatmap(x=data['a1'], y=data['cos1'], p=data['p_cos1'], ax=ax, cmap=cmap)
if len(a1) > 0:
add_a1_line(ax, a1)
plt.tight_layout()
plt.minorticks_off()
plt.savefig(f"{basepth}/p_a1c1.png")
def plot_p_cos1_given_a1(p, a1, basepth):
fig, ax = plt.subplots(1, 1, figsize=FSIZE)
ax.set_xlabel(LAB_cos1)
ax.set_ylabel(LAB_pc1)
ax.set_yticks([])
ax.set_xticks([-1, 0, 1])
ax.set_xlim([-1, 1])
for i, a1i in enumerate(a1):
c1_p = p.get_cos1_prior(a1i)
y = smooth(c1_p.yy)
ax.plot(c1_p.xx, y, color=f"C{i+1}")
ax.set_ylim(bottom=0)
plt.tight_layout()
plt.minorticks_off()
plt.savefig(f"{basepth}/p_c1.png")
def plot_cache(p, a1):
pth = f"{p.cache}/given_a1"
os.makedirs(pth, exist_ok=True)
plot_p_a1(p, pth, a1)
plot_p_a1_cos1(p, pth, a1)
plot_p_cos1_given_a1(p, a1, pth)
plt.tight_layout()
plt.savefig(f"{p.cache}/plot.png")
if __name__ == "__main__":
lvk_prior = RestrictedPrior(filename="priors/high_q.prior")
plot_cache(lvk_prior, a1=[0.3, 0.8])
# ias_prior = RestrictedPrior(filename="priors/low_q.prior")
# plot_cache(ias_prior, a1=0.8)
# plot_cache(ias_prior, a1=0.6)
|
StarcoderdataPython
|
1751482
|
#!/usr/bin/env python
import argparse
import base64
import json
import logging
import subprocess
import os
import grp
import pwd
import time
def mkdirs(path):
subprocess.check_call(["mkdir", "-p", path])
def subprocess_retry(supplier, retries, process_cmd):
if retries < 0:
logging.fatal("All retries of " + process_cmd + " attempted")
raise subprocess.CalledProcessError(process_cmd)
try:
return supplier()
except subprocess.CalledProcessError as err:
logging.warning("Subprocess failed " + str(err))
time.sleep(5)
subprocess_retry(supplier, retries - 1, process_cmd)
def authenticate(address, token):
process = ["vault", "auth", "-address", address, token]
subprocess_retry(lambda: subprocess.check_call(process), 5, ' '.join(process))
logging.info("Successfully authenticated against the vault server")
def read_secret(address, name):
process = ["vault", "read",
"-address", address,
"-format", "json",
"secret/{}".format(name)]
secret_data = subprocess_retry(lambda: json.loads(subprocess.check_output(process)
), 5, ' '.join(process))
logging.info("Retrieved secret {name} with request_id {rid}".format(
name=name,
rid=secret_data["request_id"])
)
warning = secret_data.get("warnings", None)
if not warning is None:
logging.warning("Warning: {}".format(warning))
return secret_data["data"]
def main():
parser = argparse.ArgumentParser(
description="Download secrets for Spinnaker stored by Halyard"
)
parser.add_argument("--token",
type=str,
help="Vault token for authentication.",
required=True
)
parser.add_argument("--address",
type=str,
help="Vault server's address.",
required=True
)
parser.add_argument("--secret",
type=str,
help="The secret name this instance config can be found in.",
required=True
)
args = parser.parse_args()
authenticate(args.address, args.token)
config_mount = read_secret(args.address, args.secret)
spinnaker_user = pwd.getpwnam("spinnaker").pw_uid
spinnaker_group = grp.getgrnam("spinnaker").gr_gid
for config in config_mount["configs"]:
secret_id = "{name}".format(name=config)
mount = read_secret(args.address, secret_id)
file_name = mount["file"]
contents = base64.b64decode(mount["contents"])
dir_name = os.path.dirname(file_name)
if not os.path.isdir(dir_name):
mkdirs(dir_name)
os.chown(dir_name, spinnaker_user, spinnaker_group)
with open(file_name, "w") as f:
logging.info("Writing config to {}".format(file_name))
f.write(contents)
os.chown(dir_name, spinnaker_user, spinnaker_group)
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
main()
|
StarcoderdataPython
|
3379805
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
import sys
import six
from pyopenapi.migration.base import ApiBase
from pyopenapi import utils, consts
def get_test_data_folder(version='1.2', which=''):
"""
"""
import pyopenapi.tests.data
version = 'v' + version.replace('.', '_')
folder = os.path.dirname(os.path.abspath(pyopenapi.tests.data.__file__))
folder = os.path.join(os.path.join(folder, version), which)
return folder
def get_test_file(version, which, file_name):
with open(
os.path.join(get_test_data_folder(version, which), file_name),
'r') as handle:
return handle.read()
class DictDB(dict):
""" Simple DB for singular model """
def __init__(self):
super(DictDB, self).__init__()
self._db = []
def create_(self, **data):
if [elm for elm in self._db if elm['id'] == data['id']]:
return False
self._db.append(data)
return True
def read_(self, key):
found = [elm for elm in self._db if elm['id'] == key]
if found:
return found[0]
return None
def update_(self, **data):
for elm in self._db:
if elm['id'] == data['id']:
elm.update(data)
return True
return False
def delete_(self, key):
residual = [elm for elm in self._db if elm['id'] != key]
found, self._db = (len(self._db) > len(residual)), residual
return found
_PET_TOM = dict(
id=1,
category=dict(id=1, name='dog'),
name='Tom',
tags=[dict(id=2, name='yellow'),
dict(id=3, name='big')],
status='sold')
_PET_MARY = dict(
id=2,
category=dict(id=2, name='cat'),
name='Mary',
tags=[dict(id=1, name='white'),
dict(id=4, name='small')],
status='pending')
_PET_JOHN = dict(
id=3,
category=dict(id=2, name='cat'),
name='John',
tags=[dict(id=2, name='yellow'),
dict(id=4, name='small')],
status='available')
_PET_SUE = dict(
id=4,
category=dict(id=3, name='fish'),
name='Sue',
tags=[dict(id=5, name='gold'),
dict(id=4, name='small')],
status='available')
def create_pet_db():
pet = DictDB()
pet.create_(**_PET_TOM)
pet.create_(**_PET_MARY)
pet.create_(**_PET_JOHN)
pet.create_(**_PET_SUE)
return pet
def gen_test_folder_hook(folder):
def _hook(url):
parsed = six.moves.urllib.parse.urlparse(url)
if parsed.scheme != 'file':
return url
path = os.path.join(folder, parsed.path
if not parsed.path.startswith('/') else
parsed.path[1:])
return six.moves.urllib.parse.urlunparse(parsed[:2] +
(path, ) + parsed[3:])
return _hook
def is_windows():
return os.name == 'nt'
def is_py2():
return sys.version_info.major < 3
class SampleApp(ApiBase):
""" app for test
"""
def __init__(self, url, url_load_hook, resolver, sep):
super(SampleApp, self).__init__(
url, url_load_hook=url_load_hook, resolver=resolver, sep=sep)
self.raw = None
self.root = None
def prepare_obj(self, obj, jref):
return obj
@classmethod
def load(cls,
url,
url_load_hook=None,
resolver=None,
getter=None,
sep=consts.SCOPE_SEPARATOR):
url = utils.normalize_url(url)
app = cls(url, url_load_hook, resolver, sep)
app.raw = app.load_obj(url, getter=getter)
return app
@classmethod
def create(cls,
url,
to_spec_version,
url_load_hook=None,
resolver=None,
getter=None,
sep=consts.SCOPE_SEPARATOR):
url = utils.normalize_url(url)
app = cls.load(
url,
url_load_hook=url_load_hook,
resolver=resolver,
getter=getter,
sep=sep)
app.root = app.migrate_obj(app.raw, url, to_spec_version)
return app
|
StarcoderdataPython
|
6463028
|
<filename>setup.py
from setuptools import setup
VERSION = '0.0.0'
setup(
name='django-cerebral-forms',
version=VERSION,
packages=['cerebral'],
install_requires=[],
description='Progressive forms for intelligent websites',
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
)
|
StarcoderdataPython
|
11321024
|
from src.models.resnet_simclr import ResNetSimCLR
from src.models.scatnet_simclr import ScatSimCLR
from src.models.logistic_regression import LogisticRegression
|
StarcoderdataPython
|
4971284
|
from datetime import timedelta
import grpc
from google.protobuf import empty_pb2
from psycopg2.extras import DateTimeTZRange
from sqlalchemy.sql import and_, func, or_, update
from couchers import errors
from couchers.db import can_moderate_node, get_parent_node_at_location, session_scope
from couchers.models import (
AttendeeStatus,
Cluster,
Event,
EventOccurrence,
EventOccurrenceAttendee,
EventOrganizer,
EventSubscription,
Node,
Thread,
Upload,
User,
)
from couchers.servicers.threads import thread_to_pb
from couchers.sql import couchers_select as select
from couchers.utils import (
Timestamp_from_datetime,
create_coordinate,
dt_from_millis,
millis_from_dt,
now,
to_aware_datetime,
)
from proto import events_pb2, events_pb2_grpc
attendancestate2sql = {
events_pb2.AttendanceState.ATTENDANCE_STATE_NOT_GOING: None,
events_pb2.AttendanceState.ATTENDANCE_STATE_GOING: AttendeeStatus.going,
events_pb2.AttendanceState.ATTENDANCE_STATE_MAYBE: AttendeeStatus.maybe,
}
attendancestate2api = {
None: events_pb2.AttendanceState.ATTENDANCE_STATE_NOT_GOING,
AttendeeStatus.going: events_pb2.AttendanceState.ATTENDANCE_STATE_GOING,
AttendeeStatus.maybe: events_pb2.AttendanceState.ATTENDANCE_STATE_MAYBE,
}
MAX_PAGINATION_LENGTH = 25
def _is_event_owner(event: Event, user_id):
"""
Checks whether the user can act as an owner of the event
"""
if event.owner_user:
return event.owner_user_id == user_id
# otherwise owned by a cluster
return event.owner_cluster.admins.where(User.id == user_id).one_or_none() is not None
def _can_moderate_event(session, event: Event, user_id):
# if the event is owned by a cluster, then any moderator of that cluster can moderate this event
if event.owner_cluster is not None and can_moderate_node(session, user_id, event.owner_cluster.parent_node_id):
return True
# finally check if the user can moderate the parent node of the cluster
return can_moderate_node(session, user_id, event.parent_node_id)
def _can_edit_event(session, event, user_id):
return _is_event_owner(event, user_id) or _can_moderate_event(session, event, user_id)
def event_to_pb(session, occurrence: EventOccurrence, context):
event = occurrence.event
next_occurrence = (
event.occurrences.where(EventOccurrence.end_time >= now()).order_by(EventOccurrence.end_time.asc()).first()
)
owner_community_id = None
owner_group_id = None
if event.owner_cluster:
if event.owner_cluster.is_official_cluster:
owner_community_id = event.owner_cluster.parent_node_id
else:
owner_group_id = event.owner_cluster.id
attendance = occurrence.attendees.where(EventOccurrenceAttendee.user_id == context.user_id).one_or_none()
attendance_state = attendance.attendee_status if attendance else None
can_moderate = _can_moderate_event(session, event, context.user_id)
going_count = session.execute(
select(func.count())
.select_from(EventOccurrenceAttendee)
.where_users_column_visible(context, EventOccurrenceAttendee.user_id)
.where(EventOccurrenceAttendee.occurrence_id == occurrence.id)
.where(EventOccurrenceAttendee.attendee_status == AttendeeStatus.going)
).scalar_one()
maybe_count = session.execute(
select(func.count())
.select_from(EventOccurrenceAttendee)
.where_users_column_visible(context, EventOccurrenceAttendee.user_id)
.where(EventOccurrenceAttendee.occurrence_id == occurrence.id)
.where(EventOccurrenceAttendee.attendee_status == AttendeeStatus.maybe)
).scalar_one()
organizer_count = session.execute(
select(func.count())
.select_from(EventOrganizer)
.where_users_column_visible(context, EventOrganizer.user_id)
.where(EventOrganizer.event_id == event.id)
).scalar_one()
subscriber_count = session.execute(
select(func.count())
.select_from(EventSubscription)
.where_users_column_visible(context, EventSubscription.user_id)
.where(EventSubscription.event_id == event.id)
).scalar_one()
return events_pb2.Event(
event_id=occurrence.id,
is_next=occurrence.id == next_occurrence.id,
title=event.title,
slug=event.slug,
content=occurrence.content,
photo_url=occurrence.photo.full_url if occurrence.photo else None,
online_information=events_pb2.OnlineEventInformation(
link=occurrence.link,
)
if occurrence.link
else None,
offline_information=events_pb2.OfflineEventInformation(
lat=occurrence.coordinates[0],
lng=occurrence.coordinates[1],
address=occurrence.address,
)
if occurrence.geom
else None,
created=Timestamp_from_datetime(occurrence.created),
last_edited=Timestamp_from_datetime(occurrence.last_edited),
creator_user_id=occurrence.creator_user_id,
start_time=Timestamp_from_datetime(occurrence.start_time),
end_time=Timestamp_from_datetime(occurrence.end_time),
timezone=occurrence.timezone,
start_time_display=str(occurrence.start_time),
end_time_display=str(occurrence.end_time),
attendance_state=attendancestate2api[attendance_state],
organizer=event.organizers.where(EventOrganizer.user_id == context.user_id).one_or_none() is not None,
subscriber=event.subscribers.where(EventSubscription.user_id == context.user_id).one_or_none() is not None,
going_count=going_count,
maybe_count=maybe_count,
organizer_count=organizer_count,
subscriber_count=subscriber_count,
owner_user_id=event.owner_user_id,
owner_community_id=owner_community_id,
owner_group_id=owner_group_id,
thread=thread_to_pb(event.thread_id),
can_edit=_is_event_owner(event, context.user_id),
can_moderate=can_moderate,
)
def _check_occurrence_time_validity(start_time, end_time, context):
if start_time < now():
context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.EVENT_IN_PAST)
if end_time < start_time:
context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.EVENT_ENDS_BEFORE_STARTS)
if end_time - start_time > timedelta(days=7):
context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.EVENT_TOO_LONG)
if start_time - now() > timedelta(days=365):
context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.EVENT_TOO_FAR_IN_FUTURE)
class Events(events_pb2_grpc.EventsServicer):
def CreateEvent(self, request, context):
if not request.title:
context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.MISSING_EVENT_TITLE)
if not request.content:
context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.MISSING_EVENT_CONTENT)
if request.HasField("online_information"):
online = True
geom = None
address = None
if not request.online_information.link:
context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.ONLINE_EVENT_REQUIRES_LINK)
link = request.online_information.link
elif request.HasField("offline_information"):
online = False
if not (
request.offline_information.address
and request.offline_information.lat
and request.offline_information.lng
):
context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.MISSING_EVENT_ADDRESS_OR_LOCATION)
if request.offline_information.lat == 0 and request.offline_information.lng == 0:
context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.INVALID_COORDINATE)
geom = create_coordinate(request.offline_information.lat, request.offline_information.lng)
address = request.offline_information.address
link = None
else:
context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.MISSING_EVENT_ADDRESS_LOCATION_OR_LINK)
start_time = to_aware_datetime(request.start_time)
end_time = to_aware_datetime(request.end_time)
_check_occurrence_time_validity(start_time, end_time, context)
with session_scope() as session:
if request.parent_community_id:
parent_node = session.execute(
select(Node).where(Node.id == request.parent_community_id)
).scalar_one_or_none()
else:
if online:
context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.ONLINE_EVENT_MISSING_PARENT_COMMUNITY)
# parent community computed from geom
parent_node = get_parent_node_at_location(session, geom)
if not parent_node:
context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.COMMUNITY_NOT_FOUND)
if (
request.photo_key
and not session.execute(select(Upload).where(Upload.key == request.photo_key)).scalar_one_or_none()
):
context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.PHOTO_NOT_FOUND)
event = Event(
title=request.title,
parent_node_id=parent_node.id,
owner_user_id=context.user_id,
thread=Thread(),
creator_user_id=context.user_id,
)
session.add(event)
occurrence = EventOccurrence(
event=event,
content=request.content,
geom=geom,
address=address,
link=link,
photo_key=request.photo_key if request.photo_key != "" else None,
# timezone=timezone,
during=DateTimeTZRange(start_time, end_time),
creator_user_id=context.user_id,
)
session.add(occurrence)
organizer = EventOrganizer(
user_id=context.user_id,
event=event,
)
session.add(organizer)
subscription = EventSubscription(
user_id=context.user_id,
event=event,
)
session.add(subscription)
attendee = EventOccurrenceAttendee(
user_id=context.user_id,
occurrence=occurrence,
attendee_status=AttendeeStatus.going,
)
session.add(attendee)
session.commit()
return event_to_pb(session, occurrence, context)
def ScheduleEvent(self, request, context):
if not request.content:
context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.MISSING_EVENT_CONTENT)
if request.HasField("online_information"):
online = True
geom = None
address = None
link = request.online_information.link
elif request.HasField("offline_information"):
online = False
if not (
request.offline_information.address
and request.offline_information.lat
and request.offline_information.lng
):
context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.MISSING_EVENT_ADDRESS_OR_LOCATION)
if request.offline_information.lat == 0 and request.offline_information.lng == 0:
context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.INVALID_COORDINATE)
geom = create_coordinate(request.offline_information.lat, request.offline_information.lng)
address = request.offline_information.address
link = None
else:
context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.MISSING_EVENT_ADDRESS_LOCATION_OR_LINK)
start_time = to_aware_datetime(request.start_time)
end_time = to_aware_datetime(request.end_time)
_check_occurrence_time_validity(start_time, end_time, context)
with session_scope() as session:
res = session.execute(
select(Event, EventOccurrence)
.where(EventOccurrence.id == request.event_id)
.where(EventOccurrence.event_id == Event.id)
).one_or_none()
if not res:
context.abort(grpc.StatusCode.NOT_FOUND, errors.EVENT_NOT_FOUND)
event, occurrence = res
if not _can_edit_event(session, event, context.user_id):
context.abort(grpc.StatusCode.PERMISSION_DENIED, errors.EVENT_EDIT_PERMISSION_DENIED)
if (
request.photo_key
and not session.execute(select(Upload).where(Upload.key == request.photo_key)).scalar_one_or_none()
):
context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.PHOTO_NOT_FOUND)
during = DateTimeTZRange(start_time, end_time)
# && is the overlap operator for ranges
if (
session.execute(
select(EventOccurrence.id)
.where(EventOccurrence.event_id == event.id)
.where(EventOccurrence.during.op("&&")(during))
)
.scalars()
.first()
is not None
):
context.abort(grpc.StatusCode.FAILED_PRECONDITION, errors.EVENT_CANT_OVERLAP)
occurrence = EventOccurrence(
event=event,
content=request.content,
geom=geom,
address=address,
link=link,
photo_key=request.photo_key if request.photo_key != "" else None,
# timezone=timezone,
during=during,
creator_user_id=context.user_id,
)
session.add(occurrence)
attendee = EventOccurrenceAttendee(
user_id=context.user_id,
occurrence=occurrence,
attendee_status=AttendeeStatus.going,
)
session.add(attendee)
session.flush()
# TODO: notify
return event_to_pb(session, occurrence, context)
def UpdateEvent(self, request, context):
with session_scope() as session:
res = session.execute(
select(Event, EventOccurrence)
.where(EventOccurrence.id == request.event_id)
.where(EventOccurrence.event_id == Event.id)
).one_or_none()
if not res:
context.abort(grpc.StatusCode.NOT_FOUND, errors.EVENT_NOT_FOUND)
event, occurrence = res
if not _can_edit_event(session, event, context.user_id):
context.abort(grpc.StatusCode.PERMISSION_DENIED, errors.EVENT_EDIT_PERMISSION_DENIED)
occurrence_update = {"last_edited": now()}
if request.HasField("title"):
event.title = request.title.value
event.last_edited = now()
if request.HasField("content"):
occurrence_update["content"] = request.content.value
if request.HasField("photo_key"):
occurrence_update["photo_key"] = request.photo_key.value
if request.HasField("online_information"):
if not request.online_information.link:
context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.ONLINE_EVENT_REQUIRES_LINK)
occurrence_update["link"] = request.online_information.link
occurrence_update["geom"] = None
occurrence_update["address"] = None
elif request.HasField("offline_information"):
occurrence_update["link"] = None
if request.offline_information.lat == 0 and request.offline_information.lng == 0:
context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.INVALID_COORDINATE)
occurrence_update["geom"] = create_coordinate(
request.offline_information.lat, request.offline_information.lng
)
occurrence_update["address"] = request.offline_information.address
if request.HasField("start_time") or request.HasField("end_time"):
if request.update_all_future:
context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.EVENT_CANT_UPDATE_ALL_TIMES)
if request.HasField("start_time"):
start_time = to_aware_datetime(request.start_time)
else:
start_time = occurrence.start_time
if request.HasField("end_time"):
end_time = to_aware_datetime(request.end_time)
else:
end_time = occurrence.end_time
_check_occurrence_time_validity(start_time, end_time, context)
during = DateTimeTZRange(start_time, end_time)
# && is the overlap operator for ranges
if (
session.execute(
select(EventOccurrence.id)
.where(EventOccurrence.event_id == event.id)
.where(EventOccurrence.id != occurrence.id)
.where(EventOccurrence.during.op("&&")(during))
)
.scalars()
.first()
is not None
):
context.abort(grpc.StatusCode.FAILED_PRECONDITION, errors.EVENT_CANT_OVERLAP)
occurrence_update["during"] = during
# TODO
# if request.HasField("timezone"):
# occurrence_update["timezone"] = request.timezone
# allow editing any event which hasn't ended more than 24 hours before now
# when editing all future events, we edit all which have not yet ended
if request.update_all_future:
session.execute(
update(EventOccurrence)
.where(EventOccurrence.end_time >= now() - timedelta(hours=24))
.where(EventOccurrence.start_time >= occurrence.start_time)
.values(occurrence_update)
.execution_options(synchronize_session=False)
)
else:
if occurrence.end_time < now() - timedelta(hours=24):
context.abort(grpc.StatusCode.FAILED_PRECONDITION, errors.EVENT_CANT_UPDATE_OLD_EVENT)
session.execute(
update(EventOccurrence)
.where(EventOccurrence.end_time >= now() - timedelta(hours=24))
.where(EventOccurrence.id == occurrence.id)
.values(occurrence_update)
.execution_options(synchronize_session=False)
)
# TODO notify
session.flush()
# since we have synchronize_session=False, we have to refresh the object
session.refresh(occurrence)
return event_to_pb(session, occurrence, context)
def GetEvent(self, request, context):
with session_scope() as session:
occurrence = session.execute(
select(EventOccurrence).where(EventOccurrence.id == request.event_id)
).scalar_one_or_none()
if not occurrence:
context.abort(grpc.StatusCode.NOT_FOUND, errors.EVENT_NOT_FOUND)
return event_to_pb(session, occurrence, context)
def ListEventOccurrences(self, request, context):
with session_scope() as session:
page_size = min(MAX_PAGINATION_LENGTH, request.page_size or MAX_PAGINATION_LENGTH)
# the page token is a unix timestamp of where we left off
page_token = dt_from_millis(int(request.page_token)) if request.page_token else now()
occurrence = session.execute(
select(EventOccurrence).where(EventOccurrence.id == request.event_id)
).scalar_one_or_none()
if not occurrence:
context.abort(grpc.StatusCode.NOT_FOUND, errors.EVENT_NOT_FOUND)
occurrences = select(EventOccurrence).where(EventOccurrence.event_id == Event.id)
if not request.past:
occurrences = occurrences.where(EventOccurrence.end_time > page_token - timedelta(seconds=1)).order_by(
EventOccurrence.start_time.asc()
)
else:
occurrences = occurrences.where(EventOccurrence.end_time < page_token + timedelta(seconds=1)).order_by(
EventOccurrence.start_time.desc()
)
occurrences = occurrences.limit(page_size + 1)
occurrences = session.execute(occurrences).scalars().all()
return events_pb2.ListEventOccurrencesRes(
events=[event_to_pb(session, occurrence, context) for occurrence in occurrences[:page_size]],
next_page_token=str(millis_from_dt(occurrences[-1].end_time)) if len(occurrences) > page_size else None,
)
def ListEventAttendees(self, request, context):
with session_scope() as session:
page_size = min(MAX_PAGINATION_LENGTH, request.page_size or MAX_PAGINATION_LENGTH)
next_user_id = int(request.page_token) if request.page_token else 0
occurrence = session.execute(
select(EventOccurrence).where(EventOccurrence.id == request.event_id)
).scalar_one_or_none()
if not occurrence:
context.abort(grpc.StatusCode.NOT_FOUND, errors.EVENT_NOT_FOUND)
attendees = (
session.execute(
select(EventOccurrenceAttendee)
.where_users_column_visible(context, EventOccurrenceAttendee.user_id)
.where(EventOccurrenceAttendee.occurrence_id == occurrence.id)
.where(EventOccurrenceAttendee.user_id >= next_user_id)
.order_by(EventOccurrenceAttendee.user_id)
.limit(page_size + 1)
)
.scalars()
.all()
)
return events_pb2.ListEventAttendeesRes(
attendee_user_ids=[attendee.user_id for attendee in attendees[:page_size]],
next_page_token=str(attendees[-1].user_id) if len(attendees) > page_size else None,
)
def ListEventSubscribers(self, request, context):
with session_scope() as session:
page_size = min(MAX_PAGINATION_LENGTH, request.page_size or MAX_PAGINATION_LENGTH)
next_user_id = int(request.page_token) if request.page_token else 0
res = session.execute(
select(Event, EventOccurrence)
.where(EventOccurrence.id == request.event_id)
.where(EventOccurrence.event_id == Event.id)
).one_or_none()
if not res:
context.abort(grpc.StatusCode.NOT_FOUND, errors.EVENT_NOT_FOUND)
event, occurrence = res
subscribers = (
session.execute(
select(EventSubscription)
.where_users_column_visible(context, EventSubscription.user_id)
.where(EventSubscription.event_id == event.id)
.where(EventSubscription.user_id >= next_user_id)
.order_by(EventSubscription.user_id)
.limit(page_size + 1)
)
.scalars()
.all()
)
return events_pb2.ListEventSubscribersRes(
subscriber_user_ids=[subscriber.user_id for subscriber in subscribers[:page_size]],
next_page_token=str(subscribers[-1].user_id) if len(subscribers) > page_size else None,
)
def ListEventOrganizers(self, request, context):
with session_scope() as session:
page_size = min(MAX_PAGINATION_LENGTH, request.page_size or MAX_PAGINATION_LENGTH)
next_user_id = int(request.page_token) if request.page_token else 0
res = session.execute(
select(Event, EventOccurrence)
.where(EventOccurrence.id == request.event_id)
.where(EventOccurrence.event_id == Event.id)
).one_or_none()
if not res:
context.abort(grpc.StatusCode.NOT_FOUND, errors.EVENT_NOT_FOUND)
event, occurrence = res
organizers = (
session.execute(
select(EventOrganizer)
.where_users_column_visible(context, EventOrganizer.user_id)
.where(EventOrganizer.event_id == event.id)
.where(EventOrganizer.user_id >= next_user_id)
.order_by(EventOrganizer.user_id)
.limit(page_size + 1)
)
.scalars()
.all()
)
return events_pb2.ListEventOrganizersRes(
organizer_user_ids=[organizer.user_id for organizer in organizers[:page_size]],
next_page_token=str(organizers[-1].user_id) if len(organizers) > page_size else None,
)
def TransferEvent(self, request, context):
with session_scope() as session:
res = session.execute(
select(Event, EventOccurrence)
.where(EventOccurrence.id == request.event_id)
.where(EventOccurrence.event_id == Event.id)
).one_or_none()
if not res:
context.abort(grpc.StatusCode.NOT_FOUND, errors.EVENT_NOT_FOUND)
event, occurrence = res
if not _can_edit_event(session, event, context.user_id):
context.abort(grpc.StatusCode.PERMISSION_DENIED, errors.EVENT_TRANSFER_PERMISSION_DENIED)
if request.WhichOneof("new_owner") == "new_owner_group_id":
cluster = session.execute(
select(Cluster).where(~Cluster.is_official_cluster).where(Cluster.id == request.new_owner_group_id)
).scalar_one_or_none()
elif request.WhichOneof("new_owner") == "new_owner_community_id":
cluster = session.execute(
select(Cluster)
.where(Cluster.parent_node_id == request.new_owner_community_id)
.where(Cluster.is_official_cluster)
).scalar_one_or_none()
if not cluster:
context.abort(grpc.StatusCode.NOT_FOUND, errors.GROUP_OR_COMMUNITY_NOT_FOUND)
event.owner_user = None
event.owner_cluster = cluster
session.commit()
return event_to_pb(session, occurrence, context)
def SetEventSubscription(self, request, context):
with session_scope() as session:
res = session.execute(
select(Event, EventOccurrence)
.where(EventOccurrence.id == request.event_id)
.where(EventOccurrence.event_id == Event.id)
).one_or_none()
if not res:
context.abort(grpc.StatusCode.NOT_FOUND, errors.EVENT_NOT_FOUND)
event, occurrence = res
current_subscription = session.execute(
select(EventSubscription)
.where(EventSubscription.user_id == context.user_id)
.where(EventSubscription.event_id == event.id)
).scalar_one_or_none()
# if not subscribed, subscribe
if request.subscribe and not current_subscription:
session.add(EventSubscription(user_id=context.user_id, event_id=event.id))
# if subscribed but unsubbing, remove subscription
if not request.subscribe and current_subscription:
session.delete(current_subscription)
session.flush()
return event_to_pb(session, occurrence, context)
def SetEventAttendance(self, request, context):
with session_scope() as session:
occurrence = session.execute(
select(EventOccurrence).where(EventOccurrence.id == request.event_id)
).scalar_one_or_none()
if not occurrence:
context.abort(grpc.StatusCode.NOT_FOUND, errors.EVENT_NOT_FOUND)
current_attendance = session.execute(
select(EventOccurrenceAttendee)
.where(EventOccurrenceAttendee.user_id == context.user_id)
.where(EventOccurrenceAttendee.occurrence_id == occurrence.id)
).scalar_one_or_none()
if request.attendance_state == events_pb2.ATTENDANCE_STATE_NOT_GOING:
if current_attendance:
session.delete(current_attendance)
# if unset/not going, nothing to do!
else:
if current_attendance:
current_attendance.attendee_status = attendancestate2sql[request.attendance_state]
else:
# create new
attendance = EventOccurrenceAttendee(
user_id=context.user_id,
occurrence_id=occurrence.id,
attendee_status=attendancestate2sql[request.attendance_state],
)
session.add(attendance)
session.flush()
return event_to_pb(session, occurrence, context)
def ListMyEvents(self, request, context):
with session_scope() as session:
page_size = min(MAX_PAGINATION_LENGTH, request.page_size or MAX_PAGINATION_LENGTH)
# the page token is a unix timestamp of where we left off
page_token = dt_from_millis(int(request.page_token)) if request.page_token else now()
occurrences = select(EventOccurrence).join(Event, Event.id == EventOccurrence.event_id)
include_all = not (request.subscribed or request.attending or request.organizing)
include_subscribed = request.subscribed or include_all
include_organizing = request.organizing or include_all
include_attending = request.attending or include_all
where_ = []
if include_subscribed:
occurrences = occurrences.outerjoin(
EventSubscription,
and_(EventSubscription.event_id == Event.id, EventSubscription.user_id == context.user_id),
)
where_.append(EventSubscription.user_id != None)
if include_organizing:
occurrences = occurrences.outerjoin(
EventOrganizer, and_(EventOrganizer.event_id == Event.id, EventOrganizer.user_id == context.user_id)
)
where_.append(EventOrganizer.user_id != None)
if include_attending:
occurrences = occurrences.outerjoin(
EventOccurrenceAttendee,
and_(
EventOccurrenceAttendee.occurrence_id == EventOccurrence.id,
EventOccurrenceAttendee.user_id == context.user_id,
),
)
where_.append(EventOccurrenceAttendee.user_id != None)
occurrences = occurrences.where(or_(*where_))
if not request.past:
occurrences = occurrences.where(EventOccurrence.end_time > page_token - timedelta(seconds=1)).order_by(
EventOccurrence.start_time.asc()
)
else:
occurrences = occurrences.where(EventOccurrence.end_time < page_token + timedelta(seconds=1)).order_by(
EventOccurrence.start_time.desc()
)
occurrences = occurrences.limit(page_size + 1)
occurrences = session.execute(occurrences).scalars().all()
return events_pb2.ListMyEventsRes(
events=[event_to_pb(session, occurrence, context) for occurrence in occurrences[:page_size]],
next_page_token=str(millis_from_dt(occurrences[-1].end_time)) if len(occurrences) > page_size else None,
)
def ListAllEvents(self, request, context):
with session_scope() as session:
page_size = min(MAX_PAGINATION_LENGTH, request.page_size or MAX_PAGINATION_LENGTH)
# the page token is a unix timestamp of where we left off
page_token = dt_from_millis(int(request.page_token)) if request.page_token else now()
occurrences = select(EventOccurrence).join(Event, Event.id == EventOccurrence.event_id)
if not request.past:
occurrences = occurrences.where(EventOccurrence.end_time > page_token - timedelta(seconds=1)).order_by(
EventOccurrence.start_time.asc()
)
else:
occurrences = occurrences.where(EventOccurrence.end_time < page_token + timedelta(seconds=1)).order_by(
EventOccurrence.start_time.desc()
)
occurances = occurrences.limit(page_size + 1)
occurrences = session.execute(occurances).scalars().all()
return events_pb2.ListAllEventsRes(
events=[event_to_pb(session, occurrence, context) for occurrence in occurrences[:page_size]],
next_page_token=str(millis_from_dt(occurrences[-1].end_time)) if len(occurrences) > page_size else None,
)
def InviteEventOrganizer(self, request, context):
with session_scope() as session:
res = session.execute(
select(Event, EventOccurrence)
.where(EventOccurrence.id == request.event_id)
.where(EventOccurrence.event_id == Event.id)
).one_or_none()
if not res:
context.abort(grpc.StatusCode.NOT_FOUND, errors.EVENT_NOT_FOUND)
event, occurrence = res
if not _can_edit_event(session, event, context.user_id):
context.abort(grpc.StatusCode.PERMISSION_DENIED, errors.EVENT_EDIT_PERMISSION_DENIED)
if not session.execute(
select(User).where_users_visible(context).where(User.id == request.user_id)
).scalar_one_or_none():
context.abort(grpc.StatusCode.PERMISSION_DENIED, errors.USER_NOT_FOUND)
organizer = EventOrganizer(
user_id=request.user_id,
event=event,
)
session.add(organizer)
session.flush()
# TODO: notify
return empty_pb2.Empty()
def RemoveEventOrganizer(self, request, context):
with session_scope() as session:
res = session.execute(
select(Event, EventOccurrence)
.where(EventOccurrence.id == request.event_id)
.where(EventOccurrence.event_id == Event.id)
).one_or_none()
if not res:
context.abort(grpc.StatusCode.NOT_FOUND, errors.EVENT_NOT_FOUND)
event, occurrence = res
if event.owner_user_id == context.user_id:
context.abort(grpc.StatusCode.FAILED_PRECONDITION, errors.EVENT_CANT_REMOVE_OWNER_AS_ORGANIZER)
current = session.execute(
select(EventOrganizer)
.where(EventOrganizer.user_id == context.user_id)
.where(EventOrganizer.event_id == event.id)
).scalar_one_or_none()
if not current:
context.abort(grpc.StatusCode.FAILED_PRECONDITION, errors.EVENT_NOT_AN_ORGANIZER)
session.delete(current)
return empty_pb2.Empty()
|
StarcoderdataPython
|
4938896
|
#!/usr/bin/env python3
"""
# Processing Status
## Initial
The initial processing_status when the container first runs is:
{
processing_status = ProcessingStatus.PENDING
upload_status = UploadStatus.WAITING
upload_progress = 0
upload_message = ""
validation_status = ValidationStatus
validation_message = ""
conversion_loom_status = ConversionStatus
conversion_rds_status = ConversionStatus
conversion_cxg_status = ConversionStatus
conversion_anndata_status = ConversionStatus
}
## Upload
While uploading, upload_status changes UploadStatus.UPLOADING and upload_progress is updated regularly.
The processing_status should look like this:
{
processing_status = ProcessingStatus.PENDING
upload_status = UploadStatus.UPLOADING
upload_progress = 0.25
}
If upload succeeds the processing_status changes to:
{
processing_status = ProcessingStatus.PENDING
upload_status = UploadStatus.UPLOADED
upload_progress = 1.0
}
If upload fails the processing_status changes to:
{
processing_status = ProcessingStatus.FAILURE
upload_status = UploadStatus.FAILED
upload_progress = 0.25
upload_message = "Some message"
}
## Validation
After upload, validation starts and processing status changes to:
{
processing_status = ProcessingStatus.PENDING
upload_status = UploadStatus.UPLOADED
upload_progress = 1.0
validation_status = ValidationStatus.VALIDATING
}
If validation succeeds the process_status changes to:
{
processing_status = ProcessingStatus.PENDING
upload_status = UploadStatus.UPLOADED
upload_progress = 1.0
validation_status = ValidationStatus.VALID
conversion_loom_status = ConversionStatus.CONVERTING
conversion_rds_status = ConversionStatus.CONVERTING
conversion_cxg_status = ConversionStatus.CONVERTING
conversion_anndata_status = ConversionStatus.CONVERTING
}
If validation fails the processing_status change to:
{
processing_status = ProcessingStatus.FAILURE
upload_status = UploadStatus.UPLOADED
upload_progress = 1.0
validation_status = ValidationStatus.FAILED
}
## Conversion
After each conversion the processing_status change from CONVERTING to CONVERTED. Cellxgene data is converted first.
{
processing_status = ProcessingStatus.PENDING
upload_status = UploadStatus.UPLOADED
upload_progress = 1.0
validation_status = ValidationStatus
conversion_loom_status = ConversionStatus.CONVERTING
conversion_rds_status = ConversionStatus.CONVERTING
conversion_cxg_status = ConversionStatus.CONVERTED
conversion_anndata_status = ConversionStatus.CONVERTING
}
If a conversion fails the processing_status will indicated it as follow:
{
processing_status = ProcessingStatus.PENDING
upload_status = UploadStatus.UPLOADED
upload_progress = 1.0
validation_status = ValidationStatus
conversion_loom_status = ConversionStatus.FAILED
conversion_rds_status = ConversionStatus.CONVERTING
conversion_cxg_status = ConversionStatus.CONVERTED
conversion_anndata_status = ConversionStatus.CONVERTING
}
Once all conversion are compelete, the conversion status for each file will be either CONVERTED or FAILED:
{
processing_status = ProcessingStatus.SUCCESS
upload_status = UploadStatus.UPLOADED
upload_progress = 1.0
validation_status = ValidationStatus
conversion_loom_status = ConversionStatus.FAILED
conversion_rds_status = ConversionStatus.CONVERTED
conversion_cxg_status = ConversionStatus.CONVERTED
conversion_anndata_status = ConversionStatus.FAILED
}
"""
import logging
import os
import requests
import subprocess
import typing
from os.path import join
import numpy
import scanpy
import sys
from backend.corpora.common.corpora_config import CorporaConfig
from backend.corpora.common.utils.dl_sources.url import from_url
from backend.corpora.dataset_processing.exceptions import ProcessingFailed, ValidationFailed, ProcessingCancelled
from backend.corpora.common.corpora_orm import (
DatasetArtifactFileType,
ConversionStatus,
ValidationStatus,
ProcessingStatus,
DatasetArtifactType,
)
from backend.corpora.common.entities import Dataset, DatasetAsset
from backend.corpora.common.utils.db_session import db_session_manager
from backend.corpora.common.utils.db_helpers import processing_status_updater
from backend.corpora.dataset_processing.download import download
from backend.corpora.dataset_processing.h5ad_data_file import H5ADDataFile
from backend.corpora.dataset_processing.slack import format_slack_message
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
# This is unfortunate, but this information doesn't appear to live anywhere
# accessible to the uploader
DEPLOYMENT_STAGE_TO_URL = {
"staging": "https://cellxgene.staging.single-cell.czi.technology/e",
"prod": "https://cellxgene.cziscience.com/e",
"rdev": os.environ.get("FRONTEND_URL"),
"dev": "https://cellxgene.dev.single-cell.czi.technology/e",
"test": "http://frontend.corporanet.local:3000",
}
def check_env():
"""Verify that the required environment variables are set."""
missing = []
for env_var in ["DROPBOX_URL", "ARTIFACT_BUCKET", "CELLXGENE_BUCKET", "DATASET_ID", "DEPLOYMENT_STAGE"]:
if env_var not in os.environ:
missing.append(env_var)
if missing:
raise EnvironmentError(f"Missing environment variables: {missing}")
def create_artifact(
file_name: str, artifact_type: DatasetArtifactFileType, bucket_prefix: str, dataset_id: str, artifact_bucket: str
):
logger.info(f"Uploading [{dataset_id}/{file_name}] to S3 bucket: [{artifact_bucket}].")
s3_uri = DatasetAsset.upload(file_name, bucket_prefix, artifact_bucket)
with db_session_manager() as session:
logger.info(f"Updating database with {artifact_type}.")
DatasetAsset.create(
session,
dataset_id=dataset_id,
filename=file_name,
filetype=artifact_type,
type_enum=DatasetArtifactType.REMIX,
user_submitted=True,
s3_uri=s3_uri,
)
def create_artifacts(local_filename, dataset_id, artifact_bucket):
bucket_prefix = get_bucket_prefix(dataset_id)
logger.info("Creating Artifacts.")
# upload AnnData
create_artifact(local_filename, DatasetArtifactFileType.H5AD, bucket_prefix, dataset_id, artifact_bucket)
update_db(
dataset_id,
processing_status=dict(conversion_anndata_status=ConversionStatus.CONVERTED),
)
# Process loom
loom_filename, status = convert_file_ignore_exceptions(make_loom, local_filename, "Issue creating loom.")
if loom_filename:
create_artifact(loom_filename, DatasetArtifactFileType.LOOM, bucket_prefix, dataset_id, artifact_bucket)
update_db(
dataset_id,
processing_status=dict(conversion_loom_status=status),
)
# Process seurat
seurat_filename, status = convert_file_ignore_exceptions(make_seurat, local_filename, "Issue creating seurat.")
if seurat_filename:
create_artifact(seurat_filename, DatasetArtifactFileType.RDS, bucket_prefix, dataset_id, artifact_bucket)
update_db(dataset_id, processing_status=dict(conversion_rds_status=status))
def cancel_dataset(dataset_id):
with db_session_manager() as session:
dataset = Dataset.get(session, dataset_id, include_tombstones=True)
dataset.asset_deletion()
dataset.delete()
logger.info("Upload Canceled.")
def update_db(dataset_id, metadata=None, processing_status=None):
with db_session_manager() as session:
dataset = Dataset.get(session, dataset_id, include_tombstones=True)
if dataset.tombstone:
raise ProcessingCancelled
if metadata:
# TODO: Delete this line once mean_genes_per_cell is in the db
metadata.pop("mean_genes_per_cell", None)
logger.debug("Updating metadata.")
dataset.update(**metadata)
if processing_status:
logger.debug(f"updating processing_status.{processing_status}")
processing_status_updater(session, dataset.processing_status.id, processing_status)
def download_from_dropbox_url(dataset_uuid: str, dropbox_url: str, local_path: str) -> str:
"""Given a dropbox url, download it to local_path.
Handles fixing the url so it downloads directly.
"""
file_url = from_url(dropbox_url)
if not file_url:
raise ValueError(f"Malformed Dropbox URL: {dropbox_url}")
file_info = file_url.file_info()
status = download(dataset_uuid, file_url.url, local_path, file_info["size"])
logger.info(status)
logger.info("Download complete")
return local_path
def extract_metadata(filename):
"""Pull metadata out of the AnnData file to insert into the dataset table."""
adata = scanpy.read_h5ad(filename, backed="r")
try:
raw_layer_name = [k for k, v in adata.uns["layer_descriptions"].items() if v == "raw"][0]
except (KeyError, IndexError):
raise RuntimeError("Raw layer not found in layer descriptions!")
if raw_layer_name == "X":
raw_layer = adata.X
elif raw_layer_name == "raw.X":
raw_layer = adata.raw.X
else:
raw_layer = adata.layers[raw_layer_name]
# Calling np.count_nonzero on and h5py.Dataset appears to read the entire thing
# into memory, so we need to chunk it to be safe.
stride = 50000
numerator, denominator = 0, 0
for bounds in zip(range(0, raw_layer.shape[0], stride), range(stride, raw_layer.shape[0] + stride, stride)):
chunk = raw_layer[bounds[0] : bounds[1], :]
numerator += chunk.nnz if hasattr(chunk, "nnz") else numpy.count_nonzero(chunk)
denominator += chunk.shape[0]
def _get_term_pairs(base_term):
base_term_id = base_term + "_ontology_term_id"
return [
{"label": k[0], "ontology_term_id": k[1]}
for k in adata.obs.groupby([base_term, base_term_id]).groups.keys()
]
metadata = {
"name": adata.uns["title"],
"organism": {"label": adata.uns["organism"], "ontology_term_id": adata.uns["organism_ontology_term_id"]},
"tissue": _get_term_pairs("tissue"),
"assay": _get_term_pairs("assay"),
"disease": _get_term_pairs("disease"),
"sex": list(adata.obs.sex.unique()),
"ethnicity": _get_term_pairs("ethnicity"),
"development_stage": _get_term_pairs("development_stage"),
"cell_count": adata.shape[0],
"mean_genes_per_cell": numerator / denominator,
}
logger.info(f"Extract metadata: {metadata}")
return metadata
def make_loom(local_filename):
"""Create a loom file from the AnnData file."""
adata = scanpy.read_h5ad(local_filename)
column_name_map = {}
for column in adata.obs.columns:
if "/" in column:
column_name_map[column] = column.replace("/", "-")
if column_name_map:
adata.obs = adata.obs.rename(columns=column_name_map)
loom_filename = local_filename.replace(".h5ad", ".loom")
adata.write_loom(loom_filename, True)
return loom_filename
def make_seurat(local_filename):
"""Create a Seurat rds file from the AnnData file."""
try:
subprocess.run(
["Rscript", os.path.join(os.path.abspath(os.path.dirname(__file__)), "make_seurat.R"), local_filename],
capture_output=True,
check=True,
)
except subprocess.CalledProcessError as ex:
msg = f"Seurat conversion failed: {ex.output} {ex.stderr}"
logger.exception(msg)
raise RuntimeError(msg) from ex
return local_filename.replace(".h5ad", ".rds")
def make_cxg(local_filename):
"""
Convert the uploaded H5AD file to the CXG format servicing the cellxgene Explorer.
"""
cxg_output_container = local_filename.replace(".h5ad", ".cxg")
try:
h5ad_data_file = H5ADDataFile(local_filename)
h5ad_data_file.to_cxg(cxg_output_container, 10.0)
except Exception as ex:
msg = "CXG conversion failed."
logger.exception(msg)
raise RuntimeError(msg) from ex
return cxg_output_container
def copy_cxg_files_to_cxg_bucket(cxg_dir, object_key, cellxgene_bucket):
"""
Copy cxg files to the cellxgene bucket (under the given object key) for access by the explorer
returns the s3_uri where the cxg is stored
"""
command = ["aws"]
s3_uri = f"s3://{cellxgene_bucket}/{object_key}.cxg/"
if os.getenv("BOTO_ENDPOINT_URL"):
command.append(f"--endpoint-url={os.getenv('BOTO_ENDPOINT_URL')}")
command.extend(
[
"s3",
"cp",
cxg_dir,
s3_uri,
"--recursive",
"--acl",
"bucket-owner-full-control",
]
)
subprocess.run(
command,
check=True,
)
return s3_uri
def convert_file_ignore_exceptions(
converter: typing.Callable, local_filename: str, error_message: str
) -> typing.Tuple[str, ConversionStatus]:
try:
file_dir = converter(local_filename)
status = ConversionStatus.CONVERTED
except Exception:
file_dir = None
status = ConversionStatus.FAILED
logger.exception(error_message)
return file_dir, status
def get_bucket_prefix(dataset_id):
remote_dev_prefix = os.environ.get("REMOTE_DEV_PREFIX", "")
if remote_dev_prefix:
return join(remote_dev_prefix, dataset_id).strip("/")
else:
return dataset_id
def process_cxg(local_filename, dataset_id, cellxgene_bucket):
bucket_prefix = get_bucket_prefix(dataset_id)
cxg_dir, status = convert_file_ignore_exceptions(make_cxg, local_filename, "Issue creating cxg.")
if cxg_dir:
s3_uri = copy_cxg_files_to_cxg_bucket(cxg_dir, bucket_prefix, cellxgene_bucket)
metadata = {
"explorer_url": join(DEPLOYMENT_STAGE_TO_URL[os.environ["DEPLOYMENT_STAGE"]], dataset_id + ".cxg", "")
}
with db_session_manager() as session:
logger.info(f"Updating database with cxg artifact for dataset {dataset_id}. s3_uri is {s3_uri}")
DatasetAsset.create(
session,
dataset_id=dataset_id,
filename="explorer_cxg",
filetype=DatasetArtifactFileType.CXG,
type_enum=DatasetArtifactType.REMIX,
user_submitted=True,
s3_uri=s3_uri,
)
else:
metadata = None
update_db(dataset_id, metadata, processing_status=dict(conversion_cxg_status=status))
def validate_h5ad_file(dataset_id, local_filename):
update_db(dataset_id, processing_status=dict(validation_status=ValidationStatus.VALIDATING))
val_proc = subprocess.run(["cellxgene-schema", "validate", local_filename], capture_output=True)
if val_proc.returncode != 0:
logger.error("Validation failed!")
logger.error(f"stdout: {val_proc.stdout}")
logger.error(f"stderr: {val_proc.stderr}")
status = dict(
validation_status=ValidationStatus.INVALID,
validation_message=val_proc.stdout,
processing_status=ProcessingStatus.FAILURE,
)
update_db(dataset_id, processing_status=status)
raise ValidationFailed
else:
logger.info("Validation complete")
status = dict(
conversion_cxg_status=ConversionStatus.CONVERTING,
conversion_loom_status=ConversionStatus.CONVERTING,
conversion_rds_status=ConversionStatus.CONVERTING,
conversion_anndata_status=ConversionStatus.CONVERTING,
validation_status=ValidationStatus.VALID,
)
update_db(dataset_id, processing_status=status)
def log_batch_environment():
batch_environment_variables = [
"AWS_BATCH_CE_NAME",
"AWS_BATCH_JOB_ATTEMPT",
"AWS_BATCH_JOB_ID",
"DROPBOX_URL",
"ARTIFACT_BUCKET",
"CELLXGENE_BUCKET",
"DATASET_ID",
"DEPLOYMENT_STAGE",
]
env_vars = dict()
for var in batch_environment_variables:
env_vars[var] = os.getenv(var)
logger.info(f"Batch Job Info: {env_vars}")
def process(dataset_id, dropbox_url, cellxgene_bucket, artifact_bucket):
update_db(dataset_id, processing_status=dict(processing_status=ProcessingStatus.PENDING))
local_filename = download_from_dropbox_url(
dataset_id,
dropbox_url,
"local.h5ad",
)
validate_h5ad_file(dataset_id, local_filename)
# Process metadata
metadata = extract_metadata(local_filename)
update_db(dataset_id, metadata)
# create artifacts
process_cxg(local_filename, dataset_id, cellxgene_bucket)
create_artifacts(local_filename, dataset_id, artifact_bucket)
update_db(dataset_id, processing_status=dict(processing_status=ProcessingStatus.SUCCESS))
def main():
return_value = 0
check_env()
log_batch_environment()
dataset_id = os.environ["DATASET_ID"]
try:
process(dataset_id, os.environ["DROPBOX_URL"], os.environ["CELLXGENE_BUCKET"], os.environ["ARTIFACT_BUCKET"])
except ProcessingCancelled:
cancel_dataset(dataset_id)
except (ValidationFailed, ProcessingFailed):
logger.exception("An Error occured while processing.")
return_value = 1
except Exception:
message = "An unexpect error occured while processing the data set."
logger.exception(message)
update_db(
dataset_id, processing_status=dict(processing_status=ProcessingStatus.FAILURE, upload_message=message)
)
return_value = 1
if return_value > 0:
notify_slack_failure(dataset_id)
return return_value
def notify_slack_failure(dataset_id):
data = format_slack_message(dataset_id)
logger.info(data)
if os.getenv("DEPLOYMENT_STAGE") == "prod":
slack_webhook = CorporaConfig().slack_webhook
requests.post(slack_webhook, headers={"Content-type": "application/json"}, data=data)
if __name__ == "__main__":
rv = main()
sys.exit(rv)
|
StarcoderdataPython
|
8057081
|
<filename>weasyl/report.py<gh_stars>0
import arrow
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.orm import aliased, contains_eager, joinedload
import sqlalchemy as sa
import web
from libweasyl.models.content import Report, ReportComment
from libweasyl.models.users import Login
from libweasyl import constants, staff
from weasyl.error import WeasylError
from weasyl import macro as m, define as d, media, note
_CONTENT = 2000
def _convert_violation(target):
violation = [i[2] for i in m.MACRO_REPORT_VIOLATION if i[0] == target]
return violation[0] if violation else 'Unknown'
def _dict_of_targetid(submitid, charid, journalid):
"""
Given a target of some type, return a dictionary indicating what the 'some
type' is. The dictionary's key will be the appropriate column on the Report
model.
"""
if submitid:
return {'target_sub': submitid}
elif charid:
return {'target_char': charid}
elif journalid:
return {'target_journal': journalid}
else:
raise ValueError('no ID given')
# form
# submitid violation
# charid content
# journalid
def create(userid, form):
form.submitid = d.get_int(form.submitid)
form.charid = d.get_int(form.charid)
form.journalid = d.get_int(form.journalid)
form.violation = d.get_int(form.violation)
form.content = form.content.strip()[:_CONTENT]
# get the violation type from allowed types
try:
vtype = next(x for x in m.MACRO_REPORT_VIOLATION if x[0] == form.violation)
except StopIteration:
raise WeasylError("Unexpected")
if not form.submitid and not form.charid and not form.journalid:
raise WeasylError("Unexpected")
elif form.violation == 0:
if userid not in staff.MODS:
raise WeasylError("Unexpected")
elif (form.submitid or form.charid) and not 2000 <= form.violation < 3000:
raise WeasylError("Unexpected")
elif form.journalid and not 3000 <= form.violation < 4000:
raise WeasylError("Unexpected")
elif vtype[3] and not form.content:
raise WeasylError("ReportCommentRequired")
is_hidden = d.engine.scalar(
"SELECT settings ~ 'h' FROM %s WHERE %s = %i" % (
("submission", "submitid", form.submitid) if form.submitid else
("character", "charid", form.charid) if form.charid else
("journal", "journalid", form.journalid)
)
)
if is_hidden is None or (form.violation != 0 and is_hidden):
raise WeasylError("TargetRecordMissing")
now = arrow.get()
target_dict = _dict_of_targetid(form.submitid, form.charid, form.journalid)
report = Report.query.filter_by(is_closed=False, **target_dict).first()
if report is None:
if form.violation == 0:
raise WeasylError("Unexpected")
urgency = vtype[1]
report = Report(urgency=urgency, opened_at=now, **target_dict)
Report.dbsession.add(report)
Report.dbsession.add(ReportComment(
report=report, violation=form.violation, userid=userid, unixtime=now, content=form.content))
Report.dbsession.flush()
_report_types = [
'_target_sub',
'_target_char',
'_target_journal',
]
def select_list(userid, form):
# Find the unique violation types and the number of reporters. This will be
# joined against the Report model to get the violations/reporters for each
# selected report.
subq = (
ReportComment.dbsession.query(
ReportComment.reportid,
sa.func.count(),
sa.type_coerce(
sa.func.array_agg(ReportComment.violation.distinct()),
ARRAY(sa.Integer, as_tuple=True)).label('violations'))
.filter(ReportComment.violation != 0)
.group_by(ReportComment.reportid)
.subquery())
# Find reports, joining against the aforementioned subquery, and eager-load
# the reports' owners.
q = (
Report.dbsession.query(Report, subq)
.options(joinedload(Report.owner))
.join(subq, Report.reportid == subq.c.reportid)
.reset_joinpoint())
# For each type of report, eagerly load the content reported and the
# content's owner. Also, keep track of the Login model aliases used for each
# report type so they can be filtered against later.
login_aliases = []
for column_name in _report_types:
login_alias = aliased(Login)
login_aliases.append(login_alias)
q = (
q
.outerjoin(getattr(Report, column_name))
.outerjoin(login_alias)
.options(contains_eager(column_name + '.owner', alias=login_alias))
.reset_joinpoint())
# Filter by report status. form.status can also be 'all', in which case no
# filter is applied.
if form.status == 'closed':
q = q.filter_by(is_closed=True)
elif form.status == 'open':
q = q.filter_by(is_closed=False)
# If filtering by the report's content's owner, iterate over the previously
# collected Login model aliases to compare against Login.login_name.
if form.submitter:
submitter = d.get_sysname(form.submitter)
q = q.filter(sa.or_(l.login_name == submitter for l in login_aliases))
# If filtering by violation type, see if the violation is in the array
# aggregate of unique violations for this report.
if form.violation and form.violation != '-1':
q = q.filter(sa.literal(int(form.violation)) == sa.func.any(subq.c.violations))
q = q.order_by(Report.opened_at.desc())
return [(report, report_count, list(map(_convert_violation, violations)))
for report, _, report_count, violations in q.all()]
def select_view(userid, form):
report = (
Report.query
.options(joinedload('comments', innerjoin=True).joinedload('poster', innerjoin=True))
.get_or_404(int(form.reportid)))
report.old_style_comments = [
{
'userid': c.userid,
'username': c.poster.profile.username,
'unixtime': c.unixtime,
'content': c.content,
'violation': _convert_violation(c.violation),
} for c in report.comments]
media.populate_with_user_media(report.old_style_comments)
report.old_style_comments.sort(key=lambda c: c['unixtime'])
return report
_closure_actions = {
'no_action_taken': constants.ReportClosureReason.no_action_taken,
'action_taken': constants.ReportClosureReason.action_taken,
'invalid': constants.ReportClosureReason.invalid,
}
def close(userid, form):
if userid not in staff.MODS:
raise WeasylError("InsufficientPermissions")
root_report = Report.query.get(int(form.reportid))
if root_report is None or root_report.is_closed:
return
if 'close_all_user_reports' in form:
# If we're closing all of the reports opened against a particular content
# owner, do the same thing as in the select_list function and collect Login
# aliases so that filtering can be done by Login.login_name.
q = Report.query
login_aliases = []
for column_name in _report_types:
login_alias = aliased(Login)
login_aliases.append(login_alias)
q = (
q
.outerjoin(getattr(Report, column_name))
.outerjoin(login_alias)
.reset_joinpoint())
q = (
q
.filter_by(is_closed=False)
.filter(sa.or_(l.login_name == root_report.target.owner.login_name for l in login_aliases)))
reports = q.all()
else:
reports = [root_report]
for report in reports:
if report.is_closed:
raise RuntimeError("a closed report shouldn't have gotten this far")
report.closerid = userid
report.settings.mutable_settings.clear()
if 'assign' in form:
report.is_under_review = True
elif 'unassign' in form:
report.closerid = None
else:
report.closed_at = arrow.get()
report.closure_explanation = form.explanation
report.closure_reason = _closure_actions[form.action]
Report.dbsession.flush()
if form.action == 'action_taken':
# TODO(hyena): Remove this dependency on web.py's Storage objects.
note_form = web.Storage()
note_form.title = form.note_title
note_form.content = form.user_note
note_form.recipient = root_report.target.owner.login_name
note_form.mod_copy = True
note_form.staff_note = form.explanation
note.send(userid, note_form)
def check(submitid=None, charid=None, journalid=None):
return bool(
Report.query
.filter_by(is_closed=False, **_dict_of_targetid(submitid, charid, journalid))
.count())
def select_reported_list(userid):
q = (
Report.query
.join(ReportComment)
.options(contains_eager(Report.comments))
.options(joinedload('_target_sub'))
.options(joinedload('_target_char'))
.options(joinedload('_target_journal'))
.filter(ReportComment.violation != 0)
.filter_by(userid=userid))
reports = q.all()
for report in reports:
report.latest_report = max(c.unixtime for c in report.comments)
reports.sort(key=lambda r: r.latest_report, reverse=True)
return reports
|
StarcoderdataPython
|
4873193
|
class Vector:
head: Vector = None
tail: Vector = None
val: int = 0
def create(self: Vector, val: int) -> Vector:
self.val = val
return self
def append(self: Vector, val: int) -> Vector:
newObj: Vector = Vector()
newObj.val = val
if (self.head is None):
self.head = newObj
if (self.tail is None):
self.tail = newObj
else:
self.tail.head = newObj
self.tail = newObj
return self
def print(self: Vector):
print(self.val)
if (not self.head is None):
self.head.print()
head: Vector = Vector().create(1)
head.append(2).append(3).append(4)
head.append(5)
head.print()
|
StarcoderdataPython
|
1881949
|
<filename>sahara/service/volumes.py
# Copyright (c) 2013 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, 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.
from oslo_config import cfg
from oslo_log import log as logging
from sahara import conductor as c
from sahara import context
from sahara import exceptions as ex
from sahara.i18n import _
from sahara.i18n import _LE
from sahara.utils import cluster_progress_ops as cpo
from sahara.utils.openstack import cinder
from sahara.utils.openstack import nova
from sahara.utils import poll_utils
conductor = c.API
LOG = logging.getLogger(__name__)
CONF = cfg.CONF
CONF.import_opt('api_version', 'sahara.utils.openstack.cinder',
group='cinder')
def _count_instances_to_attach(instances):
result = 0
for instance in instances:
if instance.node_group.volumes_per_node > 0:
result += 1
return result
def _count_volumes_to_mount(instances):
return sum([inst.node_group.volumes_per_node for inst in instances])
def attach_to_instances(instances):
instances_to_attach = _count_instances_to_attach(instances)
if instances_to_attach == 0:
return
cpo.add_provisioning_step(
instances[0].cluster_id, _("Attach volumes to instances"),
instances_to_attach)
with context.ThreadGroup() as tg:
for instance in instances:
if instance.node_group.volumes_per_node > 0:
tg.spawn(
'attach-volumes-for-instance-%s' % instance.instance_name,
_attach_volumes_to_node, instance.node_group, instance)
@poll_utils.poll_status(
'await_attach_volumes', _("Await for attaching volumes to instances"),
sleep=2)
def _await_attach_volumes(instance, devices):
return _count_attached_devices(instance, devices) == len(devices)
@cpo.event_wrapper(mark_successful_on_exit=True)
def _attach_volumes_to_node(node_group, instance):
ctx = context.ctx()
size = node_group.volumes_size
volume_type = node_group.volume_type
devices = []
for idx in range(1, node_group.volumes_per_node + 1):
display_name = "volume_" + instance.instance_name + "_" + str(idx)
device = _create_attach_volume(
ctx, instance, size, volume_type,
node_group.volume_local_to_instance, display_name,
node_group.volumes_availability_zone)
devices.append(device)
LOG.debug("Attached volume {device} to instance {uuid}".format(
device=device, uuid=instance.instance_id))
_await_attach_volumes(instance, devices)
paths = instance.node_group.storage_paths()
for idx in range(0, instance.node_group.volumes_per_node):
LOG.debug("Mounting volume {volume} to instance {id}"
.format(volume=devices[idx], id=instance.instance_id))
_mount_volume(instance, devices[idx], paths[idx])
LOG.debug("Mounted volume to instance {id}"
.format(id=instance.instance_id))
@poll_utils.poll_status(
'volume_available_timeout', _("Await for volume become available"),
sleep=1)
def _await_available(volume):
volume = cinder.get_volume(volume.id)
if volume.status == 'error':
raise ex.SystemError(_("Volume %s has error status") % volume.id)
return volume.status == 'available'
def _create_attach_volume(ctx, instance, size, volume_type,
volume_local_to_instance, name=None,
availability_zone=None):
if CONF.cinder.api_version == 1:
kwargs = {'size': size, 'display_name': name}
else:
kwargs = {'size': size, 'name': name}
kwargs['volume_type'] = volume_type
if availability_zone is not None:
kwargs['availability_zone'] = availability_zone
if volume_local_to_instance:
kwargs['scheduler_hints'] = {'local_to_instance': instance.instance_id}
volume = cinder.client().volumes.create(**kwargs)
conductor.append_volume(ctx, instance, volume.id)
_await_available(volume)
resp = nova.client().volumes.create_server_volume(
instance.instance_id, volume.id, None)
return resp.device
def _count_attached_devices(instance, devices):
code, part_info = instance.remote().execute_command('cat /proc/partitions')
count = 0
for line in part_info.split('\n')[1:]:
tokens = line.split()
if len(tokens) > 3:
dev = '/dev/' + tokens[3]
if dev in devices:
count += 1
return count
def mount_to_instances(instances):
if len(instances) == 0:
return
cpo.add_provisioning_step(
instances[0].cluster_id,
_("Mount volumes to instances"), _count_volumes_to_mount(instances))
with context.ThreadGroup() as tg:
for instance in instances:
devices = _find_instance_volume_devices(instance)
# Since formatting can take several minutes (for large disks) and
# can be done in parallel, launch one thread per disk.
for idx in range(0, instance.node_group.volumes_per_node):
tg.spawn('mount-volume-%d-to-node-%s' %
(idx, instance.instance_name),
_mount_volume_to_node, instance, idx, devices[idx])
def _find_instance_volume_devices(instance):
volumes = nova.client().volumes.get_server_volumes(instance.instance_id)
devices = [volume.device for volume in volumes]
return devices
@cpo.event_wrapper(mark_successful_on_exit=True)
def _mount_volume_to_node(instance, idx, device):
LOG.debug("Mounting volume {device} to instance {id}".format(
device=device, id=instance.instance_id))
mount_point = instance.node_group.storage_paths()[idx]
_mount_volume(instance, device, mount_point)
LOG.debug("Mounted volume to instance {id}".format(
id=instance.instance_id))
def _mount_volume(instance, device_path, mount_point):
with instance.remote() as r:
try:
# Mount volumes with better performance options:
# - reduce number of blocks reserved for root to 1%
# - use 'dir_index' for faster directory listings
# - use 'extents' to work faster with large files
# - disable journaling
# - enable write-back
# - do not store access time
fs_opts = '-m 1 -O dir_index,extents,^has_journal'
mount_opts = '-o data=writeback,noatime,nodiratime'
r.execute_command('sudo mkdir -p %s' % mount_point)
r.execute_command('sudo mkfs.ext4 %s %s' % (fs_opts, device_path))
r.execute_command('sudo mount %s %s %s' %
(mount_opts, device_path, mount_point))
except Exception:
LOG.error(_LE("Error mounting volume to instance {id}")
.format(id=instance.instance_id))
raise
def detach_from_instance(instance):
for volume_id in instance.volumes:
_detach_volume(instance, volume_id)
_delete_volume(volume_id)
@poll_utils.poll_status(
'detach_volume_timeout', _("Await for volume become detached"), sleep=2)
def _await_detach(volume_id):
volume = cinder.get_volume(volume_id)
if volume.status not in ['available', 'error']:
return False
return True
def _detach_volume(instance, volume_id):
volume = cinder.get_volume(volume_id)
try:
LOG.debug("Detaching volume {id} from instance {instance}".format(
id=volume_id, instance=instance.instance_name))
nova.client().volumes.delete_server_volume(instance.instance_id,
volume_id)
except Exception:
LOG.error(_LE("Can't detach volume {id}").format(id=volume.id))
detach_timeout = CONF.timeouts.detach_volume_timeout
LOG.debug("Waiting {timeout} seconds to detach {id} volume".format(
timeout=detach_timeout, id=volume_id))
_await_detach(volume_id)
def _delete_volume(volume_id):
LOG.debug("Deleting volume {volume}".format(volume=volume_id))
volume = cinder.get_volume(volume_id)
try:
volume.delete()
except Exception:
LOG.error(_LE("Can't delete volume {volume}").format(
volume=volume.id))
|
StarcoderdataPython
|
1643010
|
from mysql import *
from mysql.connector import pooling
import sys
class Conexion:
_DATABASE = 'bqifo1pz07m1cxqswphy'
_USERNAME = 'uqqvf5c2n9ccrnrv'
_PASSWORD = '<PASSWORD>'
_DB_PORT = '21374'
_HOST = 'bqifo1pz07m1cxqswphy-mysql.services.clever-cloud.com'
_MAX_CON = 5
_pool = None
@classmethod
def obtenerPool(cls):
if cls._pool is None:
try:
#Aqui estaba el error faltaba un .
cls._pool = pooling.MySQLConnectionPool(pool_name='mypool',
pool_size=cls._MAX_CON,
host=cls._HOST,
user=cls._USERNAME,
password=<PASSWORD>,
port=cls._DB_PORT,
database=cls._DATABASE)
#log.debug(f'Creación del pool exitoso: {cls._pool}')
return cls._pool
except Exception as e:
#log.error(f'Ocurrio un problema al obtener el pool de conexiones {e}')
sys.exit()
else:
return cls._pool
@classmethod
def obtenerConexion(cls):
conexion = cls.obtenerPool().get_connection()
#log.debug(f'Conexión establecida exitosamente: {conexion}')
return conexion
@classmethod
def liberarConexion(cls, conexion):
conexion.close()
#log.debug(f'Liberando la conexión exitosamente: {conexion}')
@classmethod
def cerrarConexion(cls):
cls.obtenerPool().closeall()
|
StarcoderdataPython
|
1987071
|
<filename>Website/main.py
from flask import Flask, render_template, request, redirect,send_file, g
import requests
import csv
import pandas as pd
selcted_side = 0
chosen_product_1 = {}
chosen_product_2 = {}
app = Flask("Comparison Website")
@app.route('/')
def home():
term = request.form.get("term")
return render_template("home.html",term=term)
@app.route('/left')
def left():
global selcted_side
selcted_side = 0;
term = request.form.get("term")
return render_template("home.html",term=term)
@app.route('/right')
def right():
global selcted_side
selcted_side = 1;
term = request.form.get("term")
return render_template("home.html",term=term)
@app.route('/search')
def search():
term=request.args.get('term')
df = pd.read_csv('phones.csv', encoding='euc-kr')
df = df.dropna()
global found_phones
found_phones = pd.DataFrame(columns=df.columns)
for row in df.iterrows():
if term in row[1]['기종']:
found_phones=found_phones.append(row[1])
return render_template("search_result.html", results=found_phones.iterrows(), term=term)
@app.route('/compare/<phoneID>')
def compare(phoneID):
if selcted_side == 0:
global chosen_product_1
global chosen_product_2
print(chosen_product_2)
chosen_product_1 = found_phones.loc[int(phoneID)]
return render_template("compare.html", chosen_product_1=chosen_product_1, chosen_product_2=chosen_product_2)
else:
chosen_product_2 = found_phones.loc[int(phoneID)]
print("right")
return render_template("compare.html", chosen_product_1=chosen_product_1, chosen_product_2=chosen_product_2)
#print("phoneID: ", phoneID)
# for row in found_phones:
# print(row)
#print(found_phones.iloc)
app.run(host="0.0.0.0")
|
StarcoderdataPython
|
73601
|
<filename>pyutils/iolib/video.py
import os, re
import numpy as np
from pyutils.cmd import runSystemCMD
import skimage.io as sio
OPENCV = 0
IMAGEIO = 1
FFMPEG = 2
BACKENDS = {'opencv': OPENCV, 'imageio': IMAGEIO, 'ffmpeg': FFMPEG}
def getFFprobeMeta(fn):
cmd = 'ffprobe -hide_banner -loglevel panic ' + fn + ' -show_streams'
log, _ = runSystemCMD(cmd)
log = log.split('\n')
start_stream = [i for i, l in enumerate(log) if l == '[STREAM]']
end_stream = [i for i, l in enumerate(log) if l == '[/STREAM]']
streams = []
for init, end in zip(start_stream, end_stream):
streams.append(log[init+1:end])
meta = dict()
for stream in streams:
tmp = {}
for l in stream:
m = re.match('(.*)=(.*)', l)
if m is None:
continue
tmp[m.group(1)] = m.group(2)
meta[tmp['codec_type']] = tmp
return meta
class BasicVideoReader:
def __init__(self, video_fn,
backend='imageio',
fps=None,
seek=0,
duration=None):
self.backend = BACKENDS[backend]
if self.backend == IMAGEIO:
import imageio
self.reader = imageio.get_reader(video_fn)#, format='AVBIN')
self.reader_iter = self.reader.iter_data()
w, h = self.reader._meta['size']
self.frame_shape = (h, w)
self._raw_duration = self.reader._meta['duration']
self._raw_fps = self.reader._meta['fps']
self._raw_frames = int(self._raw_duration * self._raw_fps)
elif self.backend == OPENCV:
import cv2
self.reader = cv2.VideoCapture(video_fn)
w = int(self.reader.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH))
h = int(self.reader.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT))
self.frame_shape = (h, w)
self._raw_frames = int(self.reader.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT))
self._raw_fps = self.reader.get(cv2.cv.CV_CAP_PROP_FPS)
self._raw_duration = self._raw_frames / float(self._raw_fps)
else:
raise ValueError, 'Backend not supported'
if duration is not None:
self.end_time = min(duration + seek, self._raw_duration)
else:
self.end_time = self._raw_duration
self.duration = self.end_time - seek
self.fps = fps if fps is not None else self._raw_fps
self._raw_delta = 1. / self._raw_fps
self._raw_frame_no = -1
self._raw_time = self._raw_frame_no * self._raw_delta
self.delta = 1. / self.fps
self.frame_no = -1
self.time = self.frame_no * self.delta
self.eof = False
if seek > 0:
n_skips = int(seek * self.fps)
self.skip(n_skips)
def _read_next(self):
if self.eof:
return None
self._raw_frame_no += 1
self._raw_time = self._raw_frame_no * self._raw_delta
if self._raw_time > self.end_time:
self.eof = True
return None
if self.backend == IMAGEIO:
try:
frame = next(self.reader_iter)
except StopIteration:
self.eof = True
elif self.backend == OPENCV:
success, frame = self.reader.read()
if not success:
self.eof = True
return frame if not self.eof else None
def get(self):
if self.eof:
return None
EPS = 1e-4
self.frame_no += 1
self.time = self.frame_no * self.delta
while self._raw_time < self.time - EPS and not self.eof:
frame = self._read_next()
if self.eof:
self.frame_no -= 1
self.time = self.frame_no * self.delta
return None
if self.backend == OPENCV:
frame = np.flip(frame, 2)
return frame
def loop(self):
while True:
frame = self.get()
if frame is None:
break
yield frame
def skip(self, n):
for _ in range(n):
frame = self.get()
if frame is None:
return False
return True
class FrameReader:
def __init__(self, video_folder,
fps=None,
seek=0,
duration=None):
self.video_folder = video_folder
self.raw_fps = 10.
frame_fns = os.listdir(video_folder)
self.num_frames = len(frame_fns)
self.duration = self.num_frames / self.raw_fps
img = sio.imread(os.path.join(video_folder, frame_fns[0]))
self.frame_shape = img.shape[:2]
self.fps = fps if fps is not None else self.raw_fps
self.delta = 1. / self.fps
self.cur_frame = int(seek * self.fps) - 1
self.time = self.cur_frame * self.delta
self.max_frame = self.num_frames
if duration is not None:
self.max_frame = min(int((seek + duration) * self.fps), self.max_frame)
def get_by_index(self, start_time, size):
ss = int(start_time * self.fps)
chunk = []
for fno in range(ss, ss+size):
fn = os.path.join(self.video_folder, '{:06d}.jpg'.format(fno))
if not os.path.exists(fn):
return None
chunk.append(sio.imread(fn))
return np.stack(chunk, 0) if len(chunk) > 1 else chunk[0][np.newaxis]
def get(self):
self.cur_frame += 1
if self.cur_frame >= self.max_frame:
return None
self.time = self.cur_frame * self.delta
frame_no = int(self.time * self.raw_fps)
fn = os.path.join(self.video_folder, '{:06d}.jpg'.format(frame_no))
return sio.imread(fn)
def loop(self):
while True:
frame = self.get()
if frame is None:
break
yield frame
def skip(self, n):
for _ in range(n):
frame = self.get()
if frame is None:
return False
return True
class VideoReader:
def __init__(self, video_fn,
backend='imageio',
rate=None,
seek=0,
pad_start=0,
duration=None,
rotation=None,
img_prep=None):
if pad_start != 0:
assert seek == 0 and isinstance(pad_start, int)
self.backend = backend
if backend != 'jpg':
self.reader = BasicVideoReader(video_fn, backend, rate, seek, duration)
else:
self.reader = FrameReader(video_fn, rate, seek, duration)
self.fps = self.reader.fps
self.duration = self.reader.duration
self.num_frames = int (self.duration * self.fps)
self.img_prep = img_prep if img_prep is not None else lambda x: x
raw_shape = self.reader.frame_shape + (3, )
dummy_img = self.img_prep(np.zeros(raw_shape, dtype=np.uint8))
self.frame_shape = dummy_img.shape
self.pad_start = pad_start
if rotation is not None:
assert -np.pi <= rotation < np.pi
self.roll = -int(rotation / (2. * np.pi) * self.frame_shape[1])
else:
self.roll = None
def get_by_index(self, start_time, size):
assert self.backend == 'jpg'
chunk = self.reader.get_by_index(start_time, size)
if chunk is None:
return None
elif len(chunk) > 1:
chunk = np.stack([self.img_prep(frame) for frame in chunk], 0)
else:
chunk = self.img_prep(chunk[0])[np.newaxis]
return chunk
def get(self):
if self.pad_start > 0:
frame = np.zeros(self.frame_shape, dtype=np.uint8)
self.pad_start -= 1
else:
frame = self.reader.get()
if frame is not None:
frame = self.img_prep(frame)
if self.roll is not None:
frame = np.roll(frame, self.roll, axis=1)
return frame
def loop(self):
while True:
frame = self.get()
if frame is None:
break
yield frame
def get_chunk(self, n=1, force_size=False):
chunk = []
for i in range(n):
frame = self.get()
if frame is None:
break
chunk.append(frame)
if len(chunk) == 0: # End of video
return None
if force_size and len(chunk) != n: # Not have enough frames
return None
if len(chunk) > 1:
return np.stack(chunk, axis=0)
else:
return np.expand_dims(chunk[0], 0)
def loop_chunks(self, n=1, force_size=False):
while True:
chunk = self.get_chunk(n, force_size=force_size)
if chunk is None:
break
yield chunk
class VideoWriter:
def __init__(self, video_fn, video_fps, backend='imageio', codec='libx264', quality=5, overwrite=False):
if overwrite and os.path.exists(video_fn):
os.remove(video_fn)
assert not os.path.exists(video_fn)
self.backend = BACKENDS[backend]
self.video_fn = video_fn
self.fps = video_fps
if self.backend == IMAGEIO:
import imageio
self.writer = imageio.get_writer(video_fn,
fps=video_fps,
codec=codec,
pixelformat='yuv420p',
quality=quality)
else:
raise ValueError, 'Backend not supported'
def __del__(self):
if self.backend == IMAGEIO:
self.writer.close()
def close(self):
if self.backend == IMAGEIO:
self.writer.close()
def write_frame(self, frame):
if self.backend == IMAGEIO:
self.writer.append_data(frame)
def write_chunk(self, chunk):
for frame in chunk:
self.write_frame(frame)
def test_basic_reader():
import time
from matplotlib import pyplot as plt
fn = '../../data/youtube/preproc/3n0JIuX9fZA-video.mp4'
reader = BasicVideoReader(fn, backend='opencv', seek=30, fps=10, duration=30)
duration = []
start_time = time.time()
for v in reader.loop():
duration.append(time.time() - start_time)
print(reader.time, v.shape, duration[-1])
plt.imshow(v)
plt.show()
start_time = time.time()
print 'Done'
print reader.time
# test_basic_reader()
def test_video_reader():
from matplotlib import pyplot as plt
import time
fn = '/gpu2_data/morgado/spatialaudiogen/youtube/train/74ZiZ1iGG4k/video'
reader = VideoReader(fn, backend='jpg', rate=10, pad_start=0, seek=0,
duration=10, rotation=np.pi/2, img_prep=None)
duration = []
start_time = time.time()
for v in reader.loop_chunks(10):
duration.append(time.time() - start_time)
print(reader.reader.time, v.shape, duration[-1])
plt.imshow(v[0])
plt.show()
start_time = time.time()
# test_video_reader()
def test_video_writer():
import os
fn = '../../data/youtube/preproc/3n0JIuX9fZA-video.mp4'
reader = VideoReader(fn, rate=10, pad_start=0, seek=30,
duration=30, rotation=np.pi/2, img_prep=None)
writer = VideoWriter('tmp.mp4', 10, backend='imageio', overwrite=True)
for v in reader.loop():
writer.write_frame(v)
print(v.shape)
writer.close()
os.system('ffplay tmp.mp4')
os.remove('tmp.mp4')
# test_video_writer()
|
StarcoderdataPython
|
345186
|
<filename>exp/train_search.py
'''
@author: <NAME>
@contact: <EMAIL>
@github: github.com/mrluin
'''
import os
import torch
import glob
from models.gumbel_super_network import GumbelAutoDeepLab
from run_manager import RunConfig
from nas_manager import ArchSearchConfig, ArchSearchRunManager
from configs.train_search_config import obtain_train_search_args
from utils.common import set_manual_seed, print_experiment_environment, time_for_file, create_exp_dir
from utils.common import save_configs
def main(args):
assert torch.cuda.is_available(), 'CUDA is not available'
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
torch.set_num_threads(args.workers)
set_manual_seed(args.random_seed)
print_experiment_environment()
os.makedirs(args.path, exist_ok=True)
EXP_time = time_for_file()
args.path = os.path.join(args.path, args.exp_name, EXP_time)
create_exp_dir(args.path, scripts_to_save=glob.glob('./*/*.py'))
# weight optimizer config, related to network_weight_optimizer, scheduler, and criterion
if args.weight_optimizer_type == 'SGD':
weight_optimizer_params = {
'momentum': args.momentum,
'nesterov': args.nesterov,
'weight_decay': args.weight_decay,
}
elif args.weight_optimizer_type == 'RMSprop':
weight_optimizer_params = {
'momentum': args.momentum,
'weight_decay': args.weight_decay,
}
else: weight_optimizer_params = None
if args.scheduler == 'cosine':
# TODO: add additional params in args
scheduler_params = {
'T_max': args.T_max,
'eta_min': args.eta_min
}
elif args.scheduler == 'multistep':
scheduler_params = {
'milestones': args.milestones,
'gammas': args.gammas
}
elif args.scheduler == 'exponential':
scheduler_params = {'gamma': args.gamma}
elif args.scheduler == 'linear':
scheduler_params = {'min_lr': args.min_lr}
else: scheduler_params = None
if args.criterion == 'SmoothSoftmax':
criterion_params = {'label_smooth': args.label_smoothing}
else: criterion_params = None
# weight_optimizer_config, used in run_manager to get weight_optimizer, scheduler, and criterion.
args.optimizer_config = {
'optimizer_type' : args.weight_optimizer_type,
'optimizer_params' : weight_optimizer_params,
'scheduler' : args.scheduler,
'scheduler_params' : scheduler_params,
'criterion' : args.criterion,
'criterion_params' : criterion_params,
'init_lr' : args.init_lr,
'warmup_epoch' : args.warmup_epochs,
'epochs' : args.total_epochs,
'class_num' : args.nb_classes,
}
# TODO need modification
args.conv_candidates = [
'3x3_MBConv3', '3x3_MBConv6',
'5x5_MBConv3', '5x5_MBConv6',
'7x7_MBConv3', '7x7_MBConv6',
'Zero', #'Identity'
]
run_config = RunConfig( **args.__dict__ )
# arch_optimizer_config
if args.arch_optimizer_type == 'adam':
args.arch_optimizer_params = {
'betas': (args.arch_adam_beta1, args.arch_adam_beta2),
'eps': args.arch_adam_eps
}
else: args.arch_optimizer_params = None
# related to hardware constraint
# TODO: get rid of
if args.reg_loss_type == 'add#linear':
args.reg_loss_params = {'lambda': args.reg_loss_lambda}
elif args.reg_loss_type == 'mul#log':
args.reg_loss_params = {
'alpha': args.reg_loss_alpha,
'beta': args.reg_loss_beta
}
else: args.reg_loss_params = None
arch_search_config = ArchSearchConfig( **args.__dict__ )
# perform config save, for run_configs and arch_search_configs
save_configs(run_config.config, arch_search_config.config, args.path)
print('Run Configs:')
for k, v in run_config.config.items():
print('\t{}: {}'.format(k, v))
print('Architecture Search Configs:')
for k, v in arch_search_config.config.items():
print('\t{}: {}'.format(k, v))
# TODO: configs saving
super_network = GumbelAutoDeepLab(
args.filter_multiplier, args.block_multiplier, args.steps,
args.nb_classes, args.nb_layers, args.conv_candidates
)
arch_search_run_manager = ArchSearchRunManager(args.path, super_network, run_config, arch_search_config)
# TODO: perform resume
# warm up phase
if arch_search_run_manager.warmup:
arch_search_run_manager.warm_up(warmup_epochs=args.warmup_epochs)
# train search phase
arch_search_run_manager.train()
if __name__ == '__main__':
args = obtain_train_search_args()
main(args)
|
StarcoderdataPython
|
8110052
|
from django.db import models
# Create your models here.
class Images(models.Model):
'''
model to handle images
'''
image_link = models.ImageField(upload_to='images/')
title = models.CharField(max_length=80)
description = models.TextField()
category = models.ForeignKey('Categories', on_delete=models.CASCADE, default=1)
location = models.ForeignKey('Locations', on_delete=models.CASCADE, default=1)
def __str__(self):
return self.title
def save_image(self):
'''
method to save an image
'''
self.save()
def delete_image(self):
'''
method to delete an image
'''
self.delete()
def update_image(self, new_url):
'''
method to update an image's link
'''
try:
self.image_link = new_url
self.save()
return self
except self.DoesNotExist:
print('Image you specified does not exist')
@classmethod
def get_all(cls):
'''
method to retrieve all images
'''
pics = Images.objects.all()
return pics
@classmethod
def get_image_by_id(cls, id):
'''
method to retrieve images by unique id
'''
retrieved = Images.objects.get(id = id)
return retrieved
@classmethod
def search_image(cls, cat):
'''
method to search images by category
'''
retrieved = cls.objects.filter(category__name__contains=cat) #images assoc w/ this cat
return retrieved #list of instances
@classmethod
def filter_by_location(cls ,location):
'''
method to retrive images by their locations
'''
retrieved = Images.objects.filter(location__city__contains=location)
return retrieved
class Categories(models.Model):
'''
model to handle categories
'''
name = models.CharField(max_length=30)
def __str__(self):
return self.name
def save_category(self):
'''
method to save a category
'''
self.save()
def delete_category(self):
'''
method to delete a category
'''
self.delete()
@classmethod
def update_category(cls, search_term , new_cat):
'''
method to update a category
'''
try:
to_update = Categories.objects.get(name = search_term)
to_update.name = new_cat
to_update.save()
return to_update
except Categories.DoesNotExist:
print('Category you specified does not exist')
class Locations(models.Model):
'''
model to handle locations
'''
city = models.CharField(max_length=30)
country = models.CharField(max_length=30)
def __str__(self):
return self.city
def save_location(self):
'''
method to save a location
'''
self.save()
def delete_location(self):
'''
method to delete a location
'''
self.delete()
@classmethod
def update_location(cls, search_term , new_locale):
'''
method to update a location's city name
'''
try:
to_update = Locations.objects.get(country = search_term)
to_update.city = new_locale
to_update.save()
return to_update
except Locations.DoesNotExist:
print('Location you specified does not exist')
@classmethod
def get_all(cls):
'''
method to retrive all stored locations
'''
cities = Locations.objects.all()
return cities
|
StarcoderdataPython
|
5050204
|
#/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright (c) 2016 Red Hat, Inc.
#
# 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 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.
#
# Written by <NAME> <<EMAIL>>
import unittest
import os
import sys
DIR = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(DIR, ".."))
import modulemd
class TestLicenses(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.mmd = modulemd.ModuleMetadata()
def test_add_module_license(self):
self.assertNotIn("AddModuleLicense", self.mmd.module_licenses)
self.mmd.add_module_license("AddModuleLicense")
self.assertIn("AddModuleLicense", self.mmd.module_licenses)
def test_del_module_license(self):
self.mmd.module_licenses = set(["DelModuleLicense"])
self.mmd.del_module_license("DelModuleLicense")
self.assertNotIn("DelModuleLicense", self.mmd.module_licenses)
def test_clear_module_licenses(self):
self.mmd.module_licenses = set(["ClearModuleLicenses"])
self.mmd.clear_module_licenses()
self.assertEqual(self.mmd.module_licenses, set([]))
def test_add_content_license(self):
self.assertNotIn("AddContentLicense", self.mmd.content_licenses)
self.mmd.add_content_license("AddContentLicense")
self.assertIn("AddContentLicense", self.mmd.content_licenses)
def test_del_content_license(self):
self.mmd.content_licenses = set(["DelContentLicense"])
self.mmd.del_content_license("DelContentLicense")
self.assertNotIn("DelContentLicense", self.mmd.content_licenses)
def test_clear_content_licenses(self):
self.mmd.content_licenses = set(["ClearContentLicenses"])
self.mmd.clear_content_licenses()
self.assertEqual(self.mmd.content_licenses, set([]))
if __name__ == "__main__":
unittest.main()
|
StarcoderdataPython
|
9616820
|
<reponame>meyt/linkable-py
import re
from linkable.tld_list import tld_list
from linkable import emoji
_flags = re.UNICODE | re.IGNORECASE
# Extracted from: https://data.iana.org/TLD/tlds-alpha-by-domain.txt
tld_list = tld_list.split('\n')
tld_list = tuple(map(
lambda i: i[4:].encode().decode('punycode') if i.startswith('XN--') else i,
tld_list
))
tld_list = '|'.join(tld_list)
ip_middle_octet = r'(\.(1?\d{1,2}|2[0-4]\d|25[0-5]))'
ip_last_octet = r'(\.([1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))'
hashtag_punctuations = r'.,/##!‼⁉〰〽$%^&*;:=`~@?-'
word_pattern = re.compile(
r'\S+', _flags)
brackets_pattern = re.compile(
r'(?!'
# Begin brackets
r'[({\[⟨《]|'
# Begin guillemets
r'[<«‹]|'
# Begin quotations
r'[‘“\'\"„”]'
# Any word else
r')\S+(?='
# End brackets
r'[)}\]⟩》]|'
# End guillemets
r'[>»›]|'
# End quotations
r'[’”\'\"“]'
r')'
)
url_scheme_pattern = re.compile(
r'\S+://', _flags)
twitter_mention_pattern = re.compile(
r'^@([a-z_])([a-z\d_]*)$', _flags)
github_mention_pattern = re.compile(
r'^@([a-z\d-]+)$', _flags)
email_pattern = re.compile(
r'^[^\s@]+@[^\s@]+\.[^\s@]+$', _flags)
hashtag_pattern = re.compile(
r'^'
# Start with # or #
r'[##]'
# Escape start with keypad unicode variations
r'(?!\uFE0F\u20E3)'
# Escape start with numbers
r'(?!\d\d)(?!\d$)'
# Escape multiple hash symbols
r'(?![##]+$)'
# Match hashtag
r'('
# Match any (unicode) characters exclude symbols
r'([^\s{\}()' + hashtag_punctuations + '])+|'
# Exclude keypad unicode variation
r'\*\uFE0F\u20E3|'
r'#\uFE0F\u20E3'
r')'
r'$',
_flags
)
dirty_hashtag_pattern = re.compile(
# Negative lookahead any invisible character
r'(?:^|(?<=\s|#|#))'
# Any hashtag-like word exclude punctuation at end
r'('
r'[##](?![##])(?:'
r'.(?!'
r'[\s' + hashtag_punctuations.replace('##', '') + ']|' + emoji.pattern +
r'))*.)',
_flags
)
# from: https://github.com/kvesteri/validators/blob/master/validators/url.py
url_pattern = re.compile(
r'^'
# protocol identifier
r'((https?|ftp)://)?'
# user:pass authentication
r'([-a-z\u00a1-\uffff0-9._~%!$&\'()*+,;=:]+'
r'(:[-a-z0-9._~%!$&\'()*+,;=:]*)?@)?'
r'('
# IP address exclusion
# private & local networks
r'((10|127)' + ip_middle_octet + r'{2}' + ip_last_octet + r')|'
r'((169\.254|192\.168)' + ip_middle_octet + ip_last_octet + r')|'
r'(172\.(1[6-9]|2\d|3[0-1])' + ip_middle_octet + ip_last_octet + r')'
r'|'
# private & local hosts
r'(localhost)'
r'|'
# IP address dotted notation octets
# excludes loopback network 0.0.0.0
# excludes reserved space >= 192.168.3.11
# excludes network & broadcast addresses
# (first & last IP address of each class)
r'([1-9]\d?|1\d\d|2[01]\d|22[0-3])'
r'' + ip_middle_octet + r'{2}'
r'' + ip_last_octet +
r'|'
# IPv6 RegEx from https://stackoverflow.com/a/17871737
r'\[('
# fc00:e968:6179::de52:7100
r'([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|'
# 1:: 1:2:3:4:5:6:7::
r'([0-9a-fA-F]{1,4}:){1,7}:|'
# fc00:e968:6179::de52:7100 fc00:e968:6179::de52:7100 fc00:e968:6179::de52:7100
r'([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|'
# fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b fc00:db20:35b:7399::5:8 fc00:e968:6179::de52:7100
r'([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|'
# fc00:e968:6179::de52:7100:7:8 fdf8:f53e:61e4::18:7:8 fdf8:f53e:61e4::18
r'([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|'
# fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:6:7:8 fc00:e968:6179::de52:7100:6:7:8 fdf8:f53e:61e4::18
r'([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|'
# fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:5:6:7:8 fdf8:f53e:61e4::18:5:6:7:8 fc00:e968:6179::de52:7100
r'([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|'
# fc00:db20:35b:7399::5:5:6:7:8 fdf8:f53e:61e4::18:4:5:6:7:8 fc00:e968:6179::de52:7100
r'[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|'
# fc00:e968:6179::de52:7100:4:5:6:7:8 fc00:e968:6179::de52:7100:4:5:6:7:8 ::8 ::
r':((:[0-9a-fA-F]{1,4}){1,7}|:)|'
# fe80::7:8%eth0 fe80::7:8%1
# (link-local IPv6 addresses with zone index)
r'fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]+|'
r'::(ffff(:0{1,4})?:)?'
r'((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\.){3}'
# fc00:db20:35b:7399::5.255.255.255 fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:255.255.255.255 fc00:e968:6179::de52:7100:255.255.255.255
# (IPv4-mapped IPv6 addresses and IPv4-translated addresses)
r'(25[0-5]|(2[0-4]|1?[0-9])?[0-9])|'
r'([0-9a-fA-F]{1,4}:){1,4}:'
r'((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\.){3}'
# 2001:db8:3:4::192.0.2.33 fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b.0.2.33
# (IPv4-Embedded IPv6 Address)
r'(25[0-5]|(2[0-4]|1?[0-9])?[0-9])'
r')\]|'
# host name
r'(([a-z\u00a1-\uffff0-9]-?)*[a-z\u00a1-\uffff0-9]+)'
# domain name
r'(\.([a-z\u00a1-\uffff0-9]-?)*[a-z\u00a1-\uffff0-9]+)*'
# TLD identifier
r'(\.(?:' + tld_list + r'|test|localhost))'
r')'
# port number
r'(:\d{2,5})?'
# resource path
r'(/[-a-z\u00a1-\uffff0-9._~%!$&\'()*+,;=:@/]*)??'
# query string
r'(\?\S*)?'
# fragment
r'(#\S*)?'
r'$',
_flags
)
|
StarcoderdataPython
|
11283604
|
<reponame>charlesblakemore/opt_lev_analysis
import numpy as np
import bead_util as bu
import matplotlib.pyplot as plt
import os
import scipy.signal as sig
import scipy
import glob
from scipy.optimize import curve_fit
data_dir1 = "/data/20180529/imaging_tests/p0/xprofile"
def spatial_bin(xvec, yvec, bin_size = .13):
fac = 1./bin_size
bins_vals = np.around(fac*xvec)
bins_vals/=fac
bins = np.unique(bins_vals)
y_binned = np.zeros_like(bins)
y_errors = np.zeros_like(bins)
for i, b in enumerate(bins):
idx = bins_vals == b
y_binned[i] = np.mean(yvec[idx])
y_errors[i] = scipy.stats.sem(yvec[idx])
return bins, y_binned, y_errors
def gauss(x, A, mu, sig):
'''gaussian fitting function'''
return A*np.exp(-1.*(x-mu)**2/(2.*sig**2))
def profile(fname, data_column = 3):
df = bu.DataFile()
df.load(fname)
df.load_other_data()
df.calibrate_stage_position()
if 'ysweep' in fname:
stage_column = 1
if 'left' in fname:
sign = -1.0
elif 'right' in fname:
sign = 1.0
else:
sign = 1.0
else:
stage_column = 0
sign = 1.0
b, a = sig.butter(1, 0.5)
#shape = np.shape(df.other_data)
#for i in range(shape[0]):
# plt.plot(df.other_data[i, :], label = str(i))
#plt.legend()
#plt.show()
int_filt = sig.filtfilt(b, a, df.other_data[data_column, :])
proft = np.gradient(int_filt)
stage_filt = sig.filtfilt(b, a, df.cant_data[stage_column, :])
dir_sign = np.sign(np.gradient(stage_filt)) * sign
xvec = df.cant_data[stage_column, :]
yvec = (proft - proft * dir_sign) * 0.5 - (proft + proft * dir_sign) * 0.5
b, y, e = spatial_bin(xvec, yvec)
return b, y, e
class File_prof:
"Class storing information from a single file"
def __init__(self, b, y, e):
self.bins = b
self.dxs = np.append(np.diff(b), 0)#0 pad left trapizoid rule
self.y = y
self.errors = e
self.mean = "mean not computed"
self.sigmasq = "std dev not computed"
self.date = "date not entered"
def dist_mean(self, roi = [-10, 10]):
#Finds the cnetroid of intensity distribution iteratively. First over all the data then the centroind over the region of interst
norm = np.sum(self.y*self.dxs)
c1 = np.sum(self.dxs*self.y*self.bins)/norm
lebin = np.argmin((self.bins - (c1+roi[0]))**2)
rebin = np.argmin((self.bins - (c1+roi[1]))**2)
norm2 = np.sum(self.y[lebin:rebin]*self.dxs[lebin:rebin])
c2 = np.sum(self.dxs[lebin:rebin]*self.y[lebin:rebin]*\
self.bins[lebin:rebin])/norm2
self.mean = c2
def sigsq(self):
#finds second moment of intensity distribution.
if type(self.mean) == str:
self.dist_mean()
derp1 = self.bins > ROI[0]
derp2 = self.bins < ROI[1]
ROIbool = np.array([a and b for a, b in zip(derp1, derp2)])
norm = np.sum(self.y[ROIbool]*self.dxs[ROIbool])
self.sigmasq = np.sum(self.bins[ROIbool]**2*self.y[ROIbool])/norm
def sigsq2(self, p0 = [1., 0., 3.], make_plot = False, plt_region = [-10, 10]):
'''finds second moment by fitting to gaussian'''
if type(self.mean) == str:
self.dist_mean()
popt, pcov = curve_fit(gauss, self.bins, self.y, p0 = p0)
if make_plot:
pb = (self.bins<plt_region[1])*(self.bins>plt_region[0])
plt.semilogy(self.bins[pb], self.y[pb], 'o')
plt.semilogy(self.bins[pb], gauss(self.bins[pb], *popt), 'r')
plt.show()
self.sigmasq = popt[-1]**2
def proc_dir(dir):
files = bu.find_all_fnames(dir)
file_profs = []
cents = []
for fi in files:
b, y, e = profile(fi)
f = File_prof(b, y, e)
f.date = dir[8:16]
file_profs.append(f)
f.dist_mean()
cents.append(f.mean)
return cents, file_profs
def plot_profs(fp_arr):
#plots different profiles
i = 1
for fp in fp_arr:
plt.plot(fp.bins, fp.y / np.max(fp.y), 'o')
plt.ylim(10**(-5), 10)
plt.xlabel("position [um]")
plt.ylabel("margenalized irradiance ~[W/m]")
plt.gca().set_yscale('linear')
plt.show()
def find_beam_crossing(directory, make_plot = True):
cents, fps = proc_dir(directory)
cmean = np.mean(cents)
error = scipy.stats.sem(cents)
if make_plot:
plot_profs(fps)
return cmean, error
|
StarcoderdataPython
|
1674218
|
import unittest
from wasmtime import *
class TestTrap(unittest.TestCase):
def test_new(self):
store = Store()
trap = Trap(store, 'x')
self.assertEqual(trap.message(), u'x')
def test_errors(self):
store = Store()
with self.assertRaises(TypeError):
Trap(1, '')
with self.assertRaises(TypeError):
Trap(store, 1)
def test_frames(self):
store = Store()
module = Module(store, """
(module $module
(func (export "init")
call $foo)
(func $foo
call $bar)
(func $bar
unreachable)
)
""")
i = Instance(module, [])
try:
i.exports()[0].func().call()
except Trap as e:
trap = e
frames = trap.frames()
self.assertEqual(len(frames), 3)
self.assertEqual(frames[0].func_index(), 2)
self.assertEqual(frames[1].func_index(), 1)
self.assertEqual(frames[2].func_index(), 0)
self.assertEqual(frames[0].func_name(), 'bar')
self.assertEqual(frames[1].func_name(), 'foo')
self.assertEqual(frames[2].func_name(), None)
self.assertEqual(frames[0].module_name(), 'module')
self.assertEqual(frames[1].module_name(), 'module')
self.assertEqual(frames[2].module_name(), 'module')
self.assertEqual(str(trap), """\
wasm trap: unreachable, source location: @002d
wasm backtrace:
0: module!bar
1: module!foo
2: module!<wasm function 0>
""")
def test_frames_no_module(self):
store = Store()
module = Module(store, """
(module
(func (export "init") unreachable)
)
""")
i = Instance(module, [])
try:
i.exports()[0].func().call()
except Trap as e:
trap = e
frames = trap.frames()
self.assertEqual(len(frames), 1)
self.assertEqual(frames[0].func_index(), 0)
self.assertEqual(frames[0].func_name(), None)
self.assertEqual(frames[0].module_name(), None)
|
StarcoderdataPython
|
11215301
|
<reponame>acidburn0zzz/llvm-project<gh_stars>100-1000
# encoding: utf-8
"""
Test lldb date formatter subsystem.
"""
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
from ObjCDataFormatterTestCase import ObjCDataFormatterTestCase
import datetime
class ObjCDataFormatterNSDate(ObjCDataFormatterTestCase):
def test_nsdate_with_run_command(self):
"""Test formatters for NSDate."""
self.appkit_tester_impl(self.nsdate_data_formatter_commands)
def nsdate_data_formatter_commands(self):
self.expect(
'frame variable date1 date2',
patterns=[
'(1985-04-10|1985-04-11)',
'(2011-01-01|2010-12-31)'])
# this test might fail if we hit the breakpoint late on December 31st of some given year
# and midnight comes between hitting the breakpoint and running this line of code
# hopefully the output will be revealing enough in that case :-)
now_year = '%s-' % str(datetime.datetime.now().year)
self.expect('frame variable date3', substrs=[now_year])
self.expect('frame variable date4', substrs=['1970'])
self.expect('frame variable date5', substrs=[now_year])
self.expect('frame variable date1_abs date2_abs',
substrs=['1985-04', '2011-01'])
self.expect('frame variable date3_abs', substrs=[now_year])
self.expect('frame variable date4_abs', substrs=['1970'])
self.expect('frame variable date5_abs', substrs=[now_year])
# Check that LLDB always follow's NSDate's rounding behavior (which
# is always rounding down).
self.expect_expr("date_1970_minus_06", result_summary="1969-12-31 23:59:59 UTC")
self.expect_expr("date_1970_minus_05", result_summary="1969-12-31 23:59:59 UTC")
self.expect_expr("date_1970_minus_04", result_summary="1969-12-31 23:59:59 UTC")
self.expect_expr("date_1970_plus_06", result_summary="1970-01-01 00:00:00 UTC")
self.expect_expr("date_1970_plus_05", result_summary="1970-01-01 00:00:00 UTC")
self.expect_expr("date_1970_plus_04", result_summary="1970-01-01 00:00:00 UTC")
self.expect('frame variable cupertino home europe',
substrs=['@"America/Los_Angeles"',
'@"Europe/Rome"',
'@"Europe/Paris"'])
self.expect('frame variable cupertino_ns home_ns europe_ns',
substrs=['@"America/Los_Angeles"',
'@"Europe/Rome"',
'@"Europe/Paris"'])
self.expect(
'frame variable mut_bv',
substrs=[
'(CFMutableBitVectorRef) mut_bv = ',
'1110 0110 1011 0000 1101 1010 1000 1111 0011 0101 1101 0001 00'])
self.expect_expr("distant_past", result_summary="0001-01-01 00:00:00 UTC")
self.expect_expr("distant_future", result_summary="4001-01-01 00:00:00 UTC")
|
StarcoderdataPython
|
390523
|
import pytest
import numpy as np
import numpy.linalg
import theano
from numpy import inf
from numpy.testing import assert_array_almost_equal
from theano import tensor, function
from theano.tensor.basic import _allclose
from theano import config
from theano.tensor.nlinalg import (
MatrixInverse,
matrix_inverse,
pinv,
AllocDiag,
alloc_diag,
ExtractDiag,
extract_diag,
diag,
trace,
det,
Eig,
eig,
eigh,
matrix_dot,
qr,
matrix_power,
norm,
svd,
SVD,
TensorInv,
tensorinv,
tensorsolve,
)
from tests import unittest_tools as utt
def test_pseudoinverse_correctness():
rng = np.random.RandomState(utt.fetch_seed())
d1 = rng.randint(4) + 2
d2 = rng.randint(4) + 2
r = rng.randn(d1, d2).astype(theano.config.floatX)
x = tensor.matrix()
xi = pinv(x)
ri = function([x], xi)(r)
assert ri.shape[0] == r.shape[1]
assert ri.shape[1] == r.shape[0]
assert ri.dtype == r.dtype
# Note that pseudoinverse can be quite unprecise so I prefer to compare
# the result with what np.linalg returns
assert _allclose(ri, np.linalg.pinv(r))
def test_pseudoinverse_grad():
rng = np.random.RandomState(utt.fetch_seed())
d1 = rng.randint(4) + 2
d2 = rng.randint(4) + 2
r = rng.randn(d1, d2).astype(theano.config.floatX)
utt.verify_grad(pinv, [r])
class TestMatrixInverse(utt.InferShapeTester):
def setup_method(self):
super().setup_method()
self.op_class = MatrixInverse
self.op = matrix_inverse
self.rng = np.random.RandomState(utt.fetch_seed())
def test_inverse_correctness(self):
r = self.rng.randn(4, 4).astype(theano.config.floatX)
x = tensor.matrix()
xi = self.op(x)
ri = function([x], xi)(r)
assert ri.shape == r.shape
assert ri.dtype == r.dtype
rir = np.dot(ri, r)
rri = np.dot(r, ri)
assert _allclose(np.identity(4), rir), rir
assert _allclose(np.identity(4), rri), rri
def test_infer_shape(self):
r = self.rng.randn(4, 4).astype(theano.config.floatX)
x = tensor.matrix()
xi = self.op(x)
self._compile_and_check([x], [xi], [r], self.op_class, warn=False)
def test_matrix_dot():
rng = np.random.RandomState(utt.fetch_seed())
n = rng.randint(4) + 2
rs = []
xs = []
for k in range(n):
rs += [rng.randn(4, 4).astype(theano.config.floatX)]
xs += [tensor.matrix()]
sol = matrix_dot(*xs)
theano_sol = function(xs, sol)(*rs)
numpy_sol = rs[0]
for r in rs[1:]:
numpy_sol = np.dot(numpy_sol, r)
assert _allclose(numpy_sol, theano_sol)
def test_qr_modes():
rng = np.random.RandomState(utt.fetch_seed())
A = tensor.matrix("A", dtype=theano.config.floatX)
a = rng.rand(4, 4).astype(theano.config.floatX)
f = function([A], qr(A))
t_qr = f(a)
n_qr = np.linalg.qr(a)
assert _allclose(n_qr, t_qr)
for mode in ["reduced", "r", "raw"]:
f = function([A], qr(A, mode))
t_qr = f(a)
n_qr = np.linalg.qr(a, mode)
if isinstance(n_qr, (list, tuple)):
assert _allclose(n_qr[0], t_qr[0])
assert _allclose(n_qr[1], t_qr[1])
else:
assert _allclose(n_qr, t_qr)
try:
n_qr = np.linalg.qr(a, "complete")
f = function([A], qr(A, "complete"))
t_qr = f(a)
assert _allclose(n_qr, t_qr)
except TypeError as e:
assert "name 'complete' is not defined" in str(e)
class TestSvd(utt.InferShapeTester):
op_class = SVD
dtype = "float32"
def setup_method(self):
super().setup_method()
self.rng = np.random.RandomState(utt.fetch_seed())
self.A = theano.tensor.matrix(dtype=self.dtype)
self.op = svd
def test_svd(self):
A = tensor.matrix("A", dtype=self.dtype)
U, S, VT = svd(A)
fn = function([A], [U, S, VT])
a = self.rng.rand(4, 4).astype(self.dtype)
n_u, n_s, n_vt = np.linalg.svd(a)
t_u, t_s, t_vt = fn(a)
assert _allclose(n_u, t_u)
assert _allclose(n_s, t_s)
assert _allclose(n_vt, t_vt)
fn = function([A], svd(A, compute_uv=False))
t_s = fn(a)
assert _allclose(n_s, t_s)
def test_svd_infer_shape(self):
self.validate_shape((4, 4), full_matrices=True, compute_uv=True)
self.validate_shape((4, 4), full_matrices=False, compute_uv=True)
self.validate_shape((2, 4), full_matrices=False, compute_uv=True)
self.validate_shape((4, 2), full_matrices=False, compute_uv=True)
self.validate_shape((4, 4), compute_uv=False)
def validate_shape(self, shape, compute_uv=True, full_matrices=True):
A = self.A
A_v = self.rng.rand(*shape).astype(self.dtype)
outputs = self.op(A, full_matrices=full_matrices, compute_uv=compute_uv)
if not compute_uv:
outputs = [outputs]
self._compile_and_check([A], outputs, [A_v], self.op_class, warn=False)
def test_tensorsolve():
rng = np.random.RandomState(utt.fetch_seed())
A = tensor.tensor4("A", dtype=theano.config.floatX)
B = tensor.matrix("B", dtype=theano.config.floatX)
X = tensorsolve(A, B)
fn = function([A, B], [X])
# slightly modified example from np.linalg.tensorsolve docstring
a = np.eye(2 * 3 * 4).astype(theano.config.floatX)
a.shape = (2 * 3, 4, 2, 3 * 4)
b = rng.rand(2 * 3, 4).astype(theano.config.floatX)
n_x = np.linalg.tensorsolve(a, b)
t_x = fn(a, b)
assert _allclose(n_x, t_x)
# check the type upcast now
C = tensor.tensor4("C", dtype="float32")
D = tensor.matrix("D", dtype="float64")
Y = tensorsolve(C, D)
fn = function([C, D], [Y])
c = np.eye(2 * 3 * 4, dtype="float32")
c.shape = (2 * 3, 4, 2, 3 * 4)
d = rng.rand(2 * 3, 4).astype("float64")
n_y = np.linalg.tensorsolve(c, d)
t_y = fn(c, d)
assert _allclose(n_y, t_y)
assert n_y.dtype == Y.dtype
# check the type upcast now
E = tensor.tensor4("E", dtype="int32")
F = tensor.matrix("F", dtype="float64")
Z = tensorsolve(E, F)
fn = function([E, F], [Z])
e = np.eye(2 * 3 * 4, dtype="int32")
e.shape = (2 * 3, 4, 2, 3 * 4)
f = rng.rand(2 * 3, 4).astype("float64")
n_z = np.linalg.tensorsolve(e, f)
t_z = fn(e, f)
assert _allclose(n_z, t_z)
assert n_z.dtype == Z.dtype
def test_inverse_singular():
singular = np.array([[1, 0, 0]] + [[0, 1, 0]] * 2, dtype=theano.config.floatX)
a = tensor.matrix()
f = function([a], matrix_inverse(a))
try:
f(singular)
except np.linalg.LinAlgError:
return
assert False
def test_inverse_grad():
rng = np.random.RandomState(utt.fetch_seed())
r = rng.randn(4, 4)
tensor.verify_grad(matrix_inverse, [r], rng=np.random)
rng = np.random.RandomState(utt.fetch_seed())
r = rng.randn(4, 4)
tensor.verify_grad(matrix_inverse, [r], rng=np.random)
def test_det():
rng = np.random.RandomState(utt.fetch_seed())
r = rng.randn(5, 5).astype(config.floatX)
x = tensor.matrix()
f = theano.function([x], det(x))
assert np.allclose(np.linalg.det(r), f(r))
def test_det_grad():
rng = np.random.RandomState(utt.fetch_seed())
r = rng.randn(5, 5).astype(config.floatX)
tensor.verify_grad(det, [r], rng=np.random)
def test_det_shape():
rng = np.random.RandomState(utt.fetch_seed())
r = rng.randn(5, 5).astype(config.floatX)
x = tensor.matrix()
f = theano.function([x], det(x))
f_shape = theano.function([x], det(x).shape)
assert np.all(f(r).shape == f_shape(r))
class TestDiag:
"""
Test that linalg.diag has the same behavior as numpy.diag.
numpy.diag has two behaviors:
(1) when given a vector, it returns a matrix with that vector as the
diagonal.
(2) when given a matrix, returns a vector which is the diagonal of the
matrix.
(1) and (2) are tested by test_alloc_diag and test_extract_diag
respectively.
test_diag test makes sure that linalg.diag instantiates
the right op based on the dimension of the input.
"""
def setup_method(self):
self.mode = None
self.shared = tensor._shared
self.floatX = config.floatX
self.type = tensor.TensorType
def test_alloc_diag(self):
rng = np.random.RandomState(utt.fetch_seed())
x = theano.tensor.vector()
g = alloc_diag(x)
f = theano.function([x], g)
# test "normal" scenario (5x5 matrix) and special cases of 0x0 and 1x1
for shp in [5, 0, 1]:
m = rng.rand(shp).astype(self.floatX)
v = np.diag(m)
r = f(m)
# The right matrix is created
assert (r == v).all()
# Test we accept only vectors
xx = theano.tensor.matrix()
ok = False
try:
alloc_diag(xx)
except TypeError:
ok = True
assert ok
# Test infer_shape
f = theano.function([x], g.shape)
topo = f.maker.fgraph.toposort()
if config.mode != "FAST_COMPILE":
assert sum([node.op.__class__ == AllocDiag for node in topo]) == 0
for shp in [5, 0, 1]:
m = rng.rand(shp).astype(self.floatX)
assert (f(m) == m.shape).all()
def test_alloc_diag_grad(self):
rng = np.random.RandomState(utt.fetch_seed())
x = rng.rand(5)
tensor.verify_grad(alloc_diag, [x], rng=rng)
def test_diag(self):
# test that it builds a matrix with given diagonal when using
# vector inputs
x = theano.tensor.vector()
y = diag(x)
assert y.owner.op.__class__ == AllocDiag
# test that it extracts the diagonal when using matrix input
x = theano.tensor.matrix()
y = extract_diag(x)
assert y.owner.op.__class__ == ExtractDiag
# not testing the view=True case since it is not used anywhere.
def test_extract_diag(self):
rng = np.random.RandomState(utt.fetch_seed())
m = rng.rand(2, 3).astype(self.floatX)
x = self.shared(m)
g = extract_diag(x)
f = theano.function([], g)
assert [
isinstance(node.inputs[0].type, self.type)
for node in f.maker.fgraph.toposort()
if isinstance(node.op, ExtractDiag)
] == [True]
for shp in [(2, 3), (3, 2), (3, 3), (1, 1), (0, 0)]:
m = rng.rand(*shp).astype(self.floatX)
x.set_value(m)
v = np.diag(m)
r = f()
# The right diagonal is extracted
assert (r == v).all()
# Test we accept only matrix
xx = theano.tensor.vector()
ok = False
try:
extract_diag(xx)
except TypeError:
ok = True
except ValueError:
ok = True
assert ok
# Test infer_shape
f = theano.function([], g.shape)
topo = f.maker.fgraph.toposort()
if config.mode != "FAST_COMPILE":
assert sum([node.op.__class__ == ExtractDiag for node in topo]) == 0
for shp in [(2, 3), (3, 2), (3, 3)]:
m = rng.rand(*shp).astype(self.floatX)
x.set_value(m)
assert f() == min(shp)
def test_extract_diag_grad(self):
rng = np.random.RandomState(utt.fetch_seed())
x = rng.rand(5, 4).astype(self.floatX)
tensor.verify_grad(extract_diag, [x], rng=rng)
@pytest.mark.slow
def test_extract_diag_empty(self):
c = self.shared(np.array([[], []], self.floatX))
f = theano.function([], extract_diag(c), mode=self.mode)
assert [
isinstance(node.inputs[0].type, self.type)
for node in f.maker.fgraph.toposort()
if isinstance(node.op, ExtractDiag)
] == [True]
def test_trace():
rng = np.random.RandomState(utt.fetch_seed())
x = theano.tensor.matrix()
g = trace(x)
f = theano.function([x], g)
for shp in [(2, 3), (3, 2), (3, 3)]:
m = rng.rand(*shp).astype(config.floatX)
v = np.trace(m)
assert v == f(m)
xx = theano.tensor.vector()
ok = False
try:
trace(xx)
except TypeError:
ok = True
except ValueError:
ok = True
assert ok
class TestEig(utt.InferShapeTester):
op_class = Eig
op = eig
dtype = "float64"
def setup_method(self):
super().setup_method()
self.rng = np.random.RandomState(utt.fetch_seed())
self.A = theano.tensor.matrix(dtype=self.dtype)
self.X = np.asarray(self.rng.rand(5, 5), dtype=self.dtype)
self.S = self.X.dot(self.X.T)
def test_infer_shape(self):
A = self.A
S = self.S
self._compile_and_check(
[A], # theano.function inputs
self.op(A), # theano.function outputs
# S must be square
[S],
self.op_class,
warn=False,
)
def test_eval(self):
A = theano.tensor.matrix(dtype=self.dtype)
assert [e.eval({A: [[1]]}) for e in self.op(A)] == [[1.0], [[1.0]]]
x = [[0, 1], [1, 0]]
w, v = [e.eval({A: x}) for e in self.op(A)]
assert_array_almost_equal(np.dot(x, v), w * v)
class TestEigh(TestEig):
op = staticmethod(eigh)
def test_uplo(self):
S = self.S
a = theano.tensor.matrix(dtype=self.dtype)
wu, vu = [out.eval({a: S}) for out in self.op(a, "U")]
wl, vl = [out.eval({a: S}) for out in self.op(a, "L")]
assert_array_almost_equal(wu, wl)
assert_array_almost_equal(vu * np.sign(vu[0, :]), vl * np.sign(vl[0, :]))
def test_grad(self):
X = self.X
# We need to do the dot inside the graph because Eigh needs a
# matrix that is hermitian
utt.verify_grad(lambda x: self.op(x.dot(x.T))[0], [X], rng=self.rng)
utt.verify_grad(lambda x: self.op(x.dot(x.T))[1], [X], rng=self.rng)
utt.verify_grad(lambda x: self.op(x.dot(x.T), "U")[0], [X], rng=self.rng)
utt.verify_grad(lambda x: self.op(x.dot(x.T), "U")[1], [X], rng=self.rng)
class TestEighFloat32(TestEigh):
dtype = "float32"
def test_uplo(self):
super().test_uplo()
def test_grad(self):
super().test_grad()
class TestLstsq:
def test_correct_solution(self):
x = tensor.lmatrix()
y = tensor.lmatrix()
z = tensor.lscalar()
b = theano.tensor.nlinalg.lstsq()(x, y, z)
f = function([x, y, z], b)
TestMatrix1 = np.asarray([[2, 1], [3, 4]])
TestMatrix2 = np.asarray([[17, 20], [43, 50]])
TestScalar = np.asarray(1)
f = function([x, y, z], b)
m = f(TestMatrix1, TestMatrix2, TestScalar)
assert np.allclose(TestMatrix2, np.dot(TestMatrix1, m[0]))
def test_wrong_coefficient_matrix(self):
x = tensor.vector()
y = tensor.vector()
z = tensor.scalar()
b = theano.tensor.nlinalg.lstsq()(x, y, z)
f = function([x, y, z], b)
with pytest.raises(np.linalg.linalg.LinAlgError):
f([2, 1], [2, 1], 1)
def test_wrong_rcond_dimension(self):
x = tensor.vector()
y = tensor.vector()
z = tensor.vector()
b = theano.tensor.nlinalg.lstsq()(x, y, z)
f = function([x, y, z], b)
with pytest.raises(np.linalg.LinAlgError):
f([2, 1], [2, 1], [2, 1])
class TestMatrix_power:
def test_numpy_compare(self):
rng = np.random.RandomState(utt.fetch_seed())
A = tensor.matrix("A", dtype=theano.config.floatX)
Q = matrix_power(A, 3)
fn = function([A], [Q])
a = rng.rand(4, 4).astype(theano.config.floatX)
n_p = np.linalg.matrix_power(a, 3)
t_p = fn(a)
assert np.allclose(n_p, t_p)
def test_non_square_matrix(self):
rng = np.random.RandomState(utt.fetch_seed())
A = tensor.matrix("A", dtype=theano.config.floatX)
Q = matrix_power(A, 3)
f = function([A], [Q])
a = rng.rand(4, 3).astype(theano.config.floatX)
with pytest.raises(ValueError):
f(a)
class TestNormTests:
def test_wrong_type_of_ord_for_vector(self):
with pytest.raises(ValueError):
norm([2, 1], "fro")
def test_wrong_type_of_ord_for_matrix(self):
with pytest.raises(ValueError):
norm([[2, 1], [3, 4]], 0)
def test_non_tensorial_input(self):
with pytest.raises(ValueError):
norm(3, None)
def test_tensor_input(self):
with pytest.raises(NotImplementedError):
norm(np.random.rand(3, 4, 5), None)
def test_numpy_compare(self):
rng = np.random.RandomState(utt.fetch_seed())
M = tensor.matrix("A", dtype=theano.config.floatX)
V = tensor.vector("V", dtype=theano.config.floatX)
a = rng.rand(4, 4).astype(theano.config.floatX)
b = rng.rand(4).astype(theano.config.floatX)
A = (
[None, "fro", "inf", "-inf", 1, -1, None, "inf", "-inf", 0, 1, -1, 2, -2],
[M, M, M, M, M, M, V, V, V, V, V, V, V, V],
[a, a, a, a, a, a, b, b, b, b, b, b, b, b],
[None, "fro", inf, -inf, 1, -1, None, inf, -inf, 0, 1, -1, 2, -2],
)
for i in range(0, 14):
f = function([A[1][i]], norm(A[1][i], A[0][i]))
t_n = f(A[2][i])
n_n = np.linalg.norm(A[2][i], A[3][i])
assert _allclose(n_n, t_n)
class TestTensorInv(utt.InferShapeTester):
def setup_method(self):
super().setup_method()
self.A = tensor.tensor4("A", dtype=theano.config.floatX)
self.B = tensor.tensor3("B", dtype=theano.config.floatX)
self.a = np.random.rand(4, 6, 8, 3).astype(theano.config.floatX)
self.b = np.random.rand(2, 15, 30).astype(theano.config.floatX)
self.b1 = np.random.rand(30, 2, 15).astype(
theano.config.floatX
) # for ind=1 since we need prod(b1.shape[:ind]) == prod(b1.shape[ind:])
def test_infer_shape(self):
A = self.A
Ai = tensorinv(A)
self._compile_and_check(
[A], # theano.function inputs
[Ai], # theano.function outputs
[self.a], # value to substitute
TensorInv,
)
def test_eval(self):
A = self.A
Ai = tensorinv(A)
n_ainv = np.linalg.tensorinv(self.a)
tf_a = function([A], [Ai])
t_ainv = tf_a(self.a)
assert _allclose(n_ainv, t_ainv)
B = self.B
Bi = tensorinv(B)
Bi1 = tensorinv(B, ind=1)
n_binv = np.linalg.tensorinv(self.b)
n_binv1 = np.linalg.tensorinv(self.b1, ind=1)
tf_b = function([B], [Bi])
tf_b1 = function([B], [Bi1])
t_binv = tf_b(self.b)
t_binv1 = tf_b1(self.b1)
assert _allclose(t_binv, n_binv)
assert _allclose(t_binv1, n_binv1)
|
StarcoderdataPython
|
80654
|
<gh_stars>0
""" Welcome The User To Masonite """
from masonite.request import Request
from masonite.view import View
from events import Event
from app.League import League
from masonite import Broadcast
class WelcomeController:
""" Controller For Welcoming The User """
def __init__(self, view: View, request: Request):
self.view = view
self.request = request
def show(self, event: Event, broadcast: Broadcast) -> View.render:
''' Show Welcome Template '''
return self.view.render('index')
def discover(self) -> View.render:
"""Shows the discover page
Returns:
View.render
"""
if self.request.input('search'):
leagues = League.order_by('id', 'desc').get().filter(lambda league: self.request.input(
'search').lower() in league.name.lower())
else:
leagues = League.order_by('id', 'desc').get().take(100)
return self.view.render('discover', {'leagues': leagues})
def slack(self):
return ''
# response = IntegrationManager.driver('discord').user()
# requests.post(
# 'https://discordapp.com/api/webhooks/{0}/{1}'.format(
# response['webhook']['id'],
# response['webhook']['token']
# ),
# json={
# 'content': 'Masonite was successfully integrated!',
# 'username': 'Masonite'
# }
# )
# return response['access_token']
|
StarcoderdataPython
|
4932746
|
# coding=utf-8
# @Time : 2020/12/2 18:49
# @Auto : zzf-jeff
from abc import ABCMeta, abstractmethod
class BaseEncodeConverter(metaclass=ABCMeta):
def __init__(self,
max_text_length,
character_dict_path=None,
character_type='ch',
use_space_char=False):
"""rec label converter
:param max_text_length:
:param character_dict_path:
:param character_type:
:param use_space_char:
"""
support_character_type = [
'ch', 'en'
]
assert character_type in support_character_type, "Only {} are supported now but get {}".format(
support_character_type, character_type)
self.max_text_len = max_text_length
if character_type == "en":
self.character_str = "0123456789abcdefghijklmnopqrstuvwxyz"
dict_character = list(self.character_str)
elif character_type in ["ch"]:
self.character_str = ""
assert character_dict_path is not None, "character_dict_path should not be None when character_type is ch"
with open(character_dict_path, "rb") as fin:
lines = fin.readlines()
for line in lines:
line = line.decode('utf-8').strip("\n").strip("\r\n")
self.character_str += line
if use_space_char:
self.character_str += " "
dict_character = list(self.character_str)
else:
raise Exception('dict_character is empty')
self.character_type = character_type
dict_character = self.add_special_char(dict_character)
self.dict = {}
for i, char in enumerate(dict_character):
self.dict[char] = i
self.character = dict_character
def add_special_char(self, dict_character):
return dict_character
@abstractmethod
def encode(self, *args, **kwargs):
pass
|
StarcoderdataPython
|
3363237
|
"""Profiles"""
import os
import random
import sqlite3
from datetime import datetime
import scrapy
from scrapy.http import Request
from scrapy.selector import Selector
from scrapy_jsonschema.item import JsonSchemaItem
from ..items import ParliamentPipeline
parties_dictionary = {
"ПП ГЕРБ": "GERP",
"БСП за БЪЛГАРИЯ": "BSP",
"ВОЛЯ": "VOLQ",
"Движение за права и свободи - ДПС": "DPS",
"ОБЕДИНЕНИ ПАТРИОТИ - НФСБ, АТАКА и ВМРО": "OP",
}
class ProductItem(JsonSchemaItem):
""" json schema to check jsons """
jsonschema = {
"$schema": "http://json-schema.org/schema#",
"type": "object",
"properties": {
"name": {"type": "string"},
"place_born": {"type": ["null", "string"]},
"date_born": {"type": "string", "format": "date"},
"profession": {"type": ["null", "string"]},
"lang": {"type": ["null", "string"]},
"party": {"type": "string"},
"email": {"type": "string"},
"fb": {"type": ["null", "string"]},
"url": {"type": ["null", "string"]},
"pp": {"type": "string"},
"dob": {"type": "integer"},
},
}
def extract_date_place(date_born_place):
""" extract date born and place born """
start_date = date_born_place.find(": ") + 2
end_date = start_date + 10
date_born_scraped = date_born_place[start_date:end_date]
date_born = datetime.strptime(date_born_scraped, "%d/%m/%Y").strftime("%Y-%m-%d")
place_born = date_born_place[end_date + 1 :]
if place_born == ", ":
place_born = None
if place_born == ", България":
place_born = "България"
return date_born, place_born
def parse_following_urls(response):
"""extracting 3 names, date and place of birth,
profession, lang, party, e-mail, fb"""
items = ParliamentPipeline()
first_name = response.css("strong::text")[0].get()
second_name = response.css(".MProwD::text").get()
third_name = response.css("strong::text")[1].get()
name = f"{first_name}{second_name}{third_name}"
data = response.xpath("//div[4]/div[2]/div/ul/li/text()").getall()
date_born, place_born = extract_date_place(data[0])
lang_row = 2 # defining lang and party rows because some rows are
# missing sometimes
party_row = 3
if data[1].startswith("Професия:"):
profession = data[1][data[1].find(": ") + 2 : -1]
else:
profession = None
lang_row -= 1
party_row -= 1
if data[lang_row].startswith("Езици:"):
lang = data[lang_row][data[lang_row].find(": ") + 2 : -1]
else:
lang = None
party_row -= 1
if data[party_row].startswith("Избран"):
party = data[party_row][data[party_row].find(": ") + 2 : -7]
party = party.rstrip()
try:
email_href = response.xpath("//div[4]/div[2]/div/ul/li/a/@href").getall()[-1]
if email_href.startswith("mailto:") is True:
email = response.xpath("//div[4]/div[2]/div/ul/li/a/text()").getall()[-1]
fb_href = None
else:
fb_href = response.xpath("//div[4]/div[2]/div/ul/li/a/@href").getall()[-1]
if fb_href.startswith("https://www.facebook.com/"):
fb_href = response.xpath("//div[4]/div[2]/div/ul/li/a/@href").getall()[
-1
]
email = response.xpath("//div[4]/div[2]/div/ul/li/a/text()").getall()[
-2
]
except BaseException as ex: # if e-mail and fb_link are missing
print(ex)
email = None
fb_href = None
items["name"] = name
items["date_born"] = date_born
items["place_born"] = place_born
items["profession"] = profession
items["lang"] = lang
items["party"] = party
items["email"] = email
items["fb"] = fb_href
items["url"] = response.request.url[-11:]
items["pp"] = parties_dictionary[party] # political party short version
items["dob"] = date_born.replace("-", "") # date of birth short version
yield items
class PostsSpider(scrapy.Spider):
""" spyder who crawl"""
name = "posts"
allowed_domains = "parliament.bg"
start_urls = ["https://www.parliament.bg/bg/MP/"]
def parse(self, response):
# parse any elements you need from the start_urls and, optionally,
# store them as Items.
# See http://doc.scrapy.org/en/latest/topics/items.html
selector = Selector(response)
urls_short = selector.xpath("//div[3]/div/div/div/a/@href").getall()
# get unique from 2 different lists short_urls and links from DB
path = os.path.dirname(os.path.abspath(__file__))
db = os.path.join(path, "db.sqlite3")
conn = sqlite3.connect(db)
c = conn.cursor()
c.execute("SELECT url FROM Parliament1;")
rows_urls = c.fetchall()
rows = [i[0] for i in rows_urls]
urls_short_unique = [i for i in urls_short if i not in rows]
start_urls = [
"https://www.parliament.bg" + short for short in urls_short_unique
]
start_urls = start_urls[: random.randint(100, 140)]
for url in start_urls:
yield Request(url, callback=parse_following_urls, dont_filter=True)
|
StarcoderdataPython
|
6700009
|
from mgear.core import pyqt
from mgear.vendor.Qt import QtCore, QtWidgets, QtGui
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(297, 300)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(Form.sizePolicy().hasHeightForWidth())
Form.setSizePolicy(sizePolicy)
self.gridLayout = QtWidgets.QGridLayout(Form)
self.gridLayout.setSpacing(3)
self.gridLayout.setContentsMargins(3, 3, 3, 3)
self.gridLayout.setObjectName("gridLayout")
self.groupBox = QtWidgets.QGroupBox(Form)
self.groupBox.setObjectName("groupBox")
self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.groupBox)
self.verticalLayout_2.setSpacing(3)
self.verticalLayout_2.setContentsMargins(3, 3, 3, 3)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.verticalLayout = QtWidgets.QVBoxLayout()
self.verticalLayout.setObjectName("verticalLayout")
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.xgen_description_label = QtWidgets.QLabel(self.groupBox)
self.xgen_description_label.setObjectName("xgen_description_label")
self.horizontalLayout.addWidget(self.xgen_description_label)
self.xgen_description_lineEdit = QtWidgets.QLineEdit(self.groupBox)
self.xgen_description_lineEdit.setEnabled(False)
self.xgen_description_lineEdit.setFocusPolicy(QtCore.Qt.NoFocus)
self.xgen_description_lineEdit.setObjectName("xgen_description_lineEdit")
self.horizontalLayout.addWidget(self.xgen_description_lineEdit)
self.xgen_description_pushButton = QtWidgets.QPushButton(self.groupBox)
self.xgen_description_pushButton.setObjectName("xgen_description_pushButton")
self.horizontalLayout.addWidget(self.xgen_description_pushButton)
self.verticalLayout.addLayout(self.horizontalLayout)
self.verticalLayout_2.addLayout(self.verticalLayout)
self.add_curve_pushButton = QtWidgets.QPushButton(self.groupBox)
self.add_curve_pushButton.setObjectName("add_curve_pushButton")
self.verticalLayout_2.addWidget(self.add_curve_pushButton)
self.gridLayout.addWidget(self.groupBox, 0, 0, 1, 1)
self.groupBox_2 = QtWidgets.QGroupBox(Form)
self.groupBox_2.setObjectName("groupBox_2")
self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.groupBox_2)
self.verticalLayout_3.setSpacing(3)
self.verticalLayout_3.setContentsMargins(3, 3, 3, 3)
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.horizontalLayout_9 = QtWidgets.QHBoxLayout()
self.horizontalLayout_9.setSpacing(3)
self.horizontalLayout_9.setObjectName("horizontalLayout_9")
self.duplicate_pushButton = QtWidgets.QPushButton(self.groupBox_2)
self.duplicate_pushButton.setObjectName("duplicate_pushButton")
self.horizontalLayout_9.addWidget(self.duplicate_pushButton)
self.duplicate_sym_pushButton = QtWidgets.QPushButton(self.groupBox_2)
self.duplicate_sym_pushButton.setObjectName("duplicate_sym_pushButton")
self.horizontalLayout_9.addWidget(self.duplicate_sym_pushButton)
self.move_pushButton = QtWidgets.QPushButton(self.groupBox_2)
self.move_pushButton.setObjectName("move_pushButton")
self.horizontalLayout_9.addWidget(self.move_pushButton)
self.verticalLayout_3.addLayout(self.horizontalLayout_9)
self.gridLayout.addWidget(self.groupBox_2, 2, 0, 1, 1)
self.color_groupBox = QtWidgets.QGroupBox(Form)
self.color_groupBox.setObjectName("color_groupBox")
self.horizontalLayout_7 = QtWidgets.QHBoxLayout(self.color_groupBox)
self.horizontalLayout_7.setSpacing(2)
self.horizontalLayout_7.setContentsMargins(3, 0, 3, 3)
self.horizontalLayout_7.setObjectName("horizontalLayout_7")
self.orange_pushButton = QtWidgets.QPushButton(self.color_groupBox)
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 170, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 213, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 191, 63))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 85, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(170, 113, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.BrightText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 170, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 212, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 170, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 213, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 191, 63))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 85, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(170, 113, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.BrightText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 170, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 212, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 85, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 170, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 213, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 191, 63))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 85, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(170, 113, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 85, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.BrightText, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 85, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 170, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 170, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 170, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText, brush)
self.orange_pushButton.setPalette(palette)
self.orange_pushButton.setText("")
self.orange_pushButton.setObjectName("orange_pushButton")
self.horizontalLayout_7.addWidget(self.orange_pushButton)
self.blue_pushButton = QtWidgets.QPushButton(self.color_groupBox)
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 85, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 170, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(63, 127, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 42, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 56, 170))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.BrightText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 85, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 170, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 85, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 170, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(63, 127, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 42, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 56, 170))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.BrightText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 85, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 170, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 42, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 85, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 170, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(63, 127, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 42, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 56, 170))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 42, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.BrightText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 42, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 85, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 85, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 85, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText, brush)
self.blue_pushButton.setPalette(palette)
self.blue_pushButton.setText("")
self.blue_pushButton.setObjectName("blue_pushButton")
self.horizontalLayout_7.addWidget(self.blue_pushButton)
self.green_pushButton = QtWidgets.QPushButton(self.color_groupBox)
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 170, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 212, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 85, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 113, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.BrightText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 170, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 212, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 170, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 212, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 85, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 113, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.BrightText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 170, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 212, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 85, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 170, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 212, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 85, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 113, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 85, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.BrightText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 85, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 170, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 170, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 170, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText, brush)
self.green_pushButton.setPalette(palette)
self.green_pushButton.setText("")
self.green_pushButton.setObjectName("green_pushButton")
self.horizontalLayout_7.addWidget(self.green_pushButton)
self.red_pushButton = QtWidgets.QPushButton(self.color_groupBox)
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 127, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 63, 63))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(170, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.BrightText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 127, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 127, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 63, 63))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(170, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.BrightText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 127, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 127, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 63, 63))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(170, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.BrightText, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText, brush)
self.red_pushButton.setPalette(palette)
self.red_pushButton.setText("")
self.red_pushButton.setObjectName("red_pushButton")
self.horizontalLayout_7.addWidget(self.red_pushButton)
self.pink_pushButton = QtWidgets.QPushButton(self.color_groupBox)
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 85, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 213, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 149, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 42, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(170, 56, 170))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.BrightText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 85, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 170, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 85, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 213, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 149, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 42, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(170, 56, 170))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.BrightText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 85, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 170, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 42, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 85, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 213, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 149, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 42, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(170, 56, 170))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 42, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.BrightText, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 42, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 85, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 85, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 85, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText, brush)
self.pink_pushButton.setPalette(palette)
self.pink_pushButton.setText("")
self.pink_pushButton.setObjectName("pink_pushButton")
self.horizontalLayout_7.addWidget(self.pink_pushButton)
self.lightblue_pushButton = QtWidgets.QPushButton(self.color_groupBox)
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(85, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(213, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(149, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(42, 127, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(56, 170, 170))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.BrightText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(85, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(170, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(85, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(213, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(149, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(42, 127, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(56, 170, 170))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.BrightText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(85, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(170, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(42, 127, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(85, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(213, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(149, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(42, 127, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(56, 170, 170))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(42, 127, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.BrightText, brush)
brush = QtGui.QBrush(QtGui.QColor(42, 127, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(85, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(85, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(85, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText, brush)
self.lightblue_pushButton.setPalette(palette)
self.lightblue_pushButton.setText("")
self.lightblue_pushButton.setObjectName("lightblue_pushButton")
self.horizontalLayout_7.addWidget(self.lightblue_pushButton)
self.yellow_pushButton = QtWidgets.QPushButton(self.color_groupBox)
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 63))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 127, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(170, 170, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.BrightText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 63))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 127, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(170, 170, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.BrightText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 127, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 63))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 127, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(170, 170, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 127, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.BrightText, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 127, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText, brush)
self.yellow_pushButton.setPalette(palette)
self.yellow_pushButton.setText("")
self.yellow_pushButton.setObjectName("yellow_pushButton")
self.horizontalLayout_7.addWidget(self.yellow_pushButton)
self.gridLayout.addWidget(self.color_groupBox, 4, 0, 1, 1)
self.groupBox_4 = QtWidgets.QGroupBox(Form)
self.groupBox_4.setObjectName("groupBox_4")
self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.groupBox_4)
self.verticalLayout_5.setSpacing(3)
self.verticalLayout_5.setContentsMargins(3, 3, 3, 3)
self.verticalLayout_5.setObjectName("verticalLayout_5")
self.verticalLayout_6 = QtWidgets.QVBoxLayout()
self.verticalLayout_6.setSpacing(3)
self.verticalLayout_6.setObjectName("verticalLayout_6")
self.horizontalLayout_5 = QtWidgets.QHBoxLayout()
self.horizontalLayout_5.setSpacing(3)
self.horizontalLayout_5.setObjectName("horizontalLayout_5")
self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
self.horizontalLayout_3.setSpacing(3)
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
self.lock_length_checkBox = QtWidgets.QCheckBox(self.groupBox_4)
self.lock_length_checkBox.setText("")
self.lock_length_checkBox.setObjectName("lock_length_checkBox")
self.horizontalLayout_3.addWidget(self.lock_length_checkBox)
self.lenght_label = QtWidgets.QLabel(self.groupBox_4)
self.lenght_label.setObjectName("lenght_label")
self.horizontalLayout_3.addWidget(self.lenght_label)
self.length_doubleSpinBox = QtWidgets.QDoubleSpinBox(self.groupBox_4)
self.length_doubleSpinBox.setFocusPolicy(QtCore.Qt.ClickFocus)
self.length_doubleSpinBox.setPrefix("")
self.length_doubleSpinBox.setMinimum(0.0)
self.length_doubleSpinBox.setMaximum(999.99)
self.length_doubleSpinBox.setProperty("value", 3.0)
self.length_doubleSpinBox.setObjectName("length_doubleSpinBox")
self.horizontalLayout_3.addWidget(self.length_doubleSpinBox)
self.horizontalLayout_5.addLayout(self.horizontalLayout_3)
self.horizontalLayout_27 = QtWidgets.QHBoxLayout()
self.horizontalLayout_27.setSpacing(3)
self.horizontalLayout_27.setObjectName("horizontalLayout_27")
self.sections_label = QtWidgets.QLabel(self.groupBox_4)
self.sections_label.setObjectName("sections_label")
self.horizontalLayout_27.addWidget(self.sections_label)
self.sections_spinBox = QtWidgets.QSpinBox(self.groupBox_4)
self.sections_spinBox.setFocusPolicy(QtCore.Qt.ClickFocus)
self.sections_spinBox.setMinimum(4)
self.sections_spinBox.setObjectName("sections_spinBox")
self.horizontalLayout_27.addWidget(self.sections_spinBox)
self.thickness_label = QtWidgets.QLabel(self.groupBox_4)
self.thickness_label.setObjectName("thickness_label")
self.horizontalLayout_27.addWidget(self.thickness_label)
self.thickness_spinBox = QtWidgets.QSpinBox(self.groupBox_4)
self.thickness_spinBox.setFocusPolicy(QtCore.Qt.ClickFocus)
self.thickness_spinBox.setMinimum(1)
self.thickness_spinBox.setProperty("value", 3)
self.thickness_spinBox.setObjectName("thickness_spinBox")
self.horizontalLayout_27.addWidget(self.thickness_spinBox)
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_27.addItem(spacerItem)
self.horizontalLayout_5.addLayout(self.horizontalLayout_27)
self.verticalLayout_6.addLayout(self.horizontalLayout_5)
self.verticalLayout_5.addLayout(self.verticalLayout_6)
self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
self.horizontalLayout_4.setSpacing(9)
self.horizontalLayout_4.setObjectName("horizontalLayout_4")
self.label_5 = QtWidgets.QLabel(self.groupBox_4)
self.label_5.setObjectName("label_5")
self.horizontalLayout_4.addWidget(self.label_5)
self.interpolated_max_spinBox = QtWidgets.QSpinBox(self.groupBox_4)
self.interpolated_max_spinBox.setFocusPolicy(QtCore.Qt.ClickFocus)
self.interpolated_max_spinBox.setMinimum(2)
self.interpolated_max_spinBox.setMaximum(10)
self.interpolated_max_spinBox.setObjectName("interpolated_max_spinBox")
self.horizontalLayout_4.addWidget(self.interpolated_max_spinBox)
self.interpolated_shape_checkBox = QtWidgets.QCheckBox(self.groupBox_4)
self.interpolated_shape_checkBox.setObjectName("interpolated_shape_checkBox")
self.horizontalLayout_4.addWidget(self.interpolated_shape_checkBox)
self.interpolated_scale_checkBox = QtWidgets.QCheckBox(self.groupBox_4)
self.interpolated_scale_checkBox.setObjectName("interpolated_scale_checkBox")
self.horizontalLayout_4.addWidget(self.interpolated_scale_checkBox)
self.interpolated_rotate_checkBox = QtWidgets.QCheckBox(self.groupBox_4)
self.interpolated_rotate_checkBox.setObjectName("interpolated_rotate_checkBox")
self.horizontalLayout_4.addWidget(self.interpolated_rotate_checkBox)
spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_4.addItem(spacerItem1)
self.verticalLayout_5.addLayout(self.horizontalLayout_4)
self.gridLayout.addWidget(self.groupBox_4, 1, 0, 1, 1)
spacerItem2 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.gridLayout.addItem(spacerItem2, 5, 0, 1, 1)
self.groupBox_5 = QtWidgets.QGroupBox(Form)
self.groupBox_5.setObjectName("groupBox_5")
self.verticalLayout_8 = QtWidgets.QVBoxLayout(self.groupBox_5)
self.verticalLayout_8.setSpacing(3)
self.verticalLayout_8.setContentsMargins(3, 3, 3, 3)
self.verticalLayout_8.setObjectName("verticalLayout_8")
self.horizontalLayout_26 = QtWidgets.QHBoxLayout()
self.horizontalLayout_26.setSpacing(3)
self.horizontalLayout_26.setObjectName("horizontalLayout_26")
self.vis_hair_pushButton = QtWidgets.QPushButton(self.groupBox_5)
self.vis_hair_pushButton.setObjectName("vis_hair_pushButton")
self.horizontalLayout_26.addWidget(self.vis_hair_pushButton)
self.vis_guides_pushButton = QtWidgets.QPushButton(self.groupBox_5)
self.vis_guides_pushButton.setObjectName("vis_guides_pushButton")
self.horizontalLayout_26.addWidget(self.vis_guides_pushButton)
self.vis_scalp_pushButton = QtWidgets.QPushButton(self.groupBox_5)
self.vis_scalp_pushButton.setObjectName("vis_scalp_pushButton")
self.horizontalLayout_26.addWidget(self.vis_scalp_pushButton)
self.verticalLayout_8.addLayout(self.horizontalLayout_26)
self.gridLayout.addWidget(self.groupBox_5, 3, 0, 1, 1)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(pyqt.fakeTranslate("Form", "Form", None, -1))
self.groupBox.setTitle(pyqt.fakeTranslate("Form", "Create", None, -1))
self.xgen_description_label.setText(pyqt.fakeTranslate("Form", "Description", None, -1))
self.xgen_description_pushButton.setText(pyqt.fakeTranslate("Form", "<<", None, -1))
self.add_curve_pushButton.setText(pyqt.fakeTranslate("Form", "Add Curve Guide", None, -1))
self.groupBox_2.setTitle(pyqt.fakeTranslate("Form", "Modify", None, -1))
self.duplicate_pushButton.setToolTip(pyqt.fakeTranslate("Form", "Duplicate Click Session.", None, -1))
self.duplicate_pushButton.setText(pyqt.fakeTranslate("Form", "Duplicate", None, -1))
self.duplicate_sym_pushButton.setToolTip(pyqt.fakeTranslate("Form", "Duplicate selection symmetrical", None, -1))
self.duplicate_sym_pushButton.setText(pyqt.fakeTranslate("Form", "Dup. Sym.", None, -1))
self.move_pushButton.setToolTip(pyqt.fakeTranslate("Form", "Mode guide click session", None, -1))
self.move_pushButton.setText(pyqt.fakeTranslate("Form", "Move", None, -1))
self.color_groupBox.setTitle(pyqt.fakeTranslate("Form", "Color", None, -1))
self.groupBox_4.setTitle(pyqt.fakeTranslate("Form", "Options", None, -1))
self.lock_length_checkBox.setToolTip(pyqt.fakeTranslate("Form", "Lock guides lenght", None, -1))
self.lenght_label.setText(pyqt.fakeTranslate("Form", "Length", None, -1))
self.sections_label.setText(pyqt.fakeTranslate("Form", "Points", None, -1))
self.thickness_label.setText(pyqt.fakeTranslate("Form", "Thickness", None, -1))
self.label_5.setText(pyqt.fakeTranslate("Form", "Interpolate", None, -1))
self.interpolated_shape_checkBox.setToolTip(pyqt.fakeTranslate("Form", "Interpolate Curve Guide Shape", None, -1))
self.interpolated_shape_checkBox.setText(pyqt.fakeTranslate("Form", "Shape", None, -1))
self.interpolated_scale_checkBox.setToolTip(pyqt.fakeTranslate("Form", "Interpolate Curve Guide Scale", None, -1))
self.interpolated_scale_checkBox.setText(pyqt.fakeTranslate("Form", "Scl", None, -1))
self.interpolated_rotate_checkBox.setToolTip(pyqt.fakeTranslate("Form", "Interpolate Curve Guide Rotation", None, -1))
self.interpolated_rotate_checkBox.setText(pyqt.fakeTranslate("Form", " Rot", None, -1))
self.groupBox_5.setTitle(pyqt.fakeTranslate("Form", "Visibility", None, -1))
self.vis_hair_pushButton.setToolTip(pyqt.fakeTranslate("Form", "Duplicate Click Session.", None, -1))
self.vis_hair_pushButton.setText(pyqt.fakeTranslate("Form", "Toggle Hair", None, -1))
self.vis_guides_pushButton.setToolTip(pyqt.fakeTranslate("Form", "Duplicate selection symmetrical", None, -1))
self.vis_guides_pushButton.setText(pyqt.fakeTranslate("Form", "Toggle Guides", None, -1))
self.vis_scalp_pushButton.setToolTip(pyqt.fakeTranslate("Form", "Mode guide click session", None, -1))
self.vis_scalp_pushButton.setText(pyqt.fakeTranslate("Form", "Toggle Scalp", None, -1))
|
StarcoderdataPython
|
4829230
|
# -*- coding: UTF-8 -*-
import clr
clr.AddReferenceByPartialName("PresentationCore")
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("WindowsBase")
from System import *
from System.Windows import *
from System.Windows.Controls import *
from System.Windows.Media.Imaging import *
class PicViewWindow(Window):
def __init__(self):
self.Title = "PicView"
self.Drop += self.on_drop
self.AllowDrop = True
self.Width = 300
self.Height = 300
self.image = Image()
self.Content = self.image
def on_drop(self, sender, e):
filename = e.Data.GetData(DataFormats.FileDrop)[0].ToString()
self.image.Source = BitmapImage(Uri(filename))
def main():
Application().Run(PicViewWindow())
if __name__ == "__main__":
main()
|
StarcoderdataPython
|
9636971
|
<reponame>isaiah/jy3k<gh_stars>1-10
def f(x):
class Foo():
@classmethod
def x(cls):
print(__class__)
print(cls)
@staticmethod
def y(x):
print(x)
print(__class__)
def bar(self):
print(x)
print(__class__)
return Foo
def xxxxxxxx():
f(1000)().bar()
f(1).y(1)
f(1).x()
|
StarcoderdataPython
|
9658886
|
#!/usr/bin/env python
#
# Copyright (c) 2011 <NAME>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
# Provides tools for management of users in a target Pedigree image. Can be used
# to create users for servers/daemons, or to create a user for the builder to
# use when logging in to Pedigree.
import os, sys, sqlite3, getpass
scriptdir = os.path.dirname(os.path.realpath(__file__))
imagedir = os.path.realpath(scriptdir + "/../images/local")
usersdir = os.path.join(imagedir, "users")
configdb = os.path.realpath(scriptdir + "/../build/config.db") # TODO: build dir is not always 'build'
# Try to connect to the database
try:
conn = sqlite3.connect(configdb)
except:
print "Configuration database is not available. Please run 'scons build/config.db'."
exit(2)
# Check for an existing users directory
if not os.path.exists(usersdir):
os.mkdir(usersdir)
def ignore():
pass
def getnextuid():
q = conn.execute("select uid from users order by uid desc limit 1")
u = q.fetchone()
return u[0] + 1
def safe_input():
try:
line = raw_input("> ")
except KeyboardInterrupt:
print # a newline
conn.close()
exit(1)
return line
def main_menu(funcmap):
print "Select an option below:"
print "1. Add a new user"
print "2. Change the password of an existing user"
print "3. Change attributes of an existing user"
print "4. Delete user"
print "5. Exit"
option = 0
while True:
line = safe_input()
try:
option = int(line)
except ValueError:
print "Please enter a number."
continue
if not option in funcmap.keys():
print "Please enter a valid option."
continue
break
funcmap[option]()
userattrs = [["fullname", "New User", False], ["groupname", "users", False], ["homedir", "/users/user", False], ["shell", "/applications/bash", False], ["password", "", True]]
def adduser():
print "Please type the username for the new user."
username = safe_input()
# Make sure the user does not exist.
q = conn.execute("select uid from users where username=?", [username])
user = q.fetchone()
if not user is None:
print "User '%s' already exists." % (username,)
return
uid = getnextuid()
newattrs = [uid, username]
# Get all attributes
for attr in userattrs:
if attr[2]:
while True:
# Secure.
a = getpass.getpass("%s: " % (attr[0],))
b = getpass.getpass("Confirm %s: " % (attr[0],))
if not a == b:
print "Passwords do not match."
else:
newattrs += [a]
break
else:
data = raw_input("%s [default=%s]: " % (attr[0], attr[1]))
if data == "":
data = attr[1]
newattrs += [data]
# Insert.
conn.execute("insert into users (uid, username, fullname, groupname, homedir, shell, password) values (?, ?, ?, ?, ?, ?, ?)", newattrs)
conn.commit()
# Home directory.
homedir = newattrs[4][1:]
os.mkdir(os.path.join(imagedir, homedir))
print "Created user '%s'" % (username,)
def validuser(username):
# Check for a valid user in the database.
q = conn.execute("select uid, password from users where username=?", [username])
user = q.fetchone()
if user is None:
print "The user '%s' does not exist." % (username,)
return False
return True
def changepassword():
print "Please type the username of the user for which you want to change password."
username = safe_input()
# Check for a valid user in the database.
if not validuser(username):
return
# Confirm the password
print "Changing password for '%s'..." % (username,)
curr = getpass.getpass("Current password: ")
if curr == user[1]:
new = getpass.getpass("New password: ")
# Commit to the DB
conn.execute("update users set password=? where uid=?", [new, user[0]])
conn.commit()
else:
print "Incorrect password."
print "Changed password for user '%s'" % (username,)
def changeattr():
print "Please type the username of the user for which you want to change attributes."
username = safe_input()
# Check for a valid user in the database.
if not validuser(username):
return
newattrs = []
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
old_factory = conn.row_factory
conn.row_factory = dict_factory
q = conn.execute("select uid, fullname, groupname, homedir, shell from users where username=?", [username])
user = q.fetchone()
# Get all attributes
n = 0
for attr in userattrs:
if not attr[2]:
data = raw_input("%s [current=%s]: " % (attr[0], user[attr[0]]))
if data == "":
data = user[attr[0]]
newattrs += [data]
n += 1
newattrs += [user["uid"]]
# Update.
conn.execute("update users set fullname=?, groupname=?, homedir=?, shell=? where uid=?", newattrs)
conn.commit()
# Create home directory in case it changed.
homedir = newattrs[2]
if True or (not homedir == user["homedir"]):
oldhome = os.path.join(imagedir, user["homedir"][1:])
newhome = os.path.join(imagedir, homedir[1:])
if not os.path.exists(oldhome):
os.mkdir(newhome)
else:
os.rename(oldhome, newhome)
conn.row_factory = old_factory
def deleteuser():
print "Please type the username for the user to delete."
username = safe_input()
# Check for a valid user in the database.
if not validuser(username):
return
# Delete the user.
conn.execute("delete from users where uid=?", [user[0]])
conn.commit()
print "Deleted user '%s'" % (username,)
options = {1 : adduser, 2 : changepassword, 3 : changeattr, 4 : deleteuser, 5 : ignore}
main_menu(options)
conn.close()
|
StarcoderdataPython
|
5005177
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2016-12-05 09:16
from __future__ import unicode_literals
import django.contrib.postgres.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('presentation', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='course',
name='average',
field=models.FloatField(null=True),
),
migrations.AddField(
model_name='student',
name='grades',
field=django.contrib.postgres.fields.ArrayField(base_field=models.FloatField(), null=True, size=None),
),
migrations.AddField(
model_name='student',
name='risk',
field=models.FloatField(null=True),
),
]
|
StarcoderdataPython
|
1873544
|
<filename>cvrf/forms.py
from django import forms
class AcknowledgmentType_form(forms.Form):
Name = forms.MultipleChoiceField(NameType_model.objects.all())
Organization = forms.MultipleChoiceField(OrganizationType_model.objects.all())
Description = forms.MultipleChoiceField(DescriptionType2_model.objects.all())
URL = forms.CharField(max_length=1000, blank=True)
class AcknowledgmentType11_form(forms.Form):
Name = forms.MultipleChoiceField(NameType12_model.objects.all())
Organization = forms.MultipleChoiceField(OrganizationType13_model.objects.all())
Description = forms.MultipleChoiceField(DescriptionType14_model.objects.all())
URL = forms.CharField(max_length=1000, blank=True)
class AcknowledgmentsType_form(forms.Form):
Acknowledgment = forms.MultipleChoiceField(AcknowledgmentType_model.objects.all())
class AcknowledgmentsType10_form(forms.Form):
Acknowledgment = forms.MultipleChoiceField(AcknowledgmentType11_model.objects.all())
class AggregateSeverityType_form(forms.Form):
Namespace = forms.CharField(max_length=1000, blank=True)
valueOf_x = forms.MultipleChoiceField(localizedString_model.objects.all())
class AliasType_form(forms.Form):
valueOf_x = forms.MultipleChoiceField(localizedString_model.objects.all())
class BranchType_form(forms.Form):
Type = forms.CharField(max_length=1000, blank=True)
Name = forms.CharField(max_length=1000, blank=True)
FullProductName = forms.MultipleChoiceField(FullProductName_model.objects.all())
Branch = forms.MultipleChoiceField(BranchType_model.objects.all())
class CVSSScoreSetsType_form(forms.Form):
ScoreSet = forms.MultipleChoiceField(ScoreSetType_model.objects.all())
class CWEType_form(forms.Form):
ID = forms.CharField(max_length=1000, blank=True)
valueOf_x = forms.MultipleChoiceField(localizedString_model.objects.all())
class ContactDetailsType_form(forms.Form):
valueOf_x = forms.MultipleChoiceField(localizedString_model.objects.all())
class DescriptionType_form(forms.Form):
valueOf_x = forms.MultipleChoiceField(localizedString_model.objects.all())
class DescriptionType1_form(forms.Form):
valueOf_x = forms.MultipleChoiceField(localizedString_model.objects.all())
class DescriptionType14_form(forms.Form):
valueOf_x = forms.MultipleChoiceField(localizedString_model.objects.all())
class DescriptionType15_form(forms.Form):
valueOf_x = forms.MultipleChoiceField(localizedString_model.objects.all())
class DescriptionType2_form(forms.Form):
valueOf_x = forms.MultipleChoiceField(localizedString_model.objects.all())
class DescriptionType5_form(forms.Form):
valueOf_x = forms.MultipleChoiceField(localizedString_model.objects.all())
class DescriptionType6_form(forms.Form):
valueOf_x = forms.MultipleChoiceField(localizedString_model.objects.all())
class DescriptionType7_form(forms.Form):
valueOf_x = forms.MultipleChoiceField(localizedString_model.objects.all())
class DescriptionType9_form(forms.Form):
valueOf_x = forms.MultipleChoiceField(localizedString_model.objects.all())
class DocumentDistributionType_form(forms.Form):
valueOf_x = forms.MultipleChoiceField(localizedString_model.objects.all())
class DocumentNotesType_form(forms.Form):
Note = forms.MultipleChoiceField(NoteType_model.objects.all())
class DocumentPublisherType_form(forms.Form):
VendorID = forms.CharField(max_length=1000, blank=True)
Type = forms.CharField(max_length=1000, blank=True)
ContactDetails = forms.MultipleChoiceField(ContactDetailsType_model.objects.all())
IssuingAuthority = forms.MultipleChoiceField(IssuingAuthorityType_model.objects.all())
class DocumentReferencesType_form(forms.Form):
Reference = forms.MultipleChoiceField(ReferenceType_model.objects.all())
class DocumentTitleType_form(forms.Form):
valueOf_x = forms.MultipleChoiceField(localizedNormalizedString_model.objects.all())
class DocumentTrackingType_form(forms.Form):
Identification = forms.MultipleChoiceField(IdentificationType_model.objects.all())
Status = forms.CharField(max_length=1000, blank=True)
Version = forms.CharField(max_length=1000, blank=True)
RevisionHistory = forms.MultipleChoiceField(RevisionHistoryType_model.objects.all())
InitialReleaseDate = forms.DateTimeField(blank=True)
CurrentReleaseDate = forms.DateTimeField(blank=True)
Generator = forms.MultipleChoiceField(GeneratorType_model.objects.all())
class DocumentTypeType_form(forms.Form):
valueOf_x = forms.MultipleChoiceField(localizedNormalizedString_model.objects.all())
class EngineType_form(forms.Form):
valueOf_x = forms.MultipleChoiceField(localizedString_model.objects.all())
class EntitlementType_form(forms.Form):
valueOf_x = forms.MultipleChoiceField(localizedString_model.objects.all())
class FactRefType_form(forms.Form):
name = forms.CharField(max_length=1000, blank=True)
class FullProductName_form(forms.Form):
CPE = forms.CharField(max_length=1000, blank=True)
ProductID = forms.CharField(max_length=1000, blank=True)
valueOf_x = forms.CharField(max_length=1000, blank=True)
class GeneratorType_form(forms.Form):
Engine = forms.MultipleChoiceField(EngineType_model.objects.all())
Date = forms.DateTimeField(blank=True)
class GroupType_form(forms.Form):
GroupID = forms.CharField(max_length=1000, blank=True)
Description = forms.MultipleChoiceField(DescriptionType15_model.objects.all())
ProductID = forms.CharField(max_length=1000, blank=True)
class IDType_form(forms.Form):
valueOf_x = forms.MultipleChoiceField(localizedString_model.objects.all())
class IDType3_form(forms.Form):
SystemName = forms.CharField(max_length=1000, blank=True)
valueOf_x = forms.CharField(max_length=1000, blank=True)
class IdentificationType_form(forms.Form):
ID = forms.MultipleChoiceField(IDType_model.objects.all())
Alias = forms.MultipleChoiceField(AliasType_model.objects.all())
class InvolvementType_form(forms.Form):
Status = forms.CharField(max_length=1000, blank=True)
Party = forms.CharField(max_length=1000, blank=True)
Description = forms.MultipleChoiceField(DescriptionType5_model.objects.all())
class InvolvementsType_form(forms.Form):
Involvement = forms.MultipleChoiceField(InvolvementType_model.objects.all())
class IssuingAuthorityType_form(forms.Form):
valueOf_x = forms.MultipleChoiceField(localizedString_model.objects.all())
class LogicalTestType_form(forms.Form):
operator = forms.CharField(max_length=1000, blank=True)
negate = forms.BooleanField(blank=True)
logical_test = forms.MultipleChoiceField(LogicalTestType_model.objects.all())
fact_ref = forms.MultipleChoiceField(fact_ref_model.objects.all())
class NameType_form(forms.Form):
valueOf_x = forms.MultipleChoiceField(localizedString_model.objects.all())
class NameType12_form(forms.Form):
valueOf_x = forms.MultipleChoiceField(localizedString_model.objects.all())
class NoteType_form(forms.Form):
Ordinal = forms.IntegerField(blank=True)
Audience = forms.CharField(max_length=1000, blank=True)
Type = forms.CharField(max_length=1000, blank=True)
Title = forms.CharField(max_length=1000, blank=True)
valueOf_x = forms.MultipleChoiceField(localizedString_model.objects.all())
class NoteType4_form(forms.Form):
Ordinal = forms.IntegerField(blank=True)
Audience = forms.CharField(max_length=1000, blank=True)
Type = forms.CharField(max_length=1000, blank=True)
Title = forms.CharField(max_length=1000, blank=True)
valueOf_x = forms.MultipleChoiceField(localizedString_model.objects.all())
class NotesType_form(forms.Form):
Note = forms.MultipleChoiceField(NoteType4_model.objects.all())
class OrganizationType_form(forms.Form):
valueOf_x = forms.MultipleChoiceField(localizedString_model.objects.all())
class OrganizationType13_form(forms.Form):
valueOf_x = forms.MultipleChoiceField(localizedString_model.objects.all())
class PlatformBaseType_form(forms.Form):
title = forms.MultipleChoiceField(title_model.objects.all())
remark = forms.MultipleChoiceField(TextType_model.objects.all())
logical_test = forms.MultipleChoiceField(logical_test_model.objects.all())
class PlatformType_form(forms.Form):
idx = forms.CharField(max_length=1000, blank=True)
class ProductGroupsType_form(forms.Form):
Group = forms.MultipleChoiceField(GroupType_model.objects.all())
class ProductStatusesType_form(forms.Form):
Status = forms.MultipleChoiceField(StatusType_model.objects.all())
class ProductTree_form(forms.Form):
Branch = forms.MultipleChoiceField(BranchType_model.objects.all())
FullProductName = forms.MultipleChoiceField(FullProductName_model.objects.all())
Relationship = forms.MultipleChoiceField(RelationshipType_model.objects.all())
ProductGroups = forms.MultipleChoiceField(ProductGroupsType_model.objects.all())
class ReferenceType_form(forms.Form):
Type = forms.CharField(max_length=1000, blank=True)
URL = forms.CharField(max_length=1000, blank=True)
Description = forms.MultipleChoiceField(DescriptionType1_model.objects.all())
class ReferenceType8_form(forms.Form):
Type = forms.CharField(max_length=1000, blank=True)
URL = forms.CharField(max_length=1000, blank=True)
Description = forms.MultipleChoiceField(DescriptionType9_model.objects.all())
class ReferencesType_form(forms.Form):
Reference = forms.MultipleChoiceField(ReferenceType8_model.objects.all())
class RelationshipType_form(forms.Form):
RelationType = forms.CharField(max_length=1000, blank=True)
RelatesToProductReference = forms.CharField(max_length=1000, blank=True)
ProductReference = forms.CharField(max_length=1000, blank=True)
FullProductName = forms.MultipleChoiceField(FullProductName_model.objects.all())
class RemediationType_form(forms.Form):
Date = forms.DateTimeField(blank=True)
Type = forms.CharField(max_length=1000, blank=True)
Description = forms.MultipleChoiceField(DescriptionType7_model.objects.all())
Entitlement = forms.MultipleChoiceField(EntitlementType_model.objects.all())
URL = forms.CharField(max_length=1000, blank=True)
ProductID = forms.CharField(max_length=1000, blank=True)
GroupID = forms.CharField(max_length=1000, blank=True)
class RemediationsType_form(forms.Form):
Remediation = forms.MultipleChoiceField(RemediationType_model.objects.all())
class RevisionHistoryType_form(forms.Form):
Revision = forms.MultipleChoiceField(RevisionType_model.objects.all())
class RevisionType_form(forms.Form):
Number = forms.CharField(max_length=1000, blank=True)
Date = forms.DateTimeField(blank=True)
Description = forms.MultipleChoiceField(DescriptionType_model.objects.all())
class ScoreSetType_form(forms.Form):
BaseScore = forms.FloatField(blank=True)
TemporalScore = forms.FloatField(blank=True)
EnvironmentalScore = forms.FloatField(blank=True)
Vector = forms.CharField(max_length=1000, blank=True)
ProductID = forms.CharField(max_length=1000, blank=True)
class SimpleLiteral_form(forms.Form):
lang = forms.CharField(max_length=1000, blank=True)
= forms.CharField(max_length=1000, blank=True)
class StatusType_form(forms.Form):
Type = forms.CharField(max_length=1000, blank=True)
ProductID = forms.CharField(max_length=1000, blank=True)
class TextType_form(forms.Form):
lang = forms.CharField(max_length=1000, blank=True)
valueOf_x = forms.CharField(max_length=1000, blank=True)
class ThreatType_form(forms.Form):
Date = forms.DateTimeField(blank=True)
Type = forms.CharField(max_length=1000, blank=True)
Description = forms.MultipleChoiceField(DescriptionType6_model.objects.all())
ProductID = forms.CharField(max_length=1000, blank=True)
GroupID = forms.CharField(max_length=1000, blank=True)
class ThreatsType_form(forms.Form):
Threat = forms.MultipleChoiceField(ThreatType_model.objects.all())
class TitleType_form(forms.Form):
valueOf_x = forms.MultipleChoiceField(localizedString_model.objects.all())
class Vulnerability_form(forms.Form):
Ordinal = forms.IntegerField(blank=True)
Title = forms.MultipleChoiceField(TitleType_model.objects.all())
ID = forms.MultipleChoiceField(IDType3_model.objects.all())
Notes = forms.MultipleChoiceField(NotesType_model.objects.all())
DiscoveryDate = forms.DateTimeField(blank=True)
ReleaseDate = forms.DateTimeField(blank=True)
Involvements = forms.MultipleChoiceField(InvolvementsType_model.objects.all())
CVE = forms.CharField(max_length=1000, blank=True)
CWE = forms.MultipleChoiceField(CWEType_model.objects.all())
ProductStatuses = forms.MultipleChoiceField(ProductStatusesType_model.objects.all())
Threats = forms.MultipleChoiceField(ThreatsType_model.objects.all())
CVSSScoreSets = forms.MultipleChoiceField(CVSSScoreSetsType_model.objects.all())
Remediations = forms.MultipleChoiceField(RemediationsType_model.objects.all())
References = forms.MultipleChoiceField(ReferencesType_model.objects.all())
Acknowledgments = forms.MultipleChoiceField(AcknowledgmentsType10_model.objects.all())
class accessComplexityType_form(forms.Form):
approximated = forms.BooleanField(blank=True)
valueOf_x = forms.CharField(max_length=1000, blank=True)
class accessVectorType_form(forms.Form):
approximated = forms.BooleanField(blank=True)
valueOf_x = forms.CharField(max_length=1000, blank=True)
class assessmentMethodType_form(forms.Form):
assessment_check = forms.MultipleChoiceField(checkReferenceType_model.objects.all())
assessment_engine = forms.CharField(max_length=1000, blank=True)
class authenticationType_form(forms.Form):
approximated = forms.BooleanField(blank=True)
valueOf_x = forms.CharField(max_length=1000, blank=True)
class baseMetricsType_form(forms.Form):
score = forms.FloatField(blank=True)
exploit_subscore = forms.FloatField(blank=True)
impact_subscore = forms.FloatField(blank=True)
access_vector = forms.MultipleChoiceField(accessVectorType_model.objects.all())
access_complexity = forms.MultipleChoiceField(accessComplexityType_model.objects.all())
authentication = forms.MultipleChoiceField(authenticationType_model.objects.all())
confidentiality_impact = forms.MultipleChoiceField(ciaType_model.objects.all())
integrity_impact = forms.MultipleChoiceField(ciaType_model.objects.all())
availability_impact = forms.MultipleChoiceField(ciaType_model.objects.all())
source = forms.MultipleChoiceField(source_model.objects.all())
generated_on_datetime = forms.CharField(max_length=1000, blank=True)
class checkReferenceType_form(forms.Form):
href = forms.CharField(max_length=1000, blank=True)
class checkSearchType_form(forms.Form):
system = forms.CharField(max_length=1000, blank=True)
name = forms.CharField(max_length=1000, blank=True)
class ciaRequirementType_form(forms.Form):
approximated = forms.BooleanField(blank=True)
valueOf_x = forms.CharField(max_length=1000, blank=True)
class ciaType_form(forms.Form):
approximated = forms.BooleanField(blank=True)
valueOf_x = forms.CharField(max_length=1000, blank=True)
class collateralDamagePotentialType_form(forms.Form):
approximated = forms.BooleanField(blank=True)
valueOf_x = forms.CharField(max_length=1000, blank=True)
class confidenceType_form(forms.Form):
approximated = forms.BooleanField(blank=True)
valueOf_x = forms.CharField(max_length=1000, blank=True)
class contributor_form(forms.Form):
class controlMappingType_form(forms.Form):
source = forms.CharField(max_length=1000, blank=True)
system_id = forms.CharField(max_length=1000, blank=True)
last_modified = forms.DateTimeField(blank=True)
mapping = forms.MultipleChoiceField(mappingInstanceType_model.objects.all())
class controlMappingsType_form(forms.Form):
control_mapping = forms.MultipleChoiceField(controlMappingType_model.objects.all())
class coverage_form(forms.Form):
class creator_form(forms.Form):
class cvrfdoc_form(forms.Form):
DocumentTitle = forms.MultipleChoiceField(DocumentTitleType_model.objects.all())
DocumentType = forms.MultipleChoiceField(DocumentTypeType_model.objects.all())
DocumentPublisher = forms.MultipleChoiceField(DocumentPublisherType_model.objects.all())
DocumentTracking = forms.MultipleChoiceField(DocumentTrackingType_model.objects.all())
DocumentNotes = forms.MultipleChoiceField(DocumentNotesType_model.objects.all())
DocumentDistribution = forms.MultipleChoiceField(DocumentDistributionType_model.objects.all())
AggregateSeverity = forms.MultipleChoiceField(AggregateSeverityType_model.objects.all())
DocumentReferences = forms.MultipleChoiceField(DocumentReferencesType_model.objects.all())
Acknowledgments = forms.MultipleChoiceField(AcknowledgmentsType_model.objects.all())
ProductTree = forms.MultipleChoiceField(ProductTree_model.objects.all())
Vulnerability = forms.MultipleChoiceField(Vulnerability_model.objects.all())
class cvssImpactBaseType_form(forms.Form):
base_metrics = forms.MultipleChoiceField(baseMetricsType_model.objects.all())
class cvssImpactEnvironmentalType_form(forms.Form):
environmental_metrics = forms.MultipleChoiceField(environmentalMetricsType_model.objects.all())
class cvssImpactTemporalType_form(forms.Form):
temporal_metrics = forms.MultipleChoiceField(temporalMetricsType_model.objects.all())
class cvssImpactType_form(forms.Form):
base_metrics = forms.MultipleChoiceField(baseMetricsType_model.objects.all())
environmental_metrics = forms.MultipleChoiceField(environmentalMetricsType_model.objects.all())
temporal_metrics = forms.MultipleChoiceField(temporalMetricsType_model.objects.all())
class cvssType_form(forms.Form):
base_metrics = forms.MultipleChoiceField(baseMetricsType_model.objects.all())
environmental_metrics = forms.MultipleChoiceField(environmentalMetricsType_model.objects.all())
temporal_metrics = forms.MultipleChoiceField(temporalMetricsType_model.objects.all())
class date_form(forms.Form):
class description_form(forms.Form):
class elementContainer_form(forms.Form):
any = forms.MultipleChoiceField(SimpleLiteral_model.objects.all())
class environmentalMetricsType_form(forms.Form):
score = forms.FloatField(blank=True)
collateral_damage_potential = forms.MultipleChoiceField(collateralDamagePotentialType_model.objects.all())
target_distribution = forms.MultipleChoiceField(targetDistributionType_model.objects.all())
confidentiality_requirement = forms.MultipleChoiceField(ciaRequirementType_model.objects.all())
integrity_requirement = forms.MultipleChoiceField(ciaRequirementType_model.objects.all())
availability_requirement = forms.MultipleChoiceField(ciaRequirementType_model.objects.all())
source = forms.MultipleChoiceField(source_model.objects.all())
generated_on_datetime = forms.CharField(max_length=1000, blank=True)
class exploitabilityType_form(forms.Form):
approximated = forms.BooleanField(blank=True)
valueOf_x = forms.CharField(max_length=1000, blank=True)
class format_form(forms.Form):
class identifier_form(forms.Form):
class identifyableAssessmentMethodType_form(forms.Form):
idx = forms.IntegerField(blank=True)
class language_form(forms.Form):
class localizedNormalizedString_form(forms.Form):
lang = forms.CharField(max_length=1000, blank=True)
valueOf_x = forms.CharField(max_length=1000, blank=True)
class localizedString_form(forms.Form):
lang = forms.CharField(max_length=1000, blank=True)
valueOf_x = forms.CharField(max_length=1000, blank=True)
class mappingInstanceType_form(forms.Form):
published = forms.DateTimeField(blank=True)
valueOf_x = forms.CharField(max_length=1000, blank=True)
class metricsType_form(forms.Form):
upgraded_from_version = forms.FloatField(blank=True)
class platformSpecificationType_form(forms.Form):
platform = forms.MultipleChoiceField(PlatformType_model.objects.all())
class publisher_form(forms.Form):
class relation_form(forms.Form):
class remediationLevelType_form(forms.Form):
approximated = forms.BooleanField(blank=True)
valueOf_x = forms.CharField(max_length=1000, blank=True)
class rights_form(forms.Form):
class searchableCpeReferencesType_form(forms.Form):
cpe_name = forms.CharField(max_length=1000, blank=True)
cpe_searchable_name = forms.CharField(max_length=1000, blank=True)
class source_form(forms.Form):
class subject_form(forms.Form):
class targetDistributionType_form(forms.Form):
approximated = forms.BooleanField(blank=True)
valueOf_x = forms.CharField(max_length=1000, blank=True)
class temporalMetricsType_form(forms.Form):
score = forms.FloatField(blank=True)
temporal_multiplier = forms.CharField(max_length=1000, blank=True)
exploitability = forms.MultipleChoiceField(exploitabilityType_model.objects.all())
remediation_level = forms.MultipleChoiceField(remediationLevelType_model.objects.all())
report_confidence = forms.MultipleChoiceField(confidenceType_model.objects.all())
source = forms.MultipleChoiceField(source_model.objects.all())
generated_on_datetime = forms.CharField(max_length=1000, blank=True)
class title_form(forms.Form):
class type__form(forms.Form):
|
StarcoderdataPython
|
3378501
|
<reponame>xiuhanq/pt-qiandao
from loguru import logger
import yaml
import os
import requests
class Notify(object):
# def __init__(self):
def get_notify_url(self):
# 获取当前脚本所在文件夹路径
current_path = os.path.abspath(".")
# 获取yaml配置文件路径
yamlPath = os.path.join(current_path, "config.yaml")
# open方法打开直接读出来
file = open(yamlPath, 'r', encoding='utf-8')
# 读出来是字符串
cfgStr = file.read()
# 用load方法转字典
cfg = yaml.load(cfgStr, Loader=yaml.FullLoader)
qiandaoCfg = cfg.get('qiandao')
# logger.info('签到配置文件:{}',str(qiandaoCfg))
file.close()
return qiandaoCfg.get('qiyeweixin')
def notify(self,notify_list=[],since=0,time_elapsed=0):
content = '# PT站点自动签到结果 \n'
for result in notify_list:
content = content + '> #### '+ str(result.siteName) +' \n'
content = content + '> 登录:'
if result.loginResult == True:
content = content + '<font color="info">成功</font>'
else:
content = content + '<font color="red">失败</font>'
content = content+'\n'
content = content + ' 签到:'
if result.attendanceResult == True:
content = content + '<font color="info">成功</font>'
content = content + '【'
content = content + result.attendanceResultTxt
content = content + '】'
else:
content = content + '<font color="red">失败</font>'
content = content+'\n'
content = content+'> ### 总用时【 {:.0f}m {:.0f}s】 \n'.format(time_elapsed // 60, time_elapsed % 60)
data={
"msgtype": "markdown",
"markdown": {
"content": content
}
}
requests.post(url=self.get_notify_url(),json=data)
|
StarcoderdataPython
|
371478
|
<filename>rllib/util/input_transformations.py<gh_stars>0
"""Input transformations for spot."""
from abc import ABC, abstractmethod
class AbstractTransform(ABC):
"""Abstract Transformation definition."""
extra_dim: int
@abstractmethod
def __call__(self, state):
"""Apply transformation."""
raise NotImplementedError
class ComposeTransforms(AbstractTransform):
"""Compose a list of transformations."""
def __init__(self, transforms):
super().__init__()
self.extra_dim = 0
for transform in transforms:
self.extra_dim += transform.extra_dim
self.transforms = transforms
def __call__(self, x):
"""Apply sequence of transformations."""
for transform in self.transforms:
x = transform(x)
return x
|
StarcoderdataPython
|
9635186
|
<reponame>esehara/skiski<filename>skiski/ski.py<gh_stars>0
from skiski.base import V
from skiski.helper import Typename
class VirtualCurry:
def __b__(self, x):
return self.dot(x)
class I(metaclass=Typename("I")):
"""
the identity operator
(lambda x: x)(5) => 5
>>> I(5).w()
5
"""
def __init__(self, x):
self.x = x
def w(self):
return self.x
@classmethod
def __w__(cls, x):
if isinstance(cls, type):
return cls(x)
else:
return cls.dot(x)
def dot(self, x):
y = self.w()
return y.__w__(x)
def __str__(self):
return "(I " + str(self.x) + ") "
def __repr__(self):
return self.__str__()
@classmethod
def to_ski(cls):
"""
Only S and K combinator make I combinator.
>>> skk = S(K).dot(K).dot(1)
>>> skk.w()
(K 1 (K 1) )
>>> skk.w().w()
1
It's behavior means 'I combinator'.
"""
return S(K).dot(K)
class K(metaclass=Typename("K")):
"""
which forms constant functions
(lambda x, y)(True, False) => True
>>> K(True).dot(False).w()
True
"""
def __init__(self, x):
self.x = x
def dot(self, y):
return _K2(self.x, y)
def __str__(self):
return "(K " + str(self.x) + ") "
def __repr__(self):
return self.__str__()
class _K2(metaclass=Typename("K")):
def __init__(self, x, y):
self.x = x
self.y = y
def w(self):
return self.x
def dot(self, z):
x = self.b()
if isinstance(x, type):
return x(z)
else:
return x.dot(z)
def __repr__(self):
return self.__str__()
def __str__(self):
return "(K " + str(self.x) + " " + str(self.y) + ") "
class S(metaclass=Typename("S")):
"""
a stronger composition operator
(lambda x, y, z)(f, g, h) => f(h, g(h))
>>> S(K).dot(K).dot(5).w().w()
5
SII(SII) combinator is infinity loop ;)
>>> siisii = S(I).dot(I).dot(S(I).dot(I))
>>> siisii.w().w().w().w()
(S I I (I (S I I) ) )
"""
def __init__(self, x):
self.x = x
def dot(self, y):
return S2(self.x, y)
def w(self):
return self
def __str__(self):
return "(S " + str(self.x) + ") "
def __repr__(self):
return self.__str__()
class S2(VirtualCurry, metaclass=Typename("S")):
def __init__(self, x, y):
self.x = x
self.y = y
def dot(self, z):
return S3(self.x, self.y, z)
def __str__(self):
return "(S " + str(self.x) + " " + str(self.y) + ") "
def w(self):
return self
def __repr__(self):
return self.__str__()
class S3(metaclass=Typename("S")):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def w(self):
yz = self._wrap_w_(self.y, self.z)
xz = self._wrap_w_(self.x, self.z)
if self.is_dot(xz):
return xz.dot(yz)
else:
return xz(yz)
def __str__(self):
return "(S " + str(self.x) + " " + str(self.y) + " " + str(self.z) + ") "
def __repr__(self):
return self.__str__()
@classmethod
def is_dot(cls, x):
return (not isinstance(x, type)) and hasattr(x, "dot")
@classmethod
def _wrap_w_(cls, x, y):
xy = cls.__w__(x, y)
if hasattr(xy, "w"):
xy = xy.w()
return xy
@classmethod
def _eval_i_(cls, x):
while isinstance(x, I):
x = x.w()
return x
@classmethod
def __w__(cls, x, y):
x = cls._eval_i_(x)
y = cls._eval_i_(y)
if cls.is_dot(x):
return x.dot(y)
else:
return x(y)
if __name__ == "__main__":
import doctest
doctest.testmod()
|
StarcoderdataPython
|
5170329
|
#@+leo-ver=5-thin
#@+node:edream.110203113231.741: * @file ../plugins/add_directives.py
"""Allows users to define new @direcives."""
from leo.core import leoGlobals as g
directives = ("markup",) # A tuple with one string.
#@+others
#@+node:ekr.20070725103420: ** init
def init():
"""Return True if the plugin has loaded successfully."""
g.registerHandler("start1", addPluginDirectives)
return True
#@+node:edream.110203113231.742: ** addPluginDirectives
def addPluginDirectives(tag, keywords):
"""Add all new directives to g.globalDirectiveList"""
global directives
for s in directives:
if s.startswith('@'):
s = s[1:]
if s not in g.globalDirectiveList:
g.globalDirectiveList.append(s)
#@-others
#@@language python
#@@tabwidth -4
#@-leo
|
StarcoderdataPython
|
1836759
|
<gh_stars>1-10
#!/usr/bin/env python
"""Day 15 of advent of code"""
def generate_next_number(previous, factor, multiple):
"""Generates next number in sequence"""
while True:
value = (previous * factor) % 2147483647
if value % multiple == 0:
return value
previous = value
def count_collisions(data, rounds, multiples):
"""Count number of collisions"""
factors = [16807, 48271]
start = map(int, data.split(","))
previous = start[:]
matches = 0
for _ in range(rounds):
gen_a = generate_next_number(previous[0], factors[0], multiples[0])
gen_b = generate_next_number(previous[1], factors[1], multiples[1])
previous = gen_a, gen_b
if (gen_a & 65535) == (gen_b & 65535):
matches += 1
return matches
def part_one(data):
"""Part one"""
return count_collisions(data, 40000000, [1, 1])
def part_two(data):
"""Part two"""
return count_collisions(data, 5000000, [4, 8])
if __name__ == '__main__':
with open('day15.input', 'r') as f:
INPUT_DATA = f.read()
print part_one(INPUT_DATA)
print part_two(INPUT_DATA)
|
StarcoderdataPython
|
1879403
|
#!/usr/bin/env python3
# coding=utf-8
import signal
from converter_lib import Converter
class SignalConverter(Converter):
NAME = "signal"
NUMBER_RANGE = range(1, 65)
@staticmethod
def number2code(number):
return signal.Signals(int(number)).name
@staticmethod
def code2number(code):
return getattr(signal, code).value
@staticmethod
def get_candidates():
return dir(signal)
@staticmethod
def number2description(number):
return signal.strsignal(signal.Signals(int(number))) # Python3.8
SignalConverter.parse()
|
StarcoderdataPython
|
1814453
|
from typing import Union, List, Dict
from toolz import get_in
from roadmaps.models import RoadmapNode
from roadmaps.services.progress import ProgressCalculator
from roadmaps.types import TreeNode
class TreeWithProgressTransformer:
@classmethod
def transform(cls, node: Dict[str, Union[str, List[TreeNode]]]):
name = get_in(['data', 'name'], node)
return TreeNode(
name=name,
progress=ProgressCalculator.calculate(RoadmapNode.objects.get(name=name)),
children=[cls.transform(ch) for ch in node.get('children', [])])
|
StarcoderdataPython
|
356418
|
# -*- coding: utf-8 -*-
'''
Execution module for `ciscoconfparse <http://www.pennington.net/py/ciscoconfparse/index.html>`_
.. versionadded:: 2019.2.0
This module can be used for basic configuration parsing, audit or validation
for a variety of network platforms having Cisco IOS style configuration (one
space indentation), including: Cisco IOS, Cisco Nexus, Cisco IOS-XR,
Cisco IOS-XR, Cisco ASA, Arista EOS, Brocade, HP Switches, Dell PowerConnect
Switches, or Extreme Networks devices. In newer versions, ``ciscoconfparse``
provides support for brace-delimited configuration style as well, for platforms
such as: Juniper Junos, Palo Alto, or F5 Networks.
See http://www.pennington.net/py/ciscoconfparse/index.html for further details.
:depends: ciscoconfparse
This module depends on the Python library with the same name,
``ciscoconfparse`` - to install execute: ``pip install ciscoconfparse``.
'''
# Import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
# Import Salt modules
from salt.ext import six
from salt.exceptions import SaltException
try:
import ciscoconfparse
HAS_CISCOCONFPARSE = True
except ImportError:
HAS_CISCOCONFPARSE = False
# ------------------------------------------------------------------------------
# module properties
# ------------------------------------------------------------------------------
__virtualname__ = 'ciscoconfparse'
# ------------------------------------------------------------------------------
# property functions
# ------------------------------------------------------------------------------
def __virtual__():
return HAS_CISCOCONFPARSE
# ------------------------------------------------------------------------------
# helper functions -- will not be exported
# ------------------------------------------------------------------------------
def _get_ccp(config=None, config_path=None, saltenv='base'):
'''
'''
if config_path:
config = __salt__['cp.get_file_str'](config_path, saltenv=saltenv)
if config is False:
raise SaltException('{} is not available'.format(config_path))
if isinstance(config, six.string_types):
config = config.splitlines()
ccp = ciscoconfparse.CiscoConfParse(config)
return ccp
# ------------------------------------------------------------------------------
# callable functions
# ------------------------------------------------------------------------------
def find_objects(config=None, config_path=None, regex=None, saltenv='base'):
'''
Return all the line objects that match the expression in the ``regex``
argument.
.. warning::
This function is mostly valuable when invoked from other Salt
components (i.e., execution modules, states, templates etc.). For CLI
usage, please consider using
:py:func:`ciscoconfparse.find_lines <salt.ciscoconfparse_mod.find_lines>`
config
The configuration sent as text.
.. note::
This argument is ignored when ``config_path`` is specified.
config_path
The absolute or remote path to the file with the configuration to be
parsed. This argument supports the usual Salt filesystem URIs, e.g.,
``salt://``, ``https://``, ``ftp://``, ``s3://``, etc.
regex
The regular expression to match the lines against.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file. This
argument is ignored when ``config_path`` is not a ``salt://`` URL.
Usage example:
.. code-block:: python
objects = __salt__['ciscoconfparse.find_objects'](config_path='salt://path/to/config.txt',
regex='Gigabit')
for obj in objects:
print(obj.text)
'''
ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv)
lines = ccp.find_objects(regex)
return lines
def find_lines(config=None, config_path=None, regex=None, saltenv='base'):
'''
Return all the lines (as text) that match the expression in the ``regex``
argument.
config
The configuration sent as text.
.. note::
This argument is ignored when ``config_path`` is specified.
config_path
The absolute or remote path to the file with the configuration to be
parsed. This argument supports the usual Salt filesystem URIs, e.g.,
``salt://``, ``https://``, ``ftp://``, ``s3://``, etc.
regex
The regular expression to match the lines against.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file. This
argument is ignored when ``config_path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' ciscoconfparse.find_lines config_path=https://bit.ly/2mAdq7z regex='ip address'
Output example:
.. code-block:: text
cisco-ios-router:
- ip address dhcp
- ip address 172.20.0.1 255.255.255.0
- no ip address
'''
lines = find_objects(config=config,
config_path=config_path,
regex=regex,
saltenv=saltenv)
return [line.text for line in lines]
def find_objects_w_child(config=None,
config_path=None,
parent_regex=None,
child_regex=None,
ignore_ws=False,
saltenv='base'):
'''
Parse through the children of all parent lines matching ``parent_regex``,
and return a list of child objects, which matched the ``child_regex``.
.. warning::
This function is mostly valuable when invoked from other Salt
components (i.e., execution modules, states, templates etc.). For CLI
usage, please consider using
:py:func:`ciscoconfparse.find_lines_w_child <salt.ciscoconfparse_mod.find_lines_w_child>`
config
The configuration sent as text.
.. note::
This argument is ignored when ``config_path`` is specified.
config_path
The absolute or remote path to the file with the configuration to be
parsed. This argument supports the usual Salt filesystem URIs, e.g.,
``salt://``, ``https://``, ``ftp://``, ``s3://``, etc.
parent_regex
The regular expression to match the parent lines against.
child_regex
The regular expression to match the child lines against.
ignore_ws: ``False``
Whether to ignore the white spaces.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file. This
argument is ignored when ``config_path`` is not a ``salt://`` URL.
Usage example:
.. code-block:: python
objects = __salt__['ciscoconfparse.find_objects_w_child'](config_path='https://bit.ly/2mAdq7z',
parent_regex='line con',
child_regex='stopbits')
for obj in objects:
print(obj.text)
'''
ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv)
lines = ccp.find_objects_w_child(parent_regex, child_regex, ignore_ws=ignore_ws)
return lines
def find_lines_w_child(config=None,
config_path=None,
parent_regex=None,
child_regex=None,
ignore_ws=False,
saltenv='base'):
r'''
Return a list of parent lines (as text) matching the regular expression
``parent_regex`` that have children lines matching ``child_regex``.
config
The configuration sent as text.
.. note::
This argument is ignored when ``config_path`` is specified.
config_path
The absolute or remote path to the file with the configuration to be
parsed. This argument supports the usual Salt filesystem URIs, e.g.,
``salt://``, ``https://``, ``ftp://``, ``s3://``, etc.
parent_regex
The regular expression to match the parent lines against.
child_regex
The regular expression to match the child lines against.
ignore_ws: ``False``
Whether to ignore the white spaces.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file. This
argument is ignored when ``config_path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' ciscoconfparse.find_lines_w_child config_path=https://bit.ly/2mAdq7z parent_line='line con' child_line='stopbits'
salt '*' ciscoconfparse.find_lines_w_child config_path=https://bit.ly/2uIRxau parent_regex='ge-(.*)' child_regex='unit \d+'
'''
lines = find_objects_w_child(config=config,
config_path=config_path,
parent_regex=parent_regex,
child_regex=child_regex,
ignore_ws=ignore_ws,
saltenv=saltenv)
return [line.text for line in lines]
def find_objects_wo_child(config=None,
config_path=None,
parent_regex=None,
child_regex=None,
ignore_ws=False,
saltenv='base'):
'''
Return a list of parent ``ciscoconfparse.IOSCfgLine`` objects, which matched
the ``parent_regex`` and whose children did *not* match ``child_regex``.
Only the parent ``ciscoconfparse.IOSCfgLine`` objects will be returned. For
simplicity, this method only finds oldest ancestors without immediate
children that match.
.. warning::
This function is mostly valuable when invoked from other Salt
components (i.e., execution modules, states, templates etc.). For CLI
usage, please consider using
:py:func:`ciscoconfparse.find_lines_wo_child <salt.ciscoconfparse_mod.find_lines_wo_child>`
config
The configuration sent as text.
.. note::
This argument is ignored when ``config_path`` is specified.
config_path
The absolute or remote path to the file with the configuration to be
parsed. This argument supports the usual Salt filesystem URIs, e.g.,
``salt://``, ``https://``, ``ftp://``, ``s3://``, etc.
parent_regex
The regular expression to match the parent lines against.
child_regex
The regular expression to match the child lines against.
ignore_ws: ``False``
Whether to ignore the white spaces.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file. This
argument is ignored when ``config_path`` is not a ``salt://`` URL.
Usage example:
.. code-block:: python
objects = __salt__['ciscoconfparse.find_objects_wo_child'](config_path='https://bit.ly/2mAdq7z',
parent_regex='line con',
child_regex='stopbits')
for obj in objects:
print(obj.text)
'''
ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv)
lines = ccp.find_objects_wo_child(parent_regex, child_regex, ignore_ws=ignore_ws)
return lines
def find_lines_wo_child(config=None,
config_path=None,
parent_regex=None,
child_regex=None,
ignore_ws=False,
saltenv='base'):
'''
Return a list of parent ``ciscoconfparse.IOSCfgLine`` lines as text, which
matched the ``parent_regex`` and whose children did *not* match ``child_regex``.
Only the parent ``ciscoconfparse.IOSCfgLine`` text lines will be returned.
For simplicity, this method only finds oldest ancestors without immediate
children that match.
config
The configuration sent as text.
.. note::
This argument is ignored when ``config_path`` is specified.
config_path
The absolute or remote path to the file with the configuration to be
parsed. This argument supports the usual Salt filesystem URIs, e.g.,
``salt://``, ``https://``, ``ftp://``, ``s3://``, etc.
parent_regex
The regular expression to match the parent lines against.
child_regex
The regular expression to match the child lines against.
ignore_ws: ``False``
Whether to ignore the white spaces.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file. This
argument is ignored when ``config_path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' ciscoconfparse.find_lines_wo_child config_path=https://bit.ly/2mAdq7z parent_line='line con' child_line='stopbits'
'''
lines = find_objects_wo_child(config=config,
config_path=config_path,
parent_regex=parent_regex,
child_regex=child_regex,
ignore_ws=ignore_ws,
saltenv=saltenv)
return [line.text for line in lines]
def filter_lines(config=None,
config_path=None,
parent_regex=None,
child_regex=None,
saltenv='base'):
'''
Return a list of detailed matches, for the configuration blocks (parent-child
relationship) whose parent respects the regular expressions configured via
the ``parent_regex`` argument, and the child matches the ``child_regex``
regular expression. The result is a list of dictionaries with the following
keys:
- ``match``: a boolean value that tells whether ``child_regex`` matched any
children lines.
- ``parent``: the parent line (as text).
- ``child``: the child line (as text). If no child line matched, this field
will be ``None``.
Note that the return list contains the elements that matched the parent
condition, the ``parent_regex`` regular expression. Therefore, the ``parent``
field will always have a valid value, while ``match`` and ``child`` may
default to ``False`` and ``None`` respectively when there is not child match.
CLI Example:
.. code-block:: bash
salt '*' ciscoconfparse.filter_lines config_path=https://bit.ly/2mAdq7z parent_regex='Gigabit' child_regex='shutdown'
Example output (for the example above):
.. code-block:: python
[
{
'parent': 'interface GigabitEthernet1',
'match': False,
'child': None
},
{
'parent': 'interface GigabitEthernet2',
'match': True,
'child': ' shutdown'
},
{
'parent': 'interface GigabitEthernet3',
'match': True,
'child': ' shutdown'
}
]
'''
ret = []
ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv)
parent_lines = ccp.find_objects(parent_regex)
for parent_line in parent_lines:
child_lines = parent_line.re_search_children(child_regex)
if child_lines:
for child_line in child_lines:
ret.append({
'match': True,
'parent': parent_line.text,
'child': child_line.text
})
else:
ret.append({
'match': False,
'parent': parent_line.text,
'child': None
})
return ret
|
StarcoderdataPython
|
5193631
|
import os
import json
from glob import glob
from utils import get_code, SexpCache, set_paths, extract_code, dst_filename
from serapi import SerAPI
from time import time
import sexpdata
from proof_tree import ProofTree
from extract_proof import goal_is_prop, check_topology
import pdb
def close_proof(sexp_cache, serapi):
fg_goals, bg_goals, shelved_goals, given_up_goals = serapi.query_goals()
assert bg_goals + shelved_goals == []
if fg_goals == []:
return []
num_goals_left = len(fg_goals)
cmds = []
for i in range(num_goals_left):
_, ast = serapi.execute('auto.')
cmds.append(('auto.', 'VernacExtend', sexp_cache.dump(ast)))
fg_goals, bg_goals, shelved_goals, given_up_goals = serapi.query_goals()
if fg_goals == []:
return cmds
return None
def subgoals2hypotheses(script, serapi):
'Execute `script` and convert all unsolved new sub-goals into hypotheses in the context of the current goal'
serapi.push()
fg_goals, bg_goals, shelved_goals, given_up_goals = serapi.query_goals()
assert shelved_goals + given_up_goals == []
assert len(fg_goals) == 1
current_goal_id = fg_goals[0]['id']
existing_goal_ids = set([g['id'] for g in fg_goals + bg_goals])
local_context = []
for hyp in fg_goals[0]['hypotheses']:
for ident in hyp['idents'][::-1]:
local_context.append((ident, hyp['type']))
local_context = local_context[::-1]
for cmd, _, _ in script:
serapi.execute(cmd)
fg_goals, bg_goals, shelved_goals, given_up_goals = serapi.query_goals()
assert shelved_goals + given_up_goals == []
unsolved_goal_ids = set([g['id'] for g in fg_goals + bg_goals])
if bg_goals != [] or not existing_goal_ids.issubset(unsolved_goal_ids.union({current_goal_id})):
# consider only the case when there is no unfocused goal left.
# and no existing goal other than the current_goal was decomposed (the sub-tree of the current goal has insufficient height)
serapi.pull()
return None
hypotheses = {}
# convert the focused goals
for n, g in enumerate(fg_goals, start=1):
serapi.push()
serapi.execute('Focus %d.' % n)
local_context_g = []
for hyp in g['hypotheses']:
for ident in hyp['idents'][::-1]:
local_context_g.append((ident, hyp['type']))
local_context_g = local_context_g[::-1]
local_context_diff = [p for p in local_context_g if p not in local_context]
for ident, _ in local_context_diff:
serapi.execute('generalize %s.' % ident)
fg_goals, _, _, _ = serapi.query_goals()
assert len(fg_goals) == 1
hypotheses[g['id']] = fg_goals[0]['type']
serapi.pop()
serapi.pop()
return hypotheses
def set_up_hypotheses(hyps, sexp_cache, serapi):
'Set up the hypotheses converted from the subgoals'
cmds = []
for goal_id, hyp in hyps.items():
H = 'assert (HYPOTHESIS_FROM_SUBGOAL_%d: %s); [> admit | idtac].' % (goal_id, hyp)
_, ast = serapi.execute(H, return_ast=True)
cmds.append((H, 'VernacExtend', sexp_cache.dump(ast)))
return cmds
def goal2subproof(goal, length, line_nb, script, sexp_cache, serapi):
'Extract a synthetic proof a fixed length from a goal'
hypotheses = subgoals2hypotheses(script, serapi)
if hypotheses is None:
return None
cmds = set_up_hypotheses(hypotheses, sexp_cache, serapi)
subproof_data = {
'goal_id': goal['id'],
'length': length,
'line_nb': line_nb,
'entry_cmds': cmds,
'steps': [],
'goals': {},
'proof_tree': None,
}
# execute the proof
for num_executed, (cmd, cmd_type, _) in enumerate(script, start=line_nb + 1):
# keep track of the goals
fg_goals, bg_goals, shelved_goals, given_up_goals = serapi.query_goals()
for g in fg_goals + bg_goals:
g['sexp'] = sexp_cache.dump(g['sexp'])
for i, h in enumerate(g['hypotheses']):
g['hypotheses'][i]['sexp'] = sexp_cache.dump(g['hypotheses'][i]['sexp'])
subproof_data['goals'][g['id']] = g
ast = sexpdata.dumps(serapi.query_ast(cmd))
subproof_data['steps'].append({'command': (cmd, cmd_type, sexp_cache.dump(ast)),
'goal_ids': {'fg': [g['id'] for g in fg_goals],
'bg': [g['id'] for g in bg_goals]}
})
# the proof ends
if cmd_type == 'VernacEndProof':
return None # there is no such proof
# run the tactic
if args.debug:
print('SUBPROOF-id%d-len%d %d: %s' % (goal['id'], length, num_executed, cmd))
serapi.execute(cmd)
if num_executed == line_nb + length: # now, try to close the proof
exit_cmds = close_proof(sexp_cache, serapi)
if exit_cmds is None:
print('failed')
return None
print('succeeded')
subproof_data['exit_cmds'] = exit_cmds
break
assert check_topology(subproof_data['steps'])
subproof_data['proof_tree'] = ProofTree(subproof_data['steps'], subproof_data['goals']).to_dict()
return subproof_data
def record_subproofs(line_nb, script, sexp_cache, serapi):
'For a human-written proof, extract all synthetic proofs from all goals'
assert script[-1][1] == 'VernacEndProof'
subproofs_data = []
# execute the proof
for num_executed, (cmd, cmd_type, _) in enumerate(script, start=line_nb + 1):
# keep track of the goals
fg_goals, bg_goals, shelved_goals, given_up_goals = serapi.query_goals()
if fg_goals != []:
g = fg_goals[0]
if g['id'] in subproofs_data:
continue
if not goal_is_prop(g, serapi):
continue
serapi.push()
serapi.execute('Focus 1.')
for i in range(1, min(args.max_length, len(script) - 2) + 1):
serapi.push()
subprf = goal2subproof(g, i, num_executed - 1, script[num_executed - line_nb - 1 : num_executed - line_nb - 1 + i],
sexp_cache, serapi)
if subprf is not None:
subproofs_data.append(subprf)
serapi.pop()
serapi.pop()
# run the tactic
if args.debug:
print('PROOF %d: %s' % (num_executed, cmd))
serapi.execute(cmd)
return subproofs_data
def get_subproofs(human_proof_file, vernac_cmds, sexp_cache, args):
prf = json.load(open(human_proof_file))
line_nb = prf['line_nb']
with SerAPI(args.timeout, args.debug) as serapi:
for cmd, _, _ in vernac_cmds[:line_nb + 1]:
serapi.execute(cmd)
subproofs_data = record_subproofs(line_nb, vernac_cmds[line_nb + 1 : line_nb + 1 + len(prf['steps'])],
sexp_cache, serapi)
return subproofs_data
def dump(subproofs_data, args):
print('%d synthetic proofs extracted' % len(subproofs_data))
if subproofs_data == []:
return
for i, subprf in enumerate(subproofs_data):
subproofs_data[i]['name'] = args.proof
dirname = dst_filename(args.file, args.data_path) + '-SUBPROOFS/'
json.dump(subproofs_data, open(os.path.join(dirname, args.proof + '.json'), 'wt'))
if __name__ == '__main__':
import sys
sys.setrecursionlimit(100000)
import argparse
arg_parser = argparse.ArgumentParser(description='Extract the synthetic proofs from intermediate goals')
arg_parser.add_argument('--debug', action='store_true')
arg_parser.add_argument('--file', type=str, help='The meta file to process')
arg_parser.add_argument('--proof', type=str, help='The proof to extract')
arg_parser.add_argument('--max_length', type=int, default=4, help='The maximum length for synthetic proofs')
arg_parser.add_argument('--timeout', type=int, default=3600, help='Timeout for SerAPI')
arg_parser.add_argument('--data_path', type=str, default='./data')
args = arg_parser.parse_args()
print(args)
human_proof_file = dst_filename(args.file, args.data_path) + '-PROOFS/' + args.proof + '.json'
if not os.path.exists(human_proof_file):
print('%s does not exist. Exiting..' % human_proof_file)
sys.exit(0)
dirname = dst_filename(args.file, args.data_path) + '-SUBPROOFS/'
try:
os.makedirs(dirname)
except os.error:
pass
db_path = os.path.join(dirname, args.proof + '_sexp_cache')
sexp_cache = SexpCache(db_path)
file_data = json.load(open(dst_filename(args.file, args.data_path) + '.json'))
subproofs_data = get_subproofs(human_proof_file, file_data['vernac_cmds'], sexp_cache, args)
dump(subproofs_data, args)
|
StarcoderdataPython
|
9602026
|
__author__ = 'Folaefolc'
"""
Code par Folaefolc
Licence MIT
"""
from constantes import DEBUG_LEVEL, ree, POL_ANTIALISING
def println(*args, sep=" ", end="\r\n"):
if DEBUG_LEVEL >= 1:
print(*args, sep=sep, end=end)
def onscreen_debug(ecran, font, *debug_infos, **kwargs):
if DEBUG_LEVEL >= 2:
start_y = kwargs.get("y", 0)
start_x = kwargs.get("x", 0)
size_y = kwargs.get("sy", -1)
line_height = kwargs.get("line_height", 18)
line_width = kwargs.get("line_width", 150)
if size_y == -1:
ree.draw_rect(ecran, (start_x, start_y, line_width, len(debug_infos) * line_height), (128, 128, 128))
else:
ree.draw_rect(ecran, (start_x, start_y, line_width, size_y), (128, 128, 128))
for count, info in enumerate(debug_infos):
ecran.blit(font.render(str(info), POL_ANTIALISING, (10, 10, 10)), (start_x, start_y + count * line_height))
|
StarcoderdataPython
|
12836936
|
<reponame>f4str/neural-networks-sandbox
from .elasticnet_regression import ElasticNetRegression
from .lasso_regression import LassoRegression
from .linear_regression import LinearRegression
from .logistic_regression import LogisticRegression
from .ridge_regression import RidgeRegression
__all__ = [
'ElasticNetRegression',
'LassoRegression',
'LinearRegression',
'LogisticRegression',
'RidgeRegression',
]
|
StarcoderdataPython
|
8071572
|
<filename>sources/thedailybeast.py
from sources import RSSSource
class Source(RSSSource):
name = 'The Daily Beast'
url = 'https://www.thedailybeast.com/'
feeds = [
('https://feeds.thedailybeast.com/rss/politics', 'politics'),
('https://feeds.thedailybeast.com/rss/us-news', 'us'),
('https://feeds.thedailybeast.com/rss/world', 'world'),
'https://feeds.thedailybeast.com/rss/articles',
]
def format_body(self, body):
p = body.find('p')
if p is not None:
body = p
return body.get_text().strip()
def map(self, x):
parts = x['url'].split('?', 1)
url = parts[0]
x['url'] = url
x['id'] = url
return x
|
StarcoderdataPython
|
3510333
|
<reponame>meysam81/SampleCRUD
from http import HTTPStatus
from operator import itemgetter
class TestGetAll:
URL = '/api/v1/books'
def test_other_methods_not_allowed(self, app):
expected_status = HTTPStatus.METHOD_NOT_ALLOWED
for method in ('patch', 'put', 'delete', 'options'):
func = getattr(app, method)
rv = func(self.URL, status=expected_status)
assert rv.status_code == expected_status
def test_get_all_books_empty_db(self, Book, app):
books = []
Book.query.all.return_value = books
rv = app.get(self.URL)
assert rv.status_code == HTTPStatus.OK
assert rv.content_type == "application/json"
assert len(rv.json) == 0
Book.query.all.assert_called_once()
def test_get_all_books_populated_db(self, Book, app):
books = [
(1, "book1"),
(2, "book2"),
(3, "book3"),
]
db_books = [Book(id=k, name=v) for k, v in books]
Book.query.all.return_value = db_books
rv = app.get(self.URL)
assert rv.status_code == HTTPStatus.OK
assert rv.content_type == "application/json"
for item in rv.json:
assert item["id"] in map(itemgetter(0), books)
Book.query.all.assert_called_once()
|
StarcoderdataPython
|
1724817
|
import sys
import logging
import winreg, itertools, glob
from datetime import datetime
import re
from copy import deepcopy
from PyQt5.QtCore import QVariant, pyqtProperty, pyqtSlot, pyqtSignal, QObject
from playhouse.shortcuts import model_to_dict, dict_to_model
from PyQt5.QtQml import QJSValue
from py.common.FramListModel import FramListModel
from py.hookandline.HookandlineFpcDB_model import database, TideStations, Sites, Lookups, \
Equipment, DeployedEquipment, ParsingRules, JOIN
class ParsedSentencesModel(FramListModel):
def __init__(self):
super().__init__()
self.add_role_name(name="column1")
self.add_role_name(name="column2")
self.add_role_name(name="column3")
self.add_role_name(name="column4")
self.add_role_name(name="column5")
self.add_role_name(name="column6")
self.add_role_name(name="column7")
self.add_role_name(name="column8")
self.add_role_name(name="column9")
self.add_role_name(name="column10")
self.add_role_name(name="column11")
self.add_role_name(name="column12")
class RawSentencesModel(FramListModel):
def __init__(self):
super().__init__()
self.add_role_name(name="sentence")
class TestSentencesModel(FramListModel):
def __init__(self):
super().__init__()
self.add_role_name(name="sentence")
class ErrorMessagesModel(FramListModel):
def __init__(self):
super().__init__()
self.add_role_name(name="date_time")
self.add_role_name(name="com_port")
self.add_role_name(name="message")
self.add_role_name(name="resolution")
self.add_role_name(name="exception")
class SensorConfigurationModel(FramListModel):
def __init__(self, app=None):
super().__init__()
self._app = app
self.add_role_name(name="data_status")
self.add_role_name(name="start_stop_status")
self.add_role_name(name="com_port")
self.add_role_name(name="moxa_port")
self.add_role_name(name="equipment")
self.add_role_name(name="delete_row")
self.add_role_name(name="baud_rate")
self.add_role_name(name="data_bits")
self.add_role_name(name="stop_bits")
self.add_role_name(name="parity")
self.add_role_name(name="flow_control")
self.add_role_name(name="deployed_equipment_id")
self.populate_model()
def populate_model(self):
"""
Method to retrieve all of the sensor configurations from the database
deployed_equipment table and use them to populate the tvSensorConfiguration
tableview on the SensorDataFeeds.qml screen
:return:
"""
self.clear()
Organization = Lookups.alias()
records = DeployedEquipment.select(DeployedEquipment, Equipment, Organization)\
.join(Equipment)\
.join(Organization, on=(Organization.lookup == Equipment.organization).alias('org'))\
.where(DeployedEquipment.deactivation_date.is_null())\
.order_by(DeployedEquipment.com_port.asc())
for record in records:
item = dict()
item["equipment"] = record.equipment.org.value + " " + record.equipment.model
# item["com_port"] = "COM{0}".format(record.com_port)
item["com_port"] = record.com_port
item["moxa_port"] = record.moxa_port
item["data_status"] = "red"
item["start_stop_status"] = "stopped"
item["delete_row"] = ""
item["baud_rate"] = record.baud_rate if record.baud_rate else 9600
item["data_bits"] = record.data_bits if record.data_bits else 8
item["parity"] = record.parity if record.parity else "None"
item["stop_bits"] = record.stop_bits if record.stop_bits else 1
item["flow_control"] = record.flow_control if record.flow_control else "None"
item["deployed_equipment_id"] = record.deployed_equipment
self.appendItem(item)
self._app.serial_port_manager.add_thread(com_port_dict=item)
self.setItems(sorted(self.items, key=lambda x: int(x["com_port"].strip("COM"))))
@pyqtSlot(int, str, str, int, int, int, str, float, str)
def add_row(self, equipment_id=None, equipment=None, com_port=None, moxa_port=None,
baud_rate=9600, data_bits=8, parity="None", stop_bits=1, flow_control="None"):
"""
Method called by the AddComportDialog.qml to add a new equipment/comport/moxaport
entry into the tvSensorConfiguration tableview
:param equipment_id: int
:param equipment: str
:param com_port: str - of the form: COM4, COM5, etc.
:param moxa_port: int
:return:
"""
if not isinstance(equipment_id, int) or \
not re.search(r"^COM\d{1,3}$", com_port):
logging.error("require equipment and comport to add a new row: {0}, {1}"
.format(equipment, com_port))
return
# Add to the database
try:
DeployedEquipment.insert(equipment=equipment_id,
com_port=com_port,
moxa_port=moxa_port,
baud_rate=baud_rate,
data_bits=data_bits,
stop_bits=stop_bits,
parity=parity,
flow_control=flow_control,
activation_date=datetime.now()).execute()
deployed_equipment_id = DeployedEquipment.select()\
.order_by(DeployedEquipment.deployed_equipment.desc()).get().deployed_equipment
except Exception as ex:
logging.info('Error inserting new sensor configuration: {0}'.format(ex))
return
# Add to the model
item = dict()
item["data_status"] = "red"
item["start_stop_status"] = "stopped"
item["delete_row"] = ""
item["equipment"] = equipment
item["com_port"] = com_port
item["moxa_port"] = moxa_port
item["deployed_equipment_id"] = deployed_equipment_id
item["baud_rate"] = baud_rate
item["data_bits"] = data_bits
item["stop_bits"] = stop_bits
item["parity"] = parity
item["flow_control"] = flow_control
self.appendItem(item)
self.setItems(sorted(self.items, key=lambda x: int(x["com_port"].strip("COM"))))
# Add to Serial Port Manager threads
self._app.serial_port_manager.add_thread(com_port_dict=item)
@pyqtSlot(str)
def remove_row(self, com_port=None):
"""
Method to remove the sensor configuration row from the SensorDataFeeds.qml
tvSensorConfigurations tableview. The comport to be removed is required
:param comport: str
:return:
"""
if not re.search(r"^COM\d{1,3}$", com_port):
return
# Delete the thread - com_port should be of the form: COM5
self._app.serial_port_manager.delete_thread(com_port=com_port)
# Remove from the model - com_port should be of the form: COM5
self.removeItem(index=self.get_item_index(rolename="com_port", value=com_port))
# Delete from the database deployed_equipment table
DeployedEquipment.update(deactivation_date=datetime.now()).where(DeployedEquipment.com_port == com_port).execute()
@pyqtSlot(QVariant)
def update_row(self, item=None):
"""
Method to update the serial port settings for the given com_port. Note that item is a dictionary
of the following format:
item = {"com_port": "COM3", "baud_rate": 9600, "data_bits": 8, "parity": "None",
"stop_bits": 1, "flow_control": "None"}
:param item:
:return:
"""
if isinstance(item, QJSValue):
item = item.toVariant()
# Ensure that the newly proposed com_port doesn't already exist in this model
# Logic for checking this is handled in the btnUpdate onClicked method
# Convert to appropriate data types
item["deployed_equipment_id"] = int(item["deployed_equipment_id"])
item["baud_rate"] = int(item["baud_rate"])
item["data_bits"] = int(item["data_bits"])
item["stop_bits"] = float(item["stop_bits"])
# Update the Database
try:
DeployedEquipment.update(com_port=item["com_port"], baud_rate=item["baud_rate"],
data_bits=item["data_bits"], parity=item["parity"],
stop_bits=item["stop_bits"], flow_control=item["flow_control"])\
.where(DeployedEquipment.deployed_equipment == item["deployed_equipment_id"]).execute()
except Exception as ex:
logging.info('Error updating DeployedEquipment table: {0}'.format(ex))
return
# Update the model
index = self.get_item_index(rolename="deployed_equipment_id", value=item["deployed_equipment_id"])
if index != -1:
old_com_port = self.get(index)["com_port"]
old_start_stop_status = self.get(index)["start_stop_status"]
for key in item:
self.setProperty(index=index, property=key, value=item[key])
else:
logging.info('Unable to find the deployed_equipment_id in the model: {0}'.format(item["deployed_equipment_id"]))
return
self.setItems(sorted(self.items, key=lambda x: int(x["com_port"].strip("COM"))))
# Delete the old thread
self._app.serial_port_manager.delete_thread(com_port=old_com_port)
# Add the new thread
self._app.serial_port_manager.add_thread(com_port_dict=item)
# Check if thread was previously started, if so, stop and restart it
if old_start_stop_status == "started":
self._app.serial_port_manager.start_thread(com_port=item["com_port"])
class ComportModel(FramListModel):
def __init__(self):
super().__init__()
self.add_role_name(name="lookup_id")
self.add_role_name(name="com_port")
self.add_role_name(name="text")
self.populate_model()
def populate_model(self):
"""
Method to retrieve all of the equipment from the database equipment table
and use them to populate the lvEquipment Listiew on the AddComportDialog.qml
called from the SensorDataFeeds.qml screen
:return:
"""
self.clear()
records = self.get_available_serial_ports()
records = sorted(records, key=lambda port: int(port.strip("COM")))
for record in records:
item = dict()
item["lookup_id"] = record
item["com_port"] = record
item["text"] = record
self.appendItem(item)
@staticmethod
def get_available_serial_ports():
"""Lists serial ports
:raises EnvironmentError:
On unsupported or unknown platforms
:returns:
A list of available serial ports
"""
if sys.platform.startswith('win'):
# ports = ['COM' + str(i + 1) for i in range(256)]
ports = [i + 1 for i in range(256)]
elif sys.platform.startswith('linux'):
# this is to exclude your current terminal "/dev/tty"
ports = glob.glob('/dev/tty[A-Za-z]*')
elif sys.platform.startswith('darwin'):
ports = glob.glob('/dev/tty.*')
else:
raise EnvironmentError('Unsupported platform')
result = []
# for port in ports:
# try:
# print("Port Number: COM", str(port))
# # s = serial.Serial(port)
# s = serial.Serial(port='COM' + str(port), timeout=0.01)
# s.close()
# result.append(port)
# except (OSError, serial.SerialException):
# print('\tError occurred: ', str(serial.SerialException))
# pass
path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
try:
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
for i in itertools.count():
try:
val = winreg.EnumValue(key, i)
# yield str(val[1])
# print(str(val[1].strip('COM')))
# result.append(int(val[1].strip('COM')))
result.append(val[1])
except EnvironmentError:
break
except WindowsError as ex:
logging.info(f"Error accessing serial ports in registry: {ex}")
# raise WindowsError
# print('Ports: ', str(result))
return result
class EquipmentModel(FramListModel):
def __init__(self):
super().__init__()
self.add_role_name(name="equipment_id")
self.add_role_name(name="equipment")
self.add_role_name(name="equipment_type")
self.populate_model()
def populate_model(self):
"""
Method to retrieve all of the equipment from the database equipment table
and use them to populate the lvEquipment Listiew on the AddComportDialog.qml
called from the SensorDataFeeds.qml screen
:return:
"""
self.clear()
Make = Lookups.alias()
Category = Lookups.alias()
records = Equipment.select(Equipment, Make, Category)\
.join(Make, on=(Make.lookup == Equipment.organization).alias('make'))\
.switch(Equipment)\
.join(Category, on=(Category.lookup == Equipment.equipment_category).alias('category'))\
.where(Equipment.is_active == "True")\
.order_by(Make.value.asc(), Equipment.name.asc(), Category.value.asc())
for record in records:
item = dict()
item["equipment_id"] = record.equipment
item["equipment"] = " ".join([record.make.value, record.model])
item["equipment_type"] = record.category.value
self.appendItem(item)
class MeasurementsModel(FramListModel):
def __init__(self):
super().__init__()
self.add_role_name(name="lookup_id")
self.add_role_name(name="text")
self.populate_model()
def populate_model(self):
"""
Method to retrieve all of the measurements form the database lookups table
and use them to populate the cbMeasurement combobox on the NewMeasurementDialog.qml
called from the SensorDataFeeds.qml screen
:return:
"""
self.clear()
records = Lookups.select(Lookups.value, Lookups.lookup) \
.where(Lookups.type == "Measurement", Lookups.is_active == "True")\
.order_by(Lookups.value.asc()) \
.group_by(Lookups.value)
for record in records:
item = dict()
item["lookup_id"] = record.lookup
item["text"] = record.value
self.appendItem(item)
def add_row(self, lookup_id, value):
"""
Method to add a new measurement value to the model
:param lookup_id:
:param value:
:return:
"""
if not isinstance(lookup_id, int) or \
not isinstance(value, str):
return
# First check if the value already exists in the model or not
if self.get_item_index(rolename="text", value=value) == -1:
item = dict()
item["lookup_id"] = lookup_id
item["text"] = value
self.appendItem(item)
self.sort(rolename="text")
class UnitsOfMeasurementModel(FramListModel):
def __init__(self):
super().__init__()
self.add_role_name(name="lookup_id")
self.add_role_name(name="text")
self.populate_model()
def populate_model(self):
"""
Method to retrieve all of the units of measurement from the database lookups table
and use them to populate the cbUnitOfMeasurement combobox on the
NewMeasurementDialog.qml that is called from the SensorDataFeeds.qml page
:return:
"""
self.clear()
# TODO - Ensure that the units of measurement returned are unique
records = Lookups.select(Lookups.subvalue, Lookups.lookup) \
.where(Lookups.type == "Measurement", Lookups.is_active == "True") \
.order_by(Lookups.subvalue.asc()) \
.group_by(Lookups.subvalue)
for record in records:
item = dict()
item["lookup_id"] = record.lookup
item["text"] = record.subvalue
self.appendItem(item)
def add_row(self, lookup_id, subvalue):
"""
Method to add a new row to UOM model that includes the lookup_id as well
as the various units of measurement
:param lookup_id:
:param subvalue:
:return:
"""
if not isinstance(lookup_id, int) or \
not isinstance(subvalue, str):
return
# First check if the subvalue already exists in the model or not
if self.get_item_index(rolename="text", value=subvalue) == -1:
item = dict()
item["lookup_id"] = lookup_id
item["text"] = subvalue
self.appendItem(item)
self.sort(rolename="text")
class MeasurementsUnitsOfMeasurementModel(FramListModel):
def __init__(self):
super().__init__()
self.add_role_name(name="lookup_id")
self.add_role_name(name="text")
self.populate_model()
def populate_model(self):
"""
Method to retrieve all of measurements + units of measurement from the database lookups table
and use them to populate the cbMeasurement combobox on the SensorDataFeeds.qml page
:return:
"""
self.clear()
records = Lookups.select(Lookups.value, Lookups.subvalue, Lookups.lookup)\
.where(Lookups.type == "Measurement", Lookups.is_active == "True")\
.order_by(Lookups.value.asc()) \
.group_by(Lookups.value, Lookups.subvalue)
for record in records:
item = dict()
item["lookup_id"] = record.lookup
item["text"] = record.value + ", " + record.subvalue \
if record.subvalue else record.value
self.appendItem(item)
def add_row(self, lookup_id, value, subvalue):
"""
Method to add a new row to the model that includes the Lookup table components
for a measurement type, i.e. the lookup_id, value (= measurement) and
subvalue (= unit of measurement)
:param lookup_id: int
:param value: str
:param subvalue: str
:return:
"""
if not isinstance(lookup_id, int) or \
not isinstance(value, str) or \
not isinstance(subvalue, str):
return
value_str = value + ", " + subvalue if subvalue else value
if self.get_item_index(rolename="text", value=value_str) == -1:
item = dict()
item["lookup_id"] = lookup_id
item["text"] = value_str
self.appendItem(item)
self.sort(rolename="text")
class MeasurementConfigurationModel(FramListModel):
def __init__(self):
super().__init__()
self.add_role_name(name="parsing_rules_id")
self.add_role_name(name="equipment")
self.add_role_name(name="line_starting")
self.add_role_name(name="is_line_starting_substr")
self.add_role_name(name="field_position")
self.add_role_name(name="line_ending")
self.add_role_name(name="measurement")
self.add_role_name(name="priority")
self.populate_model()
def populate_model(self):
"""
Method to populate the model by pull all active parsing methods from the
ParsingRules table in the database
:return:
"""
self.clear()
Measurements = Lookups.alias()
Organizations = Lookups.alias()
rules = ParsingRules.select(ParsingRules, Equipment, Measurements, Organizations)\
.join(Measurements, JOIN.LEFT_OUTER, on=(Measurements.lookup == ParsingRules.measurement_lu).alias("measurement"))\
.switch(ParsingRules)\
.join(Equipment)\
.join(Organizations, on=(Equipment.organization == Organizations.lookup).alias("org"))\
.order_by(ParsingRules.priority.asc())
for rule in rules:
item = dict()
item["parsing_rules_id"] = rule.parsing_rules
item["equipment"] = "{0} {1}".format(rule.equipment.org.value, rule.equipment.model)
item["line_starting"] = rule.line_starting
item["is_line_starting_substr"] = rule.is_line_starting_substr
item["field_position"] = rule.field_position
item["line_ending"] = rule.line_ending
item["measurement"] = "{0}, {1}".format(rule.measurement.value, rule.measurement.subvalue)
item["priority"] = rule.priority
self.appendItem(item)
@pyqtProperty(QVariant)
def line_startings(self):
"""
Method to return all of the line_startings. This is used to identify
which sentences are needed for parsing values of interest, as defined
by this model
:return:
"""
return list(set(x["line_starting"] for x in self.items))
@pyqtSlot(str, result=QVariant)
def sentence_rules(self, sentence):
"""
Method to get all of the rules for the given sentence string
:param sentence: str - the name of the sentence, e.g. $GPRMC, $IIGLL, etc.
:return:
"""
return [x for x in self.items if x["line_starting"] == sentence]
@pyqtSlot(QVariant)
def add_row(self, item):
"""
Method to add a new row to the ParsingRules table
:param item: dictionary containing the items used to populate ParsingRules and the model
:return: None
"""
if isinstance(item, QJSValue):
item = item.toVariant()
# Must have at least the following fields:
if "equipment_id" not in item or \
"line_starting" not in item or \
"measurement_lu_id" not in item:
logging.error("Failed to add a new measurement configuration, missing necessary keys: {0}".format(item))
return
for key in ["field_position", "start_position", "end_position",
"equipment_id", "measurement_lu_id"]:
item[key] = int(item[key])
# Insert into the ParsingRules tables of the database
db_item = deepcopy({k: item[k] for k in item.keys() & {"equipment_id",
"line_starting",
"is_line_starting_substr",
"fixed_or_delimited",
"delimiter",
"field_position",
"start_position",
"end_position",
"line_ending",
"measurement_lu_id",
"priority"}})
db_item["equipment"] = db_item.pop("equipment_id")
db_item["measurement_lu"] = db_item.pop("measurement_lu_id")
db_item["field_position"] = int(db_item["field_position"])
try:
new_rule = ParsingRules.create(**db_item)
except Exception as ex:
logging.error("Error adding a new measurement configuration: {0}".format(ex))
return
# Insert into the model
model_item = deepcopy({k: item[k] for k in item.keys() & {"equipment", "line_starting", "is_line_starting_substr",
"field_position", "line_ending", "measurement", "priority"}})
model_item["parsing_rules_id"] = new_rule.parsing_rules
self.appendItem(model_item)
self.sort(rolename="priority")
@pyqtSlot(QVariant)
def update_row(self, item):
"""
Method to update a measurement configuration row in the model. The input, an item, will contain the
updated elements as well as the primary key to support an update
:param item:
:return:
"""
if isinstance(item, QJSValue):
item = item.toVariant()
# Must have at least the following fields:
if "equipment_id" not in item or \
"line_starting" not in item or \
"measurement_lu_id" not in item or \
"parsing_rules_id" not in item:
logging.error("Failed to update an exist measurement configuration, missing necessary keys: {0}".format(item))
return
for key in ["field_position", "start_position", "end_position",
"equipment_id", "measurement_lu_id", "parsing_rules_id"]:
item[key] = int(item[key])
# Update the database
db_item = deepcopy({k: item[k] for k in item.keys() & {"equipment_id",
"line_starting",
"is_line_starting_substr",
"fixed_or_delimited",
"delimiter",
"field_position",
"start_position",
"end_position",
"line_ending",
"measurement_lu_id",
"priority",
"parsing_rules_id"}})
db_item["equipment"] = db_item.pop("equipment_id")
db_item["measurement_lu"] = db_item.pop("measurement_lu_id")
db_item["parsing_rules"] = db_item.pop("parsing_rules_id")
try:
ParsingRules.update(**db_item).where(ParsingRules.parsing_rules == db_item["parsing_rules"]).execute()
except Exception as ex:
logging.error("Error updating the measurement configuration: {0}".format(ex))
return
# Update the model
model_item = deepcopy({k: item[k] for k in item.keys() & {"equipment", "line_starting", "is_line_starting_substr",
"field_position", "line_ending", "measurement", "priority",
"parsing_rules_id"}})
index = self.get_item_index(rolename="parsing_rules_id", value=model_item["parsing_rules_id"])
if index != -1:
self.replace(index=index, item=model_item)
self.sort(rolename="priority")
@pyqtSlot(int)
def delete_row(self, parsing_rules_id):
"""
Method to delete a row from the model and ParsingRules tables
:param item:
:return:
"""
if not isinstance(parsing_rules_id, int):
logging.error("Failed to delete the parsing rule: {0}".format(parsing_rules_id))
return
# Remove from database
ParsingRules.delete().where(ParsingRules.parsing_rules == parsing_rules_id).execute()
# Remove from model
index = self.get_item_index(rolename="parsing_rules_id", value=parsing_rules_id)
if index != -1:
self.removeItem(index=index)
class SensorDataFeeds(QObject):
displayModeChanged = pyqtSignal()
measurementsModelChanged = pyqtSignal()
unitsOfMeasurementModelChanged = pyqtSignal()
measurementsUomModelChanged = pyqtSignal(str, arguments=["value"])
equipmentModelChanged = pyqtSignal()
comportModelChanged = pyqtSignal()
sensorConfigurationModelChanged = pyqtSignal()
testSentencesModelChanged = pyqtSignal()
rawSentencesModelChanged = pyqtSignal()
parsedSentencesModelChanged = pyqtSignal()
errorMessagesModelChanged = pyqtSignal()
measurementConfigurationModelChanged = pyqtSignal()
def __init__(self, app=None, db=None):
super().__init__()
self._logger = logging.getLogger(__name__)
self._app = app
self._db = db
self._display_mode = "operations"
# Set up the various List Models used throughout the screen
self._measurements_model = MeasurementsModel()
self._units_of_measurement_model = UnitsOfMeasurementModel()
self._measurements_uom_model = MeasurementsUnitsOfMeasurementModel()
self._equipment_model = EquipmentModel()
self._comport_model = ComportModel()
self._sensor_configuration_model = SensorConfigurationModel(app=self._app)
self._test_sentences_model = TestSentencesModel()
self._raw_sentences_model = RawSentencesModel()
self._parsed_sentences_model = ParsedSentencesModel()
self._error_messages_model = ErrorMessagesModel()
self._measurement_configuration_model = MeasurementConfigurationModel()
# self._app.serial_port_manager.add_all_threads(sensor_config_model=self._sensor_configuration_model.items)
@pyqtSlot(str, str)
def add_new_measurement(self, measurement, unit_of_measurement):
"""
Method called by the NewMeasurementDialog.qml via SensorDataFeeds.qml when a
user wants to add a new measurement type. This consists of the measurement name
as well as the unit of measurement
:param measurement: str - should be in the form: Latitude - Vessel, Time - UTC, etc.
:param unit_of_measurement: str - abbreviated unit of measurements, e.g. m, kg, km, etc.
:return:
"""
if not isinstance(measurement, str) or not isinstance(unit_of_measurement, str) or \
measurement == "" or unit_of_measurement == "":
logging.error("Invalid measurement of unit of measurement provided: {0}, {1}"
.format(measurement, unit_of_measurement))
return
# Insert into the Lookups table in the database
try:
# Lookups.insert(type="Measurement", value=measurement, subvalue=unit_of_measurement,
# is_active="True").execute()
# lookup_id = Lookups.select().order_by(Lookups.lookup.desc()).get().lookup
lookup, created = Lookups.get_or_create(
type="Measurement", value=measurement, subvalue=unit_of_measurement, is_active="True"
)
lookup_id = lookup.lookup
except Exception as ex:
logging.error("failed to insert new measurement type: {0}".format(ex))
# Add to the various models - measurements, uom, and measurementsUofm
self._measurements_model.add_row(lookup_id=lookup_id, value=measurement)
self._units_of_measurement_model.add_row(lookup_id=lookup_id, subvalue=unit_of_measurement)
self._measurements_uom_model.add_row(lookup_id=lookup_id, value=measurement,
subvalue=unit_of_measurement)
# Emit a signal - this is used to auto-select this newly added measurement in SensorDataFeeds.qml
self.measurementsUomModelChanged.emit("{0}, {1}".format(measurement, unit_of_measurement))
@pyqtProperty(str, notify=displayModeChanged)
def displayMode(self):
"""
Method to return the self._display_mode. This keeps track of what
is display in SensorDataFeeds.qml, in the rightPanel. Options include:
- raw sentences
- identify measurements
:return:
"""
return self._display_mode
@displayMode.setter
def displayMode(self, value):
"""
Method to set the self._display_mode
:param value:
:return:
"""
self._display_mode = value
self.displayModeChanged.emit()
@pyqtProperty(FramListModel, notify=measurementsModelChanged)
def measurementsModel(self):
"""
Method to return the self._measurements_model that is used by the
SensorDataFeeds.qml cbMeasurement combobox that lists out the measurements
to select when adding in NMEA sentence parsing instructions
:return:
"""
return self._measurements_model
@pyqtProperty(FramListModel, notify=unitsOfMeasurementModelChanged)
def unitsOfMeasurementModel(self):
"""
Method to return the self._units_of_measurement_model that is used by the
SensorDataFeeds.qml NewMeasurementDialog.qml cbUnitOfMeasurement combobox
that lists out the units of measurement to select when adding a new
measurement
:return:
"""
return self._units_of_measurement_model
@pyqtProperty(FramListModel, notify=measurementsUomModelChanged)
def measurementsUnitsOfMeasurementModel(self):
"""
Method to return the self._measurements_uom_model that is used by the
SensorDataFeeds.qml cbMeasurement combobox
that lists out the measurements + units of measurement to
select when adding a new matching item
:return:
"""
return self._measurements_uom_model
@pyqtProperty(FramListModel, notify=equipmentModelChanged)
def equipmentModel(self):
"""
Method to return the self._equipment_model that is used by the
SensorDataFeeds.qml AddComportDialog.qml lvEquipment listview
that lists out the equipment from which to select when adding a new
com port
:return:
"""
return self._equipment_model
@pyqtProperty(FramListModel, notify=comportModelChanged)
def comportModel(self):
"""
Method to return the self._comport_model that is used by the
SensorDataFeeds.qml AddComportDialog.qml tvComport tableview
that lists out the comports from which to select when adding a new
com port
:return:
"""
return self._comport_model
@pyqtProperty(FramListModel, notify=sensorConfigurationModelChanged)
def sensorConfigurationModel(self):
"""
Method to return the self._sensor_configuration_model that is used by the
SensorDataFeeds.qml tvSensorConfiguration tableview
that lists out the equipment / comport / moxaport settings and is the primary
tableview for the operations views
:return:
"""
return self._sensor_configuration_model
@pyqtProperty(FramListModel, notify=testSentencesModelChanged)
def testSentencesModel(self):
"""
Method to return the self._test_sentences_model that is used by the
SensorDataFeeds.qml tvTestSentences tableview
that lists out raw sentence data in the Testing mode
:return:
"""
return self._test_sentences_model
@pyqtProperty(FramListModel, notify=rawSentencesModelChanged)
def rawSentencesModel(self):
"""
Method to return the self._raw_sentences_model that is used by the
SensorDataFeeds.qml tvRawSentences tableview
that lists out raw sentence data in the Testing and Operations modes
:return:
"""
return self._raw_sentences_model
@pyqtProperty(FramListModel, notify=parsedSentencesModelChanged)
def parsedSentencesModel(self):
"""
Method to return the self._parsed_sentences_model that is used by the
SensorDataFeeds.qml tvParsedSentences tableview
that lists out parsed sentence data in the Measurement mode
:return:
"""
return self._parsed_sentences_model
@pyqtProperty(FramListModel, notify=errorMessagesModelChanged)
def errorMessagesModel(self):
"""
Method to return the self._error_messages_model that is used by the
SensorDataFeeds.qml tvErrorMessages tableview
that lists out serial port exceptions
:return:
"""
return self._error_messages_model
@pyqtProperty(FramListModel, notify=measurementConfigurationModelChanged)
def measurementConfigurationModel(self):
"""
Return the self._measurement_configuration_model for use in
SensorDataFeeds.qml
:return:
"""
return self._measurement_configuration_model
|
StarcoderdataPython
|
4991864
|
"""Visualize various data collected from given query session."""
import pdb
import os
import time
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
def save_data(
data: list, labels: list, num_runs: int, directory: str, filename: str
) -> None:
"""Save data to file in directory."""
agents = labels
data_stack = np.stack(data, axis=1)
tasks = [i for i in range(data_stack.shape[0])]
runs = [i for i in range(num_runs)]
test_states = [i for i in range(data_stack.shape[3])]
queries = [i for i in range(data_stack.shape[-1])]
index = pd.MultiIndex.from_product(
[tasks, agents, runs, test_states], #queries, test_states],
names=["task", "agent", "run", "test state"], #"query", "test state"],
)
path = Path(directory)
if not path.exists():
path.mkdir(parents=True)
df = pd.DataFrame(data_stack.reshape(-1, data_stack.shape[-1]), index=index)
df.to_csv(directory + "/" + filename)
def og_plot_results(results, labels, dir_name, filename):
colors = ["r", "b", "g", "c", "m", "y", "k"]
task_mat = np.stack(results, axis=1)
file_path = os.path.realpath(__file__)
output_dir = os.path.dirname(file_path) + "/" + dir_name + "/"
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# For each task:
for t in range(task_mat.shape[0]):
# For each agent:
for a in range(task_mat.shape[1]):
# Get the #query-by-#(runs*tests) matrix:
series = np.transpose(task_mat[t, a])
label = labels[a]
x = [i + 1 + (0.05 * a) for i in range(series.shape[0])]
# Get the median across each query's runs*tests:
med = np.median(series, axis=1)
# Define error as
err = abs(np.percentile(series, (25, 75), axis=1) - med)
plt.errorbar(
x,
med,
fmt=".-",
yerr=err,
color=colors[a % len(colors)],
label=label,
)
def plot_performance_distance_matrices(
directory: str = None, file: str = None
) -> None:
"""See reward and distance-from-ground-truth over subsequent queries."""
if directory is not None:
file_path = Path(directory + "/" + file)
if not file_path.exists():
print(f"The path {file_path} doesn't exist.")
return
else:
df = pd.read_csv(file_path)
else:
print(
"Need to provide a path to the directory and the pertinent "
"file's name."
)
agents = list(df.index.levels[1])
tasks = list(df.index.levels[0])
fig = go.Figure()
for agent in agents:
b = df.loc[agent].reset_index()
for t in tasks:
fig.add_trace(go.Box(x=b["query"], y=b[t]))
fig.show()
#if __name__ == "__main__":
# plot_performance_distance_matrices(
# labels="inquire_agent",
# directory="output",
# file="05:03:22:03:52_performance_data_linear_system.csv",
# )
|
StarcoderdataPython
|
4957123
|
from scripts.make_test_data import main as make_test_data
from scripts.set_version import main as set_version
|
StarcoderdataPython
|
5171931
|
<gh_stars>1-10
import base64
import csv
import glob
import os
import subprocess
import requests
from typing import List, Any, Optional
from pathlib import Path
def say(text, debug=False):
if debug or True:
print(text)
process = subprocess.Popen(
['say', '-v', 'Samantha', text],
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
def b64_decode(string):
bytes_ = bytes(string, 'utf-8')
return base64.decodestring(bytes_).decode('utf-8').rstrip()
def safe_make_dir(dir: str) -> None:
Path(dir).mkdir(parents=True, exist_ok=True)
def list_files(dir: str, pattern: str) -> None:
glob_pattern = os.path.join(dir, pattern)
yield from glob.iglob(glob_pattern)
def write_to_csv(tuples: List[Any], filepath: str, headers: Optional[List[Any]] = None) -> None:
with open(filepath,'w') as fp:
csv_writer = csv.writer(fp)
if headers:
csv_writer.writerow(headers)
csv_writer.writerows(tuples)
def send_email(receipient, subject, body):
GOOGLE_APP_SCRIPT_ID = os.environ.get('EMAIL_SERVICE_GOOGLE_APP_SCRIPT_APP_ID')
EMAIL_SERVICE_URI = f'https://script.google.com/macros/s/{GOOGLE_APP_SCRIPT_ID}/exec'
SECRET = os.environ.get('EMAIL_SERVICE_GOOGLE_APP_SCRIPT_SECRET')
r = requests.post(
EMAIL_SERVICE_URI,
data={
'secret': SECRET,
'receipient': receipient,
'subject': subject,
'body': body,
}
)
if r.status_code != 200:
print(f'ERROR: {r.content}')
|
StarcoderdataPython
|
4934891
|
# -*- coding: utf-8 -*-
"""
File name: quad_mdl.py
Author: <NAME>
Created: June 2019
Description: A fault model of a multi-rotor drone.
"""
import numpy as np
from fmdtools.modeldef import *
#Define specialized flows
class Direc(Flow):
def __init__(self):
self.traj=[0,0,0]
super().__init__({'x': self.traj[0], 'y': self.traj[1], 'z': self.traj[2], 'power': 1}, 'Trajectory')
def assign(self, traj):
self.x, self.y, self.z = traj[0], traj[1], traj[2]
self.traj=traj
def status(self):
status={'x': self.traj[0], 'y': self.traj[1], 'z': self.traj[2], 'power': self.power}
return status.copy()
#Define functions
class StoreEE(FxnBlock):
def __init__(self, flows, params):
self.archtype=params['bat']
#weight, cap, voltage, drag_factor
if self.archtype == 'monolithic':
self.batparams ={'s':1,'p':1,'w':params['weight'],'v':12,'d':params['drag']}
components = {'S1P1': Battery('S1P1', self.batparams)}
elif self.archtype =='series-split':
self.batparams ={'s':2,'p':1,'w':params['weight'],'v':12,'d':params['drag']}
components = {'S1P1': Battery('S1P1', self.batparams), 'S2P1': Battery('S2P1', self.batparams)}
elif self.archtype == 'parallel-split':
self.batparams ={'s':1,'p':2,'w':params['weight'],'v':12,'d':params['drag']}
components = {'S1P1': Battery('S1P1', self.batparams),'S1P2': Battery('S1P2', self.batparams)}
elif self.archtype == 'split-both':
self.batparams ={'s':2,'p':2,'w':params['weight'],'v':12,'d':params['drag']}
components = {'S1P1': Battery('S1P1', self.batparams), 'S2P1': Battery('S2P1', self.batparams),'S1P2': Battery('S1P2', self.batparams), 'S2P2': Battery('S2P2', self.batparams)}
else: raise Exception("Invalid battery architecture")
#failrate for function w- component only applies to function modes
self.failrate=1e-4
self.assoc_modes({'nocharge':[0.2,[0.6,0.2,0.2],0],'lowcharge':[0.7,[0.6,0.2,0.2],0]})
super().__init__(['EEout', 'FS', 'HSig'], flows, {'soc': 100}, components)
def condfaults(self, time):
if self.soc<20: self.add_fault('lowcharge')
elif self.has_fault('lowcharge'):
for batname, bat in self.components.items(): bat.soc=19
if self.soc<1: self.replace_fault('lowcharge','nocharge')
elif self.has_fault('nocharge'):
for batname, bat in self.components.items(): bat.soc=0
def behavior(self, time):
EE, soc = {}, {}
rate_res=0
for batname, bat in self.components.items():
EE[bat.name], soc[bat.name], rate_res = bat.behavior(self.FS.support, self.EEout.rate/(self.batparams['s']*self.batparams['p'])+rate_res, time)
#need to incorporate max current draw somehow + draw when reconfigured
if self.archtype == 'monolithic': self.EEout.effort = EE['S1P1']
elif self.archtype == 'series-split': self.EEout.effort = np.max(list(EE.values()))
elif self.archtype == 'parallel-split': self.EEout.effort = np.sum(list(EE.values()))
elif self.archtype == 'split-both':
e=list(EE.values())
e.sort()
self.EEout.effort = e[-1]+e[-2]
self.soc=np.mean(list(soc.values()))
if self.any_faults(): self.HSig.hstate = 'faulty'
else: self.HSig.hstate = 'nominal'
class Battery(Component):
def __init__(self, name, batparams):
super().__init__(name, {'soc':100, 'EEe':1.0, 'Et':1.0})
self.failrate=1e-4
self.avail_eff = 1/batparams['p']
self.maxa = 2/batparams['s']
self.p=batparams['p']
self.s=batparams['s']
self.amt = 60*4.200/(batparams['w']*170/(batparams['d']*batparams['v']))
self.assoc_modes({'short':[0.2,[0.3,0.3,0.3],100], 'degr':[0.2,[0.3,0.3,0.3],100],
'break':[0.2,[0.2,0.2,0.2],100], 'nocharge':[0.6,[0.6,0.2,0.2],100],
'lowcharge':[0,[0.6,0.2,0.2],100]}, name=name)
def behavior(self, FS, EEoutr, time):
if FS <1.0: self.add_fault(self.name+'break')
if EEoutr>self.maxa: self.add_fault(self.name+'break')
if self.soc<20: self.add_fault(self.name+'lowcharge')
if self.soc<1: self.replace_fault(self.name+'lowcharge',self.name+'nocharge')
Et=1.0 #default
if self.has_fault(self.name+'short'): Et=0.0
elif self.has_fault(self.name+'break'): Et=0.0
elif self.has_fault(self.name+'degr'): Et=0.5
self.Et = Et*self.avail_eff
Er_res=0.0
if time > self.time:
self.soc=self.soc-100*EEoutr*self.p*self.s*(time-self.time)/self.amt
self.time=time
if self.has_fault(self.name+'nocharge'): self.soc, self.Et, Er_res = 0.0,0.0, EEoutr
return self.Et, self.soc, Er_res
class DistEE(FxnBlock):
def __init__(self,flows):
super().__init__(['EEin','EEmot','EEctl','ST'],flows, {'EEtr':1.0, 'EEte':1.0}, timely=False)
self.failrate=1e-5
self.assoc_modes({'short':[0.3,[0.33, 0.33, 0.33],300], 'degr':[0.5,[0.33, 0.33, 0.33],100],\
'break':[0.2,[0.33, 0.33, 0.33],200]})
def condfaults(self, time):
if self.ST.support<0.5 or max(self.EEmot.rate,self.EEctl.rate)>2: self.add_fault('break')
if self.EEin.rate>2: self.add_fault('short')
def behavior(self, time):
if self.has_fault('short'): self.EEte, self.EEre = 0.0,10.0
elif self.has_fault('break'): self.EEte, self.EEre = 0.0,0.0
elif self.has_fault('degr'): self.EEte=0.5
self.EEmot.effort=self.EEte*self.EEin.effort
self.EEctl.effort=self.EEte*self.EEin.effort
self.EEin.rate=m2to1([ self.EEin.effort, self.EEtr, 0.99*self.EEmot.rate+0.01*self.EEctl.rate])
class HoldPayload(FxnBlock):
def __init__(self,flows):
super().__init__(['DOF', 'Lin', 'ST'],flows, timely=False, states={'Force_GR':1.0})
self.failrate=1e-6
self.assoc_modes({'break':[0.2, [0.33, 0.33, 0.33], 1000], 'deform':[0.8, [0.33, 0.33, 0.33], 1000]})
def condfaults(self, time):
if self.DOF.elev<=0.0: self.Force_GR=min(-0.5, (self.DOF.vertvel/60-self.DOF.planvel/60)/7.5)
else: self.Force_GR=0.0
if abs(self.Force_GR/2)>0.8: self.add_fault('break')
elif abs(self.Force_GR/2)>1.0: self.add_fault('deform')
def behavior(self, time):
#need to transfer FG to FA & FS???
if self.has_fault('break'): self.Lin.support, self.ST.support = 0,0
elif self.has_fault('deform'): self.Lin.support, self.ST.support = 0.5,0.5
else: self.Lin.support, self.ST.support = 1.0,1.0
class ManageHealth(FxnBlock):
def __init__(self,flows,respolicy):
self.respolicy = respolicy
flownames=['EECtl','FS','DOFshealth', 'Bathealth', 'Trajconfig' ]
super().__init__(flownames, flows)
self.failrate=1e-6 #{'falsemaintenance':[0.8,[1.0, 0.0,0.0,0.0,0.0],1000],\
self.assoc_modes({'falsemasking':[0.1,[1.0, 0.2,0.4,0.4,0.0],1000],\
'falseemland':[0.05,[0.0, 0.2,0.4,0.4,0.0],1000],\
'lostfunction':[0.05,[0.2, 0.2,0.2,0.2,0.2],1000]})
def condfaults(self, time):
if self.FS.support<0.5 or self.EECtl.effort>2.0: self.add_fault('lostfunction')
def behavior(self, time):
if self.has_fault('lostfunction'): self.Trajconfig.mode = 'continue'
elif self.DOFshealth.hstate=='faulty': self.Trajconfig.mode = self.respolicy['line']
elif self.Bathealth.hstate=='faulty': self.Trajconfig.mode = self.respolicy['bat']
else: self.Trajconfig.mode = 'continue'
# trajconfig: continue, to_home, to_nearest, emland
class AffectDOF(FxnBlock): #EEmot,Ctl1,DOFs,Force_Lin HSig_DOFs, RSig_DOFs
def __init__(self, flows, archtype):
self.archtype=archtype
if archtype=='quad':
components={'RF':Line('RF'), 'LF':Line('LF'), 'LR':Line('LR'), 'RR':Line('RR')}
self.upward={'RF':1,'LF':1,'LR':1,'RR':1}
self.forward={'RF':0.5,'LF':0.5,'LR':-0.5,'RR':-0.5}
self.LR = {'L':{'LF', 'LR'}, 'R':{'RF','RR'}}
self.FR = {'F':{'LF', 'RF'}, 'R':{'LR', 'RR'}}
elif archtype=='hex':
components={'RF':Line('RF'), 'LF':Line('LF'), 'LR':Line('LR'), 'RR':Line('RR'),'R':Line('R'), 'F':Line('F')}
self.upward={'RF':1,'LF':1,'LR':1,'RR':1,'R':1,'F':1}
self.forward={'RF':0.5,'LF':0.5,'LR':-0.5,'RR':-0.5, 'R':-0.75, 'F':0.75}
self.LR = {'L':{'LF', 'LR'}, 'R':{'RF','RR'}}
self.FR = {'F':{'LF', 'RF', 'F'}, 'R':{'LR', 'RR', 'R'}}
elif archtype=='oct':
components={'RF':Line('RF'), 'LF':Line('LF'), 'LR':Line('LR'), 'RR':Line('RR'),'RF2':Line('RF2'), 'LF2':Line('LF2'), 'LR2':Line('LR2'), 'RR2':Line('RR2')}
self.upward={'RF':1,'LF':1,'LR':1,'RR':1,'RF2':1,'LF2':1,'LR2':1,'RR2':1}
self.forward={'RF':0.5,'LF':0.5,'LR':-0.5,'RR':-0.5,'RF2':0.5,'LF2':0.5,'LR2':-0.5,'RR2':-0.5}
self.LR = {'L':{'LF', 'LR','LF2', 'LR2'}, 'R':{'RF','RR','RF2','RR2'}}
self.FR = {'F':{'LF', 'RF','LF2', 'RF2'}, 'R':{'LR', 'RR','LR2', 'RR2'}}
super().__init__(['EEin', 'Ctlin','DOF','Dir','Force','HSig'], flows,{'LRstab':0.0, 'FRstab':0.0}, components)
def behavior(self, time):
Air,EEin={},{}
#injects faults into lines
for linname,lin in self.components.items():
cmds={'up':self.upward[linname], 'for':self.forward[linname]}
lin.behavior(self.EEin.effort, self.Ctlin, cmds, self.Force.support)
Air[lin.name]=lin.Airout
EEin[lin.name]=lin.EE_in
if any(value>=10 for value in EEin.values()): self.EEin.rate=10
elif any(value!=0.0 for value in EEin.values()): self.EEin.rate=sum(EEin.values())/len(EEin) #should it really be max?
else: self.EEin.rate=0.0
self.LRstab = (sum([Air[comp] for comp in self.LR['L']])-sum([Air[comp] for comp in self.LR['R']]))/len(Air)
self.FRstab = (sum([Air[comp] for comp in self.FR['R']])-sum([Air[comp] for comp in self.FR['F']]))/len(Air)
if abs(self.LRstab) >=0.25 or abs(self.FRstab)>=0.75: self.DOF.uppwr, self.DOF.planpwr = 0.0, 0.0
else:
Airs=list(Air.values())
self.DOF.uppwr=np.mean(Airs)
self.DOF.planpwr=self.Ctlin.forward
if self.any_faults(): self.HSig.hstate='faulty'
if time> self.time:
if self.DOF.uppwr > 1.0: self.DOF.vertvel = 60*min([(self.DOF.uppwr-1)*5, 5])
elif self.DOF.uppwr < 1.0: self.DOF.vertvel = 60*max([(self.DOF.uppwr-1)*5, -5])
else: self.DOF.vertvel = 0.0
if self.DOF.elev<=0.0:
self.DOF.vertvel=max(0,self.DOF.vertvel)
self.DOF.planvel=0.0
if self.DOF.vertvel<-self.DOF.elev:
reqdist = np.sqrt(self.Dir.x**2 + self.Dir.y**2+0.0001)
if self.DOF.planpwr>0.0:
maxdist = 600 * self.DOF.elev/(-self.DOF.vertvel+0.001)
if reqdist > maxdist: self.planvel = maxdist
else: self.planvel = reqdist
else: self.planvel = 0.1
self.DOF.x=self.DOF.x+self.planvel*self.Dir.traj[0]/reqdist
self.DOF.y=self.DOF.y+self.planvel*self.Dir.traj[1]/reqdist
self.DOF.elev=0.0
else:
self.DOF.planvel=60*min([10*self.DOF.planpwr, 10]) # 600 m/m = 23 mph
vect = np.sqrt(np.power(self.Dir.traj[0], 2)+ np.power(self.Dir.traj[1], 2))+0.001
self.DOF.x=self.DOF.x+self.DOF.planvel*self.Dir.traj[0]/vect
self.DOF.y=self.DOF.y+self.DOF.planvel*self.Dir.traj[1]/vect
self.DOF.elev=self.DOF.elev + self.DOF.vertvel
class Line(Component):
def __init__(self, name):
super().__init__(name,{'Eto': 1.0, 'Eti':1.0, 'Ct':1.0, 'Mt':1.0, 'Pt':1.0}, timely=False)
self.failrate=1e-5
self.assoc_modes({'short':[0.1, [0.33, 0.33, 0.33], 200],'openc':[0.1, [0.33, 0.33, 0.33], 200],\
'ctlbreak':[0.2, [0.33, 0.33, 0.33], 100], 'mechbreak':[0.1, [0.33, 0.33, 0.33], 500],\
'mechfriction':[0.05, [0.0, 0.5,0.5], 500], 'stuck':[0.02, [0.0, 0.5,0.5], 200]},name=name)
def behavior(self, EEin, Ctlin, cmds, Force):
if Force<=0.0: self.add_fault(self.name+'mechbreak')
elif Force<=0.5: self.add_fault(self.name+'mechfriction')
if self.has_fault(self.name+'short'): self.Eti, self.Eto = 0.0, np.inf
elif self.has_fault(self.name+'openc'): self.Eti, self.Eto =0.0, 0.0
elif Ctlin.upward==0 and Ctlin.forward == 0: self.Eto = 0.0
if self.has_fault(self.name+'ctlbreak'): self.Ct=0.0
if self.has_fault(self.name+'mechbreak'): self.Mt=0.0
elif self.has_fault(self.name+'mechfriction'): self.Mt, self.Eti = 0.5, 2.0
if self.has_fault(self.name+'stuck'): self.Pt, self.Mt, self.Eti = 0.0, 0.0, 4.0
self.Airout=m2to1([EEin,self.Eti,Ctlin.upward*cmds['up']+Ctlin.forward*cmds['for'],self.Ct,self.Mt,self.Pt])
self.EE_in=m2to1([EEin,self.Eto])
class CtlDOF(FxnBlock):
def __init__(self, flows):
super().__init__(['EEin','Dir','Ctl','DOFs','FS'],flows, {'vel':0.0, 'Cs':1.0})
self.failrate=1e-5
self.assoc_modes({'noctl':[0.2, [0.6, 0.3, 0.1], 1000], 'degctl':[0.8, [0.6, 0.3, 0.1], 1000]})
def condfaults(self, time):
if self.FS.support<0.5: self.add_fault('noctl')
def behavior(self, time):
if self.has_fault('noctl'): self.Cs=0.0
elif self.has_fault('degctl'): self.Cs=0.5
if time>self.time: self.vel=self.DOFs.vertvel
# throttle settings: 0 is off (-50 m/s), 1 is hover, 2 is max climb (5 m/s)
if self.Dir.traj[2]>0: upthrottle = 1+np.min([self.Dir.traj[2]/(50*5), 1])
elif self.Dir.traj[2] <0: upthrottle = 1+np.max([self.Dir.traj[2]/(50*5), -1])
else: upthrottle = 1.0
vect = np.sqrt(np.power(self.Dir.traj[0], 2)+ np.power(self.Dir.traj[1], 2))+0.001
forwardthrottle = np.min([vect/(60*10), 1])
self.Ctl.forward=self.EEin.effort*self.Cs*forwardthrottle*self.Dir.power
self.Ctl.upward=self.EEin.effort*self.Cs*upthrottle*self.Dir.power
class PlanPath(FxnBlock):
def __init__(self, flows, params):
super().__init__(['EEin','Env','Dir','FS','Rsig'], flows, states={'dx':0.0, 'dy':0.0, 'dz':0.0, 'pt':1, 'mode':'taxi'})
self.nearest = params['safe'][0:2]+[0]
self.goals = params['flightplan']
self.goal=self.goals[1]
self.failrate=1e-5
self.assoc_modes({'noloc':[0.2, [0.6, 0.3, 0.1], 1000], 'degloc':[0.8, [0.6, 0.3, 0.1], 1000]})
def condfaults(self, time):
if self.FS.support<0.5: self.add_fault('noloc')
def behavior(self, t):
loc = [self.Env.x, self.Env.y, self.Env.elev]
if self.pt <= max(self.goals): self.goal = self.goals[self.pt]
dist = finddist(loc, self.goal)
[self.dx,self.dy, self.dz] = vectdist(self.goal,loc)
if self.mode=='taxi' and t>5: self.mode=='taxi'
elif self.Rsig.mode == 'to_home': # add a to_nearest option
self.pt = 0
self.goal =self.goals[self.pt]
[self.dx,self.dy, self.dz] = vectdist(self.goal,loc)
elif self.Rsig.mode == 'to_nearest': self.mode = 'to_nearest'
elif self.Rsig.mode== 'emland': self.mode = 'land'
elif self.Env.elev<1 and (self.pt>=max(self.goals) or self.mode=='land'): self.mode = 'taxi'
elif dist<10 and self.pt>=max(self.goals): self.mode = 'land'
elif dist<10 and {'move'}.issuperset({self.mode}):
if self.pt < max(self.goals):
self.pt+=1
self.goal = self.goals[self.pt]
elif dist>5 and not(self.mode=='descend'): self.mode='move'
# nominal behaviors
self.Dir.power=1.0
if self.mode=='taxi': self.Dir.power=0.0
elif self.mode=='move': self.Dir.assign([self.dx,self.dy, self.dz])
elif self.mode=='land': self.Dir.assign([0,0,-self.Env.elev/2])
elif self.mode =='to_nearest': self.Dir.assign(vectdist(self.nearest,loc))
# faulty behaviors
if self.has_fault('noloc'): self.Dir.assign([0,0,0])
elif self.has_fault('degloc'): self.Dir.assign([0,0,-1])
if self.EEin.effort<0.5:
self.Dir.power=0.0
self.Dir.assign([0,0,0])
class Drone(Model):
def __init__(self, params={'flightplan':{1:[0,0,100], 2:[100, 0,100], 3:[100, 100,100], 4:[150, 150,100], 5:[0,0,100], 6:[0,0,0]},'bat':'monolithic', 'linearch':'quad','respolicy':{'bat':'to_home','line':'emland'},
'start': [0.0,0.0, 10, 10], 'target': [0, 150, 160, 160], 'safe': [0, 50, 10, 10], 'loc':'rural', 'landtime':12}):
super().__init__()
super().__init__(modelparams={'phases': {'ascend':[0,1],'forward':[1,params['landtime']],'taxis':[params['landtime'], 20]},
'times':[0,30],'units':'min'}, params=params)
self.start_area = square(self.params['start'][0:2],self.params['start'][2],self.params['start'][3] )
self.safe_area = square(self.params['safe'][0:2],self.params['safe'][2],self.params['safe'][3] )
self.target_area = square(self.params['target'][0:2],self.params['target'][2],self.params['target'][3] )
#add flows to the model
self.add_flow('Force_ST', {'support':1.0})
self.add_flow('Force_Lin', {'support':1.0} )
self.add_flow('HSig_DOFs', {'hstate':'nominal', 'config':1.0})
self.add_flow('HSig_Bat', {'hstate':'nominal', 'config':1.0} )
self.add_flow('RSig_Traj', {'mode':'continue'})
self.add_flow('EE_1', {'rate':1.0, 'effort':1.0})
self.add_flow('EEmot', {'rate':1.0, 'effort':1.0})
self.add_flow('EEctl', {'rate':1.0, 'effort':1.0})
self.add_flow('Ctl1', {'forward':0.0, 'upward':1.0})
self.add_flow('DOFs', {'vertvel':0.0, 'planvel':0.0, 'planpwr':0.0, 'uppwr':0.0, 'x':0.0,'y':0.0,'elev':0.0})
# custom flows
self.add_flow('Dir1', Direc())
#add functions to the model
flows=['EEctl', 'Force_ST', 'HSig_DOFs', 'HSig_Bat', 'RSig_Traj']
# trajconfig: continue, to_home, to_nearest, emland
self.add_fxn('ManageHealth',flows,fclass = ManageHealth, fparams=params['respolicy'])
batweight = {'monolithic':0.4, 'series-split':0.5, 'parallel-split':0.5, 'split-both':0.6}[params['bat']]
archweight = {'quad':1.2, 'hex':1.6, 'oct':2.0}[params['linearch']]
archdrag = {'quad':0.95, 'hex':0.85, 'oct':0.75}[params['linearch']]
self.add_fxn('StoreEE',['EE_1', 'Force_ST', 'HSig_Bat'],fclass = StoreEE, fparams= {'bat': params['bat'], 'weight':(batweight+archweight)/2.2 , 'drag': archdrag })
self.add_fxn('DistEE', ['EE_1','EEmot','EEctl', 'Force_ST'], fclass = DistEE)
self.add_fxn('AffectDOF',['EEmot','Ctl1','DOFs','Dir1','Force_Lin', 'HSig_DOFs'], fclass=AffectDOF, fparams = params['linearch'])
self.add_fxn('CtlDOF',['EEctl', 'Dir1', 'Ctl1', 'DOFs', 'Force_ST'], fclass = CtlDOF)
self.add_fxn('Planpath', ['EEctl', 'DOFs','Dir1', 'Force_ST', 'RSig_Traj'], fclass=PlanPath, fparams=params)
self.add_fxn('HoldPayload',['DOFs', 'Force_Lin', 'Force_ST'], fclass = HoldPayload)
pos = {'ManageHealth': [0.23793980988102348, 1.0551602632416588],
'StoreEE': [-0.9665780995752296, -0.4931538151692423],
'DistEE': [-0.1858834234148632, -0.20479989209711924],
'AffectDOF': [1.0334916329507422, 0.6317263653616103],
'CtlDOF': [0.1835014208949617, 0.32084893189175423],
'Planpath': [-0.7427736219526058, 0.8569475547950892],
'HoldPayload': [0.74072970715511, -0.7305391093272489]}
bippos = {'ManageHealth': [-0.23403572483176666, 0.8119063670455383],
'StoreEE': [-0.7099736148158298, 0.2981652748232978],
'DistEE': [-0.28748133634190726, 0.32563569654296287],
'AffectDOF': [0.9073412427515959, 0.0466423266443633],
'CtlDOF': [0.498663257339388, 0.44284186573420836],
'Planpath': [0.5353654708147643, 0.7413936186204868],
'HoldPayload': [0.329334798653681, -0.17443414674339652],
'Force_ST': [-0.2364754675127569, -0.18801548176633154],
'Force_Lin': [0.7206415618571647, -0.17552020772024013],
'HSig_DOFs': [0.3209028709788254, 0.04984245810974697],
'HSig_Bat': [-0.6358884586093769, 0.7311076416371343],
'RSig_Traj': [0.18430501738656657, 0.856472541655958],
'EE_1': [-0.48288657418004555, 0.3017533207866233],
'EEmot': [-0.0330582435936827, 0.2878069006385988],
'EEctl': [0.13195069534343862, 0.4818116953414546],
'Ctl1': [0.5682663453757308, 0.23385244312813386],
'DOFs': [0.8194232270836169, 0.3883256382522293],
'Dir1': [0.9276094920710914, 0.6064107724557304]}
self.construct_graph(graph_pos=pos, bipartite_pos=bippos)
def find_classification(self, g, endfaults, endflows, scen, mdlhist):
#landing costs
viewed = env_viewed(mdlhist['faulty']['flows']['DOFs']['x'], mdlhist['faulty']['flows']['DOFs']['y'],mdlhist['faulty']['flows']['DOFs']['elev'], self.target_area)
viewed_value = sum([0.5+2*view for k,view in viewed.items() if view!='unviewed'])
fhist=mdlhist['faulty']
faulttime = sum([any([fhist['functions'][f]['faults'][t]!={'nom'} for f in fhist['functions']]) for t in range(len(fhist['time'])) if fhist['flows']['DOFs']['elev'][t]])
Env=self.flows['DOFs']
if inrange(self.start_area, Env.x, Env.y): landloc = 'nominal' # nominal landing
elif inrange(self.safe_area, Env.x, Env.y): landloc = 'designated' # emergency safe
elif inrange(self.target_area, Env.x, Env.y): landloc = 'over target' # emergency dangerous
else: landloc = 'outside target' # emergency unsanctioned
# need a way to differentiate horizontal and vertical crashes/landings
if self.params['loc'] == 'rural': #assumed photographing a field
if landloc == 'over target':
body_strikes = density_categories[self.params['loc']]['body strike']['horiz']
head_strikes = density_categories[self.params['loc']]['head strike']['horiz']
property_restrictions = 1
elif landloc == 'outside target':
body_strikes = density_categories[self.params['loc']]['body strike']['horiz']
head_strikes = density_categories[self.params['loc']]['head strike']['horiz']
property_restrictions = 1
else:
body_strikes = 0
head_strikes = 0
property_restrictions = 0
elif self.params['loc'] == 'congested': #assumed surveiling a crowd
if landloc == 'over target':
body_strikes = density_categories[self.params['loc']]['body strike']['horiz']
head_strikes = density_categories[self.params['loc']]['head strike']['horiz']
property_restrictions = 1
elif landloc == 'outside target':
body_strikes = density_categories['urban']['body strike']['horiz']
head_strikes = density_categories['urban']['head strike']['horiz']
property_restrictions = 1
else:
body_strikes = 0
head_strikes = 0
property_restrictions = 0
else: #assumes mixed public/private areas in urban, suburban, etc environment
if landloc == 'over target':
body_strikes = density_categories[self.params['loc']]['body strike']['horiz']
head_strikes = density_categories[self.params['loc']]['head strike']['horiz']
property_restrictions = 1
elif landloc == 'outside target':
body_strikes = density_categories[self.params['loc']]['body strike']['horiz']
head_strikes = density_categories[self.params['loc']]['head strike']['horiz']
property_restrictions = 1
else:
body_strikes = 0
head_strikes = 0
property_restrictions = 0
safecost = safety_categories['hazardous']['cost'] * (head_strikes + body_strikes) + unsafecost[self.params['loc']] * faulttime
landcost = property_restrictions*propertycost[self.params['loc']]
#repair costs
repcost=min(sum([ c['rcost'] for f,m in endfaults.items() for a, c in m.items()]), 1500)
rate=scen['properties']['rate']
p_safety = 1-np.exp(-(body_strikes+head_strikes) * 60/self.times[1]) #convert to pfh
classifications = {'hazardous':rate*p_safety, 'minor':rate*(1-p_safety)}
totcost=repcost+landcost+safecost-viewed_value
expcost=totcost*rate*1e5
return {'rate':rate, 'cost': totcost, 'expected cost': expcost, 'repcost':repcost, 'landcost':landcost,'safecost':safecost,'viewed value': viewed_value, 'viewed':viewed, 'landloc':landloc,'body strikes':body_strikes, 'head strikes':head_strikes, 'property restrictions': property_restrictions, 'severities':classifications, 'unsafe flight time':faulttime}
## BASE FUNCTIONS
# creates list of corner coordinates for a square, given a center, xwidth, and ywidth
def square(center,xw,yw):
square=[[center[0]-xw/2,center[1]-yw/2],\
[center[0]+xw/2,center[1]-yw/2], \
[center[0]+xw/2,center[1]+yw/2],\
[center[0]-xw/2,center[1]+yw/2]]
return square
def rect(x1, y1, x2, y2, width, height):
vec = vectdir([x1, y1,0], [x2,y2+0.00001,0])[0:2]
normvec = np.array([vec[1], -vec[0]])
rec = [[x1, y1]+normvec*width/2+vec*height/2,[x1, y1]-normvec*width/2+vec*height/2,[x2, y2]-normvec*width/2-vec*height/2,[x2, y2]+normvec*width/2-vec*height/2]
return rec
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
def inrange(area, x, y):
point=Point(x,y)
polygon=Polygon(area)
return polygon.contains(point)
def finddist(p1, p2):
return np.sqrt((p1[0]-p2[0])**2+(p1[1]-p2[1])**2+(p1[2]-p2[2])**2)
def calcdist(p1, p2):
return np.sqrt((p1[0]-p2.x)**2+(p1[1]-p2.y)**2+(p1[2]-p2.elev)**2)
def vectdist(p1, p2):
return [p1[0]-p2[0],p1[1]-p2[1],p1[2]-p2[2]]
def vectdir(p1, p2):
return vectdist(p1,p2)/(finddist(p1,p2)+0.0001)
import matplotlib.pyplot as plt
def env_viewed(xhist, yhist,zhist, square):
viewed = {(x,y):'unviewed' for x in range(int(square[0][0]),int(square[1][0])+10,10) for y in range(int(square[0][1]),int(square[2][1])+10,10)}
for i,x in enumerate(xhist[1:len(xhist)]):
w,h,d = viewable_area(zhist[i+1])
viewed_area = rect(xhist[i],yhist[i],xhist[i+1],yhist[i+1], w+5,h+5)
if abs(xhist[i]-xhist[i+1]) + abs(yhist[i]-yhist[i+1]) > 0.1 and w >0.01:
polygon=Polygon(viewed_area)
#plt.plot(*polygon.exterior.xy) (displays area to debug code)
#plt.plot([xhist[i],xhist[i+1]],[yhist[i],yhist[i+1]])
if not polygon.is_valid:
print('invalid points')
for spot in viewed:
if polygon.contains(Point(spot)):
viewed[spot]=d
return viewed
def viewable_area(elev):
width = elev
height = elev #* 0.75 # 4/3 camera with ~45 mm lens st dist = width
detail = 1/(width*height+0.00001)
return width, height, detail
def plan_flight(elev, square, landing):
flightplan = {0:landing, 1: landing[0:2]+[elev]}
width, height, detail = viewable_area(elev)
# x,y, elev
startpt = [square[0][0]+width/2, square[0][1]+height/2, elev]
endpt = [square[1][0]-width/2, square[1][1]+height/2, elev]
num_rows = int(np.ceil((square[2][1]-square[0][1])/width))
leftpts = [[startpt[0] , startpt[1]+ r*width] for r in range(num_rows)]
rightpts = [[endpt[0], endpt[1]+ r*width] for r in range(num_rows)]
leftpts.sort(reverse=True)
rightpts.sort(reverse=True)
addpt = max(flightplan) + 1
numpts = 2*len(leftpts)
vec1 = leftpts
vec2 = rightpts
vec=[]
n=2
newplan = {}
while len(vec1+vec2+vec)>0:
newplan[n]=vec1.pop()+[elev]
n+=1
if len(vec1)< len(vec2) or n==0:
vec = vec2
vec2 = vec1
vec1 = vec
flightplan.update(newplan)
flightplan.update({max(flightplan)+1:flightplan[1], max(flightplan)+2:flightplan[0]})
return flightplan
# likelihood class schedule (pfh)
p_allowable = {'small airplane':{'no requirement':'na', 'probable':1e-3, 'remote':1e-4, 'extremely remote':1e-5, 'extremely improbable':1e-6},
'small helicopter':{'no requirement':'na', 'probable':1e-3, 'remote':1e-5, 'extremely remote':1e-7, 'extremely improbable':1e-9}}
# population schedule
density_categories = {'congested':{'density':0.006194, 'body strike':{'vert':0.1, 'horiz':0.73},'head strike':{'vert':0.0375,'horiz':0.0375}},
'urban':{'density':0.002973, 'body strike':{'vert':0.0004, 'horiz':0.0003},'head strike':{'vert':0.0002,'horiz':0.0002}},
'suburban':{'density':0.001042, 'body strike':{'vert':0.0001, 'horiz':0.0011},'head strike':{'vert':0.0001,'horiz':0.0001}},
'rural':{'density':0.0001042, 'body strike':{'vert':0.0000, 'horiz':0.0001},'head strike':{'vert':0.000,'horiz':0.000}},
'remote':{'density':1.931e-6, 'body strike':{'vert':0.0000, 'horiz':0.0000},'head strike':{'vert':0.000,'horiz':0.000}}}
unsafecost = {'congested': 1000,'urban': 100, 'suburban':25, 'rural':5, 'remote':1}
propertycost = {'congested': 100000,'urban': 10000, 'suburban':1000, 'rural':1000, 'remote':1000}
# safety class schedule
safety_categories = {'catastrophic':{'injuries':'multiple fatalities', 'safety margins':'na', 'crew workload': 'na', 'cost':2000000},
'hazardous':{'injuries':'single fatality and/or multiple serious injuries', 'safety margins':'large decrease', 'crew workload': 'compromises safety', 'cost':9600000},
'major': {'injuries':'non-serious injuries', 'safety margins':'significant decrease', 'crew workload': 'significant increase', 'cost':2428800},
'minor': {'injuries':'na', 'safety margins':'slight decrease', 'crew workload': 'slight increase', 'cost':28800},
'no effect': {'injuries':'na', 'safety margins':'na', 'crew workload': 'na','cost': 0}}
hazards = {'VH-1':'loss of control', 'VH-2':'fly-away / non-conformance', 'VH-3':'loss of communication', 'VH-4':'loss of navigation', 'VH-5':'unsuccessful landing',
'VH-6':'unintentional flight termination', 'VH-7':'collision'}
|
StarcoderdataPython
|
6648201
|
# Generated by Django 3.1.3 on 2020-11-29 20:04
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0021_auto_20201129_1954'),
]
operations = [
migrations.AddField(
model_name='hotel',
name='hotel_img',
field=models.ImageField(default='', upload_to=''),
),
migrations.AlterField(
model_name='reservation',
name='timestamp',
field=models.DateTimeField(default=datetime.datetime(2020, 11, 30, 1, 34, 27, 620747)),
),
]
|
StarcoderdataPython
|
4983436
|
<gh_stars>0
from common import *
from trezor.crypto import bip32, bip39
from trezor.utils import HashWriter
from apps.wallet.sign_tx.addresses import validate_full_path, validate_path_for_bitcoin_public_key
from apps.common.paths import HARDENED
from apps.common import coins
from apps.wallet.sign_tx.addresses import *
from apps.wallet.sign_tx.signing import *
from apps.wallet.sign_tx.writers import *
def node_derive(root, path):
node = root.clone()
node.derive_path(path)
return node
class TestAddress(unittest.TestCase):
# pylint: disable=C0301
def test_p2wpkh_in_p2sh_address(self):
coin = coins.by_name('Testnet')
address = address_p2wpkh_in_p2sh(
unhexlify('03a1af804ac108a8a51782198c2d034b28bf90c8803f5a53f76276fa69a4eae77f'),
coin
)
self.assertEqual(address, '2Mww8dCYPUpKHofjgcXcBCEGmniw9CoaiD2')
def test_p2wpkh_in_p2sh_node_derive_address(self):
coin = coins.by_name('Testnet')
seed = bip39.seed(' '.join(['all'] * 12), '')
root = bip32.from_seed(seed, 'secp256k1')
node = node_derive(root, [49 | 0x80000000, 1 | 0x80000000, 0 | 0x80000000, 1, 0])
address = address_p2wpkh_in_p2sh(node.public_key(), coin)
self.assertEqual(address, '2N1LGaGg836mqSQqiuUBLfcyGBhyZbremDX')
node = node_derive(root, [49 | 0x80000000, 1 | 0x80000000, 0 | 0x80000000, 1, 1])
address = address_p2wpkh_in_p2sh(node.public_key(), coin)
self.assertEqual(address, '2NFWLCJQBSpz1oUJwwLpX8ECifFWGznBVqs')
node = node_derive(root, [49 | 0x80000000, 1 | 0x80000000, 0 | 0x80000000, 0, 0])
address = address_p2wpkh_in_p2sh(node.public_key(), coin)
self.assertEqual(address, '2N4Q5FhU2497BryFfUgbqkAJE87aKHUhXMp')
def test_p2wpkh_address(self):
# test data from https://bc-2.jp/tools/bech32demo/index.html
coin = coins.by_name('Testnet')
address = address_p2wpkh(
unhexlify('0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),
coin
)
self.assertEqual(address, 'tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx')
def test_p2sh_address(self):
coin = coins.by_name('Testnet')
address = address_p2sh(
unhexlify('7a55d61848e77ca266e79a39bfc85c580a6426c9'),
coin
)
self.assertEqual(address, '2N4Q5FhU2497BryFfUgbqkAJE87aKHUhXMp')
def test_p2wsh_address(self):
coin = coins.by_name('Testnet')
# pubkey OP_CHECKSIG
script = unhexlify('210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798ac')
h = HashWriter(sha256())
write_bytes(h, script)
address = address_p2wsh(
h.get_digest(),
coin.bech32_prefix
)
self.assertEqual(address, 'tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7')
def test_p2wsh_in_p2sh_address(self):
coin = coins.by_name('Bitcoin')
# test data from Mastering Bitcoin
address = address_p2wsh_in_p2sh(
unhexlify('9592d601848d04b172905e0ddb0adde59f1590f1e553ffc81ddc4b0ed927dd73'),
coin
)
self.assertEqual(address, '3Dwz1MXhM6EfFoJChHCxh1jWHb8GQqRenG')
def test_multisig_address_p2sh(self):
# # test data from
# # http://www.soroushjp.com/2014/12/20/bitcoin-multisig-the-hard-way-understanding-raw-multisignature-bitcoin-transactions/
# # commented out because uncompressed public keys are not supported
# coin = coins.by_name('Bitcoin')
# pubkeys = [
# unhexlify('04a882d414e478039cd5b52a92ffb13dd5e6bd4515497439dffd691a0f12af9575fa349b5694ed3155b136f09e63975a1700c9f4d4df849323dac06cf3bd6458cd'),
# unhexlify('046ce31db9bdd543e72fe3039a1f1c047dab87037c36a669ff90e28da1848f640de68c2fe913d363a51154a0c62d7adea1b822d05035077418267b1a1379790187'),
# unhexlify('0411ffd36c70776538d079fbae117dc38effafb33304af83ce4894589747aee1ef992f63280567f52f5ba870678b4ab4ff6c8ea600bd217870a8b4f1f09f3a8e83'),
# ]
# address = address_multisig_p2sh(pubkeys, 2, coin.address_type_p2sh)
# self.assertEqual(address, '347N1Thc213QqfYCz3PZkjoJpNv5b14kBd')
coin = coins.by_name('Bitcoin')
pubkeys = [
unhexlify('<KEY>'),
unhexlify('02ff12471208c14bd580709cb2358d98975247d8765f92bc25eab3b2763ed605f8'),
]
address = address_multisig_p2sh(pubkeys, 2, coin)
self.assertEqual(address, '39bgKC7RFbpoCRbtD5KEdkYKtNyhpsNa3Z')
def test_multisig_address_p2wsh_in_p2sh(self):
# test data from
# https://bitcoin.stackexchange.com/questions/62656/generate-a-p2sh-p2wsh-address-and-spend-output-sent-to-it
coin = coins.by_name('Testnet')
pubkeys = [
unhexlify('020b020e27e49f049eac10010506499a84e1d59a500cd3680e9ded580df9a107b0'),
unhexlify('<KEY>'),
]
address = address_multisig_p2wsh_in_p2sh(pubkeys, 2, coin)
self.assertEqual(address, '2MsZ2fpGKUydzY62v6trPHR8eCx5JTy1Dpa')
# def test_multisig_address_p2wsh(self):
# todo couldn't find test data
def test_paths_btc(self):
incorrect_derivation_paths = [
([49 | HARDENED], InputScriptType.SPENDP2SHWITNESS), # invalid length
([49 | HARDENED, 0 | HARDENED, 0 | HARDENED, 0 | HARDENED, 0 | HARDENED], InputScriptType.SPENDP2SHWITNESS), # too many HARDENED
([49 | HARDENED, 0 | HARDENED], InputScriptType.SPENDP2SHWITNESS), # invalid length
([49 | HARDENED, 0 | HARDENED, 0 | HARDENED, 0, 0, 0], InputScriptType.SPENDP2SHWITNESS), # invalid length
([49 | HARDENED, 123 | HARDENED, 0 | HARDENED, 0, 0, 0], InputScriptType.SPENDP2SHWITNESS), # invalid slip44
([49 | HARDENED, 0 | HARDENED, 1000 | HARDENED, 0, 0], InputScriptType.SPENDP2SHWITNESS), # account too high
([49 | HARDENED, 0 | HARDENED, 1 | HARDENED, 2, 0], InputScriptType.SPENDP2SHWITNESS), # invalid y
([49 | HARDENED, 0 | HARDENED, 1 | HARDENED, 0, 10000000], InputScriptType.SPENDP2SHWITNESS), # address index too high
([84 | HARDENED, 0 | HARDENED, 1 | HARDENED, 0, 10000000], InputScriptType.SPENDWITNESS), # address index too high
([49 | HARDENED, 0 | HARDENED, 1 | HARDENED, 0, 0], InputScriptType.SPENDWITNESS), # invalid input type
([84 | HARDENED, 0 | HARDENED, 1 | HARDENED, 0, 0], InputScriptType.SPENDP2SHWITNESS), # invalid input type
([49 | HARDENED, 0 | HARDENED, 5 | HARDENED, 0, 10], InputScriptType.SPENDMULTISIG), # invalid input type
]
correct_derivation_paths = [
([44 | HARDENED, 0 | HARDENED, 0 | HARDENED, 0, 0], InputScriptType.SPENDADDRESS), # btc is segwit coin, but non-segwit paths are allowed as well
([44 | HARDENED, 0 | HARDENED, 0 | HARDENED, 0, 1], InputScriptType.SPENDADDRESS),
([44 | HARDENED, 0 | HARDENED, 0 | HARDENED, 1, 0], InputScriptType.SPENDADDRESS),
([49 | HARDENED, 0 | HARDENED, 0 | HARDENED, 0, 0], InputScriptType.SPENDP2SHWITNESS),
([49 | HARDENED, 0 | HARDENED, 0 | HARDENED, 1, 0], InputScriptType.SPENDP2SHWITNESS),
([49 | HARDENED, 0 | HARDENED, 0 | HARDENED, 0, 1123], InputScriptType.SPENDP2SHWITNESS),
([49 | HARDENED, 0 | HARDENED, 0 | HARDENED, 1, 44444], InputScriptType.SPENDP2SHWITNESS),
([49 | HARDENED, 0 | HARDENED, 5 | HARDENED, 0, 0], InputScriptType.SPENDP2SHWITNESS),
([84 | HARDENED, 0 | HARDENED, 0 | HARDENED, 0, 0], InputScriptType.SPENDWITNESS),
([84 | HARDENED, 0 | HARDENED, 5 | HARDENED, 0, 0], InputScriptType.SPENDWITNESS),
([84 | HARDENED, 0 | HARDENED, 5 | HARDENED, 0, 10], InputScriptType.SPENDWITNESS),
([48 | HARDENED, 0 | HARDENED, 5 | HARDENED, 0, 10], InputScriptType.SPENDMULTISIG),
]
coin = coins.by_shortcut('BTC')
for path, input_type in incorrect_derivation_paths:
self.assertFalse(validate_full_path(path, coin, input_type))
for path, input_type in correct_derivation_paths:
self.assertTrue(validate_full_path(path, coin, input_type))
self.assertTrue(validate_full_path([44 | HARDENED, 0 | HARDENED, 0 | HARDENED, 0, 0], coin, InputScriptType.SPENDADDRESS))
self.assertFalse(validate_full_path([44 | HARDENED, 0 | HARDENED, 0 | HARDENED, 0, 0], coin, InputScriptType.SPENDWITNESS))
self.assertTrue(validate_full_path([44 | HARDENED, 0 | HARDENED, 0 | HARDENED, 0, 0], coin, InputScriptType.SPENDWITNESS, validate_script_type=False))
def test_paths_bch(self):
incorrect_derivation_paths = [
([44 | HARDENED], InputScriptType.SPENDADDRESS), # invalid length
([44 | HARDENED, 145 | HARDENED, 0 | HARDENED, 0 | HARDENED, 0 | HARDENED], InputScriptType.SPENDADDRESS), # too many HARDENED
([49 | HARDENED, 145 | HARDENED, 0 | HARDENED, 0, 0], InputScriptType.SPENDP2SHWITNESS), # bch is not segwit coin so 49' is not allowed
([84 | HARDENED, 145 | HARDENED, 1 | HARDENED, 0, 1], InputScriptType.SPENDWITNESS), # and neither is 84'
([44 | HARDENED, 145 | HARDENED], InputScriptType.SPENDADDRESS), # invalid length
([44 | HARDENED, 145 | HARDENED, 0 | HARDENED, 0, 0, 0], InputScriptType.SPENDADDRESS), # invalid length
([44 | HARDENED, 123 | HARDENED, 0 | HARDENED, 0, 0, 0], InputScriptType.SPENDADDRESS), # invalid slip44
([44 | HARDENED, 145 | HARDENED, 1000 | HARDENED, 0, 0], InputScriptType.SPENDADDRESS), # account too high
([44 | HARDENED, 145 | HARDENED, 1 | HARDENED, 2, 0], InputScriptType.SPENDADDRESS), # invalid y
([44 | HARDENED, 145 | HARDENED, 1 | HARDENED, 0, 10000000], InputScriptType.SPENDADDRESS), # address index too high
([84 | HARDENED, 145 | HARDENED, 1 | HARDENED, 0, 10000000], InputScriptType.SPENDWITNESS), # address index too high
([44 | HARDENED, 145 | HARDENED, 0 | HARDENED, 0, 0], InputScriptType.SPENDWITNESS), # input type mismatch
]
correct_derivation_paths = [
([44 | HARDENED, 145 | HARDENED, 0 | HARDENED, 0, 0], InputScriptType.SPENDADDRESS),
([44 | HARDENED, 145 | HARDENED, 0 | HARDENED, 1, 0], InputScriptType.SPENDADDRESS),
([44 | HARDENED, 145 | HARDENED, 0 | HARDENED, 0, 1123], InputScriptType.SPENDADDRESS),
([44 | HARDENED, 145 | HARDENED, 0 | HARDENED, 1, 44444], InputScriptType.SPENDADDRESS),
([44 | HARDENED, 145 | HARDENED, 5 | HARDENED, 0, 0], InputScriptType.SPENDADDRESS),
([48 | HARDENED, 145 | HARDENED, 0 | HARDENED, 0, 0], InputScriptType.SPENDMULTISIG),
([48 | HARDENED, 145 | HARDENED, 5 | HARDENED, 0, 0], InputScriptType.SPENDMULTISIG),
([48 | HARDENED, 145 | HARDENED, 5 | HARDENED, 0, 10], InputScriptType.SPENDMULTISIG),
]
coin = coins.by_shortcut('BCH') # segwit is disabled
for path, input_type in incorrect_derivation_paths:
self.assertFalse(validate_full_path(path, coin, input_type))
for path, input_type in correct_derivation_paths:
self.assertTrue(validate_full_path(path, coin, input_type))
def test_paths_other(self):
incorrect_derivation_paths = [
([44 | HARDENED, 3 | HARDENED, 0 | HARDENED, 0, 0], InputScriptType.SPENDMULTISIG), # input type mismatch
]
correct_derivation_paths = [
([44 | HARDENED, 3 | HARDENED, 0 | HARDENED, 0, 0], InputScriptType.SPENDADDRESS),
([44 | HARDENED, 3 | HARDENED, 0 | HARDENED, 1, 0], InputScriptType.SPENDADDRESS),
([44 | HARDENED, 3 | HARDENED, 0 | HARDENED, 0, 1123], InputScriptType.SPENDADDRESS),
([44 | HARDENED, 3 | HARDENED, 0 | HARDENED, 1, 44444], InputScriptType.SPENDADDRESS),
]
coin = coins.by_shortcut('DOGE') # segwit is disabled
for path, input_type in correct_derivation_paths:
self.assertTrue(validate_full_path(path, coin, input_type))
for path, input_type in incorrect_derivation_paths:
self.assertFalse(validate_full_path(path, coin, input_type))
def test_paths_public_key(self):
incorrect_derivation_paths = [
[49 | HARDENED], # invalid length
[49 | HARDENED, 0 | HARDENED, 0 | HARDENED, 0 | HARDENED, 0 | HARDENED], # too many HARDENED
[49 | HARDENED, 0 | HARDENED], # invalid length
[49 | HARDENED, 0 | HARDENED, 0 | HARDENED, 0, 0, 0], # invalid length
[49 | HARDENED, 123 | HARDENED, 0 | HARDENED, 0, 0, 0], # invalid slip44
[49 | HARDENED, 0 | HARDENED, 1000 | HARDENED, 0, 0], # account too high
]
correct_derivation_paths = [
[44 | HARDENED, 0 | HARDENED, 0 | HARDENED], # btc is segwit coin, but non-segwit paths are allowed as well
[44 | HARDENED, 0 | HARDENED, 0 | HARDENED, 1, 0],
[49 | HARDENED, 0 | HARDENED, 0 | HARDENED, 0, 0],
[49 | HARDENED, 0 | HARDENED, 0 | HARDENED, 1, 0],
[49 | HARDENED, 0 | HARDENED, 5 | HARDENED],
[84 | HARDENED, 0 | HARDENED, 0 | HARDENED, 0, 0],
[84 | HARDENED, 0 | HARDENED, 5 | HARDENED, 0, 0],
[84 | HARDENED, 0 | HARDENED, 5 | HARDENED, 0, 10],
]
coin = coins.by_shortcut('BTC')
for path in correct_derivation_paths:
self.assertTrue(validate_path_for_bitcoin_public_key(path, coin))
for path in incorrect_derivation_paths:
self.assertFalse(validate_path_for_bitcoin_public_key(path, coin))
incorrect_derivation_paths = [
[49 | HARDENED, 3 | HARDENED, 0 | HARDENED, 0, 0], # no segwit
]
correct_derivation_paths = [
[44 | HARDENED, 3 | HARDENED, 0 | HARDENED],
[44 | HARDENED, 3 | HARDENED, 1 | HARDENED],
[44 | HARDENED, 3 | HARDENED, 0 | HARDENED, 0],
[44 | HARDENED, 3 | HARDENED, 0 | HARDENED, 0, 0],
]
coin = coins.by_shortcut('DOGE') # segwit is disabled
for path in correct_derivation_paths:
self.assertTrue(validate_path_for_bitcoin_public_key(path, coin))
for path in incorrect_derivation_paths:
self.assertFalse(validate_path_for_bitcoin_public_key(path, coin))
if __name__ == '__main__':
unittest.main()
|
StarcoderdataPython
|
6425428
|
from django.shortcuts import render, redirect
from firstapp.models import Article, Comment, Ticket, UserProfile
from firstapp.forms import CommentForm
from django.core.paginator import Paginator
from django.core.paginator import EmptyPage
from django.core.paginator import PageNotAnInteger
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth import login
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import User
# Create your views here.
def index(request):
article_list = Article.objects.all()
page_robot = Paginator(article_list, 5)
page_num = request.GET.get('page')
try:
article_list = page_robot.page(page_num)
except EmptyPage:
article_list = page_robot.page(page_robot.num_pages)
except PageNotAnInteger:
article_list = page_robot.page(1)
context = {}
context["article_list"] = article_list
return render(request, 'index.html', context)
def detail(request, id):
article = Article.objects.get(id=id)
if request.method == "GET":
form = CommentForm
context = {}
context["article"] = article
context['form'] = form
return render(request, 'detail.html', context)
def comment(request, id):
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
name = form.cleaned_data["name"]
comment = form.cleaned_data["comment"]
article = Article.objects.get(id=id)
c = Comment(name=name, comment=comment, belong_to=article)
c.save()
return redirect(to="detail", id=id)
return redirect(to="detail", id=id)
def index_login(request):
if request.method == "GET":
form = AuthenticationForm
if request.method == "POST":
form = AuthenticationForm(data=request.POST)
if form.is_valid():
login(request, form.get_user())
return redirect(to="index")
context = {}
context['form'] = form
return render(request, 'login.html', context)
def index_register(request):
if request.method == "GET":
form = UserCreationForm
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect(to='login')
context = {}
context['form'] = form
return render(request, 'register.html', context)
def vote(request, id):
# 未登录用户不允许投票,自动跳回详情页
if not isinstance(request.user, User):
return redirect(to="detail", id=id)
voter_id = request.user.id
try:
# 如果找不到登陆用户对此篇文章的操作,就报错
user_ticket_for_this_article = Ticket.objects.get(
voter_id=voter_id, article_id=id)
user_ticket_for_this_article.choice = request.POST["vote"]
user_ticket_for_this_article.save()
except ObjectDoesNotExist:
new_ticket = Ticket(voter_id=voter_id, article_id=id,
choice=request.POST["vote"])
new_ticket.save()
# 如果是点赞,更新点赞总数
if request.POST["vote"] == "like":
article = Article.objects.get(id=id)
article.likes += 1
article.save()
return redirect(to="detail", id=id)
def myinfo(request):
if request.method == 'POST':
form = UserProfile.objects.create(
gender=form.cleaned_data['gender'],
photo=form.cleaned_data['photo'],
user=request.user,
)
context = {}
context['form'] = form
return render(request, 'myinfo.html', context)
|
StarcoderdataPython
|
4951353
|
<reponame>kalaspuff/newshades-api<filename>app/tests/services/test_crud_service.py
from datetime import datetime
import arrow
import pytest
from pymongo.database import Database
from app.models.server import Server, ServerMember
from app.models.user import User
from app.schemas.servers import ServerCreateSchema
from app.schemas.users import UserCreateSchema
from app.services.crud import create_item, get_items
class TestCRUDService:
@pytest.mark.asyncio
async def test_create_user_ok(self, db: Database):
wallet_address = "0x123"
model = UserCreateSchema(wallet_address=wallet_address)
user = await create_item(item=model, result_obj=User, current_user=None, user_field=None)
assert user is not None
assert user.wallet_address == wallet_address
@pytest.mark.asyncio
async def test_create_user_fields_ok(self, db: Database):
wallet_address = "0x1234"
model = UserCreateSchema(wallet_address=wallet_address)
created_user = await create_item(item=model, result_obj=User, current_user=None, user_field=None)
assert created_user is not None
assert created_user.wallet_address == wallet_address
assert "created_at" in created_user._fields
assert created_user.created_at is not None
assert isinstance(created_user.created_at, datetime)
created_date = arrow.get(created_user.created_at)
assert created_date is not None
assert (arrow.utcnow() - created_date).seconds <= 2
@pytest.mark.asyncio
async def test_create_item_custom_user_field(self, db: Database, current_user: User):
server_name = "Verbs DAO"
server_model = ServerCreateSchema(name=server_name)
created_server = await create_item(
item=server_model, result_obj=Server, current_user=current_user, user_field="owner"
)
assert created_server is not None
assert created_server.name == server_name
assert "owner" in created_server._fields
assert created_server.owner is not None
assert created_server.owner == current_user
@pytest.mark.asyncio
async def test_get_items_with_size(self, db: Database, current_user: User, server: Server):
members = await get_items(filters={"server": server.pk}, result_obj=ServerMember, current_user=current_user)
assert members is not None
assert len(members) == 1
|
StarcoderdataPython
|
16912
|
import tkinter as tk
from tkinter import ttk
win = tk.Tk()
win.title("Python GUI")
win.resizable(False, False)
win.configure(background = "grey94")
a_label = ttk.Label(win, text = "Gib Deinen Namen ein:")
a_label.grid(column = 0, row = 0)
a_label.grid_configure(padx = 8, pady = 8)
def clickMe():
action.configure(text = "Hallöchen " + name.get())
name = tk.StringVar()
name_entered = ttk.Entry(win, width = 12, textvariable = name)
name_entered.grid(column = 0, row = 1)
name_entered.grid_configure(padx = 8, pady = 8)
name_entered.focus()
action = ttk.Button(win, text = "Drück mich!", command = clickMe)
action.grid(column = 1, row = 1)
action.grid_configure(padx = 8, pady = 8)
win.mainloop()
|
StarcoderdataPython
|
3427478
|
# !/usr/bin/env python
# coding=UTF-8
"""
@Author: <NAME>
@LastEditors: <NAME>
@Description:
@Date: 2021-08-31
@LastEditTime: 2021-11-11
CSV文件日志
"""
import os
import time
import csv
from typing import NoReturn, List, Optional, Any
import pandas as pd
from .base import AttackLogger
from ..attacked_text import AttackedText
from ..misc import dict_to_str, nlp_log_dir
from ...EvalBox.Attack.attack_result import AttackResult
__all__ = [
"CSVLogger",
]
class CSVLogger(AttackLogger):
"""Logs attack results to a CSV."""
__name__ = "CSVLogger"
def __init__(
self,
filename: Optional[str] = None,
stdout: bool = False,
color_method: str = "file",
) -> NoReturn:
""" """
super().__init__()
self.filename = filename or os.path.join(
nlp_log_dir, f"""{time.strftime("CSVLogger-%Y-%m-%d-%H-%M-%S.csv")}"""
)
self._default_logger.info(f"Logging to CSV at path {self.filename}")
self.stdout = stdout
if not self.stdout:
self._clear_default_logger_handlers()
self.color_method = color_method
self.df = pd.DataFrame()
self._flushed = True
def log_attack_result(self, result: AttackResult, **kwargs: Any) -> NoReturn:
original_text, perturbed_text = result.diff_color(self.color_method)
original_text = original_text.replace("\n", AttackedText.SPLIT_TOKEN)
perturbed_text = perturbed_text.replace("\n", AttackedText.SPLIT_TOKEN)
result_type = result.__class__.__name__.replace("AttackResult", "")
row = {
"original_text": original_text,
"perturbed_text": perturbed_text,
"original_score": result.original_result.score,
"perturbed_score": result.perturbed_result.score,
"original_output": result.original_result.output,
"perturbed_output": result.perturbed_result.output,
"ground_truth_output": result.original_result.ground_truth_output,
"num_queries": result.num_queries,
"result_type": result_type,
}
self.df = self.df.append(row, ignore_index=True)
self._flushed = False
if self.stdout:
self._default_logger.info(dict_to_str(row))
def flush(self) -> NoReturn:
self.df.to_csv(self.filename, quoting=csv.QUOTE_NONNUMERIC, index=False)
self._flushed = True
def close(self) -> NoReturn:
super().close()
def __del__(self) -> NoReturn:
if not self._flushed:
self._default_logger.warning("CSVLogger exiting without calling flush().")
def extra_repr_keys(self) -> List[str]:
""" """
return [
"filename",
"stdout",
"color_method",
]
|
StarcoderdataPython
|
4820737
|
try:
import webbrowser, os
import numpy as np
import calendar
import fTools as ft
import cInputOutput as cio
except:
print("ERROR: Could not load numpy.")
def make_flow_duration():
# requires csv file with
# col1 = dates
# col2 = mean daily discharge
station_name = "AFLA" # CHANGE
start_year = 1969 # CHANGE
end_year = 2009 # CHANGE
observation_period = "1969-2010" # CHANGE
path2csv = "D:\\Python\\Discharge\\" # CHANGE
csv_name = "AFLA_1969_2010_series.csv" # CHANGE
print("Reading discharge series ...")
dates = ft.read_csv(path2csv + csv_name, True, 0)
discharges = ft.read_csv(path2csv + csv_name, True, 1)
n_days = 365
print("Classifying mean daily discharge ...")
# get length of months (ignore leap years)
days_per_month = []
for m in range(1, 12 + 1):
days_per_month.append(calendar.monthrange(int(end_year), m)[1])
# prepare day-discharge dict
day_discharge_dict = {}
for d in range(1, n_days + 1):
# add one discharge entry per year
day_discharge_dict.update({d: []})
# add discharges per day of the year
i_file_read = 0
for y in range(start_year, end_year + 1):
year_day = 1
for m in range(1, 12 + 1):
month = dates[i_file_read].month
for d in range(1, days_per_month[m - 1] + 1):
day = dates[i_file_read].day
# ensure that date count matches filecount
if m == month:
if d == day:
try:
val = float(discharges[i_file_read])
except:
val = np.nan
day_discharge_dict[year_day].append(val)
# check leap years
if (month == 2) and (dates[i_file_read + 1].day == 29):
i_file_read += 2
else:
i_file_read += 1
year_day += 1
print("Averaging mean daily discharges ...")
discharge_per_day = []
for d in day_discharge_dict.keys():
discharge_per_day.append(np.nanmean(day_discharge_dict[d], axis=0))
discharge_per_day.sort(reverse=True)
day_discharge_sorted = {}
for d in day_discharge_dict.keys():
day_discharge_sorted.update({d: discharge_per_day[d - 1]})
print("Writing results to flow_duration_" + station_name + ".xlsx")
xlsx_write = cio.Write("flow_duration_" + station_name + ".xlsx")
xlsx_write.open_wb("flow_duration_template.xlsx", 0)
xlsx_write.write_cell("G", 3, station_name)
xlsx_write.write_cell("G", 4, observation_period)
xlsx_write.write_dict2xlsx(day_discharge_sorted, "C", "B", 2)
xlsx_write.save_close_wb()
webbrowser.open(os.path.dirname(os.path.abspath(__file__)) + "\\flow_duration_" + station_name + ".xlsx")
if __name__ == "__main__":
make_flow_duration()
|
StarcoderdataPython
|
11234343
|
<reponame>best-of-acrv/fcos<gh_stars>1-10
import argparse
import os
import re
import sys
import textwrap
from .fcos import Fcos
from .helpers import config_by_name
class ShowNewlines(argparse.ArgumentDefaultsHelpFormatter,
argparse.RawDescriptionHelpFormatter):
def _fill_text(self, text, width, indent):
return ''.join([
indent + i for ii in [
textwrap.fill(
s, width, drop_whitespace=False, replace_whitespace=False)
for s in text.splitlines(keepends=True)
] for i in ii
])
def main():
# Parse command line arguments
p = argparse.ArgumentParser(
prog='fcos',
formatter_class=ShowNewlines,
description="Fully convolutional one-stage object detection (FCOS).\n\n"
"Dataset interaction is performed through the acrv_datasets package. "
"Please see it for details on downloading datasets, accessing them, "
"and changing where they are stored.\n\n"
"For full documentation of FCOS, plea see "
"https://github.com/best-of-acrv/fcos.")
p_parent = argparse.ArgumentParser(add_help=False)
p_parent.add_argument(
'--config-file',
default=None,
help='YAML file from which to load FCOS configuration')
p_parent.add_argument(
'--config-list',
default=None,
help='Comma separated list of key-value config pairs '
'(e.g. MODEL.WEIGHTS=weights.pth,SOLVER.WEIGHT_DECAY=0.001)')
p_parent.add_argument('--gpu-id',
default=0,
type=int,
help="ID of GPU to use for model")
p_parent.add_argument('--load-checkpoint',
default=None,
help="Checkpoint location from which to load weights"
" (overrides --load-pretrained)")
p_parent.add_argument('--load-pretrained',
default='FCOS_imprv_R_50_FPN_1x',
choices=Fcos.PRETRAINED_MODELS.keys(),
help="Load these pre-trained weights in at startup")
p_parent.add_argument('--model-seed',
default=0,
type=int,
help="Seed used for model training")
p_parent.add_argument('--name',
default='fcos',
help="Name to give FCOS model")
sp = p.add_subparsers(dest='mode')
p_eval = sp.add_parser('evaluate',
parents=[p_parent],
formatter_class=ShowNewlines,
help="Evaluate a model's performance against a "
"specific dataset")
p_eval.add_argument('--dataset-name',
default=None,
help="Name of the dataset to use from 'acrv_datasets "
"--supported_datasets' (value in config will be used "
"if not supplied)")
p_eval.add_argument('--dataset-dir',
default=None,
help="Search this directory for datasets instead "
"of the current default in 'acrv_datasets'")
p_eval.add_argument('--output-directory',
default='.',
help="Directory to save evaluation results")
p_pred = sp.add_parser('predict',
parents=[p_parent],
formatter_class=ShowNewlines,
help="Use a model to detect objects in a given "
"input image")
p_pred.add_argument('image_file', help="Filename for input image")
p_pred.add_argument('--output-file',
default='./output.jpg',
help="Filename used for saving the output image")
p_pred.add_argument('--show-mask-heatmaps-if-available',
default=False,
action='store_true',
help="Overlay heatmaps on the output image "
"(only when the model provides them)")
p_train = sp.add_parser('train',
parents=[p_parent],
formatter_class=ShowNewlines,
help="Train a model from a previous starting "
"point using a specific dataset")
p_train.add_argument('--checkpoint-period',
default=None,
type=int,
help="Frequency with which to make checkpoints in # "
"of epochs (value in config will be used if not "
"supplied)")
p_train.add_argument('--dataset-name',
help="Name of the dataset to use from 'acrv_datasets "
"--supported_datasets' (value in config will be used "
"if not supplied)")
p_train.add_argument('--dataset-dir',
default=None,
help="Search this directory for datasets instead "
"of the current default in 'acrv_datasets'")
p_train.add_argument('--output-directory',
default=os.path.expanduser('~/fcos-output'),
help="Location where checkpoints and training "
"progress will be stored")
args = p.parse_args()
# Print help if no args provided
if len(sys.argv) == 1:
p.print_help()
return
# Run requested FCOS operations
f = Fcos(config_file=args.config_file,
config_list=None if args.config_list is None else re.split(
',|=', args.config_list),
gpu_id=args.gpu_id,
load_checkpoint=args.load_checkpoint,
load_pretrained=args.load_pretrained)
if args.mode == 'evaluate':
f.evaluate(dataset_name=args.dataset_name,
dataset_dir=args.dataset_dir,
output_directory=args.output_directory)
elif args.mode == 'predict':
f.predict(image_file=args.image_file,
output_file=args.output_file,
show_mask_heatmaps_if_available=args.
show_mask_heatmaps_if_available)
elif args.mode == 'train':
f.train(checkpoint_period=args.checkpoint_period,
dataset_name=args.dataset_name,
dataset_dir=args.dataset_dir,
output_directory=args.output_directory)
else:
raise ValueError("Unsupported mode: %s" % args.mode)
if __name__ == '__main__':
main()
|
StarcoderdataPython
|
9619173
|
from django_mailer.tests.commands import TestCommands
from django_mailer.tests.engine import LockTest #COULD DROP THIS TEST
from django_mailer.tests.backend import TestBackend
|
StarcoderdataPython
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.