import copy

class SudokuSolver():
	"""Solves a given Sudoku Grid

								                 1 | 2 | 3
	  							                ___|___|___
	local squares are mapped out in this grid    4 | 5 | 6
	  					               		    ___|___|___
	  							                 7 | 8 | 9
	"""
	def __init__(self, puzzle):
		self.puzzle = puzzle
		# Obtain (row, col) coordinates for every zero element in the give sudoku puzzle
		# Create a copy that can be modified while solving
		self.zeros = [(i, j) for i in range(9) for j in range(9) if puzzle[i][j] == 0]
		# Create a deep copy of the puzzle that can be modified while solving
		self.solving_puzzle = copy.deepcopy(puzzle)

	def puzzle_solver(self):
		# Solves the puzzle that the class was instantiated with returns solved puzzle
		puzzle = self.solving_puzzle
		zeros = self.zeros

		# Below loop will continue to calculate the possible options for each empty
		# square, filling in squares able, until the puzzl is fully solved.
		while zeros != []:
			numbers_solved = 0
			for i, j in zeros:
				options = self.get_squares_possible_options(i, j, puzzle)
				if len(options) == 1:
					puzzle[i][j] = options[0]
					zeros.remove((i, j))
					numbers_solved += 1

			#Saftey Break. I.e. if the puzzle is too hard for this method we break the loop
			if numbers_solved == 0:
				print("Puzzle is to Hard for this method")
				break
		return puzzle

	def get_squares_possible_options(self, row, col, solving_puzzle):
		# Return a list of numbers that could fit into a given position
		# Every square can have the numbers 1 to 9
		options = list(range(1, 10))
		# Get list of all the numbers in the came row, col, and local square.
		row_values = solving_puzzle[row]
		col_values = [x[col] for x in solving_puzzle if x != 0]
		local_square = [solving_puzzle[i][j] for i in range((row//3 * 3),(row//3 * 3 + 3)) for j in range((col//3 * 3),(col//3 * 3 + 3))]
		# Remove numbers in same row from options
		for x in row_values:
			if x in options:
				options.remove(x)
		# Remove numbers in the same column
		for x in col_values:
			if x in options:
				options.remove(x)
		# Remove numbers in the same local square
		for x in local_square:
			if x in options:
				options.remove(x)
		# Anything left could potentially be the correct number
		return options

puzzle1 = [[8, 7, 0, 3, 4, 5, 0, 0, 6],
		  [0, 0, 9, 0, 0, 6, 0, 0, 1],
		  [0, 5, 0, 0, 0, 1, 0, 0, 0],
		  [0, 3, 0, 4, 0, 9, 0, 8, 5],
		  [0, 9, 0, 0, 0, 0, 7, 0, 0],
		  [7, 0, 0, 5, 0, 0, 0, 0, 0],
		  [6, 0, 3, 0, 5, 0, 0, 9, 7],
		  [0, 1, 0, 6, 0, 0, 3, 0, 0],
		  [0, 2, 0, 0, 0, 0, 5, 0, 0]]

# Testing Sudoku Solver on puzzle
game = SudokuSolver(puzzle1)
solved = game.puzzle_solver()
for row in solved:
	print(row)


"""A Sphinx extension for linking to your project's issue tracker."""
import re
from typing import Callable, Optional, Tuple

from docutils import nodes, utils
from sphinx.config import Config
from sphinx.util.nodes import split_explicit_title

__version__ = "3.0.1"
__author__ = "Steven Loria"
__license__ = "MIT"

def cve_role(name, rawtext, text, lineno, inliner, options=None, content=None):
    """Sphinx role for linking to a CVE on https://cve.mitre.org.

    Examples: ::

        :cve:`CVE-2018-17175`

    """
    options = options or {}
    content = content or []
    has_explicit_title, title, target = split_explicit_title(text)

    target = utils.unescape(target).strip()
    title = utils.unescape(title).strip()
    ref = f"https://cve.mitre.org/cgi-bin/cvename.cgi?name={target}"
    text = title if has_explicit_title else target
    link = nodes.reference(text=text, refuri=ref, **options)
    return [link], []

GITHUB_USER_RE = re.compile("^https://github.com/([^/]+)/([^/]+)/.*")

def _get_default_group_and_project(
    config: Config, uri_config_option: str
) -> Optional[Tuple[str, str]]:
    """
    Get the default group/project or None if not set
    """
    old_config = getattr(config, "issues_github_path", None)
    new_config = getattr(config, "issues_default_group_project", None)

    if old_config and new_config:
        raise ValueError(
            "Both 'issues_github_path' and 'issues_default_group_project' are set, even"
            " though they define the same setting.  "
            "Please only define one of these."
        )
    group_and_project = new_config or old_config

    if group_and_project:
        assert isinstance(group_and_project, str)
        try:
            group, project = group_and_project.split("/", maxsplit=1)
            return group, project
        except ValueError as e:
            raise ValueError(
                "`issues_github_path` or `issues_default_group_project` needs to "
                "define a value in the form of `<group or user>/<project>` "
                f"but `{config}` was given."
            ) from e

    # If group and project was not set, we need to look for it within the github url
    # for backward compatibility
    if not group_and_project:
        uri = getattr(config, uri_config_option)
        if uri:
            match = GITHUB_USER_RE.match(uri)
            if match:
                return match.groups()[0], match.groups()[1]

    return None

def _get_placeholder(uri_config_option: str) -> str:
    """
    Get the placeholder from the uri_config_option
    """
    try:
        # i.e. issues_pr_uri -> pr
        return uri_config_option[:-4].split("_", maxsplit=1)[1]
    except IndexError:
        # issues_uri -> issue
        return uri_config_option[:-5]

def _get_uri_template(
    config: Config,
    uri_config_option: str,
) -> str:
    """
    Get a URL format template that can be filled with user information based
    on the given configuration

    The result always contains the following placeholder
      - n (the issue number, user, pull request, etc...)

    The result can contain the following other placeholders
      - group (same as user in github)
      - project

    Examples for possible results:

         - "https://github.com/{group}/{project}/issues/{n}"

         - "https://gitlab.company.com/{group}/{project}/{n}"

         - "https://fancy.issuetrack.com?group={group}&project={project}&issue={n}"

    Raises:
         - ValueError if the given uri contains an invalid placeholder
    """
    format_string = str(getattr(config, uri_config_option))
    placeholder = _get_placeholder(uri_config_option)

    result = format_string.replace(f"{{{placeholder}}}", "{n}")

    try:
        result.format(project="", group="", n="")
    except (NameError, KeyError) as e:
        raise ValueError(
            f"The `{uri_config_option}` option contains invalid placeholders. "
            f"Only {{group}}, {{projects}} and {{{placeholder}}} are allowed."
            f'Invalid format string: "{format_string}".'
        ) from e
    return result

def _get_uri(
    uri_config_option: str,
    config: Config,
    number: str,
    group_and_project: Optional[Tuple[str, str]] = None,
) -> str:
    """
    Get a URI based on the given configuration and do some sanity checking
    """
    format_string = _get_uri_template(config, uri_config_option)

    url_vars = {"n": number}

    config_group_and_project = _get_default_group_and_project(config, uri_config_option)
    if group_and_project:
        # Group and Project defined by call
        if config_group_and_project:
            to_replace = "/".join(config_group_and_project)
            if to_replace in format_string:
                # Backward compatibility, replace default group/project
                # with {group}/{project}
                format_string = format_string.replace(to_replace, "{group}/{project}")
        (url_vars["group"], url_vars["project"]) = group_and_project
    elif config_group_and_project:
        # If not defined by call use the default if given
        (url_vars["group"], url_vars["project"]) = config_group_and_project

    try:
        return format_string.format(**url_vars)
    except (NameError, KeyError) as e:
        # The format string was checked before, that it contains no additional not
        # supported placeholders. So this occur
        raise ValueError(
            f"The `{uri_config_option}` format `{format_string}` requires a "
            f"group/project to be defined in `issues_default_group_project`."
        ) from e

def cwe_role(name, rawtext, text, lineno, inliner, options=None, content=None):
    """Sphinx role for linking to a CWE on https://cwe.mitre.org.

    Examples: ::

        :cwe:`CWE-787`

    """
    options = options or {}
    content = content or []
    has_explicit_title, title, target = split_explicit_title(text)

    target = utils.unescape(target).strip()
    title = utils.unescape(title).strip()
    number = target[4:]
    ref = f"https://cwe.mitre.org/data/definitions/{number}.html"
    text = title if has_explicit_title else target
    link = nodes.reference(text=text, refuri=ref, **options)
    return [link], []

class IssueRole:
    # Symbols used to separate and issue/pull request/merge request etc
    # i.e
    #   - group/project#2323 for issues
    #   - group/project!1234 for merge requests (in gitlab)
    #   - group/project@adbc1234 for commits
    ELEMENT_SEPARATORS = "#@!"

    EXTERNAL_REPO_REGEX = re.compile(rf"^(\w+)/(.+)([{ELEMENT_SEPARATORS}])([\w]+)$")

    def __init__(
        self,
        config_prefix: str,
        pre_format_text: Callable[[Config, str], str] = None,
    ):
        self.uri_config = f"{config_prefix}_uri"
        self.separator_config = f"{config_prefix}_prefix"
        self.pre_format_text = pre_format_text or self.default_pre_format_text

    @staticmethod
    def default_pre_format_text(config: Config, text: str) -> str:
        return text

    def format_text(self, config: Config, issue_no: str) -> str:
        """
        Add supported separator in front of the issue or raise an error if invalid
        separator is given
        """
        separator = getattr(config, self.separator_config)
        if separator not in self.ELEMENT_SEPARATORS:
            raise ValueError(
                f"Option {self.separator_config} has to be one of "
                f"{', '.join(self.ELEMENT_SEPARATORS)}."
            )
        text = self.pre_format_text(config, issue_no.lstrip(self.ELEMENT_SEPARATORS))
        return f"{separator}{text}"

    def make_node(self, name: str, issue_no: str, config: Config, options=None):
        if issue_no in ("-", "0"):
            return None

        options = options or {}

        has_explicit_title, title, target = split_explicit_title(issue_no)

        if has_explicit_title:
            issue_no = str(target)

        repo_match = self.EXTERNAL_REPO_REGEX.match(issue_no)

        if repo_match:
            # External repo
            group, project, original_separator, issue_no = repo_match.groups()
            text = f"{group}/{project}{self.format_text(config, issue_no)}"
            ref = _get_uri(
                self.uri_config,
                config,
                issue_no,
                (group, project),
            )
        else:
            text = self.format_text(config, issue_no)
            ref = _get_uri(self.uri_config, config, issue_no)
        if has_explicit_title:
            return nodes.reference(text=title, refuri=ref, **options)
        else:
            return nodes.reference(text=text, refuri=ref, **options)

    def __call__(
        self, name, rawtext, text, lineno, inliner, options=None, content=None
    ):
        options = options or {}
        content = content or []
        issue_nos = [each.strip() for each in utils.unescape(text).split(",")]
        config = inliner.document.settings.env.app.config
        ret = []
        for i, issue_no in enumerate(issue_nos):
            node = self.make_node(name, issue_no, config, options=options)
            ret.append(node)
            if i != len(issue_nos) - 1:
                sep = nodes.raw(text=", ", format="html")
                ret.append(sep)
        return ret, []

"""Sphinx role for linking to an issue. Must have
`issues_uri` or `issues_default_group_project` configured in ``conf.py``.
Examples: ::
    :issue:`123`
    :issue:`42,45`
    :issue:`sloria/konch#123`
"""
issue_role = IssueRole(
    config_prefix="issues",
)

"""Sphinx role for linking to a pull request. Must have
`issues_pr_uri` or `issues_default_group_project` configured in ``conf.py``.
Examples: ::
    :pr:`123`
    :pr:`42,45`
    :pr:`sloria/konch#43`
"""
pr_role = IssueRole(
    config_prefix="issues_pr",
)

def format_commit_text(config, sha):
    return sha[:7]

"""Sphinx role for linking to a commit. Must have
`issues_commit_uri` or `issues_default_group_project` configured in ``conf.py``.
Examples: ::
    :commit:`123abc456def`
    :commit:`sloria/konch@123abc456def`
"""
commit_role = IssueRole(
    config_prefix="issues_commit",
    pre_format_text=format_commit_text,
)

"""Sphinx role for linking to a user profile. Defaults to linking to
GitHub profiles, but the profile URIS can be configured via the
``issues_user_uri`` config value.

Examples: ::

    :user:`sloria`

Anchor text also works: ::

    :user:`Steven Loria <sloria>`
"""
user_role = IssueRole(config_prefix="issues_user")

def setup(app):
    # Format template for issues URI
    # e.g. 'https://github.com/sloria/marshmallow/issues/{issue}
    app.add_config_value(
        "issues_uri",
        default="https://github.com/{group}/{project}/issues/{issue}",
        rebuild="html",
        types=[str],
    )
    app.add_config_value("issues_prefix", default="#", rebuild="html", types=[str])
    # Format template for PR URI
    # e.g. 'https://github.com/sloria/marshmallow/pull/{issue}
    app.add_config_value(
        "issues_pr_uri",
        default="https://github.com/{group}/{project}/pull/{pr}",
        rebuild="html",
        types=[str],
    )
    app.add_config_value("issues_pr_prefix", default="#", rebuild="html", types=[str])
    # Format template for commit URI
    # e.g. 'https://github.com/sloria/marshmallow/commits/{commit}
    app.add_config_value(
        "issues_commit_uri",
        default="https://github.com/{group}/{project}/commit/{commit}",
        rebuild="html",
        types=[str],
    )
    app.add_config_value(
        "issues_commit_prefix", default="@", rebuild="html", types=[str]
    )
    # There is no seperator config as a format_text function is given

    # Default User (Group)/Project eg. 'sloria/marshmallow'
    # Called github as the package was working with github only before
    app.add_config_value(
        "issues_github_path", default=None, rebuild="html", types=[str]
    )
    # Same as above but with new naming to reflect the new functionality
    # Only on of both can be set
    app.add_config_value(
        "issues_default_group_project", default=None, rebuild="html", types=[str]
    )
    # Format template for user profile URI
    # e.g. 'https://github.com/{user}'
    app.add_config_value(
        "issues_user_uri",
        default="https://github.com/{user}",
        rebuild="html",
        types=[str],
    )
    app.add_config_value("issues_user_prefix", default="@", rebuild="html", types=[str])
    app.add_role("issue", issue_role)
    app.add_role("pr", pr_role)
    app.add_role("user", user_role)
    app.add_role("commit", commit_role)
    app.add_role("cve", cve_role)
    app.add_role("cwe", cwe_role)
    return {
        "version": __version__,
        "parallel_read_safe": True,
        "parallel_write_safe": True,
    }


def count(mid):
    cnt=0
    for x in a:
        cnt+=x//mid
    return cnt

k,n=map(int,input().split())
a=list()
for _ in range(k):
    tmp=int(input())
    a.append(tmp)
lt=0
rt=max(a)
while lt<=rt:
    cnt=0
    mid=(lt+rt)//2
    if(cnt>=n): #커진 상황에서도 계속 진행해야 최적의 값이 나옴...
        res=mid
        lt=mid+1
    else:
        rt=mid-1
print(res)

[4-2]랜선자르기(결정알고리즘).py


import re

from bin.service import FavouriteStorage, ShoutOutStorage, UserStorage, Storage
from bin.entity import Card
import time
import pymongo

class CardStorage(Storage.Storage):

    def __init__(self):
        super().__init__()
        self.so_storage = ShoutOutStorage.ShoutOutStorage()
        self.add_text_indices()

    def add_text_indices(self):
        phoenix = self.mongo.phoenix
        card_storage = phoenix.card_storage
        try:
            card_storage.create_index([('title', pymongo.TEXT), ('text', pymongo.TEXT)])
        except Exception as e:
            print(e)

    def add_card(self, card):
        phoenix = self.mongo.phoenix
        card_storage = phoenix.card_storage
        card_storage.insert_one(card)

    def get_all_cards(self, not_empty=None, include_jira=True):
        phoenix = self.mongo.phoenix
        card_storage = phoenix.card_storage
        if not_empty is not None:
            if include_jira:
                cards = card_storage.find({'$and': [{not_empty: {'$ne': None}}, {not_empty: {'$ne': []}}]})
            else:
                cards = card_storage.find({'$and': [{not_empty: {'$ne': None}}, {not_empty: {'$ne': []}}, {'relation_type': {'$ne': 'jira'}}]})
        else:
            if include_jira:
                cards = card_storage.find()
            else:
                cards = card_storage.find({'relation_type': {'$ne': 'jira'}})
        return cards

    def get_all_ideas(self):
        phoenix = self.mongo.phoenix
        card_storage = phoenix.card_storage
        cards = card_storage.find({'type': 'idea'})
        return cards

    def get_all_facts(self):
        phoenix = self.mongo.phoenix
        card_storage = phoenix.card_storage
        cards = card_storage.find({'type': 'fact'})
        return cards

    def search_cards_by_title(self, title, include_jira):
        phoenix = self.mongo.phoenix
        card_storage = phoenix.card_storage
        if include_jira:
            cards = card_storage.find({'title': title})
        else:
            cards = card_storage.find({'title': title, 'relation_type': {'$ne': 'jira'}})
        return cards

    def search_cards_fulltext(self, query, include_jira):
        phoenix = self.mongo.phoenix
        card_storage = phoenix.card_storage
        if include_jira:
            cards = card_storage.find({'$text': {'$search': query}})
        else:
            cards = card_storage.find({'$text': {'$search': query}, 'relation_type': {'$ne': 'jira'}})
        return cards

    def search_cards_by_query(self, query, include_jira):
        phoenix = self.mongo.phoenix
        card_storage = phoenix.card_storage
        if include_jira:
            cards = card_storage.find({'title': {'$regex': str(query)}})
        else:
            cards = card_storage.find({'title': {'$regex': str(query)}, 'relation_type': {'$ne': 'jira'}})
        return cards

    def get_jira_confluence_and_phoenix_cards(self, not_empty=None):
        phoenix = self.mongo.phoenix
        card_storage = phoenix.card_storage
        if not_empty is not None:
            jira_cards = card_storage.find({'$and': [{'relation_type': 'jira'}, {not_empty: {'$ne': None}}, {not_empty: {'$ne': []}}]})
            confluence_cards = card_storage.find({'$and': [{'relation_type': 'confluence'}, {not_empty: {'$ne': None}}, {not_empty: {'$ne': []}}]})
            phoenix_cards = card_storage.find({'$and': [{'relation_type': None}, {not_empty: {'$ne': None}}, {not_empty: {'$ne': []}}]})
        else:
            jira_cards = card_storage.find({'relation_type': 'jira'})
            confluence_cards = card_storage.find({'relation_type': 'confluence'})
            phoenix_cards = card_storage.find({'relation_type': None})
        return jira_cards, confluence_cards, phoenix_cards

    def get_jira_and_confluence_ideas(self):
        phoenix = self.mongo.phoenix
        card_storage = phoenix.card_storage
        cards = card_storage.find({'$and': [{'relation_type': {'$in': ['jira', 'confluence', None]}}, {'type': 'idea'}]})
        return cards

    def get_jira_and_confluence_facts(self):
        phoenix = self.mongo.phoenix
        card_storage = phoenix.card_storage
        cards = card_storage.find({'$and': [{'relation_type': {'$in': ['jira', 'confluence', None]}}, {'type': 'fact'}]})
        return cards

    def get_jira_cards(self):
        phoenix = self.mongo.phoenix
        card_storage = phoenix.card_storage
        cards = card_storage.find({'relation_type': 'jira'})
        return cards

    def get_jira_card(self, ticket_id):
        phoenix = self.mongo.phoenix
        card_storage = phoenix.card_storage
        card = card_storage.find_one({'relation_type': 'jira', 'relation_id': ticket_id}, no_cursor_timeout=True)
        return card

    def get_confluence_cards(self):
        phoenix = self.mongo.phoenix
        card_storage = phoenix.card_storage
        cards = card_storage.find({'relation_type': 'confluence'})
        return cards

    def get_git_cards(self, not_empty=None):
        phoenix = self.mongo.phoenix
        card_storage = phoenix.card_storage
        if not_empty is not None:
            git_cards = card_storage.find({'$and': [{'relation_type': 'git'}, {not_empty: {'$ne': None}}, {not_empty: {'$ne': []}}]})
        else:
            git_cards = card_storage.find({'relation_type': 'git'})
        return git_cards

    def get_confluence_card(self, confluence_id):
        phoenix = self.mongo.phoenix
        card_storage = phoenix.card_storage
        card = card_storage.find_one({'relation_type': 'confluence', 'relation_id': confluence_id}, no_cursor_timeout=True)
        return card

    def get_git_card(self, git_id):
        phoenix = self.mongo.phoenix
        card_storage = phoenix.card_storage
        card = card_storage.find_one({'relation_type': 'git', 'relation_id': git_id}, no_cursor_timeout=True)
        return card

    def get_timed_facts(self, target_time):
        phoenix = self.mongo.phoenix
        card_storage = phoenix.card_storage
        cards = card_storage.find({'changed': {'$gt': target_time}, 'type': 'fact'})
        return cards

    def get_next_card_id(self):
        phoenix = self.mongo.phoenix
        card_storage = phoenix.card_storage
        max_id = card_storage.find(sort=[('id', -1)]).limit(1)
        if max_id.count() > 0:
            next_id = max_id[0]['id'] + 1
        else:
            next_id = 1

        return next_id

    def card_exists(self, card_id):
        phoenix = self.mongo.phoenix
        card_storage = phoenix.card_storage
        card = card_storage.find_one({'id': card_id})
        return card is not None

    def get_card(self, card_id):
        phoenix = self.mongo.phoenix
        card_storage = phoenix.card_storage
        card = card_storage.find_one({'id': card_id})
        return card

    def get_cards(self, card_ids):
        cards = []
        for card_id in card_ids:
            cards.append(self.get_card(card_id))
        return cards

    def update_card(self, card):
        success = False
        existing_card = self.get_card(card['id'])
        if existing_card is not None:
            existing_card['changed'] = time.time()
            existing_card['text'] = card['text']
            existing_card['title'] = card['title']
            existing_card['relation_id'] = card['relation_id']
            existing_card['relation_type'] = card['relation_type']
            existing_card['author'] = card['author']
            existing_card['keywords'] = card['keywords']
            existing_card['editors'] = card['editors']
            existing_card['external_link'] = card['external_link']

            if existing_card['author'] is not None and existing_card['type'] == 'idea':
                existing_card['type'] = 'fact'
            else:
                existing_card['type'] = card['type']
            self.store_card(existing_card)
            favourite_storage = FavouriteStorage.FavouriteStorage()
            favourite_storage.update_favourite_title(card['id'], card['title'])

        return success

    def store_card(self, card):
        phoenix = self.mongo.phoenix
        card_storage = phoenix.card_storage
        stored_card = card_storage.find_one({'id': card['id']})
        if stored_card is not None:
            card_storage.replace_one({'id': card['id']}, card)
        else:
            card_storage.insert_one(card)

    def get_latest_cards(self, count):
        git_enabled = self.environment.get_service_enable_git()

        cards = []
        if git_enabled:
            cards += list(self.get_git_cards('title'))

        jira_cards, confluence_cards, phoenix_cards = self.get_jira_confluence_and_phoenix_cards('title')
        cards += list(jira_cards) + list(confluence_cards) + list(phoenix_cards)
        shout_outs_exist = False

        latest_cards = []
        for check_card in cards:
            if check_card['clicks'] > 0:
                shout_outs = self.so_storage.get_card_shout_outs(check_card['id'])
                check_card['shout_outs'] = shout_outs.count()
                if check_card['shout_outs'] > 0:
                    check_card['clicks'] += 1000000000000
                    if shout_outs_exist is False:
                        shout_outs_exist = True
                latest_cards.append(check_card)

        latest_cards = sorted(latest_cards, key=lambda card: card['shout_outs'], reverse=False)
        latest_cards = self.sort_cards(latest_cards, count)

        return latest_cards

    @staticmethod
    def sort_cards(cards, count):
        cards = list(cards)
        cards_by_date = sorted(cards, key=lambda card: card['changed'], reverse=True)
        cards_by_click = sorted(cards_by_date, key=lambda card: card['clicks'], reverse=True)
        cards_by_type = sorted(cards_by_click, key=lambda card: card['type'], reverse=False)
        if len(cards) > 0 and 'probability' in cards[0]:
            cards_by_probability = sorted(cards_by_type, key=lambda card: card['probability'], reverse=False)
            cards_by_type = cards_by_probability
        limited_cards = cards_by_type[:count]
        sorted_cards = []
        for sorted_card in limited_cards:
            if '_id' in sorted_card:
                del(sorted_card['_id'])
            sorted_cards.append(sorted_card)

        return sorted_cards

    def create_card(self, title, text, keywords, external_link):
        user_storage = UserStorage.UserStorage()
        user = user_storage.get_user()

        card = Card.Card()
        card.id = self.get_next_card_id()
        card.title = title
        card.text = text
        card.keywords = keywords.split(',')
        card.created = time.time()
        card.changed = time.time()
        card.external_link = external_link
        card.type = 'fact'
        card.author = user['short']
        card.editors = [user['short']]
        self.store_card(dict(card))

        return card.id

    def get_jira_key_for_card_id(self, card_id):
        phoenix = self.mongo.phoenix
        jira_storage = phoenix.jira_storage

        key = None
        card = self.get_card(card_id)
        if card['relation_type'] == 'jira' and card['relation_id'] is not None:
            jira_card = jira_storage.find_one({'id': card['relation_id']})
            if 'key' in jira_card:
                key = jira_card['key']

        return key

    def delete_jira_entries_of_board(self, jira_board):
        if jira_board == '' or jira_board is None or jira_board is False:
            raise Exception(f"CardStorage.delete_jira_entries_of_board requires a jira_board identifier.")
        phoenix = self.mongo.phoenix
        jira_storage = phoenix.jira_storage
        jira_storage.delete_many({'key': {'$regex': f"{jira_board}-[0-9]*"}})
        card_storage = phoenix.card_storage
        card_storage.delete_many({'external_link': {'$regex': f".*{jira_board}-[0-9]*.*"}})


'''
Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

For example, given

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

'''

from treeNode import TreeNode
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def buildTree(self, preorder, inorder):
        """
        :type preorder: List[int]
        :type inorder: List[int]
        :rtype: TreeNode
        """
        if len(preorder) == 0:
            return None

        inorderIdx = {}
        for i, v in enumerate(inorder):
            inorderIdx[v] = i

        return self.bt(preorder, inorder, 0, len(preorder) - 1, 0, len(inorder) - 1, inorderIdx)

    def bt(self, preorder, inorder, pstart, pend, istart, iend, inorderIdx):
        if pstart > pend:
            return None

        node = TreeNode(preorder[pstart])

        inIdx = inorderIdx[node.val]
        leftSubNum = inIdx - istart
        node.left = self.bt(preorder, inorder, pstart + 1, pstart + leftSubNum, istart, inIdx - 1, inorderIdx)
        node.right = self.bt(preorder, inorder, pstart + leftSubNum + 1, pend, inIdx + 1, iend, inorderIdx)

        return node

    @staticmethod
    def main():
        sol = Solution()
        preorder = [3,9,20,15,7]
        inorder = [9,3,15,20,7]
        node = sol.buildTree(preorder, inorder)
        print(TreeNode.toList(node))

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


#!/usr/bin/python
# CS 260 Programming Examples
# wyu@ateneo.edu

import socket
import time

s = socket.socket()
host = socket.gethostname()
port = 12345
s.bind((host, port))
s.listen(5)

while True:
  c, addr = s.accept()
  print('Got connection from', addr)
  c.send('Thank you for connecting')
  time.sleep(5)
  c.close()


import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['axes.xmargin'] = 0

import numpy as np
import cmath
import os

#-----------------------------------------------
iteration = []
obj = []

f =open('conv_history.txt', 'r')
header = f.readline()
for line in f:
    line = line.strip()
    columns = line.split()
    #print(columns)
    iteration.append(int(columns[1]))
    obj.append(float(columns[4]))
iteration = np.array(iteration)
obj = np.array(obj)

#plt.grid(True, which="both", ls="-")
#plt.xticks(range(0,21,5))
plt.yscale('log')
plt.xlabel('# CG iteration')
plt.ylabel('$f_k/f_1$')
plt.plot(iteration, obj, 'k')
plt.savefig('CG_conv.png')
plt.show()


my_list = ['tom', 'mary', 'ken', 'kenneth']

lenght_of_names = map(lambda n: len(n), my_list)
names_longer_than_4_chars = filter(lambda n: len(n) >= 4, my_list)

print(map(lambda n: len(n), filter(lambda n: len(n) >= 3, my_list)))

print([len(name) for name in my_list if len(name) >= 4])

"""

users = [User(1), User(2), User(3)...]

def analyze_if_user_is_a_robot(user):
    True | False

users_analyzed = [analyze_if_user_is_a_robot(u) for u in users]

[True, False, False, True]

robot_users = filter(lambda u: u is True, users_analyzed)
"""


# opencv-python
import cv2
# mediapipe人工智能工具包
import mediapipe as mp
# 进度条库
from tqdm import tqdm
# 时间库
import time
# 导入python绘图matplotlib
import matplotlib.pyplot as plt

# 定义可视化图像函数
def look_img(img):
    '''opencv读入图像格式为BGR，matplotlib可视化格式为RGB，因此需将BGR转RGB'''
    img_RGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    plt.imshow(img_RGB)
    plt.show()

# 导入solution
mp_pose = mp.solutions.pose

# # 导入绘图函数
mp_drawing = mp.solutions.drawing_utils

# 导入模型
pose = mp_pose.Pose(static_image_mode=True,        # 是静态图片还是连续视频帧
                    model_complexity=1,            # 选择人体姿态关键点检测模型，0最快但性能差，2性能好但是慢
                    smooth_landmarks=True,         # 是否平滑关键点
                    min_detection_confidence=0.5,  # 置信度阈值
                    min_tracking_confidence=0.5)   # 追踪阈值

# 从图片文件读入图像，opencv读入为BGR格式
img = cv2.imread('person1.jfif')
# BGR转RGB
img_RGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# 将RGB图像输入模型，获取预测结果
results = pose.process(img_RGB)

# 可视化
mp_drawing.draw_landmarks(img, results.pose_landmarks, mp_pose.POSE_CONNECTIONS)
look_img(img)
# 在三维真实物理坐标系中可视化以米为单位的检测结果
#mp_drawing.plot_landmarks(results.pose_world_landmarks, mp_pose.POSE_CONNECTIONS)


import datetime
import os
import pathlib
from urllib.parse import quote_plus

import scrapy
import slugify

from scrapy.spidermiddlewares.httperror import HttpError
from twisted.internet.error import DNSLookupError
from twisted.internet.error import TimeoutError, TCPTimedOutError

BASE_PATH = os.environ.get('BASE_PATH', '/home/mpizarro/devel/freebsd_graphics')
SCRAPE_MODE = os.environ.get('SCRAPE_MODE', 'live')
ARCHS = {
    'x86': 'i386',
    'x64': 'amd64',
}

class NvidiaSpider(scrapy.Spider):
    '''
    scrapy crawl nvidia
    scrapy crawl --pdb nvidia -O data/nvidia/driver_specs/nvidia_driver_specs.json
    '''
    name = 'nvidia'
    allowed_domains = ['nvidia.com', 'www.nvidia.com', 'web.archive.org']
    custom_settings = {
        'ROBOTSTXT_OBEY': False
    }
    start_urls = [
        'https://www.nvidia.com/en-us/drivers/unix/freebsd-x64-archive/',
        'https://www.nvidia.com/en-us/drivers/unix/freebsd-archive/',
    ] if SCRAPE_MODE=='live' else [
        f'file://{BASE_PATH}/www_data/data/local/https_www_nvidia.com_en-us_drivers_unix_freebsd-archive.html',
        f'file://{BASE_PATH}/www_data/data/local/https_www_nvidia.com_en-us_drivers_unix_freebsd-x64-archive.html',
    ]

    def parse(self, response):
        if SCRAPE_MODE=='live':
            page = response.url.split("/")[-2]
        else:
            page = response.url.split("_")[-1].strip('.html')
        filename = f'{BASE_PATH}/www_data/data/nvidia/driver_lists/nvidia-{page}.html'
        with open(filename, 'wb') as f:
            f.write(response.body)

        default_os = 'FreeBSD x64' if 'x64' in response.url else 'FreeBSD x86'
        yield scrapy.Request(f'file://{filename}', callback=self.parse_driver_specs)
        unknowns_counter = 0
        for driver in response.css('div.pressItem'):
            spec = {
                'Version': 'unknown',
                'Operating System': default_os,
                'Release Date': 'unknown',
            }
            specs = driver.css('p::text').getall()
            url = driver.css('h4 a::attr(href)').get()
            filename = ''
            version = ''
            os = ''
            arch = ''
            if specs == [' ']:
                alt_specs = url.split('/')[-1].replace('_display', '').replace('_', '-').split('-')
                if len(alt_specs) == 4:
                    version = alt_specs[2]
                    os = alt_specs[0].lower()
                    arch = ARCHS[alt_specs[1]].lower()
                elif len(alt_specs) == 2:
                    unknowns_counter += 1
                    version = alt_specs[1]
                    os = alt_specs[0].lower()
                    arch = f'unknown{unknowns_counter}'
            else:
                for item in specs:
                    if ':' in item:
                        key, value = item.split(':')
                        spec[key.strip()] = value.strip()
                if url[0:2] == '//':
                    url = f'https:{url}'
                version = spec['Version']
                os_arch = spec['Operating System'].split()
                os = os_arch[0].lower()
                if os == 'freebsd':
                    arch = ARCHS[os_arch[1]].lower()
                else:
                    os = 'freebsd'
                    arch = 'amd64'
            filename = f'{BASE_PATH}/www_data/data/nvidia/driver_specs/nvidia_{version}_{os}_{arch}.html'
            if pathlib.Path(filename).exists():
                yield scrapy.Request(f'file://{filename}', callback=self.parse_driver_specs, dont_filter=True)
            else:
                yield scrapy.Request(url, callback=self.retrieve_driver_specs, errback=self.handle_errors, meta={'dont_retry': True}, cb_kwargs={'filename': filename})

    def parse_driver_specs(self, response):
        spec_keys = response.css('td.contentsummaryleft::text').getall()
        if not spec_keys:
            spec_keys = response.css('td#contentsummaryleft h2::text').getall()
        spec_values = response.css('td.contentsummaryright::text').getall()
        if not spec_values:
            spec_values = response.css('td#contentsummaryright h2::text').getall()
        specs = {}
        mismatches = 0
        keys = ''
        for idx, key in enumerate(spec_keys):
            key = key.strip().strip(':')
            keys += key
            value = ''
            while not value:
                value = spec_values[idx+mismatches].strip()
                if not value:
                    mismatches += 1
            if key:
                specs[key] = spec_values[idx+mismatches].strip()
            if 'Version' in keys and 'Operating System' in keys and 'Release Date' in keys:
                break
        os_arch = specs['Operating System'].split()
        os = os_arch[0]
        arch = ARCHS[os_arch[1]]
        release_date = datetime.datetime.strptime(specs['Release Date'], '%Y.%m.%d').isoformat() + 'Z'
        series_list = response.css('div#tab2_content b::text').getall()
        gpu_lists = response.css('div#tab2_content p::text').getall()
        if not gpu_lists:
            gpu_lists = response.css('div#tab2_content::text').getall()
        for idx, series in enumerate(series_list):
            gpus = gpu_lists[idx].split(', ')
            for gpu in gpus:
                yield {
                    'series': series.replace(' Series', '').replace(' series', '').strip().strip(':'),
                    'gpu': gpu,
                    'release_date': release_date,
                    'version': specs['Version'],
                    'os': os,
                    'arch': arch,
                }

    def retrieve_driver_specs(self, response, filename):
        with open(filename, 'wb') as f:
            f.write(response.body)
        yield scrapy.Request(f'file://{filename}', callback=self.parse_driver_specs)

    def retrieve_wayback_machine_capture(self, response, filename, original_url):
        last_ts = response.json()['last_ts']
        url = f'https://web.archive.org/web/{last_ts}/{original_url}'
        yield scrapy.Request(
            url,
            callback=self.retrieve_driver_specs,
            headers={'Referer': 'https://web.archive.org/web/2015*/https://www.nvidia.com/object/frds86-313.18-driver'},
            errback=self.handle_errors,
            meta={'dont_retry': True},
            cb_kwargs={'filename': filename}
        )

    def handle_errors(self, failure):
        if failure.check(HttpError) and failure.value.response.status==503:
            original_url = failure.value.response.url
            url = f'https://web.archive.org/__wb/sparkline?output=json&url={quote_plus(original_url)}&collection=web'
            filename = failure.value.response.cb_kwargs['filename']
            yield scrapy.Request(
                url,
                callback=self.retrieve_wayback_machine_capture,
                headers={'Referer': 'https://web.archive.org/web/2015*/https://www.nvidia.com/object/frds86-313.18-driver'},
                errback=self.handle_errors,
                meta={'dont_retry': True},
                cb_kwargs={'filename': filename, 'original_url': original_url}
            )
        else:
            # log all failures
            self.logger.error(repr(failure))

            if failure.check(HttpError):
                # these exceptions come from HttpError spider middleware
                # you can get the non-200 response
                response = failure.value.response
                self.logger.error('HttpError on %s', response.url)
            elif failure.check(DNSLookupError):
                # this is the original request
                request = failure.request
                self.logger.error('DNSLookupError on %s', request.url)
            elif failure.check(TimeoutError, TCPTimedOutError):
                request = failure.request
                self.logger.error('TimeoutError on %s', request.url)


"""Classes for specific report types."""
from datetime import timedelta

from flask import jsonify
from sqlalchemy import and_, func, or_
from sqlalchemy.dialects.postgresql import INTERVAL
from sqlalchemy.orm import aliased

from api.models import db
from api.models.ea_act import EAAct
from api.models.event import Event
from api.models.event_category import EventCategory
from api.models.event_configuration import EventConfiguration
from api.models.ministry import Ministry
from api.models.phase_code import PhaseCode
from api.models.project import Project
from api.models.proponent import Proponent
from api.models.region import Region
from api.models.staff import Staff
from api.models.substitution_acts import SubstitutionAct
from api.models.work import Work
from api.models.work_phase import WorkPhase
from api.models.work_status import WorkStatus

from .cdog_client import CDOGClient
from .report_factory import ReportFactory

# pylint:disable=not-callable

class EAAnticipatedScheduleReport(ReportFactory):
    """EA Anticipated Schedule Report Generator"""

    def __init__(self, filters):
        """Initialize the ReportFactory"""
        data_keys = [
            "phase_name",
            "date_updated",
            "project_name",
            "proponent",
            "region",
            "location",
            "ea_act",
            "substitution_act",
            "project_description",
            "anticipated_decision_date",
            "additional_info",
            "ministry_name",
            "referral_date",
            "eac_decision_by",
            "decision_by",
            "next_pecp_date",
            "next_pecp_title",
            "next_pecp_short_description",
            "milestone_type",
        ]
        group_by = "phase_name"
        template_name = "anticipated_schedule.docx"
        super().__init__(data_keys, group_by, template_name, filters)
        self.report_title = "Anticipated EA Referral Schedule"

    def _fetch_data(self, report_date):
        """Fetches the relevant data for EA Anticipated Schedule Report"""
        start_date = report_date + timedelta(days=-7)
        eac_decision_by = aliased(Staff)
        decision_by = aliased(Staff)
        pecp_event = aliased(Event)

        pecp_category = EventCategory.query.filter(EventCategory.name == "PCP").first()
        pecp_configuration_ids = EventConfiguration.query.filter(
            EventConfiguration.event_category_id == pecp_category.id
        ).all()
        pecp_configuration_ids = [x.id for x in pecp_configuration_ids]

        decision_category = EventCategory.query.filter(
            EventCategory.name == "Decision"
        ).first()
        decision_configuration_ids = EventConfiguration.query.filter(
            EventConfiguration.event_category_id == decision_category.id
        ).all()
        decision_configuration_ids = [x.id for x in decision_configuration_ids]

        next_decision_event_query = (
            db.session.query(
                Event.work_id,
                func.min(Event.anticipated_date).label("min_anticipated_date"),
            )
            .filter(
                Event.anticipated_date >= start_date,
                Event.event_configuration_id.in_(decision_configuration_ids),
            )
            .group_by(Event.work_id)
            .subquery()
        )

        next_pecp_query = (
            db.session.query(
                Event.work_id,
                func.min(Event.actual_date).label("min_start_date"),
            )
            .filter(
                Event.actual_date >= start_date,
                Event.event_configuration_id.in_(pecp_configuration_ids),
            )
            .group_by(Event.work_id)
            .subquery()
        )

        status_update_max_date_query = (
            db.session.query(
                WorkStatus.work_id,
                func.max(WorkStatus.posted_date).label("max_posted_date"),
            )
            .group_by(WorkStatus.work_id)
            .subquery()
        )

        latest_status_updates = WorkStatus.query.filter(
            WorkStatus.posted_date >= start_date
        ).join(
            status_update_max_date_query,
            and_(
                WorkStatus.work_id == status_update_max_date_query.c.work_id,
                WorkStatus.posted_date
                == status_update_max_date_query.c.max_posted_date,
            ),
        )

        results_qry = (
            latest_status_updates.join(Work)
            .join(Event)
            .join(
                next_decision_event_query,
                and_(
                    Event.work_id == next_decision_event_query.c.work_id,
                    Event.anticipated_date
                    == next_decision_event_query.c.min_anticipated_date,
                ),
            )
            .join(
                EventConfiguration,
                and_(
                    EventConfiguration.id == Event.event_configuration_id,
                    EventConfiguration.id.in_(decision_configuration_ids),
                ),
            )
            .join(WorkPhase, EventConfiguration.work_phase_id == WorkPhase.id)
            .join(PhaseCode, WorkPhase.phase_id == PhaseCode.id)
            .join(Project, Work.project_id == Project.id)
            .join(Proponent)
            .join(Region, Region.id == Project.region_id_env)
            .join(EAAct, EAAct.id == Work.ea_act_id)
            .join(Ministry)
            .outerjoin(eac_decision_by, Work.eac_decision_by)
            .outerjoin(decision_by, Work.decision_by)
            .outerjoin(SubstitutionAct)
            # .outerjoin(
            #     WorkEngagement,
            #     and_(
            #         WorkEngagement.project_id == Work.project_id,
            #         WorkEngagement.milestone_id.in_(pecp_configuration_ids),
            #     ),
            # )
            # .outerjoin(Engagement, WorkEngagement.engagement)
            .outerjoin(
                pecp_event,
                and_(
                    pecp_event.work_id == Work.id,
                    # next_pecp_query.c.min_start_date == pecp_event.actual_date,
                    pecp_event.event_configuration_id.in_(pecp_configuration_ids),
                ),
            )
            .outerjoin(
                next_pecp_query,
                and_(
                    next_pecp_query.c.work_id == pecp_event.work_id,
                    next_pecp_query.c.min_start_date == pecp_event.actual_date,
                    Work.project_id == Work.project_id,
                ),
            )
            # FILTER ENTRIES MATCHING MIN DATE FOR NEXT PECP OR NO WORK ENGAGEMENTS (FOR AMENDMENTS)
            .filter(
                or_(
                    next_pecp_query.c.min_start_date == pecp_event.actual_date,
                    pecp_event.id.is_(None),
                )
            )
            .add_columns(
                PhaseCode.name.label("phase_name"),
                WorkStatus.posted_date.label("date_updated"),
                Project.name.label("project_name"),
                Proponent.name.label("proponent"),
                Region.name.label("region"),
                Project.address.label("location"),
                EAAct.name.label("ea_act"),
                SubstitutionAct.name.label("substitution_act"),
                Project.description.label("project_description"),
                (
                    Event.anticipated_date + func.cast(func.concat(Event.number_of_days, " DAYS"),
                                                       INTERVAL)
                ).label("anticipated_decision_date"),
                # Event.anticipated_end_date.label("anticipated_decision_date"),
                WorkStatus.description.label("additional_info"),
                Ministry.name.label("ministry_name"),
                (
                    Event.anticipated_date + func.cast(func.concat(Event.number_of_days, " DAYS"),
                                                       INTERVAL)
                ).label("referral_date"),
                # Event.anticipated_end_date.label("referral_date"),
                eac_decision_by.full_name.label("eac_decision_by"),
                decision_by.full_name.label("decision_by"),
                EventConfiguration.event_type_id.label("milestone_type"),
                func.coalesce(pecp_event.name, Event.name).label("next_pecp_title"),
                func.coalesce(
                    pecp_event.actual_date,
                    pecp_event.anticipated_date,
                    Event.actual_date,
                ).label("next_pecp_date"),
                pecp_event.notes.label("next_pecp_short_description"),
            )
        )
        return results_qry.all()

    def generate_report(self, report_date, return_type):
        """Generates a report and returns it"""
        data = self._fetch_data(report_date)
        data = self._format_data(data)
        if return_type == "json" and data:
            return {"data": data}, None
        if not data:
            return {}, None
        api_payload = {
            "report_data": data,
            "report_title": self.report_title,
            "report_date": report_date,
        }
        template = self.generate_template()
        report_client = CDOGClient()
        report = report_client.generate_document(
            self.report_title, jsonify(api_payload).json, template
        )
        return report, f"{self.report_title}_{report_date:%Y_%m_%d}.pdf"


# encoding:utf8
import time

from appium import webdriver
from selenium.webdriver.support.wait import WebDriverWait

# 2、desired创建字典
desired_caps = dict()
# 3、platformName
# desired_caps['platformName'] = 'Android'
# # 4、platformVersion
# desired_caps['platformVersion'] = '8.0.0'
# # 5、deviceName
# desired_caps['deviceName'] = 'MI_5'
# # 6、启动程序的包名appPackage
# desired_caps["appPackage"] = 'com.qiyi.video'
# # 7、启动界面名appActivity
# desired_caps['appActivity'] = 'org.qiyi.android.video.MainActivity'
desired_caps['platformName'] = 'Android'
# 4、platformVersion
desired_caps['platformVersion'] = '5.1'
# 5、deviceName
desired_caps['deviceName'] = 'Samsung_Galaxy_S6'

desired_caps["appPackage"] = 'com.boxuegu'
# 7、启动界面名appActivity
desired_caps['appActivity'] = 'com.boxuegu.activity.MainFlutterActivity'
# 解决中文
desired_caps["unicodeKeyboard"] = True
desired_caps["resetKeyboard"] = True

# 获取toast automationName = uiautomator2
desired_caps["automationName"] = 'uiautomator2'

# 8、http，连接appium服务器
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)

# time.sleep(5)
# # 1、点击我的 id、class、xpath
# me = '//*[starts-with(@text,"我的")]'
# driver.find_element_by_xpath(me).click()
# time.sleep(5)
#
# # 点击未登录 com.qiyi.video:id/phone_my_main_head_layout  com.qiyi.video:id/ugc_feed_friends_name_and_class
# # com.qiyi.video:id/ugc_feed_friends_name
# ulogin_btn = "com.qiyi.video:id/ugc_feed_friends_name_and_class"
# driver.find_element_by_id(ulogin_btn).click()
# time.sleep(5)
# # 2、输入用户名
# username = "com.qiyi.video:id/phoneMyAccountEmail"
# driver.find_element_by_id(username).send_keys("2121908201@qq.com")
# time.sleep(2)
# # 3、输入密码
# code = "com.qiyi.video:id/phoneMyAccountPwd"
# driver.find_element_by_id(code).send_keys("1234567QWEqwe")
# time.sleep(2)
# # 4、点击登录  不要延时，因为toast信息很短会无效
# login_btn = "com.qiyi.video:id/phoneMyAccountLogin"
# driver.find_element_by_id(login_btn).click()
#
# # 5、获取toast信息   lambda表达式方法体   模糊匹配 "//*[contains(@text,'帐号或密码错误')]"
# # lambda x: x.find_element_by_xpath("//*[contains(@text,'帐号或密码错误')]")
# toast_message = "帐号或密码错误"
# message = '//*[@text=\'{}\']'.format(toast_message)
# toast_element = WebDriverWait(driver, 5).until(lambda x: x.find_element_by_xpath(message))
# # toast: object = WebDriverWait(driver, 5).until(lambda x: x.find_element_by_xpath("//*[contains(@text,'帐号或密码错误')]"))
# print(toast_element.text)

# 1、显示等待 定位暂不需要按钮
allow_btn = WebDriverWait(driver, 2, 0.5).until(
    lambda x: x.find_element_by_id("com.boxuegu:id/negative_button"))
# 2、点击操作1
allow_btn.click()
time.sleep(5)
# WebDriverWait(driver, 2, 0.5).until(lambda x: x.find_element_by_id("com.boxuegu:id/negative_button")).click()

time.sleep(5)
# 1、点击我的 id、class、xpath
me = '//*[starts-with(@text,"我的")]'
driver.find_element_by_xpath(me).click()
time.sleep(5)
# 2、输入用户名
username = "com.boxuegu:id/edit_usr"
driver.find_element_by_id(username).send_keys("12341235")
time.sleep(2)
# 3、输入验证码
code = "com.boxuegu:id/security_code"
driver.find_element_by_id(code).send_keys("1234")
time.sleep(2)
# 4、点击登录
login_btn = "com.boxuegu:id/btn_login"
driver.find_element_by_id(login_btn).click()

# 5、获取toast信息
toast = WebDriverWait(driver, 5).until(lambda x: x.find_element_by_xpath("//*[contains(@text,'手机号格式错误')]"))
print(toast.text)


import torch
import torch.nn as nn
from timm.models.layers import trunc_normal_, DropPath, to_2tuple
from mmcv.runner import load_checkpoint
from mmdet.models.builder import BACKBONES
from mmdet.utils import get_root_logger
from torch.nn.functional import interpolate as interpolate
import torch.nn.functional as F

def _to_channel_last(x):
    """
    Args:
        x: (B, C, H, W)

    Returns:
        x: (B, H, W, C)
    """
    return x.permute(0, 2, 3, 1)

def _to_channel_first(x):
    """
    Args:
        x: (B, H, W, C)

    Returns:
        x: (B, C, H, W)
    """
    return x.permute(0, 3, 1, 2)

class SE(nn.Module):
    """
    Squeeze and excitation block
    """

    def __init__(self,
                 inp,
                 oup,
                 expansion=0.25):
        """
        Args:
            inp: input features dimension.
            oup: output features dimension.
            expansion: expansion ratio.
        """

        super().__init__()
        self.avg_pool = nn.AdaptiveAvgPool2d(1)
        self.fc = nn.Sequential(
            nn.Linear(oup, int(inp * expansion), bias=False),
            nn.GELU(),
            nn.Linear(int(inp * expansion), oup, bias=False),
            nn.Sigmoid()
        )

    def forward(self, x):
        b, c, _, _ = x.size()
        y = self.avg_pool(x).view(b, c)
        y = self.fc(y).view(b, c, 1, 1)
        return x * y

class ReduceSize(nn.Module):
    """
    Down-sampling block based on: "Hatamizadeh et al.,
    Global Context Vision Transformers <https://arxiv.org/abs/2206.09959>"
    """

    def __init__(self,
                 dim,
                 norm_layer=nn.LayerNorm,
                 keep_dim=False):
        """
        Args:
            dim: feature size dimension.
            norm_layer: normalization layer.
            keep_dim: bool argument for maintaining the resolution.
        """

        super().__init__()
        self.conv = nn.Sequential(
            nn.Conv2d(dim, dim, 3, 1, 1,
                      groups=dim, bias=False),
            nn.GELU(),
            SE(dim, dim),
            nn.Conv2d(dim, dim, 1, 1, 0, bias=False),
        )
        if keep_dim:
            dim_out = dim
        else:
            dim_out = 2 * dim
        self.reduction = nn.Conv2d(dim, dim_out, 3, 2, 1, bias=False)
        self.norm2 = norm_layer(dim_out)
        self.norm1 = norm_layer(dim)

    def forward(self, x):
        x = x.contiguous()
        x = self.norm1(x)
        x = _to_channel_first(x)
        x = x + self.conv(x)
        x = self.reduction(x)
        x = _to_channel_last(x)
        x = self.norm2(x)
        return x

class PatchEmbed(nn.Module):
    """
    Patch embedding block based on: "Hatamizadeh et al.,
    Global Context Vision Transformers <https://arxiv.org/abs/2206.09959>"
    """

    def __init__(self, in_chans=3, dim=96):
        """
        Args:
            in_chans: number of input channels.
            dim: feature size dimension.
        """

        super().__init__()
        self.proj = nn.Conv2d(in_chans, dim, 3, 2, 1)
        self.conv_down = ReduceSize(dim=dim, keep_dim=True)

    def forward(self, x):
        x = self.proj(x)
        x = _to_channel_last(x)
        x = self.conv_down(x)
        return x

class FeatExtract(nn.Module):
    """
    Feature extraction block based on: "Hatamizadeh et al.,
    Global Context Vision Transformers <https://arxiv.org/abs/2206.09959>"
    """

    def __init__(self, dim, keep_dim=False):
        """
        Args:
            dim: feature size dimension.
            keep_dim: bool argument for maintaining the resolution.
        """

        super().__init__()
        self.conv = nn.Sequential(
            nn.Conv2d(dim, dim, 3, 1, 1,
                      groups=dim, bias=False),
            nn.GELU(),
            SE(dim, dim),
            nn.Conv2d(dim, dim, 1, 1, 0, bias=False),
        )
        if not keep_dim:
            self.pool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.keep_dim = keep_dim

    def forward(self, x):
        x = x.contiguous()
        x = x + self.conv(x)
        if not self.keep_dim:
            x = self.pool(x)
        return x

class Mlp(nn.Module):
    def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
        super().__init__()
        out_features = out_features or in_features
        hidden_features = hidden_features or in_features
        self.fc1 = nn.Linear(in_features, hidden_features)
        self.act = act_layer()
        self.fc2 = nn.Linear(hidden_features, out_features)
        self.drop = nn.Dropout(drop)

    def forward(self, x):
        x = self.fc1(x)
        x = self.act(x)
        x = self.drop(x)
        x = self.fc2(x)
        x = self.drop(x)
        return x

class WindowAttention(nn.Module):
    """
    Local window attention based on: "Liu et al.,
    Swin Transformer: Hierarchical Vision Transformer using Shifted Windows
    <https://arxiv.org/abs/2103.14030>"
    """

    def __init__(self,
                 dim,
                 num_heads,
                 window_size,
                 window_size_pre,
                 qkv_bias=True,
                 qk_scale=None,
                 attn_drop=0.,
                 proj_drop=0.,
                 use_rel_pos_bias=False
                 ):
        """
        Args:
            dim: feature size dimension.
            num_heads: number of attention head.
            window_size: window size.
            qkv_bias: bool argument for query, key, value learnable bias.
            qk_scale: bool argument to scaling query, key.
            attn_drop: attention dropout rate.
            proj_drop: output dropout rate.
        """

        super().__init__()
        self.num_heads = num_heads
        head_dim = dim // num_heads
        self.scale = qk_scale or head_dim ** -0.5
        self.use_rel_pos_bias = use_rel_pos_bias
        self.window_size_pre = window_size_pre
        self.window_size = (window_size, window_size)  # Wh, Ww
        window_size = (window_size_pre, window_size_pre)
        self.relative_position_bias_table = nn.Parameter(
            torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads))  # 2*Wh-1 * 2*Ww-1, nH
        # get pair-wise relative position index for each token inside the window
        coords_h = torch.arange(self.window_size[0])
        coords_w = torch.arange(self.window_size[1])
        coords = torch.stack(torch.meshgrid([coords_h, coords_w]))  # 2, Wh, Ww
        coords_flatten = torch.flatten(coords, 1)  # 2, Wh*Ww
        relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :]  # 2, Wh*Ww, Wh*Ww
        relative_coords = relative_coords.permute(1, 2, 0).contiguous()  # Wh*Ww, Wh*Ww, 2
        relative_coords[:, :, 0] += self.window_size[0] - 1  # shift to start from 0
        relative_coords[:, :, 1] += self.window_size[1] - 1
        relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
        relative_position_index = relative_coords.sum(-1)  # Wh*Ww, Wh*Ww
        self.register_buffer("relative_position_index", relative_position_index)
        self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
        self.attn_drop = nn.Dropout(attn_drop)
        self.proj = nn.Linear(dim, dim)
        self.proj_drop = nn.Dropout(proj_drop)
        self.softmax = nn.Softmax(dim=-1)

    def forward(self, x, q_global):
        B_, N, C = x.shape
        head_dim = C // self.num_heads
        qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, head_dim).permute(2, 0, 3, 1, 4)
        q, k, v = qkv[0], qkv[1], qkv[2]
        q = q * self.scale
        attn = (q @ k.transpose(-2, -1))
        if self.use_rel_pos_bias:
            relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
                self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1],
                -1)  # Wh*Ww,Wh*Ww,nH
            relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous()  # nH, Wh*Ww, Wh*Ww
            attn = attn + relative_position_bias.unsqueeze(0)
        attn = self.softmax(attn)
        attn = self.attn_drop(attn)

        x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
        x = self.proj(x)
        x = self.proj_drop(x)
        return x

class WindowAttentionGlobal(nn.Module):
    """
    Global window attention based on: "Hatamizadeh et al.,
    Global Context Vision Transformers <https://arxiv.org/abs/2206.09959>"
    """

    def __init__(self,
                 dim,
                 num_heads,
                 window_size,
                 window_size_pre,
                 qkv_bias=True,
                 qk_scale=None,
                 attn_drop=0.,
                 proj_drop=0.,
                 use_rel_pos_bias=False
                 ):
        """
        Args:
            dim: feature size dimension.
            num_heads: number of attention head.
            window_size: window size.
            qkv_bias: bool argument for query, key, value learnable bias.
            qk_scale: bool argument to scaling query, key.
            attn_drop: attention dropout rate.
            proj_drop: output dropout rate.
        """

        super().__init__()
        self.num_heads = num_heads
        head_dim = dim // num_heads
        self.scale = qk_scale or head_dim ** -0.5
        self.use_rel_pos_bias = use_rel_pos_bias
        self.window_size_pre = window_size_pre
        self.window_size = (window_size, window_size)  # Wh, Ww
        window_size = (window_size_pre, window_size_pre)
        self.relative_position_bias_table = nn.Parameter(
            torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads))  # 2*Wh-1 * 2*Ww-1, nH
        # get pair-wise relative position index for each token inside the window
        coords_h = torch.arange(self.window_size[0])
        coords_w = torch.arange(self.window_size[1])
        coords = torch.stack(torch.meshgrid([coords_h, coords_w]))  # 2, Wh, Ww
        coords_flatten = torch.flatten(coords, 1)  # 2, Wh*Ww
        relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :]  # 2, Wh*Ww, Wh*Ww
        relative_coords = relative_coords.permute(1, 2, 0).contiguous()  # Wh*Ww, Wh*Ww, 2
        relative_coords[:, :, 0] += self.window_size[0] - 1  # shift to start from 0
        relative_coords[:, :, 1] += self.window_size[1] - 1
        relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
        relative_position_index = relative_coords.sum(-1)  # Wh*Ww, Wh*Ww
        self.register_buffer("relative_position_index", relative_position_index)
        self.qkv = nn.Linear(dim, dim * 2, bias=qkv_bias)
        self.attn_drop = nn.Dropout(attn_drop)
        self.proj = nn.Linear(dim, dim)
        self.proj_drop = nn.Dropout(proj_drop)
        self.softmax = nn.Softmax(dim=-1)

    def forward(self, x, q_global):
        B_, N, C = x.shape
        B = q_global.shape[0]
        head_dim = C // self.num_heads
        B_dim = B_//B
        kv = self.qkv(x).reshape(B_, N, 2, self.num_heads, head_dim).permute(2, 0, 3, 1, 4)
        k, v = kv[0], kv[1]
        q_global = q_global.repeat(1, B_dim, 1, 1, 1)
        q = q_global.reshape(B_, self.num_heads, N, head_dim)
        q = q * self.scale
        attn = (q @ k.transpose(-2, -1))
        if self.use_rel_pos_bias:
            relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
                self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1],
                -1)  # Wh*Ww,Wh*Ww,nH
            relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous()  # nH, Wh*Ww, Wh*Ww
            attn = attn + relative_position_bias.unsqueeze(0)

        attn = self.softmax(attn)
        attn = self.attn_drop(attn)
        x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
        x = self.proj(x)
        x = self.proj_drop(x)
        return x

def window_partition(x, window_size):
    """
    Args:
        x: (B, H, W, C)
        window_size (int): window size

    Returns:
        windows: (num_windows*B, window_size, window_size, C)
    """
    B, H, W, C = x.shape
    x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
    windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
    return windows

def window_reverse(windows, window_size, H, W):
    """
    Args:
        windows: (num_windows*B, window_size, window_size, C)
        window_size (int): Window size
        H (int): Height of image
        W (int): Width of image

    Returns:
        x: (B, H, W, C)
    """
    B = int(windows.shape[0] / (H * W / window_size / window_size))
    x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
    x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
    return x

class GCViTBlock(nn.Module):
    """
    GCViT block based on: "Hatamizadeh et al.,
    Global Context Vision Transformers <https://arxiv.org/abs/2206.09959>"
    """

    def __init__(self,
                 dim,
                 input_resolution,
                 num_heads,
                 window_size_pre,
                 window_size=7,
                 mlp_ratio=4.,
                 qkv_bias=True,
                 qk_scale=None,
                 drop=0.,
                 attn_drop=0.,
                 drop_path=0.,
                 act_layer=nn.GELU,
                 attention=WindowAttentionGlobal,
                 norm_layer=nn.LayerNorm,
                 layer_scale=None,
                 use_rel_pos_bias=False
                 ):
        """
        Args:
            dim: feature size dimension.
            input_resolution: input image resolution.
            num_heads: number of attention head.
            window_size: window size.
            mlp_ratio: MLP ratio.
            qkv_bias: bool argument for query, key, value learnable bias.
            qk_scale: bool argument to scaling query, key.
            drop: dropout rate.
            attn_drop: attention dropout rate.
            drop_path: drop path rate.
            act_layer: activation function.
            attention: attention block type.
            norm_layer: normalization layer.
            layer_scale: layer scaling coefficient.
        """

        super().__init__()
        self.window_size = window_size
        self.norm1 = norm_layer(dim)

        self.attn = attention(dim,
                              num_heads=num_heads,
                              window_size=window_size,
                              window_size_pre=window_size_pre,
                              qkv_bias=qkv_bias,
                              qk_scale=qk_scale,
                              attn_drop=attn_drop,
                              proj_drop=drop,
                              use_rel_pos_bias=use_rel_pos_bias
                              )

        self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
        self.norm2 = norm_layer(dim)
        self.mlp = Mlp(in_features=dim, hidden_features=int(dim * mlp_ratio), act_layer=act_layer, drop=drop)
        self.layer_scale = False
        if layer_scale is not None and type(layer_scale) in [int, float]:
            self.layer_scale = True
            self.gamma1 = nn.Parameter(layer_scale * torch.ones(dim), requires_grad=True)
            self.gamma2 = nn.Parameter(layer_scale * torch.ones(dim), requires_grad=True)
        else:
            self.gamma1 = 1.0
            self.gamma2 = 1.0

    def forward(self, x, q_global):
        B, H, W, C = x.shape
        shortcut = x
        x = self.norm1(x)
        pad_l = pad_t = 0
        pad_r = (self.window_size - W % self.window_size) % self.window_size
        pad_b = (self.window_size - H % self.window_size) % self.window_size
        x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b))
        _, Hp, Wp, _ = x.shape
        shifted_x = x
        x_windows = window_partition(shifted_x, self.window_size)  # nW*B, window_size, window_size, C
        x_windows = x_windows.view(-1, self.window_size * self.window_size, C)
        _, h, w = x_windows.shape
        attn_windows = self.attn(x_windows, q_global)
        shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp)  # B H' W' C
        x = shifted_x
        if pad_r > 0 or pad_b > 0:
            x = x[:, :H, :W, :].contiguous()
        x = shortcut + self.drop_path(self.gamma1 * x)
        x = x + self.drop_path(self.gamma2 * self.mlp(self.norm2(x)))
        return x

class GlobalQueryGen(nn.Module):
    """
    Global query generator based on: "Hatamizadeh et al.,
    Global Context Vision Transformers <https://arxiv.org/abs/2206.09959>"
    """

    def __init__(self,
                 dim,
                 input_resolution,
                 image_resolution,
                 window_size,
                 num_heads):
        """
        Args:
            dim: feature size dimension.
            input_resolution: input image resolution.
            window_size: window size.
            num_heads: number of heads.

        For instance, repeating log(56/7) = 3 blocks, with input window dimension 56 and output window dimension 7 at
        down-sampling ratio 2. Please check Fig.5 of GC ViT paper for details.
        """

        super().__init__()
        if input_resolution == image_resolution//4:
            self.to_q_global = nn.Sequential(
                FeatExtract(dim, keep_dim=False),
                FeatExtract(dim, keep_dim=False),
                FeatExtract(dim, keep_dim=False),
            )

        elif input_resolution == image_resolution//8:
            self.to_q_global = nn.Sequential(
                FeatExtract(dim, keep_dim=False),
                FeatExtract(dim, keep_dim=False),
            )

        elif input_resolution == image_resolution//16:

            if window_size == input_resolution:
                self.to_q_global = nn.Sequential(
                    FeatExtract(dim, keep_dim=True)
                )

            else:
                self.to_q_global = nn.Sequential(
                    FeatExtract(dim, keep_dim=False)
                )

        elif input_resolution == image_resolution//32:
            self.to_q_global = nn.Sequential(
                FeatExtract(dim, keep_dim=True)
            )

        self.num_heads = num_heads
        self.N = window_size * window_size
        self.dim_head = dim // self.num_heads
        self.window_size = window_size

    def forward(self, x):
        x = self.to_q_global(x)
        B, C, H, W = x.shape
        if self.window_size != H or self.window_size !=W:
            x = interpolate(x, size=(self.window_size, self.window_size), mode='bicubic')
        x = _to_channel_last(x)
        x = x.reshape(B, 1, self.N, self.num_heads, self.dim_head).permute(0, 1, 3, 2, 4)
        return x

class GCViTLayer(nn.Module):
    """
    GCViT layer based on: "Hatamizadeh et al.,
    Global Context Vision Transformers <https://arxiv.org/abs/2206.09959>"
    """

    def __init__(self,
                 dim,
                 depth,
                 input_resolution,
                 image_resolution,
                 num_heads,
                 window_size,
                 window_size_pre,
                 downsample=True,
                 mlp_ratio=4.,
                 qkv_bias=True,
                 qk_scale=None,
                 drop=0.,
                 attn_drop=0.,
                 drop_path=0.,
                 norm_layer=nn.LayerNorm,
                 layer_scale=None,
                 use_rel_pos_bias=False):
        """
        Args:
            dim: feature size dimension.
            depth: number of layers in each stage.
            input_resolution: input image resolution.
            window_size: window size in each stage.
            downsample: bool argument for down-sampling.
            mlp_ratio: MLP ratio.
            num_heads: number of heads in each stage.
            qkv_bias: bool argument for query, key, value learnable bias.
            qk_scale: bool argument to scaling query, key.
            drop: dropout rate.
            attn_drop: attention dropout rate.
            drop_path: drop path rate.
            norm_layer: normalization layer.
            layer_scale: layer scaling coefficient.
        """

        super().__init__()
        self.blocks = nn.ModuleList([
            GCViTBlock(dim=dim,
                       num_heads=num_heads,
                       window_size=window_size,
                       window_size_pre=window_size_pre,
                       mlp_ratio=mlp_ratio,
                       qkv_bias=qkv_bias,
                       qk_scale=qk_scale,
                       attention=WindowAttention if (i % 2 == 0) else WindowAttentionGlobal,
                       drop=drop,
                       attn_drop=attn_drop,
                       drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
                       norm_layer=norm_layer,
                       layer_scale=layer_scale,
                       input_resolution=input_resolution,
                       use_rel_pos_bias=use_rel_pos_bias)
            for i in range(depth)])
        self.downsample = None if not downsample else ReduceSize(dim=dim, norm_layer=norm_layer)
        self.q_global_gen = GlobalQueryGen(dim, input_resolution, image_resolution, window_size, num_heads)

    def forward(self, x):
        q_global = self.q_global_gen(_to_channel_first(x))
        for blk in self.blocks:
            x = blk(x, q_global)

        if self.downsample is None:
            return x, x
        return self.downsample(x), x

@BACKBONES.register_module()
class GCViT(nn.Module):
    def __init__(self,
                 dim,
                 depths,
                 mlp_ratio,
                 num_heads,
                 window_size=(24, 24, 24, 24),
                 window_size_pre=(7, 7, 14, 7),
                 resolution=224,
                 drop_path_rate=0.2,
                 in_chans=3,
                 qkv_bias=True,
                 qk_scale=None,
                 drop_rate=0.,
                 attn_drop_rate=0.,
                 norm_layer=nn.LayerNorm,
                 layer_scale=None,
                 out_indices=(0, 1, 2, 3),
                 frozen_stages=-1,
                 pretrained=None,
                 use_rel_pos_bias=True,
                 **kwargs):
        super().__init__()

        self.num_levels = len(depths)
        self.embed_dim = dim
        self.num_features = [int(dim * 2 ** i) for i in range(self.num_levels)]
        self.mlp_ratio = mlp_ratio
        self.pos_drop = nn.Dropout(p=drop_rate)
        self.patch_embed = PatchEmbed(in_chans=in_chans, dim=dim)
        dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))]
        self.levels = nn.ModuleList()
        for i in range(len(depths)):
            level = GCViTLayer(dim=int(dim * 2 ** i),
                               depth=depths[i],
                               num_heads=num_heads[i],
                               window_size=window_size[i],
                               window_size_pre=window_size_pre[i],
                               mlp_ratio=mlp_ratio,
                               qkv_bias=qkv_bias,
                               qk_scale=qk_scale,
                               drop=drop_rate, attn_drop=attn_drop_rate,
                               drop_path=dpr[sum(depths[:i]):sum(depths[:i + 1])],
                               norm_layer=norm_layer,
                               downsample=(i < len(depths) - 1),
                               layer_scale=layer_scale,
                               input_resolution=int(2 ** (-2 - i) * resolution),
                               image_resolution=resolution,
                               use_rel_pos_bias=use_rel_pos_bias)
            self.levels.append(level)

        # add a norm layer for each output
        self.out_indices = out_indices
        for i_layer in self.out_indices:
            layer = norm_layer(self.num_features[i_layer])
            layer_name = f'norm{i_layer}'
            self.add_module(layer_name, layer)

        self.frozen_stages = frozen_stages
        if pretrained is not None:
            self.init_weights(pretrained)

        for level in self.levels:
            for block in level.blocks:
                w_ = block.attn.window_size[0]
                relative_position_bias_table_pre = block.attn.relative_position_bias_table
                L1, nH1 = relative_position_bias_table_pre.shape
                L2 = (2 * w_ - 1) * (2 * w_ - 1)
                S1 = int(L1 ** 0.5)
                S2 = int(L2 ** 0.5)
                relative_position_bias_table_pretrained_resized = torch.nn.functional.interpolate(
                    relative_position_bias_table_pre.permute(1, 0).view(1, nH1, S1, S1), size=(S2, S2),
                    mode='bicubic')
                relative_position_bias_table_pretrained_resized = relative_position_bias_table_pretrained_resized.view(nH1, L2).permute(1, 0)
                block.attn.relative_position_bias_table = torch.nn.Parameter(relative_position_bias_table_pretrained_resized)

    def _freeze_stages(self):
        if self.frozen_stages >= 0:
            self.patch_embed.eval()
            for param in self.patch_embed.parameters():
                param.requires_grad = False

        if self.frozen_stages >= 2:
            for i in range(0, self.frozen_stages - 1):
                m = self.network[i]
                m.eval()
                for param in m.parameters():
                    param.requires_grad = False

    def train(self, mode=True):
        super(GCViT, self).train(mode)
        self._freeze_stages()

    def init_weights(self, pretrained=None):
        """Initialize the weights in backbone.

        Args:
            pretrained (str, optional): Path to pre-trained weights.
                Defaults to None.
        """

        if isinstance(pretrained, str):
            logger = get_root_logger()
            load_checkpoint(self, pretrained, strict=False, logger=logger)
        elif pretrained is None:
            pass
        else:
            raise TypeError('pretrained must be a str or None')

    def forward_embeddings(self, x):
        x = self.patch_embed(x)
        return x

    def forward_tokens(self, x):
        outs = []
        for idx, level in enumerate(self.levels):
            x, xo = level(x)
            if idx in self.out_indices:
                norm_layer = getattr(self, f'norm{idx}')
                x_out = norm_layer(xo)
                outs.append(x_out.permute(0, 3, 1, 2).contiguous())
        return outs

    def forward(self, x):
        x = self.forward_embeddings(x)
        return self.forward_tokens(x)

    def forward_features(self, x):
        x = self.forward_embeddings(x)
        return self.forward_tokens(x)


import math
from openpyxl import *
from functools import reduce

#Read data from file and create data structure
wb = load_workbook('class_1.xlsx')

#Activate a certain worksheet, in this case just a worksheet
ws = wb.active

#{'name' : score, 'name' : score}
raw_data = {}
g = ws.rows
for c1, c2 in g:
	raw_data.update({c1.value : c2.value})

scores = []
for score in raw_data.values():
	scores.append(score)
#avg
avg = reduce(lambda a, b: a + b , scores) / len(scores)

#var
var = round(reduce(lambda a, b: a + b,
	map(lambda s: (s - avg) ** 2 / len(scores), scores)), 1)

#stdv
standard_deviation = round(math.sqrt(var), 1)

print(
    "평균 :{0}, 분산 : {1}, 표준 편차 : {2}".format(
    avg, var, standard_deviation))

if avrg <50 and standard_deviation >20:
    print("성적이 너무 저조하고 학생들의 실력 차이가 너무 크다.")
elif avrg > 50 and standard_deviation >20:
    print("성적은 평균이상이지만 학생들 실력 차이가 크다. 주의 요망!")
elif avrg < 50 and standard_deviation <20:
    print("학생들간 실력차는 나지 않으나 성적이 너무 저조하다. 주의 요망!")
elif avrg > 50 and standard_deviation <20:
    print("성적도 평균 이상이고 학생들의 실력차도 크지 않다.")


'''
Write a Python program to find the second most repeated word in a given string.
'''

string = input("Enter string: ")
count = 1
string = string.lower()

li = string.split(" ")
li2 = []

for i in li:
    if i in li:
        count = li.count(i)
        if count >= 2:
            li2.append(i)

if len(li2)>=2:
    print(li2[1], "is the second word that is repeating")
elif len(li2)<1:
    print("There is no word repeating")
else:
    print(li2[0], "is the only word that is repeating, there is no second repeating word")

assignment 4 (string handling)/assignment 4 (39).py


import os
import runpy
import sys
import sysconfig

from _flux._core import ffi, lib

def split_path(path):
    return filter(None, path.split(":"))

def builtin_python_path():
    """
    Get the path to this module and assume this is the builtin
    Python path.
    """
    #  We can't use FLUX_CONF_AUTO since the executable in this context is
    #  just python or python3, therefore determine which builtin conf flag to
    #  use dynamically from the path to the current file.
    #
    #  Note: We need to avoid importing 'flux' here, since that might trigger
    #  the problem this module is trying to solve (user modified PYTHONPATH
    #  bringing incompatible modules first). So we copy the definitions of
    #  FLUX_CONF_INTREE and FLUX_CONF_INSTALLED directly from `lib` here.
    #
    flag = lib.FLUX_CONF_INSTALLED
    if "src/cmd" in __file__:
        flag = lib.FLUX_CONF_INTREE

    return split_path(
        ffi.string(lib.flux_conf_builtin_get(b"python_path", flag)).decode("utf-8")
    )

def flux_python_path_prepend():
    """
    Get the value of FLUX_PYTHONPATH_PREPEND as a list. An empty list is
    returned if the environment variable is not set.
    """
    return split_path(os.environ.get("FLUX_PYTHONPATH_PREPEND", ""))

def prepend_standard_python_paths(patharray):
    """
    Prepend standard interpreter and Flux python module paths to the
    input array `patharray`.

    Paths that will be prepended include, in order:
    - FLUX_PYTHONPATH_PREPEND
    - The Flux builtin path to its own modules
    - The Python interpreter configured values for
      - stdlib
      - platform specific stdlib
      - platform modules
      - pure python modules
    """
    #  Set of paths to append, in order, to sys.path after builtin path:
    std_paths = ("stdlib", "platstdlib", "platlib", "purelib")

    prepend_paths = [
        *flux_python_path_prepend(),
        *builtin_python_path(),
        *[sysconfig.get_path(name) for name in std_paths],
    ]

    for path in prepend_paths:
        try:
            sys.path.remove(path)
        except ValueError:
            pass  # ignore missing path in sys.path

    # Prepend list to sys.path:
    sys.path[0:0] = prepend_paths

if __name__ == "__main__":
    #  Pop first argument which is this script, modify sys.path as noted
    #  above, then invoke target script in this interpreter using
    #  runpy.run_path():
    #
    sys.argv.pop(0)
    prepend_standard_python_paths(sys.path)
    runpy.run_path(sys.argv[0], run_name="__main__")

# vi: ts=4 sw=4 expandtab


import folium
import pandas as pd

world_geo = r'C:/Users/Erdem/python kodları/Data_Visualization/world_countries.json' # geojson file

# create a plain world map
world_map = folium.Map(location=[0, 0], zoom_start=2, tiles='Mapbox Bright')

# Preparing the data.
covid_data = pd.read_csv("C:/Users/Erdem/python kodları/Data_Visualization/covid19Datas/covid_19_data.csv")

cd_grouped = covid_data[['Country/Region', 'Confirmed']]
cd_grouped = cd_grouped.groupby('Country/Region', as_index = False).max().sort_values('Country/Region', ascending = True)

pd.set_option('display.max_rows', 250)
print(cd_grouped)

cd_grouped.at[122,'Country/Region'] = 'China'
cd_grouped.at[204,'Country/Region'] = 'United Kingdom'
cd_grouped.at[205,'Country/Region'] = 'United States of America'
cd_grouped.at[147,'Country/Region'] = 'Macedonia'
cd_grouped.at[176,'Country/Region'] = 'Republic of Serbia'
cd_grouped.at[214,'Country/Region'] = 'West Bank'
cd_grouped.at[195,'Country/Region'] = 'United Republic of Tanzania'
cd_grouped.at[44,'Country/Region'] = 'Republic of the Congo'
cd_grouped.at[45,'Country/Region'] = 'Democratic Republic of the Congo'

print(cd_grouped)

# To compare by the population.
'''
world_pop = pd.read_csv("C:/Users/Erdem/python kodları/Data_Visualization/worldPopulationData/worldPop.csv")
world_pop = world_pop[['Country/Region', '2018']]

result = pd.concat([cd_grouped, world_pop], axis=1, join='outer')
result = pd.merge(cd_grouped, world_pop, how='left', on='Country/Region')
print(result)

cd_grouped['Confirmed'] = cd_grouped['Confirmed'] / result['2018']
print(cd_grouped)
'''

# create the Choropleth map.
folium.Choropleth(
    geo_data=world_geo,
    data=cd_grouped,
    columns=['Country/Region', 'Confirmed'],
    key_on='feature.properties.name',
    fill_color='YlOrRd',
    fill_opacity=0.7,
    line_opacity=0.3,
    legend_name='Confirmed Covid-19 Cases Across the Globe',
#    legend_name='Confirmed Covid-19 Cases rated by Population',
    nan_fill_color = 'white',
    reset = True
).add_to(world_map)

# display world map
world_map.save('mapOfCases.html')
#world_map.save('mapByPopulation.html')


from struct import unpack
import wave
import sys
import numpy as np

def get_measurement_from_frame(one_frame_data, number_of_channels):
  format_str = ''.join(['h' for x in range(0, number_of_channels)])

  one_frame_data_unpacked = unpack(format_str, one_frame_data)
  measurement_data = 0
  # average across channels
  for i in range(0, number_of_channels):
    measurement_data += one_frame_data_unpacked[i]
  measurement_data /= number_of_channels

  return measurement_data

def get_peaks_from_one_second_window(wave_file_handle, number_of_channels, frames_per_second):
  window_measurements = []
  for _ in range(0, frames_per_second):
    frame_data = wave_file_handle.readframes(1)

    measurement = get_measurement_from_frame(frame_data, number_of_channels)
    window_measurements += [measurement]

  frequency_information = np.fft.rfft(window_measurements)
  amplitudes = list(map(lambda frequency_information: np.abs(frequency_information), frequency_information))

  avg_amplitude = sum(amplitudes) / len(amplitudes)

  window_peaks = []
  for frequency in range(0, len(amplitudes)):
    curr_amplitude = amplitudes[frequency]

    if curr_amplitude >= (20 * avg_amplitude):
      window_peaks += [frequency]

  return window_peaks

with wave.open(sys.argv[1], 'rb') as file:
  # number of frames per second (sampling frequency)
  frames_per_second = file.getframerate()
  number_of_channels = file.getnchannels()

  # number of frames in total
  number_of_frames = file.getnframes()
  number_of_windows = number_of_frames // frames_per_second
  all_peaks = []
  for window_number in range(0, number_of_windows):
    all_peaks += get_peaks_from_one_second_window(file, number_of_channels, frames_per_second)

  if len(all_peaks) > 0:
    high_peak = np.max(all_peaks)
    low_peak = np.min(all_peaks)
    print('low = %i, high = %i' % (low_peak, high_peak))
  else:
    print("no peaks")


def validarUsuario(usr,pasw):
    x=1
    while x <3:
        if usr=="Administrador" and pasw=="info123":
            print("Sr. Administrador bienvenido al sistema")
            x=4
        elif usr!="Administrador" or pasw!="info123":
            print("Datos incorrectos, intente nuevamente")
            usr=input("Ingrese nombre de usuario: ")
            pasw=input("Ingrese contraseña: ")
            x=x+1
    if x ==3:
        print("Ha sobrepasado el numero de intentos, el sistema cerrará")

usr=input("Ingrese nombre de usuario: ")
pasw=input("Ingrese contraseña: ")
validarUsuario(usr,pasw)


import pandas as pd
import numpy as np

#Load the dataframes
facebook_df = pd.read_csv('facebook_dataset.csv', dtype=str, low_memory=False)
google_df = pd.read_csv('google_dataset.csv', dtype=str, low_memory=False)
website_df = pd.read_csv('website_dataset.csv', dtype=str, low_memory=False)

#Adding print statements to check the data after every step
#print(google_df.head())

#Data cleaning

#1. Standardize Column Names
facebook_df = facebook_df.rename(columns={'domain': 'company_name'})
google_df = google_df.rename (columns={'domain': 'company_name'})
website_df = website_df.rename(columns={'domain': 'company_name'})

#adding print statements to check the data after every step
#print(google_df.head())

#2. Handle Missing Values using numpy
#Replace empty strings with NaN values
facebook_df.replace(r'^\s*$', np.nan, regex=True, inplace=True)
google_df.replace(r'^\s*$', np.nan, regex=True, inplace=True)
website_df.replace(r'^\s*$', np.nan, regex=True, inplace=True)

#3. Ensure the Data Types
facebook_df['phone'] = facebook_df['phone'].astype(str)
google_df['phone'] = google_df['phone'].astype(str)
website_df['phone'] = website_df['phone'].astype(str)

#adding print statements to check the data after every step
# print(google_df.head())

#4. remove Duplicates
facebook_df.drop_duplicates(subset=['company_name'], keep='first', inplace=True)
google_df.drop_duplicates(subset=['company_name'], keep='first', inplace=True)
website_df.drop_duplicates(subset=['company_name'], keep='first', inplace=True)

#Adding print statements to check the data after every step
# print(google_df.head())

#Check if 'address' column exists in each DataFrame by adding if statements
if 'address' in facebook_df.columns:
    facebook_df['address'] = facebook_df['address'].str.strip()
if 'address' in google_df.columns:
    google_df['address'] = google_df['address'].str.strip()
if 'address' in website_df.columns:
    website_df['address'] = website_df['address'].str.strip()

#5. Merging the DataFrames using an outer join
common_column = 'company_name'

merged_df = pd.merge(facebook_df, google_df, on=common_column, how='outer')
merged_df = pd.merge(merged_df, website_df, on=common_column, how='outer')

#6. Clean Columns: Strip whitespace from 'category' column
merged_df['category'] = merged_df['category'].str.strip()

#7. Select final columns
final_columns = ['company_name', 'category', 'address', 'phone']

#8. filter out rows with missing data in any of the selected columns
merged_df.dropna(subset=final_columns, how='all', inplace=True)

#9. Save the final dataframe to a .csv file
merged_df.to_csv('final_dataframe.csv', index=False)

#10. Drop the unnamed columns:

#Load the 4th (final) dataframe
df = pd.read_csv('final_dataframe.csv', dtype=str, low_memory=False)

# Get the list of unnamed columns
unnamed_columns = [column for column in df.columns if column.startswith('Unnamed:')]

#Drop the unnamed columns
df.drop(unnamed_columns, axis=1, inplace=True)

#Save the modified DataFrame final_dataframe.csv
df.to_csv('final_dataframe.csv', index=False)

#Print the final dataframe
print(merged_df)


from random import randint
from time import sleep
from operator import itemgetter
sorteio = dict()
print('Valores sorteados:')
for c in range(1, 5):
    jogador = randint(1, 6)
    sorteio[f'jogador{c}'] = jogador
print(sorteio)
for k, v in sorteio.items():
    print(f'    {k} tirou {v} no dado.')
ranking = sorted(sorteio.items(), key=itemgetter(1), reverse=True)
print(ranking)
print('Ranking dos jogadores:')
for i, v in enumerate(ranking):
    print(f'    {i + 1}º lugar: {v[0]} com {v[1]}')
    sleep(1)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date    : 2020/8/19
# @Author  : zhangranghan

import os,sys
import logging
from time import strftime
from logging.handlers import TimedRotatingFileHandler

class Logger(object):
    def __init__(self, logger_name='log'):
        self.logger = logging.getLogger(logger_name)
        logging.root.setLevel(logging.NOTSET)
        timestamp = strftime('%Y%m%d')
        self.log_file_name = 'log_%s.log' % timestamp  # 日志文件的名称
        self.backup_count = 30  # 最多存放日志的数量
        # 日志输出级别
        self.console_output_level = 'DEBUG'
        self.file_output_level = 'INFO'
        # 日志输出格式
        # self.formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        self.formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')

    def get_logger(self):
        """在logger中添加日志句柄并返回，如果logger已有句柄，则直接返回"""
        if not self.logger.handlers:  # 避免重复日志
            console_handler = logging.StreamHandler(sys.stdout)
            console_handler.setFormatter(self.formatter)
            console_handler.setLevel(self.console_output_level)
            self.logger.addHandler(console_handler)

            PROJECT_NAME = 'Autotest'
            project_path = os.path.abspath(os.path.dirname(__file__))
            # root_path = project_path[:project_path.find("{}".format(PROJECT_NAME)) + len("{}".format(PROJECT_NAME))]
            log_path = project_path + "/log"

            # 每天重新创建一个日志文件，最多保留backup_count份
            file_handler = TimedRotatingFileHandler(filename=os.path.join(log_path, self.log_file_name), when='D',
                                                    interval=1, backupCount=self.backup_count, delay=True,
                                                    encoding='utf-8')
            file_handler.setFormatter(self.formatter)
            file_handler.setLevel(self.file_output_level)
            self.logger.addHandler(file_handler)
        return self.logger

logger = Logger().get_logger()


import argparse

def get_team_name_and_score(team_name_score):
    """Parse team name and score from match score string"""
    team_split = team_name_score.split(' ')
    team_score = int(team_split[-1])
    team_name = ' '.join(team_split[:-1]).strip()

    return team_name, team_score

def get_points(team1_score, team2_score):
    """Get team points from on match score"""
    if team1_score > team2_score:
        return 3, 0
    elif team2_score > team1_score:
        return 0, 3

    return 1, 1

def calculate_scores(match_results):
    """Calculate soccer team scores from match results"""
    results_list = list(filter(None, match_results.split('\n')))
    scores = {}

    for result in results_list:
        team1, team2 = result.split(',')

        team1_name, team1_score = get_team_name_and_score(team1)
        team2_name, team2_score = get_team_name_and_score(team2)

        team1_points, team2_points = get_points(team1_score, team2_score)

        # Add points to scores dict
        scores[team1_name] = scores.get(team1_name, 0) + team1_points
        scores[team2_name] = scores.get(team2_name, 0) + team2_points

    return scores

def get_ranking_table(scores):
    """Calculate soccer ranking table from team scores"""
    output_str_list = []
    sorted_scores = sorted(scores.items(), key=lambda x: (-x[1], x[0].lower()))

    previous_score = -1
    current_place = 0
    place_plus = 0
    for score in sorted_scores:
        team_name = score[0]
        team_score = score[1]
        pts_plural = 's' if team_score != 1 else ''

        if team_score == previous_score:
            place_plus += 1
        else:
            current_place += place_plus + 1
            place_plus = 0

        previous_score = team_score
        output_str_list.append(f'{current_place}. {team_name}, {team_score} pt{pts_plural}')

    return '\n'.join(output_str_list)

def run():
    """Main CLI tool method"""
    parser = argparse.ArgumentParser(epilog=(
        'Soccer League Ranker. A handy ranking table calculator.'
    ))

    parser.add_argument(
        'stdin', help='Stdin input of games results (if -ifile not used)', nargs='?', default=None
    )
    parser.add_argument('-ifile', help='Path to input file')
    parser.add_argument('-ofile', help='Path to output file')

    args = parser.parse_args()

    # Check input
    if args.stdin:
        match_results = args.stdin
    elif args.ifile:
        match_results = open(args.ifile, 'r').read()

    scores = calculate_scores(match_results)
    ranking_table = get_ranking_table(scores)

    # Check output
    if args.ofile:
        open(args.ofile, 'w').write(ranking_table)
    else:
        print(ranking_table)

    print('Ranking table successfully calculated!')


from asyncore import read
from rest_framework import serializers
from .models import Fish

class FishSerializer(serializers.HyperlinkedModelSerializer):
    fish_detail = serializers.ModelSerializer.serializer_url_field(
        view_name='fish_detail'
    )
    class Meta:
        model = Fish
        fields = ('species_name', 'fish_detail', 'scientific_name', 'rarity', 'location', 'noaa_fisheries_region', 'population', 'physical_description', 'biology', 'taste', 'texture', 'species_illustration_photo', 'image_gallery')


from pybrain.datasets.supervised import SupervisedDataSet
from pybrain.tools.shortcuts import buildNetwork
from pybrain.structure.modules.tanhlayer import TanhLayer
from pybrain.supervised.trainers.backprop import BackpropTrainer
from pybrain.supervised.trainers.mixturedensity import BackpropTrainerMix
from pybrain.structure.networks.feedforward import FeedForwardNetwork
from pybrain.structure.modules.linearlayer import LinearLayer
from pybrain.structure.modules.sigmoidlayer import SigmoidLayer
from pybrain.structure.connections.full import FullConnection
from pybrain.structure.networks.recurrent import RecurrentNetwork

def printNetResult(identifier, net):
    print(identifier, net.activate((0, 0)), net.activate((0, 1)), net.activate((1, 0)), net.activate((1, 1)))

ds = SupervisedDataSet(2,1)

ds.addSample((0, 0), (0,))
ds.addSample((0, 1), (1,))
ds.addSample((1, 0), (1,))
ds.addSample((1, 1), (0,))

for input, target in ds:
    print(input, target)

#define net
net = RecurrentNetwork()
net.addInputModule(LinearLayer(2, name="il"))
net.addModule(SigmoidLayer(4, name="h1"))
net.addModule(SigmoidLayer(4, name="h2"))
net.addOutputModule(LinearLayer(1, name="ol"))
c1 = FullConnection(net["il"], net["h1"])
c2 = FullConnection(net["h1"], net["h2"])
c3 = FullConnection(net["h2"], net["ol"])
cr1 = FullConnection(net["h1"], net["h1"])
net.addConnection(c1)
net.addConnection(c2)
net.addConnection(c3)
net.addRecurrentConnection(cr1)
net.sortModules()

print(net)

trainer = BackpropTrainer(net, ds)

for i in range(20):
    for j in range(1000):
        trainer.train()
    printNetResult(i, net)

print(net)
print(net["il"])

print(c1.params)
print(c2.params)
print(c3.params)
print(cr1.params)