import math

def pi_cipher(text):
    """
    Encrypts or decrypts a message using the Caesar cipher technique.

    args:
        text:str = the message to encrypt or decrypt
        shift:int = the number of positions to shift each letter
    return:
        :str = the encrypted or decrypted message
    """

    count = 0
    fptr2 = open("pi.txt", "r")
    result = ""

    for char in text:
        count += 1
        if count == 40:
            fptr2.close()
            fptr2 = open("pi.txt", "r")

            shift = int(fptr2.readline())
        else:
            shift = int(fptr2.readline())

        if char.isalpha():
            # Determine the case of the character
            start = ord('A') if char.isupper() else ord('a')
            # Calculate the new position of the character after the shift
            new_pos = int((ord(char) - start + shift)) % 26
            # Convert the new position back to a character
            char = chr(start + new_pos)
        result += char
    return result

#print(caesar_cipher("well hello there", 5))
def main():
    fptr1 = open("message.txt", "r")
    message = str(fptr1.read())
    print(pi_cipher(message))
    fptr2 = open("encrypted.txt", "w")
    fptr2.write(pi_cipher(message))
main()


#!/usr/bin/env python3

import argparse
import json
from pathlib import Path
import subprocess
import sys

ROOT_DIR = Path(__file__).parent.parent.resolve()

def to_abs(f):
    return Path(f).resolve()

def indent_json(filename):
    with open(filename, "r") as f:
        j = json.load(f)
    print(json.dumps(j, indent=2))
    with open(filename, "w") as f:
        json.dump(j, f, indent=2)

ap = argparse.ArgumentParser(description="Generates a skeleton annotation file")
ap.add_argument("verilog_file")
ap.add_argument("--topmodule")
ap.add_argument("--annotation-file")
ap.add_argument("--check", action='store_true', default=False)
ap.add_argument("-I", "--include-dir", action="append", type=str, default=[])

args = ap.parse_args()

vf = to_abs(args.verilog_file)

if not args.topmodule:
    args.topmodule = vf.stem

if not args.annotation_file:
    args.annotation_file = vf.parent / ('annot-' + vf.stem + '.json')

r = subprocess.run(
      ["cabal", "v2-run", "xenon-debug", "--", "generate-annotation-file",
       vf, args.topmodule, to_abs(args.annotation_file)] + args.include_dir,
      cwd=ROOT_DIR)

if r.returncode == 0:
    indent_json(args.annotation_file)

if args.check:
    subprocess.run(
        ["./xenon", to_abs(args.verilog_file), to_abs(args.annotation_file)],
        cwd=ROOT_DIR
        )


N,M = map(int,input().split())
chess=[]
result=[]
for _ in range(N):
    chess.append(list(map(str,input())))
for i in range(0, N-7):
    for j in range(0, M-7):
        case_1 = 0
        case_2 = 0
        for x in range(i, i+8):
            for y in range(j, j+8):
                if (x+y) % 2 == 0:
                    if chess[x][y] != 'W':
                        case_1 += 1
                    if chess[x][y] != 'B':
                        case_2 += 1
                else:
                    if chess[x][y] != 'W':
                        case_2 += 1
                    if chess[x][y] != 'B':
                        case_1 += 1
        result.append(case_1)
        result.append(case_2)
print(min(result))

백준/Silver/1018. 체스판 다시 칠하기/체스판 다시 칠하기.py

체스판 다시 칠하기.py


import os
import numpy as np
import pandas as pd

## Reading file
df = pd.read_csv(os.path.abspath("THE/THE_original.csv"), index_col=0)

## Selecting only the newest data (2020)
df2020 = df[df['year']==2020]

## Pivoting table to merge with other datasets (by country)
country_subject = df2020.groupby(["country","subject"]).median().reset_index()
country_subject_pivot = country_subject.pivot(index="country", columns="subject", values="total_score")
country_subject_pivot.to_csv("THE/THE2020_bysubject_country.csv")

## By university (for extra analysis in stage 2)
uni_subject = df2020.groupby(["university_name","subject"]).median().reset_index()
uni_subject_pivot = uni_subject.pivot(index="university_name", columns="subject", values="total_score")
uni_subject_pivot.to_csv("THE/THE2020_bysubject_uni.csv")


# https://www.acmicpc.net/problem/14002

n = int(input())
a = list(map(int, input().split()))
d = [1] * n
v = [-1] * n  # indices

def solution():
    for i in range(n):
        for j in range(i):
            if a[j] < a[i] and d[j] + 1 > d[i]:
                d[i] = d[j] + 1
                v[i] = j

    return max(d)
length = solution()
print(length)
idx = d.index(length)
ans = []
while idx >= 0:
    ans.append(a[idx])
    idx = v[idx]
ans.reverse()
print(' '.join(list(map(str, ans))))


#!/bin/python3

import os

# Complete the gridSearch function below.
def gridSearch(G, P):
    g_rows = len(G)
    g_cols = len(G[0])
    p_rows = len(P)
    p_cols = len(P[0])
    for row in range(g_rows - p_rows + 1):
        for col in range(g_cols - p_cols + 1):
            if G[row][col:col + p_cols] == P[0]:
                for line in range(1, p_rows):
                    if G[row + line][col:col + p_cols] != P[line]:
                        break  # Found a mismatch
                else:
                    return 'YES'  # Found full pattern
    return 'NO'

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    t = int(input())

    for t_itr in range(t):
        RC = input().split()

        R = int(RC[0])

        C = int(RC[1])

        G = []

        for _ in range(R):
            G_item = input()
            G.append(G_item)

        rc = input().split()

        r = int(rc[0])

        c = int(rc[1])

        P = []

        for _ in range(r):
            P_item = input()
            P.append(P_item)

        result = gridSearch(G, P)

        fptr.write(result + '\n')

    fptr.close()


#kaprekarNumbers.py

def kaprekarNumbers(p, q):
    valid_range = False
    results = []
    for i in range(p,q+1):
        if i == 1:
            results.append(i)
            valid_range = True
        else:
            d=str(i)
            num = i*i
            if num > 10:
                num=str(num)
                first = int(num[0:(len(num)-len(d))])
                second = int(num[len(num)-len(d):])
                if first + second == i:
                    results.append(i)
                    valid_range = True

    if valid_range == False:
        print('INVALID RANGE')
    for num in results:
        print(num, end = ' ')

p = 1
q = 100
kaprekarNumbers(p, q)


class TicTacToe:

    def __init__(self, n: int):

        self.size = n

        self.diagonal = 0
        self.anti_diagonal = 0

        self.rows  = [0] * n
        self.cols = [0] * n

    def move(self, row: int, col: int, player: int) -> int:

        count = 1 if player == 1 else -1
        n = self.size
        if row == col:
            self.diagonal += count

        if col == self.size - 1 - row:
            self.anti_diagonal += count

        self.rows[row] += count

        self.cols[col] += count

        return player if (abs(self.diagonal) == n  or abs(self.anti_diagonal) == n or abs(self.rows[row]) == n or abs(self.cols[col]) == n) else 0


from collections import deque
grid = dict()
inp = open("input").read().strip().split("\n")
blizzards = [set(), set(), set(), set()]
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
for r, row in enumerate(inp):
    for c, cell in enumerate(row):
        if cell == ">":
            blizzards[0].add((r, c))
            cell = "."
        elif cell == "v":
            blizzards[1].add((r, c))
            cell = "."
        elif cell == "<":
            blizzards[2].add((r, c))
            cell = "."
        elif cell == "^":
            blizzards[3].add((r, c))
            cell = "."
        grid[r, c] = cell
height = len(inp)
width = len(inp[0])

b_list = [blizzards]

def step_b(init_b):
    global grid
    new_b = [set(), set(), set(), set()]
    for r, c in init_b[0]:
        c += 1
        if grid[(r, c)] == "#":
            c = 1
        new_b[0].add((r, c))
    for r, c in init_b[1]:
        r += 1
        if grid[(r, c)] == "#":
            r = 1
        new_b[1].add((r, c))
    for r, c in init_b[2]:
        c -= 1
        if grid[(r, c)] == "#":
            c = width - 2
        new_b[2].add((r, c))
    for r, c in init_b[3]:
        r -= 1
        if grid[(r, c)] == "#":
            r = height - 2
        new_b[3].add((r, c))
    return new_b

def get_b(i):
    global b_list
    if i < len(b_list):
        return b_list[i]
    for _ in range(i - len(b_list) + 1):
        b_list.append(step_b(b_list[-1]))
    return b_list[-1]

def bfs(starting_r, starting_c, starting_min, goal):
    bfs_q = deque([(starting_min, (starting_r, starting_c))])
    explored = {(starting_r, starting_c, starting_min)}
    while bfs_q:
        steps, pos = bfs_q.popleft()
        if pos == goal:
            return steps
        for dr, dc in [(0, 0), (1, 0), (-1, 0), (0, 1), (0, -1)]:
            new_pos = (pos[0] + dr, pos[1] + dc, steps + 1)
            if (0 <= new_pos[0] < height) and grid[(new_pos[0], new_pos[1])] == "." and \
                    all((new_pos[0], new_pos[1]) not in get_b(new_pos[2])[i] for i in range(4)) and \
                    new_pos not in explored:
                explored.add(new_pos)
                bfs_q.append((steps + 1, (new_pos[0], new_pos[1])))

there_min = bfs(0, 1, 0, (height - 1, width - 2))
print("Part 1:", there_min)
back_min = bfs(height - 1, width - 2, there_min, (0, 1))
print("Part 2:", bfs(0, 1, back_min, (height - 1, width - 2)))


# https://www.acmicpc.net/problem/10844
n = int(input())

# dp[자리수][마지막 숫자] = 경우의 수

dp =[ [0] * 10 for _ in range(n+1) ]

# 맨 앞에 올 수 있는 숫자들의 경우의 수 계산
for i in range(1,10):
  dp[1][i] = 1

for i in range(2, n+1):
    dp[i][0] = dp[i-1][1]
    dp[i][9] = dp[i-1][8]

for j in range(1,9):
  	dp[i][j] = dp[i-1][j-1] + dp[i-1][j+1]

print(sum(dp[n])%1000000000)

Baekjoon_Algorithm/6. Dynamic Programming/10844 쉬운 계단수.py


# Realizar un programa que pida la carga de dos listas numéricas enteras de 4 elementos cada una. Generar una tercer lista que surja de la
# suma de los elementos de la misma posición de cada lista. Mostrar esta tercer lista.

lista1=[]
lista2=[]
lista3=[]

for x in range(4):
  lista1.append(int(input("Ingrese un número en la 1º lista: ")))
  lista2.append(int(input("Ingrese un número en la 2º lista: ")))

for x in range(4):
  lista3.append(lista1[x]+lista2[x])

print(lista1)
print(lista2)
print(lista3)


import sys
sys.path.append("..")
from blackjack.Arena import Arena
from blackjack.Dealer import Dealer
from blackjack.Player import Player
from blackjack.Gamer import Gamer
from utils import *

A = ["停止叫牌", "继续叫牌"]
display = False
player = Player(action_space = A, display = display)
dealer = Dealer(action_space = A, display = display)
arena = Arena(display = display, action_space = A)

arena.play_games(dealer, player, num = 200000)

def policy_evaluation(episodes, V, Ns):
    for episode, r in episodes:
        for s, a in episode:
            ns = get_dict(Ns, s)  # 状态s 在该序列中出现了多少遍
            v = get_dict(V, s)
            set_dict(Ns, ns + 1, s)
            set_dict(V, v + (r - v) / (ns + 1), s)

V = {}
Ns = {}
policy_evaluation(arena.episodes, V, Ns)


from __future__ import print_function, division
import concurrent.futures
from functools import partial
from itertools import repeat
import time
import uproot
import pickle
import sys
import math
import copy
import cloudpickle
from tqdm.auto import tqdm
from collections import defaultdict
from cachetools import LRUCache
import lz4.frame as lz4f
from .processor import ProcessorABC
from .accumulator import (
    AccumulatorABC,
    value_accumulator,
    set_accumulator,
    dict_accumulator,
)
from .dataframe import (
    LazyDataFrame,
)

try:
    from collections.abc import Mapping, Sequence
except ImportError:
    from collections import Mapping, Sequence

_PICKLE_PROTOCOL = pickle.HIGHEST_PROTOCOL

# instrument xrootd source
if not hasattr(uproot.source.xrootd.XRootDSource, '_read_real'):
    def _read(self, chunkindex):
        self.bytesread = getattr(self, 'bytesread', 0) + self._chunkbytes
        return self._read_real(chunkindex)

    uproot.source.xrootd.XRootDSource._read_real = uproot.source.xrootd.XRootDSource._read
    uproot.source.xrootd.XRootDSource._read = _read

class FileMeta(object):
    __slots__ = ['dataset', 'filename', 'treename', 'numentries']

    def __init__(self, dataset, filename, treename, numentries=None):
        self.dataset = dataset
        self.filename = filename
        self.treename = treename
        self.numentries = numentries

    def __hash__(self):
        # As used to lookup numentries, no need for dataset
        return hash((self.filename, self.treename))

    def __eq__(self, other):
        # In case of hash collisions
        return self.filename == other.filename and self.treename == other.treename

    def maybe_populate(self, cache):
        if cache and self in cache:
            self.numentries = cache[self]

    @property
    def populated(self):
        return self.numentries is not None

    def nchunks(self, target_chunksize):
        if not self.populated:
            raise RuntimeError
        return max(round(self.numentries / target_chunksize), 1)

    def chunks(self, target_chunksize):
        n = self.nchunks(target_chunksize)
        actual_chunksize = math.ceil(self.numentries / n)
        for index in range(n):
            yield WorkItem(self.dataset, self.filename, self.treename, actual_chunksize, index)

class WorkItem(object):
    __slots__ = ['dataset', 'filename', 'treename', 'chunksize', 'index']

    def __init__(self, dataset, filename, treename, chunksize, index):
        self.dataset = dataset
        self.filename = filename
        self.treename = treename
        self.chunksize = chunksize
        self.index = index

class _compression_wrapper(object):
    def __init__(self, level, function):
        self.level = level
        self.function = function

    # no @wraps due to pickle
    def __call__(self, *args, **kwargs):
        out = self.function(*args, **kwargs)
        return lz4f.compress(pickle.dumps(out, protocol=_PICKLE_PROTOCOL), compression_level=self.level)

def _maybe_decompress(item):
    if isinstance(item, AccumulatorABC):
        return item
    try:
        item = pickle.loads(lz4f.decompress(item))
        if isinstance(item, AccumulatorABC):
            return item
        raise RuntimeError
    except (RuntimeError, pickle.UnpicklingError):
        raise ValueError("Executors can only reduce accumulators or LZ4-compressed pickled accumulators")

def _iadd(output, result):
    output += _maybe_decompress(result)

def _reduce(items):
    if len(items) == 0:
        raise ValueError("Empty list provided to reduction")
    # if dask has a cached result, we cannot alter it
    out = copy.deepcopy(_maybe_decompress(items.pop()))
    while items:
        out += _maybe_decompress(items.pop())
    return out

def _futures_handler(futures_set, output, status, unit, desc, add_fn):
    try:
        with tqdm(disable=not status, unit=unit, total=len(futures_set), desc=desc) as pbar:
            while len(futures_set) > 0:
                finished = set(job for job in futures_set if job.done())
                futures_set.difference_update(finished)
                while finished:
                    add_fn(output, finished.pop().result())
                    pbar.update(1)
                time.sleep(0.5)
    except KeyboardInterrupt:
        for job in futures_set:
            job.cancel()
        if status:
            print("Received SIGINT, killed pending jobs.  Running jobs will continue to completion.", file=sys.stderr)
            print("Running jobs:", sum(1 for j in futures_set if j.running()), file=sys.stderr)
    except Exception:
        for job in futures_set:
            job.cancel()
        raise

def iterative_executor(items, function, accumulator, **kwargs):
    """Execute in one thread iteratively

    Parameters
    ----------
        items : list
            List of input arguments
        function : callable
            A function to be called on each input, which returns an accumulator instance
        accumulator : AccumulatorABC
            An accumulator to collect the output of the function
        status : bool
            If true (default), enable progress bar
        unit : str
            Label of progress bar unit
        desc : str
            Label of progress bar description
        compression : int, optional
            Compress accumulator outputs in flight with LZ4, at level specified (default 1)
            Set to ``None`` for no compression.
    """
    if len(items) == 0:
        return accumulator
    status = kwargs.pop('status', True)
    unit = kwargs.pop('unit', 'items')
    desc = kwargs.pop('desc', 'Processing')
    clevel = kwargs.pop('compression', 1)
    if clevel is not None:
        function = _compression_wrapper(clevel, function)
    add_fn = _iadd
    for i, item in tqdm(enumerate(items), disable=not status, unit=unit, total=len(items), desc=desc):
        add_fn(accumulator, function(item))
    return accumulator

def futures_executor(items, function, accumulator, **kwargs):
    """Execute using multiple local cores using python futures

    Parameters
    ----------
        items : list
            List of input arguments
        function : callable
            A function to be called on each input, which returns an accumulator instance
        accumulator : AccumulatorABC
            An accumulator to collect the output of the function
        pool : concurrent.futures.Executor class or instance, optional
            The type of futures executor to use, defaults to ProcessPoolExecutor.
            You can pass an instance instead of a class to re-use an executor
        workers : int, optional
            Number of parallel processes for futures (default 1)
        status : bool, optional
            If true (default), enable progress bar
        unit : str, optional
            Label of progress bar unit (default: 'Processing')
        desc : str, optional
            Label of progress bar description (default: 'items')
        compression : int, optional
            Compress accumulator outputs in flight with LZ4, at level specified (default 1)
            Set to ``None`` for no compression.
    """
    if len(items) == 0:
        return accumulator
    pool = kwargs.pop('pool', concurrent.futures.ProcessPoolExecutor)
    workers = kwargs.pop('workers', 1)
    status = kwargs.pop('status', True)
    unit = kwargs.pop('unit', 'items')
    desc = kwargs.pop('desc', 'Processing')
    clevel = kwargs.pop('compression', 1)
    if clevel is not None:
        function = _compression_wrapper(clevel, function)
    add_fn = _iadd
    if isinstance(pool, concurrent.futures.Executor):
        futures = set(pool.submit(function, item) for item in items)
        _futures_handler(futures, accumulator, status, unit, desc, add_fn)
    else:
        # assume its a class then
        with pool(max_workers=workers) as executor:
            futures = set(executor.submit(function, item) for item in items)
            _futures_handler(futures, accumulator, status, unit, desc, add_fn)
    return accumulator

def dask_executor(items, function, accumulator, **kwargs):
    """Execute using dask futures

    Parameters
    ----------
        items : list
            List of input arguments
        function : callable
            A function to be called on each input, which returns an accumulator instance
        accumulator : AccumulatorABC
            An accumulator to collect the output of the function
        client : distributed.client.Client
            A dask distributed client instance
        treereduction : int, optional
            Tree reduction factor for output accumulators (default: 20)
        status : bool, optional
            If true (default), enable progress bar
        compression : int, optional
            Compress accumulator outputs in flight with LZ4, at level specified (default 1)
            Set to ``None`` for no compression.
        priority : int, optional
            Task priority, default 0
        heavy_input : serializable, optional
            Any value placed here will be broadcast to workers and joined to input
            items in a tuple (item, heavy_input) that is passed to function.
    """
    if len(items) == 0:
        return accumulator
    client = kwargs.pop('client')
    ntree = kwargs.pop('treereduction', 20)
    status = kwargs.pop('status', True)
    clevel = kwargs.pop('compression', 1)
    priority = kwargs.pop('priority', 0)
    heavy_input = kwargs.pop('heavy_input', None)
    reducer = _reduce
    if clevel is not None:
        function = _compression_wrapper(clevel, function)
        reducer = _compression_wrapper(clevel, reducer)

    if heavy_input is not None:
        heavy_token = client.scatter(heavy_input, broadcast=True, hash=False)
        items = list(zip(items, repeat(heavy_token)))
    futures = client.map(function, items, priority=priority)
    while len(futures) > 1:
        futures = client.map(
            reducer,
            [futures[i:i + ntree] for i in range(0, len(futures), ntree)],
            priority=priority,
        )
    if status:
        from dask.distributed import progress
        # FIXME: fancy widget doesn't appear, have to live with boring pbar
        progress(futures, multi=True, notebook=False)
    accumulator += _maybe_decompress(futures.pop().result())
    return accumulator

def parsl_executor(items, function, accumulator, **kwargs):
    """Execute using parsl pyapp wrapper

    Parameters
    ----------
        items : list
            List of input arguments
        function : callable
            A function to be called on each input, which returns an accumulator instance
        accumulator : AccumulatorABC
            An accumulator to collect the output of the function
        config : parsl.config.Config, optional
            A parsl DataFlow configuration object. Necessary if there is no active kernel

            .. note:: In general, it is safer to construct the DFK with ``parsl.load(config)`` prior to calling this function
        status : bool
            If true (default), enable progress bar
        unit : str
            Label of progress bar unit
        desc : str
            Label of progress bar description
        compression : int, optional
            Compress accumulator outputs in flight with LZ4, at level specified (default 1)
            Set to ``None`` for no compression.
    """
    if len(items) == 0:
        return accumulator
    import parsl
    from parsl.app.app import python_app
    from .parsl.timeout import timeout
    status = kwargs.pop('status', True)
    unit = kwargs.pop('unit', 'items')
    desc = kwargs.pop('desc', 'Processing')
    clevel = kwargs.pop('compression', 1)
    if clevel is not None:
        function = _compression_wrapper(clevel, function)
    add_fn = _iadd

    cleanup = False
    config = kwargs.pop('config', None)
    try:
        parsl.dfk()
    except RuntimeError:
        cleanup = True
        pass
    if cleanup and config is None:
        raise RuntimeError("No active parsl DataFlowKernel, must specify a config to construct one")
    elif not cleanup and config is not None:
        raise RuntimeError("An active parsl DataFlowKernel already exists")
    elif config is not None:
        parsl.clear()
        parsl.load(config)

    app = timeout(python_app(function))

    futures = set(app(item) for item in items)
    _futures_handler(futures, accumulator, status, unit, desc, add_fn)

    if cleanup:
        parsl.dfk().cleanup()
        parsl.clear()

    return accumulator

def _work_function(item, processor_instance, flatten=False, savemetrics=False, mmap=False):
    if processor_instance == 'heavy':
        item, processor_instance = item
    if not isinstance(processor_instance, ProcessorABC):
        processor_instance = cloudpickle.loads(lz4f.decompress(processor_instance))
    if mmap:
        localsource = {}
    else:
        opts = dict(uproot.FileSource.defaults)
        opts.update({'parallel': None})

        def localsource(path):
            return uproot.FileSource(path, **opts)

    file = uproot.open(item.filename, localsource=localsource)
    tree = file[item.treename]
    df = LazyDataFrame(tree, item.chunksize, item.index, flatten=flatten)
    df['dataset'] = item.dataset
    tic = time.time()
    out = processor_instance.process(df, locals())
    toc = time.time()
    metrics = dict_accumulator()
    if savemetrics:
        if isinstance(file.source, uproot.source.xrootd.XRootDSource):
            metrics['bytesread'] = value_accumulator(int, file.source.bytesread)
            metrics['dataservers'] = set_accumulator({file.source._source.get_property('DataServer')})
        metrics['columns'] = set_accumulator(df.materialized)
        metrics['entries'] = value_accumulator(int, df.size)
        metrics['processtime'] = value_accumulator(float, toc - tic)
    wrapped_out = dict_accumulator({'out': out, 'metrics': metrics})
    file.source.close()
    return wrapped_out

def _normalize_fileset(fileset, treename):
    for dataset, filelist in fileset.items():
        if isinstance(filelist, dict):
            local_treename = filelist['treename'] if 'treename' in filelist else treename
            filelist = filelist['files']
        elif isinstance(filelist, list):
            if treename is None:
                raise ValueError('treename must be specified if the fileset does not contain tree names')
            local_treename = treename
        else:
            raise ValueError('list of filenames in fileset must be a list or a dict')
        for filename in filelist:
            yield FileMeta(dataset, filename, local_treename)

def _get_metadata(item):
    nentries = uproot.numentries(item.filename, item.treename)
    return set_accumulator([FileMeta(item.dataset, item.filename, item.treename, nentries)])

def run_uproot_job(fileset,
                   treename,
                   processor_instance,
                   executor,
                   executor_args={},
                   pre_executor=None,
                   pre_args=None,
                   chunksize=200000,
                   maxchunks=None,
                   metadata_cache=LRUCache(100000)
                   ):
    '''A tool to run a processor using uproot for data delivery

    A convenience wrapper to submit jobs for a file set, which is a
    dictionary of dataset: [file list] entries.  Supports only uproot
    reading, via the LazyDataFrame class.  For more customized processing,
    e.g. to read other objects from the files and pass them into data frames,
    one can write a similar function in their user code.

    Parameters
    ----------
        fileset : dict
            A dictionary ``{dataset: [file, file], }``
            Optionally, if some files' tree name differ, the dictionary can be specified:
            ``{dataset: {'treename': 'name', 'files': [file, file]}, }``
        treename : str
            name of tree inside each root file, can be ``None``;
            treename can also be defined in fileset, which will override the passed treename
        processor_instance : ProcessorABC
            An instance of a class deriving from ProcessorABC
        executor : callable
            A function that takes 3 arguments: items, function, accumulator
            and performs some action equivalent to:
            ``for item in items: accumulator += function(item)``
        executor_args : dict, optional
            Arguments to pass to executor.  See `iterative_executor`,
            `futures_executor`, `dask_executor`, or `parsl_executor` for available options.
            Some options that affect the behavior of this function:
            'savemetrics' saves some detailed metrics for xrootd processing (default False);
            'flatten' removes any jagged structure from the input files (default False);
            'processor_compression' sets the compression level used to send processor instance
            to workers (default 1).
        pre_executor : callable
            A function like executor, used to calculate fileset metadata
            Defaults to executor
        pre_args : dict, optional
            Similar to executor_args, defaults to executor_args
        chunksize : int, optional
            Maximum number of entries to process at a time in the data frame.
        maxchunks : int, optional
            Maximum number of chunks to process per dataset
            Defaults to processing the whole dataset
        metadata_cache : mapping, optional
            A dict-like object to use as a cache for (file, tree) metadata that is used to
            determine chunking.  Defaults to a in-memory LRU cache that holds 100k entries
            (about 1MB depending on the length of filenames, etc.)  If you edit an input file
            (please don't) during a session, the session can be restarted to clear the cache.
    '''
    if not isinstance(fileset, Mapping):
        raise ValueError("Expected fileset to be a mapping dataset: list(files)")
    if not isinstance(processor_instance, ProcessorABC):
        raise ValueError("Expected processor_instance to derive from ProcessorABC")

    if pre_executor is None:
        pre_executor = executor
    if pre_args is None:
        pre_args = executor_args

    fileset = list(_normalize_fileset(fileset, treename))
    for filemeta in fileset:
        filemeta.maybe_populate(metadata_cache)

    chunks = []
    if maxchunks is None:
        # this is a bit of an abuse of map-reduce but ok
        to_get = set(filemeta for filemeta in fileset if not filemeta.populated)
        if len(to_get) > 0:
            out = set_accumulator()
            real_pre_args = {
                'desc': 'Preprocessing',
                'unit': 'file',
            }
            real_pre_args.update(pre_args)
            executor(to_get, _get_metadata, out, **real_pre_args)
            while out:
                item = out.pop()
                metadata_cache[item] = item.numentries
            for filemeta in fileset:
                filemeta.maybe_populate(metadata_cache)
        while fileset:
            filemeta = fileset.pop()
            for chunk in filemeta.chunks(chunksize):
                chunks.append(chunk)
    else:
        # get just enough file info to compute chunking
        nchunks = defaultdict(int)
        while fileset:
            filemeta = fileset.pop()
            if nchunks[filemeta.dataset] >= maxchunks:
                continue
            if not filemeta.populated:
                filemeta.numentries = _get_metadata(filemeta).pop().numentries
                metadata_cache[filemeta] = filemeta.numentries
            for chunk in filemeta.chunks(chunksize):
                chunks.append(chunk)
                nchunks[filemeta.dataset] += 1
                if nchunks[filemeta.dataset] >= maxchunks:
                    break

    # pop all _work_function args here
    savemetrics = executor_args.pop('savemetrics', False)
    flatten = executor_args.pop('flatten', False)
    mmap = executor_args.pop('mmap', False)
    pi_compression = executor_args.pop('processor_compression', 1)
    if pi_compression is None:
        pi_to_send = processor_instance
    else:
        pi_to_send = lz4f.compress(cloudpickle.dumps(processor_instance), compression_level=pi_compression)
    # hack around dask/dask#5503 which is really a silly request but here we are
    if executor is dask_executor:
        executor_args['heavy_input'] = pi_to_send
        closure = partial(_work_function,
                          processor_instance='heavy',
                          flatten=flatten,
                          savemetrics=savemetrics,
                          mmap=mmap,
                          )
    else:
        closure = partial(_work_function,
                          processor_instance=pi_to_send,
                          flatten=flatten,
                          savemetrics=savemetrics,
                          mmap=mmap,
                          )

    out = processor_instance.accumulator.identity()
    wrapped_out = dict_accumulator({'out': out, 'metrics': dict_accumulator()})
    exe_args = {
        'unit': 'chunk',
    }
    exe_args.update(executor_args)
    executor(chunks, closure, wrapped_out, **exe_args)
    wrapped_out['metrics']['chunks'] = value_accumulator(int, len(chunks))
    processor_instance.postprocess(out)
    if savemetrics:
        return out, wrapped_out['metrics']
    return out

def run_parsl_job(fileset, treename, processor_instance, executor, executor_args={}, chunksize=200000):
    '''A wrapper to submit parsl jobs

    .. note:: Deprecated in favor of `run_uproot_job` with the `parsl_executor`

    Jobs are specified by a file set, which is a dictionary of
    dataset: [file list] entries.  Supports only uproot reading,
    via the LazyDataFrame class.  For more customized processing,
    e.g. to read other objects from the files and pass them into data frames,
    one can write a similar function in their user code.

    Parameters
    ----------
        fileset : dict
            dictionary {dataset: [file, file], }
        treename : str
            name of tree inside each root file
        processor_instance : ProcessorABC
            An instance of a class deriving from ProcessorABC
        executor : coffea.processor.parsl.parsl_executor
            Must be the parsl executor, or otherwise derive from
            ``coffea.processor.parsl.ParslExecutor``
        executor_args : dict
            Extra arguments to pass to executor.  Special options
            interpreted here: 'config' provides a parsl dataflow
            configuration.
        chunksize : int, optional
            Number of entries to process at a time in the data frame

    '''

    try:
        import parsl
    except ImportError as e:
        print('you must have parsl installed to call run_parsl_job()!', file=sys.stderr)
        raise e

    import warnings

    warnings.warn("run_parsl_job is deprecated and will be removed in 0.7.0, replaced by run_uproot_job",
                  DeprecationWarning)

    from .parsl.parsl_executor import ParslExecutor
    from .parsl.detail import _default_cfg

    if not isinstance(fileset, Mapping):
        raise ValueError("Expected fileset to be a mapping dataset: list(files)")
    if not isinstance(processor_instance, ProcessorABC):
        raise ValueError("Expected processor_instance to derive from ProcessorABC")
    if isinstance(executor, ParslExecutor):
        warnings.warn("ParslExecutor class is deprecated replacing with processor.parsl_executor",
                      DeprecationWarning)
        executor = parsl_executor
    elif executor == parsl_executor:
        pass
    else:
        raise ValueError("Expected executor to derive from ParslExecutor or be executor.parsl_executor")

    executor_args.setdefault('config', _default_cfg)
    executor_args.setdefault('timeout', 180)
    executor_args.setdefault('chunking_timeout', 10)
    executor_args.setdefault('flatten', False)
    executor_args.setdefault('compression', 0)

    try:
        parsl.dfk()
        executor_args.pop('config')
    except RuntimeError:
        pass

    output = run_uproot_job(fileset,
                            treename,
                            processor_instance=processor_instance,
                            executor=executor,
                            executor_args=executor_args)

    return output

def run_spark_job(fileset, processor_instance, executor, executor_args={},
                  spark=None, partitionsize=200000, thread_workers=16):
    '''A wrapper to submit spark jobs

    A convenience wrapper to submit jobs for spark datasets, which is a
    dictionary of dataset: [file list] entries.  Presently supports reading of
    parquet files converted from root.  For more customized processing,
    e.g. to read other objects from the files and pass them into data frames,
    one can write a similar function in their user code.

    Parameters
    ----------
        fileset : dict
            dictionary {dataset: [file, file], }
        processor_instance : ProcessorABC
            An instance of a class deriving from ProcessorABC

            .. note:: The processor instance must define all the columns in data and MC that it reads as ``.columns``
        executor:
            anything that inherits from `SparkExecutor` like `spark_executor`

            In general, a function that takes 3 arguments: items, function accumulator
            and performs some action equivalent to:
            for item in items: accumulator += function(item)
        executor_args:
            arguments to send to the creation of a spark session
        spark:
            an optional already created spark instance

            if ``None`` then we create an ephemeral spark instance using a config
        partitionsize:
            partition size to try to aim for (coalescese only, repartition too expensive)
        thread_workers:
            how many spark jobs to let fly in parallel during processing steps
    '''

    try:
        import pyspark
    except ImportError as e:
        print('you must have pyspark installed to call run_spark_job()!', file=sys.stderr)
        raise e

    import pyspark.sql
    from .spark.spark_executor import SparkExecutor
    from .spark.detail import _spark_initialize, _spark_stop, _spark_make_dfs

    if not isinstance(fileset, Mapping):
        raise ValueError("Expected fileset to be a mapping dataset: list(files)")
    if not isinstance(processor_instance, ProcessorABC):
        raise ValueError("Expected processor_instance to derive from ProcessorABC")
    if not isinstance(executor, SparkExecutor):
        raise ValueError("Expected executor to derive from SparkExecutor")

    executor_args.setdefault('config', None)
    executor_args.setdefault('file_type', 'parquet')
    executor_args.setdefault('laurelin_version', '0.3.0')
    executor_args.setdefault('treeName', 'Events')
    executor_args.setdefault('flatten', False)
    executor_args.setdefault('cache', True)
    file_type = executor_args['file_type']
    treeName = executor_args['treeName']
    flatten = executor_args['flatten']
    use_cache = executor_args['cache']

    if executor_args['config'] is None:
        executor_args.pop('config')

    # initialize spark if we need to
    # if we initialize, then we deconstruct
    # when we're done
    killSpark = False
    if spark is None:
        spark = _spark_initialize(**executor_args)
        killSpark = True
        use_cache = False  # if we always kill spark then we cannot use the cache
    else:
        if not isinstance(spark, pyspark.sql.session.SparkSession):
            raise ValueError("Expected 'spark' to be a pyspark.sql.session.SparkSession")

    dfslist = {}
    if executor._cacheddfs is None:
        dfslist = _spark_make_dfs(spark, fileset, partitionsize, processor_instance.columns,
                                  thread_workers, file_type, treeName)

    output = processor_instance.accumulator.identity()
    executor(spark, dfslist, processor_instance, output, thread_workers, use_cache, flatten)
    processor_instance.postprocess(output)

    if killSpark:
        _spark_stop(spark)
        del spark
        spark = None

    return output


from collections import deque
import sys

if __name__=='__main__' :
    x=list(map(int,sys.stdin.readline().split()))
    y=list(map(int,sys.stdin.readline().split()))

    result = deque([i for i in range(1,x[0]+1)])  # deque사용

    count=0

    for i in y:
        while(i!=result[0]): #2번, 3번 수행 조건
            count+=1

            c=list(result) #slice위해 list로 변환

            #최솟값 찾기 위해 길이 구함
            a=len(c[c.index(i)::])
            b=len(c[:c.index(i)])

            if a<=b: #a가 더 작으면 오른쪽으로 이동 ak, a1, ..., ak-1
                temp=result.pop()
                result.appendleft(temp)
            else: #b가 더 작으면 왼쪽으로 이동 a2, ..., ak, a1
                temp=result.popleft()
                result.append(temp)
        result.popleft() #1번 수행

    print(count)


"""
Takes in a list of magic cards from web form and returns shopping list file.

"""

# Import statements
import json
import requests
import time
import sys

def buildCache():
    """Build cached json to speed process"""
    with open("./json_cache/manual_cache.json", "w+") as target:
        output = []
        request = requests.get("https://api.scryfall.com/cards")
        # x_counter = 0
        # y_counter = 0
        while True:
            # for i in range(10):
            # print(f"Next page is: {request.json()['next_page']}")
            for card in request.json()["data"]:
                if card["lang"] != "en":
                    continue
                else:
                    if card["prices"]["usd"] is None:
                        # x_counter += 1
                        # card["prices"]["usd"] = 0.00
                        continue
                    else:
                        card["prices"]["usd"] = float(card["prices"]["usd"])
                # y_counter += 1
                output.append(card)

            if request.json()["has_more"]:
                time.sleep(0.1)
                request = requests.get(request.json()["next_page"])
            else:
                break

        # print(f"The number of cards with None price: {x_counter}")
        # print(f"The number of cards processed: {y_counter}")
        target.write(json.dumps(output))

def getBulk(url):
    """
    Get bulk file from scryfall.

    url: https://archive.scryfall.com/json/scryfall-default-cards.json
    """
    download = requests.get(url, allow_redirects=True)
    with open("./json_cache/bulk_cache.json", "w") as target:
        target.write(json.dumps(download.json()))

def loadJson(target):
    """
    Load target json, return python json object.
    """
    with open(target, "r") as thing:
        output = json.load(thing)
    return output

def getDuplicates(card_name, bulk_json):
    """Search bulk for cards by name, return all printings."""
    output = []
    for card in bulk_json:

        if "card_faces" in card:
            for face in card["card_faces"]:
                if face["name"] == card_name:
                    output.append(card["id"])
                    break
        else:
            if card["name"] == card_name and card["lang"] == "en":
                output.append(card["id"])
    return output

def getPrices(id_list):
    """Get high and low prices from all printings, high/low"""
    high = -1
    low = 100000000
    for UUID in id_list:
        current = requests.get(f"https://api.scryfall.com/cards/{UUID}")
        if "Basic Land" in current.json()["type_line"]:
            high = 0.0
            low = 0.0
            return high, low
        time.sleep(0.12)
        current_price = current.json()["prices"]["usd"]

        if current_price == None:
            continue
        current_price = float(current_price)
        if current_price > high:
            high = current_price
        if current_price < low:
            low = current_price

    return high, low

def getLocalPrices(id_list):
    """Get high and low prices from all printings, high/low"""
    high = -1
    low = 100000000
    local = loadJson("./json_cache/manual_cache.json")

    counter = 0

    for card in local:
        if card["id"] in id_list:
            if "Basic Land" in card["type_line"]:
                high = 0.0
                low = 0.0
                return high, low

            current_price = card["prices"]["usd"]
            counter += 1
            if current_price == None:
                continue
            current_price = float(current_price)
            if current_price > high:
                high = current_price
            if current_price < low:
                low = current_price

        if counter == len(id_list):
            break

    return high, low

class Card:
    """Card class for organizing prices and ids"""

    def __init__(self, num, name):
        self.name = name
        self.UUID = getDuplicates(name, loadJson("./json_cache/manual_cache.json"))
        self.high_price, self.low_price = getLocalPrices(self.UUID)
        self.quantity = num

def shoppingList(card_list):
    """Take list of card from website input, return txt shopping list"""
    # print(card_list)

    output_list = []
    for line in card_list:
        # Format should be in "1 Arbor Elf"
        split_list = line.split(" ", 1)
        print(f"{split_list[1]} is being processed.")
        # print(split_list)
        num = split_list[0]
        name = split_list[1]
        output_list.append(Card(num, name))

    with open("./shopping_list.txt", "w") as output:
        output.write("Shopping List!\n")
        output.write("-" * 80 + "\n")
        running_high = 0
        running_low = 0
        for card in output_list:
            output.write(
                f"{card.quantity} {card.name} High: {card.high_price} Low: {card.low_price}\n"
            )
            running_high += card.high_price * float(card.quantity)
            running_low += card.low_price * float(card.quantity)
        output.write("\n")
        output.write(
            f"The total high end is: {running_high} and total low end is: {running_low}"
        )
    return 0

if __name__ == "__main__":
    print("It made it into the python.")
    shoppingList(sys.argv[1].replace("\r", "").split("\n"))

    # for i in range(len(sys.argv)):
    #     print(f"Argument {i} is :")
    #     print()
    #     print(sys.argv[i])
    #     print()


from euler_totient_func import gcd, euler_phi_func
import random

# egcd code taken from https://brilliant.org/wiki/extended-euclidean-algorithm/
# overall ref: https://www.lri.fr/~fmartignon/documenti/systemesecurite/6-PublicKey.pdf
def egcd(a, b):
	x,y, u,v = 0,1, 1,0
	while a != 0:
		q, r = b//a, b%a
		m, n = x-u*q, y-v*q
		b,a, x,y, u,v = a,r, u,v, m,n
	gcd = b
	return gcd, x, y

# find two 'large' primes
p, q = 53, 23

#compute n = p * q. The hardness assumption is, it's easy to compute n, but hard to find p, q given n.
n = p * q
phi_n = len(euler_phi_func(n))

# the result of the totient function is actually the multiplication of
# p - 1 and q - 1, phi(n) = (p-1) * (q-1)

# Select a random integer e, 1 < e < Φ(n), s.t.
# gcd(e, Φ(n)) = 1
e = 3
while True:
	e = random.randint(3, phi_n)
	if gcd(e, phi_n) == 1:
		break

# Compute d, 1< d < Φ(n) s.t. e*d ≡ 1 mod Φ(n), that is:
# find the multiplicative inverse of e, in the group modulo phi_n
# using the Extended Euclidean Algorithm, we can find gcd(a, b) and gcd(a, b) = ax + by
# in the special case where gcd(a, b) = 1, there ax + by = 1 or a | by - 1 => by = 1 mod a
# in this case, a is the phi_n, b is e, so the result of egcd algorithm would return
# the group inverse of e in the group mod phi_n in the last element as b

d = egcd(phi_n, e)[2]
if d < 0:
	while d < 0:
		d += phi_n

# Now let's say the message is 50. The encryption would be: m^e mod n
# as everyone has the public key e, and n, anyone can encrypt a message with it.
c = (50 ** e) % n
print('ciphertext c with params: (e, d, phi_n, n, c)', e, d, phi_n, n, c)
# Now to decrypt this ciphertext c, we must use the following formula:
# m = c^d mod n

# and the decryption would be:
print('decrypted msg is: ', (c ** d) % n) # outputs 50


import random

import arrow
import discord
from pymongo.errors import DuplicateKeyError
from rich.console import Console

from .cog_management import collect_cogs, load_cogs
from .mongo_db import db

class GoonBot(discord.Bot):
    """
    Goonbot5 instance
    """

    def __init__(self):
        super().__init__(
            intents=discord.Intents(
                members=True,
                messages=True,
                guilds=True,
                bans=True,
                message_content=True,
            ),
            owner_ids=[
                177131156028784640,  # Bexli
            ],
            debug_guilds=[
                510865274594131968,  # Debug guild
                177125557954281472,  # g00n guild
            ],
        )

        collect_cogs()
        load_cogs(self)

        self.startup = arrow.now()
        self.console = Console(log_time_format="[%b %d, %y @ %H:%M:%S]")
        self.db = db

    async def on_ready(self):
        """Overwrites default on_ready"""
        self.console.log(f"{self.user.name} has logged in 👍")  # type: ignore

    @property
    def suggestions(self):
        return self.db["suggestions"]

    @property
    def bios(self):
        return self.db["bios"]

    @property
    def tokens(self):
        return self.db["tokens"]

    async def get_tokens(self, user: discord.Member | discord.User):
        """Returns a user's 'tokens' document"""
        # Disgustingly hacky way to make sure user has a token document.
        try:
            await self.tokens.insert_one({"_id": user.id, "coins": 10})
        except DuplicateKeyError:
            pass

        user_tokens = await self.tokens.find_one({"_id": user.id})
        return user_tokens

    async def get_token_amount(self, token: str, user: discord.Member | discord.User):
        """Check to see how many of a specific token a user has"""
        user_tokens = await self.get_tokens(user)
        return user_tokens.get(token)

    async def change_token_amount(self, token: str, user: discord.Member | discord.User, change_amount: int):
        user_tokens = await self.get_tokens(user)
        await self.tokens.update_one(user_tokens, {"$inc": {"coins": change_amount}})
        return user_tokens.get(token)


#
# @lc app=leetcode.cn id=238 lang=python3
#
# [238] 除自身以外数组的乘积
#

# @lc code=start
class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        res, p, q = [1], 1, 1
        for i in range(len(nums) - 1):
            p *= nums[i]
            res.append(p)

        for i in range(len(nums) -1, 0, -1):
            q *= nums[i]
            res[i - 1] *= q

        return res
# @lc code=end

238.除自身以外数组的乘积.py


"""
# Definition for a Node.
class Node:
    def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next
"""

class Solution:
    def connect(self, root: 'Node') -> 'Node':

        my_queue = []

        if not root: return

        # initialize
        my_queue.append(root)

        while my_queue:
            num = len(my_queue)

            first_node = my_queue.pop(0)
            if first_node.left:
                my_queue.append(first_node.left)
            if first_node.right:
                my_queue.append(first_node.right)

            prev_node = first_node

            for i in range(1, num):
                curr_node = my_queue.pop(0)
                prev_node.next = curr_node
                prev_node = curr_node

                if curr_node.left:
                    my_queue.append(curr_node.left)
                if curr_node.right:
                    my_queue.append(curr_node.right)

        return root

"""
Results
BFS(level order traversal)
Runtime: 36 ms, faster than 99.68% of Python3 online submissions for Populating Next Right Pointers in Each Node II.
Memory Usage: 15.1 MB, less than 9.89% of Python3 online submissions for Populating Next Right Pointers in Each Node II.
"""

Round_1/117. Populating Next Right Pointers in Each Node II/solution_1.py


import cv2
import numpy as np                           #importing libraries
cap = cv2.VideoCapture(0)                #creating camera objec

while( cap.isOpened()):
	ret,img = cap.read()                         #reading the frames
	k = cv2.waitKey(10)
	gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
	blur = cv2.GaussianBlur(gray,(5,5),0)
	ret,thresh1 = cv2.threshold(blur,150,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
	cv2.imshow('input',img)                  #displaying the frames

	if k == 27:
		break


import math

class BinaryHeap:
    def __init__(self):
        self.heap_list = []
        self.size = 0

    def insert(self, node):
        self.heap_list.append(node)
        self._order_up(self.size - 1)
        self.size += 1

    def _order_up(self, index):
        parent_index = (index - 1) // 2
        while index > 0 and self.heap_list[index].factor() < self.heap_list[parent_index].factor():
            self.swap(index, parent_index)
            index = parent_index
            parent_index = (index - 1) // 2

    def _order_down(self, size, index):
        minor = index
        left = index * 2 + 1
        right = index * 2 + 2

        if left < size and self.heap_list[left].factor() > self.heap_list[minor].factor():
            minor = left

        if right < size and self.heap_list[right].factor() > self.heap_list[minor].factor():
            minor = right

        if minor != index:
            self.swap(index, minor)
            self._order_down(size, minor)

    def swap(self, pos_x, pos_y):
        aux_x = self.heap_list[pos_x]
        self.heap_list[pos_x] = self.heap_list[pos_y]
        self.heap_list[pos_y] = aux_x

    # def find_min(self):

    def delete_min(self):
        if self.is_empty():
            return None
        minor = self.heap_list[0]
        self.swap(0, self.size - 1)
        self.heap_list.pop()
        self.size -= 1
        self.heap_sort_minor()
        return minor

    def find_min(self):
        if self.is_empty():
            return None
        return self.heap_list[0]

    def is_empty(self):
        return self.size == 0

    def size(self):
        return self.size

    def build_heap(self, list_to_heap):
        self.heap_list = []
        self.size = 0
        for item in list_to_heap:
            self.insert(item)

    def heap_sort_minor(self):
        for index in range(self.size // 2 - 1, -1, -1):
            self._order_down(self.size, index)

        for index in range(self.size - 1, 0, -1):
            self.swap(0, index)
            self._order_down(index, 0)


from flask import render_template
from markupsafe import Markup

from indico.core import signals
from indico.util.signals import named_objects_from_signal
from indico.util.string import format_repr

class _MenuSectionBase:
    is_section = True

    def __init__(self, name, title, weight=-1):
        self.name = name
        self.title = title
        self.weight = weight
        self._items = set()
        self._sorted_items = None

    def add_item(self, item):
        self._sorted_items = None
        self._items.add(item)

    @property
    def items(self):
        if self._sorted_items is None:
            self._sorted_items = sorted(self._items, key=lambda x: (-x.weight, x.title.lower()))
        return self._sorted_items

class SideMenuSection(_MenuSectionBase):
    """Define a side menu section (item set).

    :param name: the unique name of the section
    :param title: the title of the section (displayed)
    :param weight: the "weight" (higher means it shows up first)
    :param active: whether the section should be shown expanded by default
    :param icon: icon that will be displayed next to the section title.
    """

    def __init__(self, name, title, weight=-1, active=False, icon=None):
        super().__init__(name, title, weight)
        self._active = active
        self.icon = 'icon-' + icon if icon else None

    @property
    def active(self):
        return self._active or any(item.active for item in self._items)

    def __repr__(self):
        return format_repr(self, 'name', 'title', active=False)

class SideMenuItem:
    """Define a side menu item.

    :param name: the unique name (within the menu) of the item
    :param title: the title of the menu item (displayed)
    :param url: the URL that the link will point to
    :param weight: the "weight" (higher means it shows up first)
    :param active: whether the item will be shown as active by default
    :param disabled: if `True`, the item will be displayed as disabled
    :param section: section the item will be put in
    :param icon: icon that will be displayed next to the item
    :param badge: text (typically a number) that is shown in a badge
    """

    is_section = False

    def __init__(self, name, title, url, weight=-1, active=False, disabled=False, section=None, icon=None,
                 sui_icon=None, badge=None):
        assert not (icon and sui_icon)
        self.name = name
        self.title = title
        self.url = url
        self.active = active
        self.disabled = disabled
        self.section = section
        self.weight = weight
        self.icon = ('icon-' + icon) if icon else None
        self.sui_icon = sui_icon
        self.badge = badge

    def __repr__(self):
        return format_repr(self, 'name', 'title', 'url', active=False, disabled=False)

class TopMenuSection(_MenuSectionBase):
    """Define a top menu section (dropdown).

    :param name: the unique name of the section
    :param title: the title of the section (displayed)
    :param weight: the "weight" (higher means it shows up first)
    """

    def __repr__(self):
        return format_repr(self, 'name', 'title')

class TopMenuItem:
    """Define a top menu item.

    :param name: the unique name (within the menu) of the item
    :param title: the title of the menu item (displayed)
    :param url: the URL that the link will point to
    :param weight: the "weight" (higher means it shows up first)
    :param section: dropdown section the item will be put in
    """

    is_section = False

    def __init__(self, name, title, url, weight=-1, section=None):
        self.name = name
        self.title = title
        self.url = url
        self.section = section
        self.weight = weight

    def __repr__(self):
        return format_repr(self, 'name', 'title', 'url')

def build_menu_structure(menu_id, active_item=None, **kwargs):
    """Build a menu (list of entries) with sections/items.

    Information is provided by specific signals and filtered
    by menu id.
    This can be used as a very thin framework for menu
    handling across the app.

    :param menu_id: menu_id used to filter out signal calls
    :param active_item: ID of currently active menu item
    :param kwargs: extra arguments passed to the signals
    :return: properly sorted list (taking weights into account)
    """
    top_level = set()
    sections = {}

    for id_, section in named_objects_from_signal(signals.menu.sections.send(menu_id, **kwargs)).items():
        sections[id_] = section
        top_level.add(section)

    for id_, item in named_objects_from_signal(signals.menu.items.send(menu_id, **kwargs)).items():
        if id_ == active_item:
            item.active = True
        if item.section is None:
            top_level.add(item)
        else:
            sections[item.section].add_item(item)

    return sorted(top_level, key=lambda x: (-x.weight, x.title))

def get_menu_item(menu_id, item, **kwargs):
    """Get a specific menu item.

    :param menu_id: menu_id used to filter out signal calls
    :param item: ID of the item to retrieve
    :param kwargs: extra arguments passed to the signals
    :return: the specified menu item or ``None``
    """
    return named_objects_from_signal(signals.menu.items.send(menu_id, **kwargs)).get(item)

def render_sidemenu(menu_id, active_item=None, **kwargs):
    """Render a sidemenu with sections/items.

    :param menu_id: The identifier of the menu.
    :param active_item: The name of the currently-active menu item.
    :param kwargs: Additional arguments passed to the menu signals.
    """
    items = build_menu_structure(menu_id, active_item=active_item, **kwargs)
    return Markup(render_template('side_menu.html', items=items, menu_id=menu_id))


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import shutil
import tempfile

import numpy as np
import six

from tensorflow.contrib.estimator.python.estimator import dnn
from tensorflow.contrib.estimator.python.estimator import head as head_lib
from tensorflow.python.estimator.canned import dnn_testing_utils
from tensorflow.python.estimator.canned import prediction_keys
from tensorflow.python.estimator.export import export
from tensorflow.python.estimator.inputs import numpy_io
from tensorflow.python.feature_column import feature_column
from tensorflow.python.framework import ops
from tensorflow.python.platform import gfile
from tensorflow.python.platform import test
from tensorflow.python.summary.writer import writer_cache

def _dnn_estimator_fn(weight_column=None, label_dimension=1, *args, **kwargs):
  """Returns a DNNEstimator that uses regression_head."""
  return dnn.DNNEstimator(
      head=head_lib.regression_head(
          weight_column=weight_column, label_dimension=label_dimension),
      *args, **kwargs)

class DNNEstimatorEvaluateTest(
    dnn_testing_utils.BaseDNNRegressorEvaluateTest, test.TestCase):

  def __init__(self, methodName='runTest'):  # pylint: disable=invalid-name
    test.TestCase.__init__(self, methodName)
    dnn_testing_utils.BaseDNNRegressorEvaluateTest.__init__(
        self, _dnn_estimator_fn)

class DNNEstimatorPredictTest(
    dnn_testing_utils.BaseDNNRegressorPredictTest, test.TestCase):

  def __init__(self, methodName='runTest'):  # pylint: disable=invalid-name
    test.TestCase.__init__(self, methodName)
    dnn_testing_utils.BaseDNNRegressorPredictTest.__init__(
        self, _dnn_estimator_fn)

class DNNEstimatorTrainTest(
    dnn_testing_utils.BaseDNNRegressorTrainTest, test.TestCase):

  def __init__(self, methodName='runTest'):  # pylint: disable=invalid-name
    test.TestCase.__init__(self, methodName)
    dnn_testing_utils.BaseDNNRegressorTrainTest.__init__(
        self, _dnn_estimator_fn)

class DNNEstimatorIntegrationTest(test.TestCase):

  def setUp(self):
    self._model_dir = tempfile.mkdtemp()

  def tearDown(self):
    if self._model_dir:
      writer_cache.FileWriterCache.clear()
      shutil.rmtree(self._model_dir)

  def _test_complete_flow(
      self, train_input_fn, eval_input_fn, predict_input_fn, input_dimension,
      label_dimension, batch_size):
    feature_columns = [
        feature_column.numeric_column('x', shape=(input_dimension,))]
    est = dnn.DNNEstimator(
        head=head_lib.regression_head(label_dimension=label_dimension),
        hidden_units=(2, 2),
        feature_columns=feature_columns,
        model_dir=self._model_dir)

    # TRAIN
    num_steps = 10
    est.train(train_input_fn, steps=num_steps)

    # EVALUTE
    scores = est.evaluate(eval_input_fn)
    self.assertEqual(num_steps, scores[ops.GraphKeys.GLOBAL_STEP])
    self.assertIn('loss', six.iterkeys(scores))

    # PREDICT
    predictions = np.array([
        x[prediction_keys.PredictionKeys.PREDICTIONS]
        for x in est.predict(predict_input_fn)
    ])
    self.assertAllEqual((batch_size, label_dimension), predictions.shape)

    # EXPORT
    feature_spec = feature_column.make_parse_example_spec(feature_columns)
    serving_input_receiver_fn = export.build_parsing_serving_input_receiver_fn(
        feature_spec)
    export_dir = est.export_savedmodel(tempfile.mkdtemp(),
                                       serving_input_receiver_fn)
    self.assertTrue(gfile.Exists(export_dir))

  def test_numpy_input_fn(self):
    """Tests complete flow with numpy_input_fn."""
    label_dimension = 2
    batch_size = 10
    data = np.linspace(0., 2., batch_size * label_dimension, dtype=np.float32)
    data = data.reshape(batch_size, label_dimension)
    # learn y = x
    train_input_fn = numpy_io.numpy_input_fn(
        x={'x': data},
        y=data,
        batch_size=batch_size,
        num_epochs=None,
        shuffle=True)
    eval_input_fn = numpy_io.numpy_input_fn(
        x={'x': data},
        y=data,
        batch_size=batch_size,
        shuffle=False)
    predict_input_fn = numpy_io.numpy_input_fn(
        x={'x': data},
        batch_size=batch_size,
        shuffle=False)

    self._test_complete_flow(
        train_input_fn=train_input_fn,
        eval_input_fn=eval_input_fn,
        predict_input_fn=predict_input_fn,
        input_dimension=label_dimension,
        label_dimension=label_dimension,
        batch_size=batch_size)

if __name__ == '__main__':
  test.main()


import urllib.request
import plotly.express as px
import pandas as pd
import numpy as np
import json

with urllib.request.urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
    counties = json.load(response)

df = pd.read_csv('https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv', dtype={"fips": str, "state": str, "county": str})
df.loc[df['county'] == "New York City",'fips'] = "36061"
df = df.groupby(['fips', 'state', 'county']).sum() #fips are index of counties
df = df.reset_index()
df['Deaths (log10)'] = np.log10(df['deaths'])

fig = px.choropleth(df, locations='Counties',
                        color='Deaths (log10)',
                        scope='usa',
                        geojson=counties,
                        hover_data=['deaths'])
fig.show()


import os
import datetime
from datetime import datetime as dt
from datetime import timedelta

from dotenv import load_dotenv
import requests
import pyodbc
from db.db import SessionLocal
from db.models import CallTouch

from logger.telegram import send_message

load_dotenv()

class CallTouchCon:
    @staticmethod
    def set_date() -> datetime.date:
        date = (dt.today() - timedelta(1)).strftime('%d/%m/%Y')
        send_message(f'ct_agent_set_date: {date}')
        return date

    def get_data(self, date=None) -> requests.Request:
        if date is None:
            date = self.set_date()
        url = f'http://api.calltouch.ru/calls-service/RestAPI/{os.getenv("CT_CLIENT")}/calls-diary/calls?clientApiId={os.getenv("CT_TOKEN")}&dateFrom={date}&dateTo={date}'
        response = requests.get(url)
        return response.json()

    @staticmethod
    def create_item(db: SessionLocal, row: dict) -> None:
        item = CallTouch(
            call_id=row.get('callId'),
            date=str(row.get('date')[0:10]),
            time=str(row.get('date')[12:20]),
            host=row.get('hostname'),
            client_number=str(row.get('callerNumber')),
            phone_number=str(row.get('phoneNumber')),
            status=str(row.get('successful')),
            uniq_target_call=str(row.get('uniqTargetCall')),
            city=row.get('city'),
            source=row.get('source'),
            medium=row.get('medium'),
            campaign=row.get('utmCampaign'),
            keyword=row.get('keyword'),
            ga_client_id=str(row.get('clientId')),
            device=row.get('device'),
            os=row.get('os')
        )
        try:
            db.add(item)
            db.commit()
            db.refresh(item)
        except pyodbc.Error:
            print('double')
            pass

    def run(self, date=None) -> requests.Request:
        data = self.get_data(date)
        if data:
            send_message('ct_agent_run witch data')
        db = SessionLocal()
        for row in data:
            self.create_item(db=db, row=row)
        return


#!/usr/bin/python
#duanjun1981@gmail.com

import sys, getopt
import matplotlib.pyplot as plt
import numpy as np
#import math
import seaborn as sns
import re

class AutoVivification(dict):
    """Implementation of perl's autovivification feature."""
    def __missing__(self, key):
        value = self[key] = type(self)()
        return value

def check_path_with_slash(folder):
    if not folder.endswith("/"):
        folder += "/"
    return folder

def sorted_by_number( l ):
    convert = lambda text: int(text) if text.isdigit() else text
    alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
    return sorted(l, key = alphanum_key)
def main(argv):
    inputfile = ''
    outputfile = ''
    number_of_columns = 5   #number of plot per row
    gene_list=["PB2","NS1","MP","NA","NP","HA","PA","PB1"]
    try:
        opts, args = getopt.getopt(argv,"hi:o:d:",["ifile=","dfile=","ofile="])
    except getopt.GetoptError:
        print('draw_coverage_v0.4.py -i <sample_list.txt> -d <input_dir> -o <outputfile>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print('draw_coverage_v0.4.py -i <sample_list.txt> -d input_dir -o <outputfile>')
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-d", "--dfile"):
            dirfile = arg
        elif opt in ("-o", "--ofile"):
            outputfile = arg
    sample_file = open(inputfile, 'r')
    samples = sample_file.read().split('\n')
    sample_file.close()
    sample_list=[]
    for sample_line in samples:
        if sample_line:
            words = sample_line.split()
            sample_list.append(words[0])
    number_of_subplots = len(sample_list)
    Rows = number_of_subplots // number_of_columns
    Rows += number_of_subplots % number_of_columns
    Position = range(1,number_of_subplots + 1)
    fig = plt.figure(figsize=(30,20))
    fontsize_cust=16
    pre_length = {
		    "PB1" : 2274,
		    "PB2" : 2007,
		    "NS1" : 693,
		    "MP" : 759,
		    "NA" : 1410,
		    "HA" : 2011,
		    "NP" : 1497,
		    "PA" : 2151,
		    	}
    for k in range(number_of_subplots):
        ax = fig.add_subplot(Rows,number_of_columns,Position[k])
        sample_name=sample_list[k]
        ax.set_title(sample_name,fontsize=fontsize_cust)
        ax.set_ylabel('Log2(Depth)',fontsize=fontsize_cust)
        ax.set_xticks([], [])
        ########################################################## read data
        pos_dict = AutoVivification()
        filename=check_path_with_slash(dirfile)+sample_name+"_cov.txt"
        datafile_raw = open(filename, 'r')
        sepfile_raw = datafile_raw.read().split('\n')
        datafile_raw.close()
        for datapair in sepfile_raw:
            if datapair:
                xypair = datapair.split('\t')
                pos_dict[xypair[0]][xypair[1]]= [xypair[2]];
        i=0
        len_list=[]
        x = []
        y = []

        for genename in gene_list:
            #print genename+"\t"+str(len(pos_dict[genename]))
            if len(pos_dict[genename])>0:
                len_list.append(len(pos_dict[genename]))
                #print pos_dict[genename]
                for position in sorted_by_number(pos_dict[genename]):
        	          i=i+1
        	          #print i
        	          #print position
        	          x.append(i)
        	          y.append(int(pos_dict[genename][position][0])+1)
            else:
                #print genename+"\t"+str(pre_length[genename])
                len_list.append(int(pre_length[genename]))
                for position in range (1,int(pre_length[genename])):
        	          i=i+1
        	         # print position
        	          x.append(i)
        	          y.append(1)
#
        y=np.log2(y)
        x_sm = np.array(x)
        y_sm = np.array(y)
        ########################################################## plot coverage
        start_x=0
        all_count=0
        label_pos=[]
        for s in len_list:
    	      start=all_count
    	      all_count=all_count+s
    	      end=all_count-1
    	      x_temp=x_sm[start:end]
    	      y_temp=y_sm[start:end]
    	      label_pos.append(start+(end-start)/2)
    	      with sns.color_palette("Set2"):
     	          plt.fill_between( x_temp, y_temp, alpha=0.8)
     	          plt.plot(x_temp, y_temp, '-',linewidth=0.3)
        plt.xticks(label_pos, gene_list, rotation='vertical',fontsize=fontsize_cust)
        plt.tight_layout(pad=5,w_pad=0, h_pad=1)
        ax.tick_params(axis='y', labelsize=fontsize_cust)

        ##########################################################

        #ax.plot(1,2)

    #plt.show()
    plt.savefig(outputfile+'.pdf')

if __name__ == "__main__":
    main(sys.argv[1:])


import pygame

CYAN = (0, 255, 255)
BLACK = (0, 0, 0)

pygame.init()

class UI:
    def __init__(self, game):
        self.game = game
        self.cell_size = 20
        self.player_image = pygame.image.load("resources/player.png")

        screen_width = game.board.width * self.cell_size
        screen_height = game.board.height * self.cell_size
        self.screen = pygame.display.set_mode((screen_width, screen_height))
        pygame.display.set_caption("Game UI")

    def draw_field(self, field):
        x = field.x * self.cell_size
        y = field.y * self.cell_size
        pygame.draw.rect(self.screen, CYAN, (x, y, self.cell_size, self.cell_size))
        pygame.draw.rect(self.screen, BLACK, (x + 3, y + 3, self.cell_size - 6, self.cell_size - 6))

    def draw(self):
        self.screen.fill((255, 255, 255))

        for x in range(self.game.board.width):
            for y in range(self.game.board.height):
                field = self.game.board.fields[x][y]
                if field.revealed:
                    self.draw_field(field)


from io import StringIO

from django.core.cache import cache
from django.core.management import call_command
from django.test import TestCase

class WarmupcacheTest(TestCase):

    def test_command_output(self):
        out = StringIO()
        call_command('warmupcache', stdout=out)
        self.assertIn('Cache was successfully warmed up', out.getvalue())

    def test_command_cache_was_cleared(self):
        cache.set('test_key', 'test value')
        self.assertIsNone(cache.get('20f180e978ce3b67ca2e7afd8a880385'))
        out = StringIO()
        call_command('warmupcache', stdout=out)
        self.assertFalse(cache.get('test_key'))
        self.assertIsNotNone(cache.get('20f180e978ce3b67ca2e7afd8a880385'))


from contextlib import contextmanager

import functools
import random
import typing

import numpy as np
import torch

class RandomGeneratorState(typing.NamedTuple):
    random: typing.Tuple[typing.Any]
    torch: torch.Tensor
    numpy: typing.Tuple[typing.Any]
    torch_cuda: typing.Optional[typing.Tuple[typing.Any]]

def get_random_generator_state(cuda: bool = torch.cuda.is_available()) -> RandomGeneratorState:
    """ Get the `torch`, `numpy` and `random` random generator state.

    Args:
        cuda (bool, optional): If `True` saves the `cuda` seed also. Note that getting and setting
            the random generator state for CUDA can be quite slow if you have a lot of GPUs.

    Returns:
        RandomGeneratorState
    """
    return RandomGeneratorState(random.getstate(), torch.random.get_rng_state(),
                                np.random.get_state(),
                                torch.cuda.get_rng_state_all() if cuda else None)

def set_random_generator_state(state: RandomGeneratorState):
    """ Set the `torch`, `numpy` and `random` random generator state.

    Args:
        state (RandomGeneratorState)
    """
    random.setstate(state.random)
    torch.random.set_rng_state(state.torch)
    np.random.set_state(state.numpy)
    if state.torch_cuda is not None and torch.cuda.is_available() and len(
            state.torch_cuda) == torch.cuda.device_count():  # pragma: no cover
        torch.cuda.set_rng_state_all(state.torch_cuda)

@contextmanager
def fork_rng(seed=None, cuda=torch.cuda.is_available()):
    """ Forks the `torch`, `numpy` and `random` random generators, so that when you return, the
    random generators are reset to the state that they were previously in.

    Args:
        seed (int or None, optional): If defined this sets the seed values for the random
            generator fork. This is a convenience parameter.
        cuda (bool, optional): If `True` saves the `cuda` seed also. Getting and setting the random
            generator state can be quite slow if you have a lot of GPUs.
    """
    state = get_random_generator_state(cuda)
    if seed is not None:
        set_seed(seed, cuda)
    try:
        yield
    finally:
        set_random_generator_state(state)

def fork_rng_wrap(function=None, **kwargs):
    """ Decorator alias for `fork_rng`.
    """
    if not function:
        return functools.partial(fork_rng_wrap, **kwargs)

    @functools.wraps(function)
    def wrapper():
        with fork_rng(**kwargs):
            return function()

    return wrapper

def set_seed(seed, cuda=torch.cuda.is_available()):
    """ Set seed values for random generators.

    Args:
        seed (int): Value used as a seed.
        cuda (bool, optional): If `True` sets the `cuda` seed also.
    """
    random.seed(seed)
    torch.manual_seed(seed)
    np.random.seed(seed)
    if cuda:  # pragma: no cover
        torch.cuda.manual_seed(seed)
        torch.cuda.manual_seed_all(seed)


from setuptools import setup, find_packages
import os

package_root = os.path.abspath(os.path.dirname(__file__))

version = {}
with open(os.path.join(package_root, "LoopProjectFile/Version.py")) as fp:
    exec(fp.read(), version)
version = version["__version__"]

setup(
    name="LoopProjectFile",
    install_requires=["netCDF4>=1.5.4", "numpy", "pandas"],
    description="Open source structural geology data storage for Loop Projects",
    author="Roy Thomson",
    author_email="roy.thomson@monash.edu",
    url="https://github.com/Loop3D/LoopProjectFile",
    classifiers=[
        "Development Status :: 3 - Alpha",
        "Intended Audience :: Developers",
        "Intended Audience :: Other Audience",
        "Intended Audience :: Science/Research",
        "License :: OSI Approved :: MIT License",
        "License :: Free for non-commercial use",
        "Natural Language :: English",
        "Programming Language :: Python",
        "Programming Language :: Python :: 3",
        "Topic :: Multimedia :: Graphics :: 3D Modeling",
        "Topic :: Scientific/Engineering",
        "Topic :: Scientific/Engineering :: GIS",
    ],
    version=version,
    packages=find_packages()
    )


import tkinter as tk
from tkinter import messagebox
import  requests
from PIL import ImageTk, Image

class UI:
    def __init__(self) :
        # Creating window
        self.root = tk.Tk()
        self.root.title("Weather")
        self.root.iconbitmap(r"C:\Users\DELL\Downloads\Wineass-Ios7-Redesign-Weather.ico")
        self.root.configure(background="black")
        self.root.geometry("300x100")
        # Creating Entry where user input the location of city
        self.city_name = tk.StringVar()
        self.entry = tk.Entry(master=self.root  , font=("Bold" , 18) , foreground="Blue" , textvariable=self.city_name).pack(padx=10 , pady=10)
        # Creating search button
        self.button = tk.Button(master=self.root , text="Search" , font=("Arial" , 18) , background="Blue" , foreground="white" , command=self.search).pack()
        self.weather_statue = "Cloudy"
        self.root.mainloop()

    def get_weather_info(self):
        try:
            URL = 'http://api.openweathermap.org/geo/1.0/direct?q={}&limit=1&appid=bb681d7c4feaad84e993fba80a2650e9'.format(self.city_name.get().capitalize())
            first_response = requests.get(URL).json()
            self.city = first_response[0]["name"]
            try:
                self.state = first_response[0]["state"]
            except:
                self.state = None
            self.country = first_response[0]["country"]
            self.lat = first_response[0]['lat']
            self.lon = first_response[0]['lon']

            URI = "https://api.openweathermap.org/data/2.5/weather?lat={}&lon={}&appid=bb681d7c4feaad84e993fba80a2650e9".format(self.lat , self.lon)
            second_response = requests.get(URI).json()
            self.weather_statue = second_response["weather"][0]["main"]
            self.weather_description = second_response["weather"][0]["description"]
            self.temp_kelvin = second_response["main"]['temp']
            self.temp_celcus = '{:.2f}'.format(self.temp_kelvin - 273,15)
            self.pressure = second_response["main"]['pressure']
            self.humidity = second_response["main"]['humidity']
        except:
            if messagebox.showerror("Error" , "City Not Founded"):
                self.root.destroy()
                exit()

    def search(self):
        """
        In this method we will update the background of the window depands on the weather
        creating labels for showing infos about the city (temp , time , weather ...)
        """
        self.display_info()

    def display_info(self):
        self.get_weather_info()
        self.root = tk.Toplevel()
        self.root.title("Weather")
        self.root.iconbitmap(r"C:\Users\DELL\Downloads\Wineass-Ios7-Redesign-Weather.ico")
        self.root.state("zoomed")
        if self.weather_statue == "Clouds":
            self.img = ImageTk.PhotoImage(Image.open(r"C:\Users\DELL\Desktop\Projects_on_Github\Weather_app\cloudy.png"))
            self.img_open = tk.Label(self.root, image = self.img) # adding the image of the company ussing pillow and tkinter(in label we can add text or image)
            self.img_open.place(x = 0 , y=0)
            self.label = tk.Label(self.root , text="About:" , font=("Bold" , 20) , foreground="Purple" , background="White").pack()
            self.label1 = tk.Label(self.root , text=f'City : {self.city} ; State : {self.state} ; Country : {self.country}' , font=("Bold" , 28) , foreground="red" ).pack()
            self.label2 = tk.Label(self.root , text=f'Weather Statue : {self.weather_statue} ; Description : {self.weather_description}' , font=("Bold" , 28) , foreground="Green" ).pack()
            self.label3 = tk.Label(self.root , text=f'Temperature in Kelvin : {self.temp_kelvin} ; Temperature in Celcuis : {self.temp_celcus} ; Pressure : {self.pressure} ; Humidity : {self.humidity}' , font=("Bold" , 20) , foreground="blue" ).pack()

        if self.weather_statue == "Clear":
            self.img = ImageTk.PhotoImage(Image.open(r"C:\Users\DELL\Downloads\fluffy-clouds-windy-sky.png"))
            self.img_open = tk.Label(self.root, image = self.img) # adding the image of the company ussing pillow and tkinter(in label we can add text or image)
            self.img_open.place(x = 0 , y=0)
            self.label = tk.Label(self.root , text="About:" , font=("Bold" , 20) , foreground="Purple" , background="White").pack()
            self.label1 = tk.Label(self.root , text=f'City : {self.city} ; State : {self.state} ; Country : {self.country}' , font=("Bold" , 28) , foreground="red" ).pack()
            self.label2 = tk.Label(self.root , text=f'Weather Statue : {self.weather_statue} ; Description : {self.weather_description}' , font=("Bold" , 28) , foreground="Green" ).pack()
            self.label3 = tk.Label(self.root , text=f'Temperature in Kelvin : {self.temp_kelvin} ; Temperature in Celcuis : {self.temp_celcus} ; Pressure : {self.pressure} ; Humidity : {self.humidity}' , font=("Bold" , 20) , foreground="blue" ).pack()
        self.root.mainloop()

UI()


import json
import csv
import sys
from pymongo import MongoClient
def json_print(tweet):
    print (json.dumps(tweet))
def json_dump(tweet,outfile):
    with open(outfile,'w') as jsonfile:
            json.dump(tweet, jsonfile)
def csv_dump(outfile,id, created_at,text):
    file = open(outfile, 'a')
    writer = csv.writer(file)
    writer.writerow(["id", "created_at", "text"])
    writer.writerow([id, created_at, text])
    file.close()
def mongo_dump(outfile,collections):
    MONGO_HOST='mongodb://localhost/twitterdb'
    client=MongoClient(MONGO_HOST)
    db=client.twitterdb
    db.collections.insert(outfile)


# Standard Library
import csv
from os.path import exists

# Django
from django.core.management.base import BaseCommand, CommandError

# Yamdb
from reviews import models

class Command(BaseCommand):
    help = 'Import csv files to table of DB'

    MODELS = {
        'User': models.User,
        'Category': models.Category,
        'Genre': models.Genre,
        'Title': models.Title,
        'Review': models.Review,
        'Comment': models.Comment,
        'TitleGenre': models.TitleGenre,
    }

    HEADERS = {
        'author': models.User,
        'category': models.Category,
    }

    def add_arguments(self, parser):
        parser.add_argument('-f', '--file', nargs='+', type=str, required=True)
        parser.add_argument(
            '-t',
            '--table',
            choices=self.MODELS.keys(),
            type=str,
            required=True,
        )

    def import_model(self, reader, model):
        """Загружает данные из csv reader в БД

        :param reader: ридер
        :param model: модель django
        """

        headers = []
        for row in reader:
            headers = row
            break

        for row in reader:
            data = {}
            try:
                for position, header in enumerate(headers):
                    if header in self.HEADERS:
                        data[header] = self.HEADERS[header].objects.get(
                            pk=row[position]
                        )
                    else:
                        data[header] = row[position]

                model.objects.get_or_create(**data)

                self.stdout.write(self.style.NOTICE(f'Load note: {data}'))
            except Exception as what:
                self.stdout.write(
                    self.style.ERROR(f'Error to load note: {what}')
                )

        self.style.SUCCESS('Successfully load table')

    def import_table(self, file, table):
        """Загружает данные csv в БД

        :param file: путь до файла
        :type file: str
        :param table: название таблицы
        :type table: str
        :raises CommandError: вызывается исключение,
        когда не удалось найти файл
        """

        if not exists(file):
            raise CommandError(f'Can\'t find file: {file}')

        model = self.MODELS[table]
        with open(file, encoding='utf-8') as csvfile:
            reader = csv.reader(csvfile, delimiter=',')
            self.import_model(reader, model)

    def handle(self, *args, **options):
        files = options['file']
        table = options['table']

        for file in files:
            self.import_table(file, table)


from sklearn import svm
import numpy as np
import matplotlib.pyplot as plt

Y = np.array([1]*8 + [-1]*9)
X = np.array([.697,.46,
    .774,.376,
    .634,.264,
    .608,.318,
    .556,.215,
    .403,.237,
    .481,.149,
    .437,.211,
    .666,.091,
    .243,.267,
    .245,.057,
    .343,.099,
    .639,.161,
    .657,.198,
    .36,.37,
    .593,.042,
    .719,.103]).reshape(-1,2)
model = svm.SVC(C=5,kernel='linear')
model.fit(X,Y)
y_pred = model.predict(X)
print(y_pred)
plt.scatter(X[:,0],X[:,1],c=Y)
ax = plt.gca()
xlim = ax.get_xlim()
ylim = ax.get_ylim()
xx = np.linspace(xlim[0], xlim[1], 30)
yy = np.linspace(ylim[0], ylim[1], 30)
YY, XX = np.meshgrid(yy, xx)
xy = np.vstack([XX.ravel(), YY.ravel()]).T
Z = model.decision_function(xy).reshape(XX.shape)
ax.contour(XX, YY, Z, colors='k', levels=[-1,0,1], alpha=0.5,
           linestyles=['--', '-', ':'])

ax.scatter(model.support_vectors_[:, 0], model.support_vectors_[:, 1], s=100,
           linewidth=1, facecolors='none', edgecolors='k')

plt.show()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar  8 19:53:43 2018

@author: redman
"""
import sys
import requests
from bs4 import BeautifulSoup
import xml
import urllib.parse
import time
import csv
from requests.exceptions import ConnectionError

def countpopular(start_date, end_date):
    names=['.png','.PNG','.jpg','.JPG','.jpeg','.JPEG','.gif','.GIF','.jPg']
    all_popular= []
    image_all=[]
    popular_num=0
    with open('all_popular.txt','r',encoding='utf-8') as f:
        all_popular.append ([line.strip().split(',') for line in f])

    for item in all_popular[0]:

        if (int(item[0])>=int(start_date) and int(item[0])<=int(end_date)):
            popular_num+=1
            url=item[-1]
            #print(url)
            response = requests.get(url)
            soup = BeautifulSoup(response.text, 'lxml')
            for images in soup.find(class_='bbs-screen bbs-content').find_all('a'):
                image=images.getText()
                for name in names:
                    if(image.find(name,-4)!=-1):
                        image_all.append(image)
    #print(image_all)
    with open('popular ['+start_date+'-'+end_date+'].txt','w') as file:
        file.write('number of popular articles: '+str(popular_num)+'\n')
        for image in image_all:
            file.write(image+'\n')

if __name__ == '__main__':
    start_date=sys.argv[1]
    end_date=sys.argv[2]
    countpopular(start_date,end_date)


#!/usr/bin/python3

# A script to interpolate the TRMM data to match ISCCP regular area boxes. The data is coarsened to 2.5 deg resolution first.

import numpy as np
import sys
from calendar import isleap
from trend_funcs import read_netcdf
from scipy.interpolate import griddata
from netCDF4 import Dataset

year = int(sys.argv[1])
datapath = '/home/btan1/Monash/Data/'
trmmpath = '/media/Sentinel/data/TRMM/3B42/netcdf/'

# ninja-load the lat/lon info
with Dataset('%s3B42.199801.nc' % (trmmpath,)) as f:
    lats = f.variables['latitude'][:].copy()
    lons = f.variables['longitude'][:].copy()

lat0 = np.where(lats == -34.875)[0][0]
lat1 = np.where(lats ==  34.875)[0][0] + 1
nlat = lat1 - lat0
nlon = len(lons)

# extract lat/lon coordinates of the TRMM grid
lats_avg = np.array([np.mean(lats[lat0 + ii : lat0 + ii + 10]) for ii in range(0, nlat, 10)])
lons_avg = np.array([np.mean(lons[jj : jj + 10]) for jj in range(0, nlon, 10)])
lons_ext = np.hstack([lons_avg, lons_avg + 360]).flatten()
pts = np.array([[lat, lon] for lat in lats_avg for lon in lons_ext])

# extract lat/lon coordinates of ISCCP grid
box_lat = read_netcdf(datapath, 2007, 1, variable = 'box_lat')
box_lon = read_netcdf(datapath, 2007, 1, variable = 'box_lon')

# load data
P = np.ma.masked_all([(365 + isleap(year)) * 8, len(box_lat)], dtype = np.float32)
mday = 0

for month in range(1, 13):

    f = Dataset('%s3B42.%d%02d.nc' % (trmmpath, year, month), 'r')
    nday = len(f.variables['pcp'])

    for day in range(nday):

        # average the data to 1 deg boxes so values are comparable to GPCP prior to interpolation
        trmm = f.variables['pcp'][day, lat0 : lat1] * 24
        trmm_avg = np.ma.masked_invalid([[np.ma.mean(trmm[ii : ii + 10, jj : jj + 10])
            for jj in range(0, nlon, 10)] for ii in range(0, nlat, 10)])

        # perform the interpolation
        trmm_ext = np.ma.concatenate([trmm_avg, trmm_avg], 1).flatten()
        mask = ~np.ma.getmaskarray(trmm_ext)
        mask_intp = griddata(pts, mask, (box_lat, box_lon), method = 'linear')
        P[mday + day] = np.ma.masked_where(mask_intp != 1,
            griddata(pts[mask], trmm_ext[mask], (box_lat, box_lon), method = 'linear'))

    mday += nday
    f.close()

with open('%strend/precip_data/trmm_%d.npy' % (datapath, year), 'wb') as f:
    np.ma.dump(P, f)


import os.path
import os

path = r'Test1.txt'
search_file = os.path.isfile(path)
if search_file is True:
    print(f'{path}({os.getcwd()})- последнее время доступа {os.path.getatime(path)} секунд')
else:
    print("Файл не существует")


from django.db import models
from book.models import Book
# Create your models here.
class Chapter(models.Model):
    name = models.CharField(max_length=108, verbose_name='章节名')
    book=models.ForeignKey(Book,on_delete='CASCADE')
    create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    content=models.TextField(verbose_name='内容')
    class Meta:
        db_table = 'chapter'


class Nodo:

    def __init__(self,  dato,  nodo):
        self.dato = dato
        self.nodo = nodo

class ListaSimple:
    lista = None

    def insertar(self, dato):
        print(f"Insertando: {dato}")
        nuevoNodo = Nodo(dato, None)
        if (self.lista != None):
            aux1 = self.lista
            aux2 = None

            while ((aux1 != None) and (aux1.dato < dato)):
                aux2 = aux1
                aux1 = aux1.nodo

            if (self.lista == aux1):
                self.lista = nuevoNodo
            else:
                aux2.nodo = nuevoNodo

            nuevoNodo.nodo = aux1

        else:
            self.lista = nuevoNodo

    def verLista(self):
        if (self.lista != None):
            nodoActual = self.lista
            print("Lista: [", end=""),
            while (nodoActual != None):
                print(f"{nodoActual.dato},", end=""),
                nodoActual = nodoActual.nodo
            print("\b]")
        else:
            print("Lista vacía")

    def buscar(self, dato):
        fueEncontrado = False
        nodoBuscado = self.lista

        while ((nodoBuscado != None) and (nodoBuscado.dato <= dato)):
            if (nodoBuscado.dato == dato):
                fueEncontrado = True
            nodoBuscado = nodoBuscado.nodo

        print(f"El dato {dato}" + (" Si " if (fueEncontrado)
                                   else " No ") + "se encuentra en la lista")

    def eliminar(self, dato):
        if (self.lista != None):
            nodoEliminar = self.lista
            nodoAnterior = None

            while ((nodoEliminar != None) and (nodoEliminar.dato != dato)):
                nodoAnterior = nodoEliminar
                nodoEliminar = nodoEliminar.nodo

            if (nodoEliminar == None):
                print(f"El dato {dato} no existe")
            elif (nodoAnterior == None):
                self.lista = self.lista.nodo
                print(f"El dato {dato} se ha eliminado")
            else:
                nodoAnterior.nodo = nodoEliminar.nodo
                print(f"El dato {dato} se ha eliminado")

    def vaciarLista(self):
        self.lista = None
        print("La lista se ha vaciado")

# Uso de la clase Lista
if __name__ == "__main__":
    lista = ListaSimple()
    lista.verLista()
    lista.insertar(666)
    lista.insertar(1)
    lista.verLista()
    lista.insertar(1000)
    lista.insertar(500)
    lista.verLista()
    lista.buscar(3)
    lista.eliminar(500)
    lista.verLista()
    lista.vaciarLista()
    lista.verLista()

''' Salida en Consola:

    Lista vacía
    Insertando: 666
    Insertando: 1
    Lista: [1,666]
    Insertando: 1000
    Insertando: 500
    Lista: [1,500,666,1000]
    El dato 3 No se encuentra en la lista
    El dato 500 se ha eliminado
    Lista: [1,666,1000]
    La lista se ha vaciado
    Lista vacía
'''


class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution:
    def printTree(self, root: TreeNode):
        def findDepth(root):
            if root==None:return 0
            return max(findDepth(root.left),findDepth(root.right))+1
        h=findDepth(root)
        col=h
        width=2*h-1
        mat=[[""]*width for _ in range(col)]
        print(mat)

        def dfs(root,row,col):
            if row>=len(mat) or col<0:return
            if root==None:return
            mat[row][col]=str(root.val)
            dfs(root.left,row+1,col-1)
            dfs(root.right,row+1,col+1)
        dfs(root,0,col//2)

        print(mat)

root=TreeNode(3)

root.left=TreeNode(5)
# root.left.left=TreeNode(6)
# root.left.right=TreeNode(2)
# root.left.right.left=TreeNode(7)
# root.left.right.right=TreeNode(4)

# root.right=TreeNode(1)
# root.right.right=TreeNode(8)
# root.right.left=TreeNode(0)

sol=Solution()

sol.printTree(root)

LeetCode/Tree/89__ 655. Print Binary Tree_.py


from flask import flash, redirect, render_template, request, url_for
from flask_login import login_required

from app.intervenants import bp
from app.models.intervenants import Intervenants
from app.intervenants.utils import update_benevole

@bp.route("/delegation", methods=["GET", "POST"])
@login_required
def accordeon_delegation():
    # get all distinct delegation to loop throught
    delegation = Intervenants.objects.distinct("delegation")
    benevoles = Intervenants.objects()

    return render_template(
        "intervenants/delegation.html",
        title="delegation",
        delegation=delegation,
        benevoles=benevoles,
    )

@bp.route("/<id>")
@login_required
def intervenant_par_id(id):
    benevole_par_id = Intervenants.objects(id=id)
    # get l'oject precis pour pouvoir avoir faire .id
    int_benevole_id = Intervenants.objects.get(id=id)
    # converti un int en str pour faire marcher dans le template html.
    benevole_id = str(int_benevole_id.id)

    return render_template(
        "intervenants/intervenant_par_id.html",
        test=benevole_par_id,
        intervenant=benevole_id,
    )

@bp.route("/update_benevole/<id>/<champs>", methods=["GET", "POST"])
@login_required
def modal_update_benevole(id, champs):
    if request.method == "POST":
        value = request.form.get("value")
        update_benevole(id, champs, value)
        flash("La fiche a bien été mise à jour!", "info")
        return redirect(url_for("intervenants.intervenant_par_id", id=id))

        ### test : jjpconsultant@gmail.com