import numpy as np

def TDMAsolver(a, b, c, d):
    n = list(np.shape(d))
    x = np.zeros([n[0], n[1]])

    # Modify the first-row coefficient
    c[0] = c[0] / b[0]  # Division by zero risk
    d[0] = d[0] / b[0]  # Division by zero would imply a singular matrix
    temp = b[1:] - a[1:] * c[:-1]
    c[1:] = c[1:] / temp
    d[1:] = (d[1:] - a[1:] * d[:-1]) / temp

    d[-1] = (d[-1] - a[-1] * d[-2]) / (b[-1] - a[-1] * c[-2])
    x[-1] = d[-1]
    x[:0:-1] = d[:0:-1] - (c[:0:-1] * x[:1])
    return x

def VGSWC(psi, thetas, thetar, alfa, n_v):
    if psi < 0:
        m = 1 - 1 / n_v
        theta = ((thetas - thetar) / (1 + alfa * abs(psi) ** n_v) ** m) + thetar
    else:
        theta = thetas
    return theta

def k_unsat(psi, thetas, thetar, alfa, n_v, k_s):
    theta = VGSWC(psi, thetas, thetar, alfa, n_v)
    se = (theta - thetar) / (thetas - thetar)
    m = 1 - 1 / n_v
    kunsat = k_s * (se ** 0.5) * (1 - (1 - se ** (1 / m)) ** m) ** 2
    return kunsat

def Cw(psi, thetas, thetar, alfa, n_v):
    if psi < 0:
        cw = ((alfa ** n_v) * (thetas - thetar) * (n_v - 1) * ((-psi) ** (n_v - 1))) / (
                (1 + (alfa * (-psi)) ** n_v) ** (2 - (1 / n_v)))
    else:
        cw = 0
    return cw

def a_trap(b, ss, h):
    area = h * (b + h * ss)
    return area

def p_trap(b, ss, h):
    perimeter = b + 2 * h * np.sqrt(1 + ss ** 2)
    return perimeter

def t_trap(b, ss, h):
    freesurf = b + 2 * h * ss
    return freesurf

def k_l(h_c, t, alph, f, w):
    infiltration = (h_c * (t ** alph) + f * t) / w
    return infiltration


#! /usr/bin/env python
# -*- coding: utf-8 -*-

# Example: Scrolling text on display if the string length is major than columns in display.
# Created by Dídac García.

# Import necessary libraries for communication and display use
import drivers
from time import sleep

# Load the driver and set it to "display"
# If you use something from the driver library use the "display." prefix first
display = drivers.Lcd()

# Main body of code
try:
	print("Press CTRL + C to stop this script!")

	def long_string(display, text='', num_line=1, num_cols=16):
		"""
		Parameters: (driver, string to print, number of line to print, number of columns of your display)
		Return: This function send to display your scrolling string.
		"""
		if len(text) > num_cols:
			display.lcd_display_string(text[:num_cols], num_line)
			sleep(1)
			for i in range(len(text) - num_cols + 1):
				text_to_print = text[i:i+num_cols]
				display.lcd_display_string(text_to_print, num_line)
				sleep(0.2)
			sleep(1)
		else:
			display.lcd_display_string(text, num_line)

	# Example of short string
	long_string(display, "Hello World!", 1)
	sleep(1)

	# Example of long string
	long_string(display, "Hello again. This is a long text.", 2)
	display.lcd_clear()
	sleep(1)

	while True:
		# An example of infinite scrolling text
		long_string(display, "Hello friend! This is a long text!", 2)
except KeyboardInterrupt:
	# If there is a KeyboardInterrupt (when you press ctrl+c), exit the program and cleanup
	print("Cleaning up!")
	display.lcd_clear()


largura=float(input('Digite a largula da parede : '))

altura=float(input('Digite a altura da parede :'))

area=largura*altura

litros=area/2

print('Sabendo que a largura é {} e que a altura é {} a area é {}'.format(largura, altura, area))

print('Sabemdo isso tudo vai ser preciso {} litros (CONTANDO QUE CADA LITRO VALE 2 METROS QUADRADOS)'.format(litros))

Projetos  3/calcular area e saber quanta tinta e preciso.py


# boj_11727 : 2xn 타일링 2
import sys

# input
N = int(sys.stdin.readline())
dp = [-1, 1, 3]

for i in range(3, N + 1):
    dp.append((dp[i - 1] + dp[i - 2] * 2) % 10007)

print(dp[N])

2×n 타일링 2.py


#!/usr/bin/env python
"""bowling"""

from bowling import Game

def play_game():
    """play game"""
    game = Game()
    print("Game start")
    while game.frame_num != 10:
        game.roll(int(input("Roll for frame {}:".format(game.frame_num + 1))))

    bonus_round = 0
    if game.frames[9].check_strike:
        bonus_round = 2

    if game.frames[9].check_spare:
        bonus_round = 1

    for i in range(bonus_round):
        game.roll(int(input("Roll for bonus round {}:".format(i))))

    game.display_score_board()
    print("\ntotal score: ", game.score())

if __name__ == '__main__':
    play_game()


"""
A script to separate the a pdf to separate slides...
"""

import os.path
import subprocess

subprocess.check_output([
    "pdfseparate",
    "file.pdf",
    "page-%d.pdf",
])
slide = 1
till = 166
width = 283 - 90
height = 498 - 340
margin_x = 50  # ?!? guessing again
for x in range(1, till):
    filename = f"page-{x}.pdf"
    if not os.path.isfile(filename):
        raise ValueError(f"no such file {filename}")
    slide_name = f"slide-{slide:03d}.pdf"
    slide += 1
    start_x = 90
    start_y = 340
    to_x = start_x + width
    to_y = start_y + height
    area = f"{start_x} {start_y} {to_x} {to_y}"
    print(f"area is {area}")
    subprocess.check_output([
        "pdfcrop",
        filename,
        "--bbox",
        area,
        slide_name,
    ])
    start_x += width + margin_x
    to_x = start_x + width
    to_y = start_y + height
    slide_name = f"slide-{slide:03}.pdf"
    slide += 1
    area = f"{start_x} {start_y} {to_x} {to_y}"
    print(f"frmt is {area}")
    subprocess.check_output([
        "pdfcrop",
        filename,
        "--bbox",
        area,
        slide_name,
    ])
    start_x += width + margin_x
    to_x = start_x + width
    to_y = start_y + height
    slide_name = f"slide-{slide:03d}.pdf"
    slide += 1
    area = f"{start_x} {start_y} {to_x} {to_y}"
    print(f"frmt is {area}")
    subprocess.check_output([
        "pdfcrop",
        filename,
        "--bbox",
        area,
        slide_name,
    ])


"""
algorithms.py
A module with algorithms for cycles enumeration.
Authors: Bc. Jan Bíl
         Bc. Michal Šedý
Last change: 15.11.2022
"""

import numpy as np
import networkx as nx
from queue import Queue
from . import digraph

def __get_cycles_nx(graph: digraph.DiGraph) -> list:
    """Enumerates all cycles (elementary circuits) in a graph.
    It uses a nonrecursive, iterator/generator version of
    Johnson's algorithm [Finding all the elementary circuits of
    a directed graph. D. B. Johnson, SIAM Journal on Computing 4,
    no. 1, 77-84, 1975. https://doi.org/10.1137/0204007].
    The time complexity is O((n + m)*(c + 1)) for n nodes, m edges
    and c elementary circuits.

    Args:
        input_graph (DiGraph): DiGraph.

    Returns:
        list: List of cycles.
    """
    graph_nx = nx.DiGraph()

    graph_nx.add_nodes_from(graph.vertices)
    for u in graph.vertices:
        for v in graph.edges[u]:
            graph_nx.add_edge(u, v)

    return list(nx.simple_cycles(graph_nx))

def __get_cycles_hj(input_graph: digraph.DiGraph) -> list:
    """Enumerates all cycles (elementary circuits) in a graph.
    It uses Hongbo's and Jiaxin's algorithm with a queue
    [Hongbo Liu and Jiaxin Wang, "A new way to enumerate cycles
    in graph," Advanced Int'l Conference on Telecommunications
    and Int'l Conference on Internet and Web Applications and
    Services (AICT-ICIW'06), 2006, pp. 57-57, doi: 10.1109/AICT-ICIW.2006.22.]
    The time complexity is O(d!*d^(n-d)) where n is a number of nodes,
    and d is maximal output degree.

    Args:
        input_graph (DiGraph): DiGraph.

    Returns:
        list: List of cycles.
    """
    # Simplify graph
    graph = digraph.DiGraph(input_graph)
    graph.prune_single_scc()

    cycles = list()
    # Init
    q = Queue()
    for v in graph.vertices:
        q.put([v])

    #Computation
    while not q.empty():
        # Get open path
        path = q.get()
        min_path = min(path)
        head, last = path[0], path[-1]
        # Extend existing open path.
        for v in graph.edges[last]:
            if v == head:
                # Report cycle.
                # Translace local vertex ids from scc to their ids from input_graph.
                cycles.append([input_graph.vertex_cname.inv[graph.vertex_cname[v]] for v in path])
            elif v > min_path:
                if v not in path:
                    q.put(path + [v])

    return cycles

def __get_cycle_wein(input_graph: digraph.DiGraph) -> list:
    """Enumerates all cycles (elementary circuits) in a graph.
    It uses Herbert Winblatt's algorithm with backtracking.
    [Herbert Weinblatt. 1972. A New Search Algorithm for Finding
    the Simple Cycles of a Finite Directed Graph. J. ACM 19,
    1 (Jan. 1972), 43–56. https://doi.org/10.1145/321679.321684]
    The time complexity is O(n^2+mn(c+1)) for n nodes, m edges
    and c elementary circuits.

    Args:
        input_graph (DiGraph): DiGraph.

    Returns:
        list: List of cycles.
    """
    def get_tail(L: list, node: int, is_cycle=False) -> list:
        """Returns a tail of given path with respect to the node.
        The time complexity is O(n) for n nodes.

        Args:
            L (list): Path
            node (int): graph node
            is_cycle (bool, optional): If True, the the first node of
                                       a path is ignored. Defaults to False.

        Returns:
            list: Path tail with respect to the vertex.
        """
        try:
            return L[1 + L.index(node, 1 if is_cycle else 0):]
        except ValueError:
            return list()

    def get_suitable_edge(TT: list):
        """Returns suitable successor of the path end.
        The time complexity is O(n) for n nodes.

        Args:
            TT (list): Path.

        Returns:
            int|None: Returns suitable successor of the path end.
        """
        u = TT[-1]
        for v in graph.edges[u]:
            if S_e[u][v] == 0:
                return v

        return None

    def concat(is_top_recursive_call: bool, TT: list, P: list) -> list:
        """Recursively creates new cycles as a combination of subsections
        of existing cycles with a examined path P.

        Args:
            is_top_recursive_call (bool): If True, than the function was called
                                          from examine. Otherwise the function
                                          was called recursively.
            TT (list): Examined path.
            P (list): Recursively constructed path.

        Returns:
            list: The function returns a list of cycles to add (when called
                  recursively; can contains duplicates), or a list of added cycles.
        """
        # Init
        cycle_tails = list()
        to_add = list()
        added = list()
        v = P[-1]

        # Test subsections of all cycles.
        for c in cycles:
            tail = get_tail(c, v, True)
            if not tail or tail in cycle_tails:
                continue
            cycle_tails.append(tail)

            if set(tail).intersection(P):
                continue

            if S_v[c[-1]] == 2:
                to_add.extend(concat(False, TT, P + tail))
                continue
            else:
                new_c = [c[-1]] + get_tail(TT, c[-1], False) + P + get_tail(c, P[-1], True)
                if is_top_recursive_call:
                    # The function was called from examine (non-recursively).
                    # Add a new cycle to the list of found cycles.
                    # if new_c not in added:
                    cycles.append(new_c)
                    added.append(new_c)
                else:
                    # The function was called recursively.
                    # Only marks the cycle for addition (to avoid duplicates).
                    to_add.append(new_c)

        if is_top_recursive_call:
            # Examine cycles founded by recursively called functions.
            # It only looks for duplicates within cycles created since last external call.
            for c in to_add:
                if c not in added:
                    assert c not in cycles, c
                    cycles.append(c)
                    added.append(c)
            return added

        return to_add

    def examine(TT: list, v: int) -> None:
        """Controls it the TT and edge to the node v can be path
        of some cycle.
        """
        if S_v[v] == 0:
            S_v[v] = 1
            TT.append(v)
            # go back to extend
        elif S_v[v] == 1:
            new_c = [v] + get_tail(TT, v) + [v]
            assert new_c not in cycles, new_c
            cycles.append(new_c)
            # go back to extend and if TT is empty, than go to the main cycle
        else:
            concat(True, TT, [v])
            # go back to extend and if TT is empty, than go to the main cycle

    def extend(TT: list) -> None:
        """Extends path TT with a suitable edge.
        """
        while TT:
            u = TT[-1]
            v = get_suitable_edge(TT)
            if v is None:
                S_v[u] = 2
                TT.pop(-1)
            else:
                S_e[u][v] = 2
                examine(TT, v)

    # Simplify graph
    graph = digraph.DiGraph(input_graph)
    graph.prune_single_scc()

    # Init
    cycles = list()
    TT = list()
    # S_e[u][v] == 0  ->  The edge (u, v) has never been on the TT.
    # S_e[u][v] == 2  ->  The edge (u, v) has been on the TT (and may still be).
    S_e = np.zeros((graph.vertices_cnt, graph.vertices_cnt), dtype=int)
    # S_v[v] == 0  ->  The node v has never been on the TT.
    # S_v[v] == 1  ->  The node v is now on the TT.
    # S_v[v] == 2  ->  The node v has been on the TT, but has been removed.
    S_v = [0] * graph.vertices_cnt

    # Calculation
    for v in graph.vertices:
        if S_v[v] == 0:
            S_v[v] = 1
            TT = [v]
            extend(TT)

    # Projects node ids from simplified graph to node ids of the original graph.
    # The time complexity is O(n * c), where n is a number of nodes and c is a number of cycles.
    return [[input_graph.vertex_cname.inv[graph.vertex_cname[v]] for v in c[:-1]] for c in cycles]

def _bet_cycles_bf(input_graph: digraph.DiGraph) -> list:
    """Enumerates all cycles (elementary circuits) in a graph.
    It uses algorithm proposed in a book by Narsingh Deo
    (page 287 Alg. 5), which is systematic and exhaustive
    search for directive circuits. [Deo, Narsingh. Graph
    Theory with Applications to Engineering and Computer
    Science. 1st ed. Dover Publications, 2017. Web. 14 Oct. 2022.]
    The time complexity is O(d!*d^(n-d)) where n is a number of nodes,
    and d is maximal output degree.

    Args:
        input_graph (DiGraph): DiGraph.

    Returns:
        list: List of cycles.
    """
    graph = digraph.DiGraph(input_graph)
    graph.prune_single_scc()
    cycles = list()
    for vertex in graph.vertices:
        #Find paths starting from each vertex
        curr_vertex = vertex
        H =  np.zeros((graph.vertices_cnt, graph.vertices_cnt), dtype=bool)
        curr_path = list()
        curr_path.append(curr_vertex)
        while curr_vertex >= 0:
            found = False
            for succ in graph.get_successors(curr_vertex):
                if H[curr_vertex][succ] == 0 and (succ not in curr_path or (succ == vertex)) and succ >= vertex:
                    #Take first available edge
                    if succ == vertex:
                        #If cycle is found, add it to list and forbid this edge from further search
                        H[curr_path[-1]][succ] = True
                        cycles.append([input_graph.vertex_cname.inv[graph.vertex_cname[v]] for v in curr_path])
                        curr_vertex = curr_path[-1]
                    else:
                        found = True
                        curr_vertex = succ
                        curr_path.append(curr_vertex)
                        break

            if not found:
                curr_path.pop(-1)
                H[curr_vertex][0:graph.vertices_cnt] = False
                # If no available edge is found, go back one step, forbid previously taken edge and continue
                if not curr_path:
                    # If no available edge from first vertex, break the while loop
                    curr_vertex = -1
                    continue
                H[curr_path[-1]][curr_vertex] = True
                curr_vertex = curr_path[-1]
    return cycles

def get_cycles(input_graph: digraph.DiGraph, algo="nx") -> list:
    """Enumerates all cycles (elementary circuits) in a graph.

    Args:
        input_graph (DiGraph): DiGraph.
        algo (str): A type of algorithm to be used.
                    nx - using networkx library
                    bf - using brute-force
                    hj - using Hongbo Liu and Jiaxin Wang algorithm
                    wein - using Weinblatt's algorithm

    Returns:
        list: List of cycles.
    """
    if algo == "nx":
        return __get_cycles_nx(input_graph)
    elif algo == "hj":
        return __get_cycles_hj(input_graph)
    elif algo == "wein":
        return __get_cycle_wein(input_graph)
    elif algo == "bf":
        return _bet_cycles_bf(input_graph)
    else:
        raise ValueError("Unknown algorithm name.")


'''
# 백준_2343_기타 레슨. 실버 1. 풀이: 23.08.16 -> 실패 -> 성공

# How to
- 블루레이 길이
    - 최소: 1개,
    - 최대: n-m+1개
- 즉, 블루레이당 크기는
    - 최소: 배열에서 가장 큰 값(max(arr)),
    - 최대: n-m+1개를 묶어서 더한 값(=sum(arr[:n-m+1]))

# Review
- 풀이 시간:
- 아예 구상이 되지 않는다.
- 어떤걸 이분탐색해야할지 모르겠다. 즉 블루레이 길이를 잡아야하나? 그럼 이때 mid는 무얼 의미하지? 모르겠다..

- 답을 찾아보지 않으려 했으나, 이후 이분탐색 문제를 풀기위해 찾아보았다.
    - 출처: https://withthemilkyway.tistory.com/28
- 핵심은 "무얼 탐색할 것인가?" 였다.
    - 이 문제에서는 mid가 곧 블루레이의 크기였다.
    - 따라서 start, end는 블루레이 크기의 최솟값, 최댓값이 된다.
- 앞으로 이분탐색에서는 'What'에 더 집중해야겠다.

- 그런데, 맞힌 사람 풀이를 보니 이분탐색에서 bisect 라이브러리까지 더해서 더욱 빠르게 풀고있다.
    - 아직 코드가 잘 이해가 가지 않는다ㅠ
- 또, start <= end 냐, 아니면 start < end냐에 따라 end 갱신이 조금 달라진다.
- 아직..이분탐색은 너무 어렵다. 우선 기본적인 풀이대로 풀어보고, 나중에 응용하면서 시간을 단축해야겠다.
'''

# Code
# 1. 풀이 찾아봄
## 메모리: 42340 KB, 시간: 228 ms
n, m = map(int, input().split())
arr = list(map(int, input().split()))

# 블루레이 크기: 최소 max(arr) ~ 최대 sum(arr)

# 블루레이의 크기 찾기
def binary_search(start, end):
    while start <= end:
        mid = (start + end) // 2
        cnt, tmp = 1, 0
        for i in arr:
            # 크기를 초과했다면, count 및 초기화
            if tmp + i > mid:
                cnt += 1
                tmp = 0
            tmp += i

        # 같거나 더 많이 담았다 -> 블루레이 크기를 줄여보자
        if cnt <= m:
            end = mid - 1
            answer = mid

        # 더 적게 담았다 -> 블루레이 크기를 키우자
        else: # cnt > m
            start = mid + 1

    return answer

print(binary_search(max(arr), sum(arr[:n-m+1])))


from django.test import TestCase
from rest_framework.test import APIRequestFactory
from rest_framework import status
from ..models import User
from ..views import user_list

class TestUserViews(TestCase):

    def setUp(self):
        self.factory = APIRequestFactory()
        self.test_user1 = User.objects.create(username='test_user1', age=25)
        self.test_user2 = User.objects.create(username='test_user2', age=30)

    def test_create_user(self):
        data = {'username': 'new_test_user', 'age': 28}
        request = self.factory.post('/api/users/', data, format='json')
        response = user_list(request)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(User.objects.count(), 3)

    def test_get_user(self):
        request = self.factory.get(f'/api/users/{self.test_user1.id}/')
        response = user_list(request)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.context['users'][0].username, self.user1.username)

    def test_delete_user(self):
        request = self.factory.delete(f'/api/users/{self.test_user2.id}/')
        response = user_list(request)
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertEqual(User.objects.count(), 1)


#join()方法：主线程A中，创建子线程B，并且在主线程A中调用B.join(),那么，主线程A会在调用的地方等待，
# 直到子线程B完成操作后，才可以接着往下执行，那么在调用这个线程可以使用被调用线程的join方法。
# 原型：join([timeout])
# 代表线程运行的时间，即如果超过这个时间，不管这个此线程有没有执行完毕都会被回收，然后主线程或函数都会被接着执行。

import threading
import time

class MyThread(threading.Thread):
    def __init__(self,id):
        threading.Thread.__init__(self)
        # super(MyThread, self).__init__()
        self.id = id

    def run(self):
        time.sleep(2)
        print(self.id)

if __name__ == '__main__':
    t1 =MyThread(999)
    t1.start()
    # t1.join()  #有没有join
    for i in range(5):
        print(i)


import os
import xarray as xr
import numpy as np
from odc.geo.xr import assign_crs

def allNaN_arg(da, dim, stat, idx=True):
    """
    Calculate da.argmax() or da.argmin() while handling
    all-NaN slices. Fills all-NaN locations with an
    float and then masks the offending cells.

    Parameters
    ----------
    da : xarray.DataArray
    dim : str
        Dimension over which to calculate argmax, argmin e.g. 'time'
    stat : str
        The statistic to calculte, either 'min' for argmin()
        or 'max' for .argmax()
    idx : bool
        If True then use da.idxmax() or da.idxmin(), otherwise
        use ds.argmax() or ds.argmin()

    Returns
    -------
    xarray.DataArray
    """
    # generate a mask where entire axis along dimension is NaN
    mask = da.isnull().all(dim)

    if stat == "max":
        y = da.fillna(float(da.min() - 1))
        if idx==True:
            y = y.idxmax(dim=dim, skipna=True).where(~mask)
        else:
            y = y.argmax(dim=dim, skipna=True).where(~mask)
        return y

    if stat == "min":
        y = da.fillna(float(da.max() + 1))
        if idx==True:
            y = y.idxmin(dim=dim, skipna=True).where(~mask)
        else:
            y = y.argmin(dim=dim, skipna=True).where(~mask)
        return y

def round_coords(ds):
    """
    Due to precision of float64 on coordinates, coordinates
    don't quite match after reprojection, resulting in adding spurious
    pixels after merge. Converting to float32 rounds coords so they match.
    """
    ds['latitude'] = ds.latitude.astype('float32')
    ds['longitude'] = ds.longitude.astype('float32')

    ds['latitude'] = np.array([round(i,4) for i in ds.latitude.values])
    ds['longitude'] = np.array([round(i,4) for i in ds.longitude.values])

    return ds

def collect_prediction_data(time_start,
                            time_end,
                            scale='1km',
                            covariables=[
                                 #'LAI',
                                 #'LAI_anom',
                                 'kNDVI',
                                 'kNDVI_anom',
                                 #'FPAR',
                                 #'FPAR-NDVI',
                                 'LST',
                                 'trees',
                                 'grass',
                                 'bare',
                                 'C4_grass',
                                 #'Tree',
                                 #'NonTree',
                                 #'NonVeg',
                                 'LST_Tair',
                                 'TWI',
                                 'NDWI',
                                 #'NDWI_anom',
                                 'rain',
                                 'rain_cml3',
                                 'rain_cml6',
                                 'rain_cml12',
                                 'rain_anom',
                                 'rain_cml3_anom',
                                 'rain_cml6_anom',
                                 'rain_cml12_anom',
                                 'srad',
                                 'srad_anom',
                                 'vpd',
                                 'tavg',
                                 'tavg_anom',
                                 #'SOC',
                                 #'CO2',
                                 #'C4percent',
                                 #'Elevation',
                                 #'MOY',
                                 'VegH',
                                 #'MI'
                            ],
                            chunks=dict(latitude=1150, longitude=1100, time=1),
                            export=False,
                            verbose=True
                           ):

    dss=[]
    base='/g/data/os22/chad_tmp/NEE_modelling/data/'
    for var in covariables:
        if verbose:
            print(f'   Extracting {var}')

        ds = xr.open_dataset(f'{base}{scale}/{var}_{scale}_monthly_2002_2022.nc',
                             chunks=chunks
                            )
        ds = ds.sel(time=slice(time_start, time_end))

        #makse sure coords match (remove trailing zeros)
        ds['latitude'] = ds.latitude.astype('float32')
        ds['latitude'] = np.array([round(i,4) for i in ds.latitude.values])
        ds['longitude'] = ds.longitude.astype('float32')
        ds['longitude'] = np.array([round(i,4) for i in ds.longitude.values])

        dss.append(ds)

    #merge all datasets together
    if verbose:
        print('   Merge and create valid data mask')
    data = xr.merge(dss, compat='override')

    # #create mask where data is valid (excludes urban, water)
    # mask = ~np.isnan(data['PFT'].isel(time=0))
    # data = data.where(mask)

    #remove landcover
    #data = data.drop('PFT')

    if verbose:
        print('   Exporting netcdf')

    # export data
    data = data.rename({'latitude':'y', 'longitude':'x'}) #this helps with predict_xr
    data = data.astype('float32') #make sure all data is in float32
    data = assign_crs(data, crs='epsg:4326')

    if export:
        data.to_netcdf('/g/data/os22/chad_tmp/NEE_modelling/results/prediction_data/prediction_data_'+time_start+'_'+time_end+'.nc')

    return data


import os

import xappy
import xapian
import decreasing_weight_source as _dws

_WEIGHTS_FILE_NAME = "weights.dat"

class _dws_mixin(object):

    def __init__(self, conn):
        super(_dws_mixin, self).__init__(os.path.join(conn._indexpath,
                                                      _WEIGHTS_FILE_NAME))

class Vector_DWS(_dws_mixin, _dws.DecreasingWeightSource):
    pass

class File_DWS(_dws_mixin, _dws.FDecreasingWeightSource):
    pass

class Vector_DWS_Cache(object):

    def __init__(self):
        self.cache = {}

    def get_Vector_DWS_for_conn(self, conn):
        cached = self.cache.get(conn)

        if cached:
            source = cached
        else:
            source = Vector_DWS(conn)
            self.cache[conn] = source

        source.reset()
        return source

FILE, VECTOR, CACHED_VECTOR = range(3)
_VCACHE = Vector_DWS_Cache()

def make_page_rank_query(conn, source_type):
    if source_type == FILE:
        source = File_DWS(conn)
    elif source_type == VECTOR:
        source = Vector_DWS(conn)
    elif source_type == CACHED_VECTOR:
        source = _VCACHE.get_Vector_DWS_for_conn(conn)
    else:
        raise ValueError("Bad source_type %s for make_page_rank_query"
                         % string(source_type))

    return xappy.Query(xapian.Query(source),
                       _refs = [source],
                       _conn = conn)


# -*- coding: utf-8 -*-
"""
@author: keshuichonglx
"""
import collections
import json
import os
import pickle
import random

import numpy as np

informable_keys = ['address', 'area', 'food', 'name', 'phone', 'pricerange']

class UserDataManager(object):

    def __init__(self):

        self.__org_goals = None
        self.__org_usr_dass = None
        self.__org_sys_dass = None

        self.__goals = None
        self.__usr_dass = None
        self.__sys_dass = None

        self.__goals_seg = None
        self.__usr_dass_seg = None
        self.__sys_dass_seg = None

        self.__voc_goal = None
        self.__voc_usr = None
        self.__voc_usr_rev = None
        self.__voc_sys = None

        self.pad = '<PAD>'
        self.unk = '<UNK>'
        self.sos = '<SOS>'
        self.eos = '<EOS>'
        self.special_words = [self.pad, self.unk, self.sos, self.eos]

        self.voc_goal, self.voc_usr, self.voc_sys = self.vocab_loader()

    @staticmethod
    def usrgoal2seq(goal: dict):
        def add(lt: list, domain_goal: dict, intent: str):
            mapping = domain_goal.get(intent, {})
            slots = [slot for slot in mapping.keys() if isinstance(mapping[slot], str)]
            if len(slots) > 0:
                lt.append(intent)
                lt.append('(')
                slots.sort()
                lt.extend(slots)
                lt.append(')')

        ret = []
        domain_goal = goal
        # info
        add(ret, domain_goal, 'info')
        # reqt
        slots = domain_goal.get('reqt', [])
        if slots:
            ret.append('reqt')
            ret.append('(')
            ret.extend(slots)
            ret.append(')')

        return ret

    @staticmethod
    def query_goal_for_sys(slot, value, goal):
        ret = None
        goal_slot = slot if slot in informable_keys else 'Unknow'
        if goal_slot != 'Unknow':
            check = {'info': None}
            for zone in check.keys():
                dt = goal.get(zone, {})
                if goal_slot in dt.keys():
                    check[zone] = (dt[goal_slot].lower() == value.lower())
            if True in check.values() or False in check.values():
                # in constraint
                ret = 'InConstraint'
                if True in check.values() and False in check.values():
                    ret += '[C]'
                elif True in check.values() and False not in check.values():
                    ret += '[R]'
                elif True not in check.values() and False in check.values():
                    ret += '[W]'
            elif goal_slot in goal.get('reqt', []):
                # in Request
                ret = 'InRequest'
            else:
                # not in goal
                ret = 'NotInGoal'
        elif goal_slot == 'Unknow':
            ret = 'Unknow'
        else:
            ret = None
        return ret

    @staticmethod
    def sysda2seq(sys_da: dict, goal: dict):
        ret = []
        for (act, pairs) in sorted(sys_da.items(), key=lambda x: x[0]):
            ret.append(act)
            ret.append('(')
            if 'general' not in act:
                for [slot, val] in sorted(pairs, key=lambda x: x[0]):
                    if (act == 'request'):
                        ret.append(slot)
                    else:
                        m_val = UserDataManager.query_goal_for_sys(slot, val, goal)
                        if m_val is not None:
                            ret.append(slot + '=' + m_val)

            ret.append(')')
        # assert len(ret) > 0, str(sys_da)
        return ret

    @staticmethod
    def query_goal_for_usr(slot, value, goal):
        ret = None
        goal_slot = slot if slot in informable_keys else 'Unknow'
        if goal_slot is not None and goal_slot != 'Unknow':
            check = {'info': None}
            for zone in check.keys():
                dt = goal.get(zone, {})
                if goal_slot in dt.keys():
                    check[zone] = (dt[goal_slot].replace(' ', '').lower() == value.replace(' ', '').lower())
            if True in check.values() or False in check.values():
                # in constraint
                if True in check.values():
                    ret = 'In' + [zone for (zone, value) in check.items() if value == True][0].capitalize()
                else:
                    ret = 'In' + [zone for (zone, value) in check.items() if value == False][0].capitalize()
            else:
                # not in goal
                ret = 'DoNotCare'
        elif goal_slot == 'Unknow':
            ret = 'Unknow'
        else:
            ret = None
        return ret

    @staticmethod
    def usrda2seq(usr_da: dict, goal: dict):
        ret = []
        for (act, pairs) in sorted(usr_da.items(), key=lambda x: x[0]):
            ret.append(act)
            ret.append('(')
            if 'general' not in act:
                for [slot, val] in sorted(pairs, key=lambda x: x[0]):
                    if (act == 'request'):
                        ret.append(slot)
                    else:
                        m_val = UserDataManager.query_goal_for_usr(slot, val, goal)
                        if m_val is not None:
                            ret.append(slot + '=' + m_val)

            ret.append(')')

        return ret

    @staticmethod
    def usrseq2da(usr_seq: list, goal: dict):
        ret = {}
        cur_act = None
        for word in usr_seq:
            if word in ['<PAD>', '<UNK>', '<SOS>', '<EOS>', '(', ')']:
                continue

            # act
            if '-' in word:
                cur_act = word
                ret[cur_act] = []

            # slot-value
            elif '=' in word and cur_act is not None:
                slot_da, value_pos = word.split('=')
                value_pos = value_pos.lower()
                slot_goal = slot_da if slot_da in informable_keys else None
                if slot_goal is not None:
                    value = None
                    if value_pos == 'ininfo':
                        value = goal.get('info', {}).get(slot_goal, None)
                    elif value_pos == 'donotcare':
                        value = 'dontcare'

                    if value is not None:
                        ret[cur_act].append([slot_da, value])
                    else:
                        pass
                        #assert False, slot_da
                else:
                    pass
                    # assert False, '%s - %s' % (domain, slot_da)

            # slot in reqt
            elif cur_act is not None:
                ret[cur_act].append([word, '?'])

        return ret

    @staticmethod
    def ref_data2stand(da):
        return eval(str(da).lower())

    def org_data_loader(self):
        if self.__org_goals is None or self.__org_usr_dass is None or self.__org_sys_dass is None:
            file_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))),
                                     'data/camrest/CamRest676_v2.json')
            # 'data/multiwoz/annotated_user_da_with_span_100sample.json')
            with open(file_path) as f:
                full_data = json.load(f)
            goals = []
            usr_dass = []
            sys_dass = []
            for session in full_data:
                goal = session.get('goal', {})
                logs = session.get('dial', [])
                usr_das, sys_das = [], []
                for turn in range(len(logs)):
                    # <class 'dict'>: {'Hotel-Inform': [['Price', 'cheap'], ['Type', 'hotel']]}
                    usr_da = self.ref_data2stand(logs[turn]['usr'].get('dialog_act', {}))
                    sys_da = self.ref_data2stand(logs[turn]['sys'].get('dialog_act', {}))
                    usr_das.append(usr_da)
                    sys_das.append(sys_da)
                else:
                    goals.append(goal)
                    usr_dass.append(usr_das)
                    sys_dass.append(sys_das)

            self.__org_goals = [UserDataManager.usrgoal2seq(goal) for goal in goals]
            self.__org_usr_dass = [[UserDataManager.usrda2seq(usr_da, goal) for usr_da in usr_das] for (usr_das, goal) in zip(usr_dass, goals)]
            self.__org_sys_dass = [[UserDataManager.sysda2seq(sys_da, goal) for sys_da in sys_das] for (sys_das, goal) in zip(sys_dass, goals)]

        return self.__org_goals, self.__org_usr_dass, self.__org_sys_dass

    def vocab_loader(self):
        if self.__voc_goal is None or self.__voc_usr is None or self.__voc_usr_rev is None or self.__voc_sys is None:
            vocab_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))),
                                      'data/camrest/goal/vocab.pkl')

            if os.path.exists(vocab_path):
                with open(vocab_path, 'rb') as f:
                    self.__voc_goal, self.__voc_usr, self.__voc_sys = pickle.load(f)
            else:
                goals, usr_dass, sys_dass = self.org_data_loader()

                # goals
                counter = collections.Counter()
                for goal in goals:
                    for word in goal:
                        counter[word] += 1
                word_list = self.special_words + [x for x in counter.keys()]
                self.__voc_goal = {x: i for i, x in enumerate(word_list)}

                counter = collections.Counter()
                for usr_das in usr_dass:
                    for usr_da in usr_das:
                        for word in usr_da:
                            counter[word] += 1
                word_list = self.special_words + [x for x in counter.keys()]
                self.__voc_usr = {x: i for i, x in enumerate(word_list)}

                counter = collections.Counter()
                for sys_das in sys_dass:
                    for sys_da in sys_das:
                        for word in sys_da:
                            counter[word] += 1
                word_list = self.special_words + [x for x in counter.keys()]
                self.__voc_sys = {x: i for i, x in enumerate(word_list)}

                with open(vocab_path, 'wb') as f:
                    pickle.dump((self.__voc_goal, self.__voc_usr, self.__voc_sys), f)
                print('voc build ok')

            self.__voc_usr_rev = {val: key for (key, val) in self.__voc_usr.items()}

        return self.__voc_goal, self.__voc_usr, self.__voc_sys

    def get_voc_size(self):
        return len(self.voc_goal), len(self.voc_usr), len(self.voc_sys)

    def data_loader(self):
        if self.__goals is None or self.__usr_dass is None or self.__sys_dass is None:
            org_goals, org_usr_dass, org_sys_dass = self.org_data_loader()
            self.__goals = [self.get_goal_id(goal) for goal in org_goals]
            self.__usr_dass = [self.get_usrda_id(usr_das) for usr_das in org_usr_dass]
            self.__sys_dass = [self.get_sysda_id(sys_das) for sys_das in org_sys_dass]
        assert len(self.__goals) == len(self.__usr_dass)
        assert len(self.__goals) == len(self.__sys_dass)
        return self.__goals, self.__usr_dass, self.__sys_dass

    @staticmethod
    def train_test_val_split(goals, usr_dass, sys_dass, test_size=0.1, val_size=0.1):
        idx = range(len(goals))
        idx_test = random.sample(idx, int(len(goals) * test_size))
        idx_train = list(set(idx) - set(idx_test))
        idx_val = random.sample(idx_train, int(len(goals) * val_size))
        idx_train = list(set(idx_train) - set(idx_val))
        idx_train = random.sample(idx_train, len(idx_train))
        return np.array(goals)[idx_train], np.array(usr_dass)[idx_train], np.array(sys_dass)[idx_train], \
               np.array(goals)[idx_test], np.array(usr_dass)[idx_test], np.array(sys_dass)[idx_test], \
               np.array(goals)[idx_val], np.array(usr_dass)[idx_val], np.array(sys_dass)[idx_val]

    def data_loader_seg(self):
        if self.__goals_seg is None or self.__usr_dass_seg is None or self.__sys_dass_seg is None:
            self.data_loader()
            self.__goals_seg, self.__usr_dass_seg, self.__sys_dass_seg = [], [], []

            for (goal, usr_das, sys_das) in zip(self.__goals, self.__usr_dass, self.__sys_dass):
                goals, usr_dass, sys_dass = [], [], []
                for length in range(len(usr_das)):
                    goals.append(goal)
                    usr_dass.append([usr_das[idx] for idx in range(length + 1)])
                    sys_dass.append([sys_das[idx] for idx in range(length + 1)])

                self.__goals_seg.append(goals)
                self.__usr_dass_seg.append(usr_dass)
                self.__sys_dass_seg.append(sys_dass)

        assert len(self.__goals_seg) == len(self.__usr_dass_seg)
        assert len(self.__goals_seg) == len(self.__sys_dass_seg)
        return self.__goals_seg, self.__usr_dass_seg, self.__sys_dass_seg

    def id2sentence(self, ids):
        sentence = [self.__voc_usr_rev[id] for id in ids]
        return sentence

    @staticmethod
    def train_test_val_split_seg(goals_seg, usr_dass_seg, sys_dass_seg, test_size=0.1, val_size=0.1):
        def dr(dss):
            return np.array([d for ds in dss for d in ds])

        idx = range(len(goals_seg))
        idx_test = random.sample(idx, int(len(goals_seg) * test_size))
        idx_train = list(set(idx) - set(idx_test))
        idx_val = random.sample(idx_train, int(len(goals_seg) * val_size))
        idx_train = list(set(idx_train) - set(idx_val))
        idx_train = random.sample(idx_train, len(idx_train))
        return dr(np.array(goals_seg)[idx_train]), dr(np.array(usr_dass_seg)[idx_train]), dr(np.array(sys_dass_seg)[idx_train]), \
               dr(np.array(goals_seg)[idx_test]), dr(np.array(usr_dass_seg)[idx_test]), dr(np.array(sys_dass_seg)[idx_test]), \
               dr(np.array(goals_seg)[idx_val]), dr(np.array(usr_dass_seg)[idx_val]), dr(np.array(sys_dass_seg)[idx_val])

    def get_goal_id(self, goal):
        return [self.voc_goal.get(word, self.voc_goal[self.unk]) for word in goal]

    def get_sysda_id(self, sys_das):
        return [[self.voc_sys.get(word, self.voc_sys[self.unk]) for word in sys_da] for sys_da in sys_das]

    def get_usrda_id(self, usr_das):
        return [[self.voc_usr[self.sos]] + [self.voc_usr.get(word, self.voc_usr[self.unk]) for word in usr_da] + [self.voc_usr[self.eos]]
                 for usr_da in usr_das]


import io

import requests

from userbot import CMD_HELP
from userbot.events import errors_handler, register

UD_QUERY_URL = 'http://api.urbandictionary.com/v0/define'
UD_RANDOM_URL = 'http://api.urbandictionary.com/v0/random'

@register(outgoing=True, pattern="ud")
@errors_handler
async def urban_dict(event):
    udquery = event.pattern_match.group(1)

    if udquery:
        params = {'term': udquery}
        url = UD_QUERY_URL
    else:
        params = None
        url = UD_RANDOM_URL

    with requests.get(url, params=params) as response:
        if response.status_code == 200:
            response = response.json()
        else:
            await event.edit(f"`An error occurred, response code:` **{response.status_code}**")
            return

    if response['list']:
        response_word = response['list'][0]
    else:
        await event.edit(f"`No results for query:` **{udquery}**")
        return

    definition = f"**{response_word['word']}**: `{response_word['definition']}`"

    if response_word['example']:
        definition += f"\n\n**Example**: `{response_word['example']}`"

    definition = definition.replace("[", "").replace("]", "")

    if len(definition) >= 4096:
        file_io = io.BytesIO()
        file_io.write(bytes(definition.encode('utf-8')))
        file_io.name = f"definition of {response_word['word']}.txt"
        await event.client.send_file(event.chat_id, file_io, caption="`Output was too large, sent it as a file.`")
        await event.delete()
        return

    await event.edit(definition)

CMD_HELP.update({
    'ud':
    ".ud <search_query>"
    "\nUsage: Does a search on Urban Dictionary."
})


# 설명
#
# 수를 곱해나가면 2, 8, 16, 80, 80 이 나옵니다. 16은 4를 제곱해 나온 수이므로 이 수는 제곱수입니다. 따라서 found를 출력합니다.
#
# 예시 2
# 입력
#
# 5
# 1
# 2
# 3
# 1
# 출력
#
# not found

import math

if __name__ == '__main__':
    numbers = [int(input()) for _ in range(5)]
    multiplied = 1
    for number in numbers:
        multiplied *= number
        if math.sqrt(multiplied) == int(math.sqrt(multiplied)):
            print('found')
            break
    else:
        print('not found')

workspace/프로그래밍강의_파이썬을 파이썬답게/flag OR else.py


# coding=utf-8
import datetime
import logging
import os

import matplotlib
from flask import g

from ..base import Base
from ...db import get_db
from ...db.dao.component import Component
from ...db.dao.evaluation import Evaluation
from ...db.dao.evaluation_file import EvaluationFile
from ...db.dao.experimental_task import ExperimentalTask
from ...db.dao.project import Project
from ...db.dao.report import Report
from ...db.models import EvaluationFileModel
from ...extensions import get_file_client
from ...filesystem import get_fs

matplotlib.use('Agg')

logging.basicConfig(
    level=logging.ERROR,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

class ReportUpload(Base):

    menu_info_names = [{'name': '删除'},
                       {'name': '提交实验结果'}]

    evaluation_info_names = [{'name': 'log', 'type': 'text'}]

    def _get_evaluation_dir(self, evaluation_id):
        return 'evaluations/%s' % evaluation_id

    def _check_valid_params(self, logger, params=None):
        if not params:
            logger.exception('params is None')
            return False
        elif not params.get('parent_id'):
            logger.exception('params has no attribute name "parent_id"')
            return False
        elif not params.get('project_id'):
            logger.exception('params has no attribute name "project_id"')
            return False
        elif not params.get('parent_task_name'):
            logger.exception('params has no attribute name "parent_task_name"')
            return False
        else:
            return True

    def execute(self, evaluation_id=None, params=None, item_id=None):
        fs = get_fs()
        file_client = get_file_client()
        evaluation_dir = self._get_evaluation_dir(item_id)
        evaluation_output_dir = fs.join(evaluation_dir, 'outputs')
        if fs.isdir(fs.join(evaluation_dir, 'outputs')):
            fs.rmtree(fs.join(evaluation_dir, 'outputs'))
        fs.makedirs(evaluation_output_dir)
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s: - %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S')
        log_path = fs.abs_path(fs.join(evaluation_output_dir, 'evaluation.log'))
        fh = logging.FileHandler(log_path)
        fh.setFormatter(formatter)
        logger.addHandler(fh)
        success = self._check_valid_params(logger, params)
        content = params.get('content')
        file_key = params.get('file_key')
        parent_id = params['parent_id']
        parent_task_name = params['parent_task_name']
        project_id = params['project_id']
        project = Project().query(project_id=project_id)[0]
        experimental_task_id = project['experimental_task_id']
        from dmlab_app.task import get_task_method, get_customized_task_method
        task_method = get_task_method(parent_task_name)
        if not task_method:
            component = Component().query(component_name=parent_task_name, user_id=params['user_id'])[0]
            task_method = get_customized_task_method(component['component_type_id'])
        if success:
            experimental_task = ExperimentalTask().query(experimental_task_id=experimental_task_id)[0]
            score_field = experimental_task['score_field']
            print(params['user_id'])
            reports = Report().query(user_id=params['user_id'], experimental_task_id=experimental_task_id)
            time_value = (experimental_task['dead_line'] - datetime.datetime.now()) / (experimental_task['dead_line'] - experimental_task['start_time'])
            score = task_method.calc_score(score_field, parent_id, len(reports), time_value)
            score_content = task_method.get_score(parent_id)
            Report().create(user_id=params['user_id'], experimental_task_id=experimental_task_id, task_name=parent_task_name, data_id=parent_id, content=content, file_key=file_key, score_content=score_content, score=score)
        logger.removeHandler(fh)
        db = get_db()
        try:
            collection = file_client.get_collection()
            file_paths = list()

            for dirpath, dirnames, filenames in os.walk(fs.abs_path(evaluation_dir)):
                for filename in filenames:
                    file_path = os.path.join(dirpath, filename)
                    r_path = os.path.relpath(file_path, fs.abs_path(evaluation_dir))
                    with open(file_path, 'rb') as fin:
                        collection.add(fin.read())
                        file_paths.append(r_path)
            rets = file_client.upload_collection(collection)
            for idx, ret in enumerate(rets):
                evaluation_file = EvaluationFileModel(evaluation_id=evaluation_id,
                                                      file_path=file_paths[idx], file_key=ret.id, deleted=0)
                db.add(evaluation_file)
            collection.close()
            # os.remove(fs.abs_path(evaluation_dir))
            db.commit()
        except:
            db.rollback()
        finally:
            db.close()
        return success

    def get_evaluation_info_list(self, item_id, info_name, config=None, limit=None, offset=None):
        assert info_name in map(lambda info_type: info_type['name'], self.evaluation_info_names)
        if info_name == 'data':
            return self._get_evaluation_data(item_id, limit=limit, offset=offset)
        elif info_name == 'log':
            return self._get_evaluation_log(item_id, limit=limit, offset=offset)
        elif info_name == 'report':
            return self._get_evaluation_report(item_id, limit=limit, offset=offset)
        else:
            raise NotImplementedError

    def _get_evaluation_data(self, item_id, limit=None, offset=None):
        return None, None, None

    def _get_evaluation_log(self, item_id, limit=None, offset=None):
        file_client = get_file_client()
        evaluation = Evaluation().query(item_id=item_id)[0]
        evaluation_file = EvaluationFile().query(evaluation_id=evaluation['evaluation_id'],
                                                 file_path='outputs/evaluation.log')
        if evaluation_file:
            log_content = file_client.download(evaluation_file[0]['file_key'])
            logs = [{
                'id': 1,
                'name': 'evaluation.log',
                'type': 'text',
                'data': str(log_content, encoding='utf-8')
            }]
        else:
            logs = []
        count = len(logs)
        if limit is None:
            limit = len(logs)
        else:
            limit = int(limit)
        if offset is None:
            offset = 0
        else:
            offset = int(offset)
        return logs[offset:offset + limit], count, None

    def _get_evaluation_report(self, item_id, limit=None, offset=None):
        return None, None, None

    def get_score(self, item_id):
        return ''


from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from bs4 import BeautifulSoup
import jsonlines

class someSpider(CrawlSpider):
    name = 'getquestions'
    allowed_domains = ['datascience.stackexchange.com']
    start_urls = ['https://datascience.stackexchange.com/questions/6107/what-are-deconvolutional-layers']
    rules = (Rule (LinkExtractor(allow="/questions/*"), callback="parse_obj", follow=True),)

    def parse_obj(self,response):
        with jsonlines.open('data.jsonl', mode='a') as writer:

            url = response.url
            question_head = response.xpath('//div[@id="question-header"]/h1/a/text()').get()
            question_body = ' '.join(response.xpath('//div[@class="s-prose js-post-body"]/p/text()').getall())

            soup = BeautifulSoup(response.text, 'lxml')
            html = [x.text for x in soup.find_all("div",attrs={"class":"answer accepted-answer"})]
            html = ' '.join(html)
            html = " ".join(line.strip() for line in html.split("\n"))
            if html:
                answer_body = html
            else:
                html = [x.text for x in soup.find_all("div",attrs={"class":"answer"})]
                html = ' '.join(html)
                html = " ".join(line.strip() for line in html.split("\n"))
                answer_body = html

            obj = {
                'url' : url,
                'question_head': question_head,
                'question_body': question_body,
                'answer_body': answer_body
            }
            writer.write(obj)


all_colors = [
	{"label": 'Red', "sexy": True},
	{"label": 'Pink', "sexy": False},
	{"label": 'Orange', "sexy": True},
	{"label": 'Brown', "sexy": False},
	{"label": 'Pink', "sexy": True},
	{"label": 'Violet', "sexy": True},
	{"label": 'Purple', "sexy": False},
]

#Your code go here:
def filter_colors(colors):
    return colors["sexy"] is True

sexy_list = list(filter(filter_colors, all_colors))

def generate_li(sexy_colors):
    for color in sexy_colors:
        print("<li>"+color["label"]+"</li>")

generate_li(sexy_list)


# -*- coding: utf-8 -*-
import scrapy
from bs4 import BeautifulSoup

class BbcworldSpider(scrapy.Spider):
    name = 'bbcworld'
    #allowed_domains = ['http://www.baidu.com']
    start_urls = ['http://www.bbc.com/news/world']

    def parse(self, response):     #找头条
        bbc_st = response.text
        bbc_st_soup = BeautifulSoup(bbc_st, 'lxml')
        url = 'http://www.bbc.com' + bbc_st_soup.find('a',{'class':'title-link'}).get('href')
        yield scrapy.Request(url, callback=self.parseAgain)

    def parseAgain(self, response):    #找文章
        bbc_f = response.text
        bbc_soup = BeautifulSoup(bbc_f, 'lxml')
        essay = bbc_soup.head.title.string + '\n'     #标题
        for i in bbc_soup.body.find('p',{"class":"story-body__introduction"}).previous_sibling.next_siblings:
            if i.name in ['p'] :
                essay = self.findText(essay,i)
            elif i.name in ['h1','h2'] :
                essay += '\n'
                essay = self.findText(essay, i)
            elif i.name == 'hr':
                if i.next_sibling.name in ['h1','h2']:
                    essay += '\n'
                    essay = self.findText(essay, i)
                else:
                    break
            elif i.name in ['ul','li']:
                essay = self.findTextList(essay,i)
            else:
                continue
        with open('bbcworld.txt', 'w',encoding='utf-8',errors='ignore') as f:
            f.write(essay)
        self.log('Saved file bbcworld.')

    def findText(self,in_txt,in_soup):
        try:
            in_txt += '\n' + in_soup
        except:
            for x in in_soup.descendants:
                try:
                    in_txt += x
                except:
                    continue
            in_txt += '\n'
        return in_txt

    def findTextList(self,in_txt,in_soup):
        try:
            in_txt += '\n' + in_soup
        except:
            for x in in_soup.descendants:
                try:
                    in_txt += x
                except:
                    continue
        in_txt += '\n'
        return in_txt


#!/usr/bin/env python

from plico.client.hackerable_client import HackerableClient
from tipico.client.abstract_instrument_client import \
    AbstractInstrumentClient
from plico.rpc.abstract_remote_procedure_call import \
    AbstractRemoteProcedureCall
from plico.utils.logger import Logger
from plico.utils.decorator import override, returns
from tipico.utils.timeout import Timeout
from tipico.types.instrument_status import InstrumentStatus
from plico.client.serverinfo_client import ServerInfoClient

class InstrumentClient(AbstractInstrumentClient,
                       HackerableClient,
                       ServerInfoClient):

    def __init__(self,
                 rpcHandler,
                 sockets):
        assert isinstance(rpcHandler, AbstractRemoteProcedureCall)

        self._rpcHandler= rpcHandler
        self._requestSocket= sockets.serverRequest()
        self._statusSocket= sockets.serverStatus()
        self._logger= Logger.of('Instrument client')

        HackerableClient.__init__(self,
                                  self._rpcHandler,
                                  self._requestSocket,
                                  self._logger)
        ServerInfoClient.__init__(self,
                                  self._rpcHandler,
                                  self._requestSocket,
                                  self._logger)

    @override
    def moveTo(self,
               actuatorPosition,
               timeoutInSec=Timeout.INSTRUMENT_MOVE_TO):
        return self._rpcHandler.sendRequest(
            self._requestSocket,
            'moveTo', [actuatorPosition],
            timeout=timeoutInSec)
        pass

    @override
    def getPosition(self, timeoutInSec=Timeout.MIRROR_GET_ZONAL_COMMAND):
        return self._rpcHandler.sendRequest(
            self._requestSocket,
            'getPosition', [],
            timeout=timeoutInSec)

    @override
    @returns(InstrumentStatus)
    def getStatus(self, timeoutInSec=Timeout.MIRROR_GET_STATUS):
        return self._rpcHandler.receivePickable(
            self._statusSocket,
            timeoutInSec)

    @override
    def getSnapshot(self,
                    prefix,
                    timeoutInSec=Timeout.MIRROR_GET_STATUS):
        return self._rpcHandler.sendRequest(
            self._requestSocket,
            'getSnapshot', [prefix],
            timeout=timeoutInSec)


'''

Popolare una lista di n elementi con i primi n numeri pari.
Dopo averli inseriti visualizzare in output i valori memorizzati nella lista e la loro posizione.

'''

def main():

    l1=[]

    #inserimento

    for j in range(10):

        if j%2==0:

            l1.append(j)

    #print

    for i in range(len(l1)):

        print("elemento" , l1[i] )

        print("posizione:",  l1.index(l1[i]))

main()


x = int(input())
y = int(input())
if x > 0:
    if y > 0:               # x > 0, y > 0
        print("Первая четверть")
    else:                   # x > 0, y < 0
        print("Четвертая четверть")
else:
    if y > 0:               # x < 0, y > 0
        print("Вторая четверть")
    else:                   # x < 0, y < 0
        print("Третья четверть")
#определяет в какой из четвертей координатной плоскости находится точка (x,y)


#1
def number_of_food_groups():
    return 5
print(number_of_food_groups())
# RESULT: prints 5

#2
def number_of_military_branches():
    return 5
print(number_of_days_in_a_week_silicon_or_triangle_sides() + number_of_military_branches())
# RESULT: returns Error (number_of_days_in_a_week_silicon_or_triangle_sides() function is not defined)

#3
def number_of_books_on_hold():
    return 5
    return 10
print(number_of_books_on_hold())
# RESULT: prints 5

#4
def number_of_fingers():
    return 5
    print(10)
print(number_of_fingers())
# RESULT: prints 5

#5
def number_of_great_lakes():
    print(5)
x = number_of_great_lakes()
print(x)
# RESULT: prints 5 but not "x" as values is not returned/stored to assign it to x var

#6
def add(b,c):
    print(b+c)
print(add(1,2) + add(2,3))
# RESULT: prints 3 and then 5 and then shows error

#7
def concatenate(b,c):
    return str(b)+str(c)
print(concatenate(2,5))
# RESULT: print 25

#8
def number_of_oceans_or_fingers_or_continents():
    b = 100
    print(b)
    if b < 10:
        return 5
    else:
        return 10
    return 7
print(number_of_oceans_or_fingers_or_continents())
# RESULT: prints 100 first, then prints 10

#9
def number_of_days_in_a_week_silicon_or_triangle_sides(b,c):
    if b<c:
        return 7
    else:
        return 14
    return 3
print(number_of_days_in_a_week_silicon_or_triangle_sides(2,3))
print(number_of_days_in_a_week_silicon_or_triangle_sides(5,3))
print(number_of_days_in_a_week_silicon_or_triangle_sides(2,3) + number_of_days_in_a_week_silicon_or_triangle_sides(5,3))
# RESULT1: prints 7
# RESULT2: prints 14
# RESULT3: prints 21

#10
def addition(b,c):
    return b+c
    return 10
print(addition(3,5))
# RESULT: prints 8

#11
b = 500
print(b)
def foobar():
    b = 300
    print(b)
print(b)
foobar()
print(b)
# RESULT: prints 500 (line 91), then prints 500 (line 95), reassigned and prints 300 (line 96), prints 500 again (line 97)

#12
b = 500
print(b)
def foobar():
    b = 300
    print(b)
    return b
print(b)
foobar()
print(b)
# RESULT: b = 500 (prints 500), b = 500 (prints 500), b = 300 (prints 300 inside function), b = 500 (prints 500)

#13
b = 500
print(b)
def foobar():
    b = 300
    print(b)
    return b
print(b)
b=foobar()
print(b)
# RESULT: b = 500 (prints 500), b = 500 (prints 500), b = 300 (prints 300 inside function), b = 300 (prints 300)

#14
def foo():
    print(1)
    bar()
    print(2)
def bar():
    print(3)
foo()
# RESULT: prints 1, then calls bar() and prints 3, then prints 2

#15
def foo():
    print(1)
    x = bar()
    print(x)
    return 10
def bar():
    print(3)
    return 5
y = foo()
print(y)
# RESULT: prints 1 (line 140), prints 3 (line 145), prints 5 (line 141), prints 10 (line 148)


import pytest

def army_to_list(army):
    return [prop for troop in army for prop in troop]

@pytest.mark.asyncio
async def test_army_to_array(arrstructs):
    troop_vals = (10, 10, 100)
    troops = [arrstructs.Troop(*troop_vals)] * 3
    army = arrstructs.Army(*troops)
    tx = await arrstructs.army_to_array(army).invoke()
    assert tx.result.a == army_to_list(army)

@pytest.mark.asyncio
async def test_array_to_army(arrstructs):
    army = [10, 10, 100, 10, 10, 100, 10, 10, 100]
    tx = await arrstructs.array_to_army(army).invoke()
    assert army_to_list(tx.result.a) == army

@pytest.mark.asyncio
async def test_new_config(arrstructs):
    tx = await arrstructs.new_config(10, 20, 30).invoke()
    assert tx.result.config == arrstructs.Config(value1=10, value2=20, value3=30)


from django.shortcuts import render
from .models import Post

# Create your views here.
def blog_index(request):
    posts = Post.objects.all().order_by('-created_on') # все объекты из базы данных Post
    context = {
        'posts':posts
    } #создали словарь, чтобы потом передать его на страницу
    return render(request, 'blog_index.html', context)

def blog_detail(request, pk):
    post = Post.objects.get(pk = pk)#вызываем конкретный объект по уникальному рк(первичный ключ, ID из таблицы базы данных
    context = {
        'post': post
    }
    return render(request, 'blog_detail.html', context)


import bpy
from bpy.types import Region
from bpy.props import IntProperty

# Tag the given region for a redraw.
# Notably used for the message bus.
def require_region_redraw(region: bpy.types.Region):
    region.tag_redraw()

# Base class for the editor's regions.
class ViewLayerManagerRegion(Region):
    bl_space_type = 'VIEW_LAYER_MANAGER_EDITOR'

class ViewLayerManagerHeaderRegion(ViewLayerManagerRegion):
    bl_region_type = 'HEADER'

    def init(self, window_manager):
        Region.header_init(self)

class ViewLayerManagerUIRegion(ViewLayerManagerRegion):
    bl_region_type = 'UI'

    def init(self, window_manager):
        Region.panels_init(window_manager, self)

class ViewLayerManagerWindowRegion(ViewLayerManagerRegion):
    bl_region_type = 'WINDOW'

    def init(self, window_manager):
        Region.panels_init(window_manager, self)

        types = (bpy.types.ViewLayer, bpy.types.LayerCollection, bpy.types.Collection)

        for t in types:
            bpy.msgbus.subscribe_rna(
                key=t,
                owner=self,
                args=(self, ),
                notify=require_region_redraw,
            )

        bpy.msgbus.subscribe_rna(
            key=(bpy.types.Scene, "view_layers"),
            owner=self,
            args=(self, ),
            notify=require_region_redraw,
        )

# Update function for the query string.
# self is the editor.
def update_search_filter(self, context):
    self.search_filter_update()

class ViewLayerManagerSpace(bpy.types.Space):
    bl_idname = 'VIEW_LAYER_MANAGER_EDITOR'
    bl_label = 'View Layer Manager'
    bl_icon = 'RENDER_RESULT'

    search_filter: bpy.props.StringProperty(name="Search Filter", update=update_search_filter, options={'TEXTEDIT_UPDATE'})

    # Property for the active view layer in the UIList.
    active_view_layer: IntProperty()

    def search_filter_get(self, region):
        return self.search_filter

classes = (
    ViewLayerManagerSpace,
    ViewLayerManagerHeaderRegion,
    ViewLayerManagerUIRegion,
    ViewLayerManagerWindowRegion,
)


import pandas as pd

data = []

with open("E:\\AI\\slogan\\type2\\자동차.txt", "r", encoding="utf-8-sig") as f:
    buff = f.readline()

    while buff:
        tmp = []

        buff = buff.split("-")

        if buff[0]:
            buff[0] = buff[0].rstrip().lstrip()
            tmp.append(buff[0])
            print(buff[0])

        if len(buff) > 1:
            try:
                buff[1] = buff[1].rstrip().lstrip()
                tmp.append(buff[1])
                print(buff[1])
            except:
                print("buff1 error!")
        else:
            tmp.append("")

        data.append(tmp)
        buff = f.readline()

print("문장 수 : ", len(data))

# index 제거
df = pd.DataFrame(data, columns = ["copywrite", "product"])
df.to_excel("car.xlsx", header=True, index=False)


#Position
#Author : Dominic Martindale
#Date: 6/06/2019
#About: A constructor for creating an container object with x and y co-ords

class Position:

    #Sets x and y values.
    #Wether postion is occupied or not can be left blank
    # the default is not occupied.
    def __init__(self, x, y, is_occupied=None):
        self.__x = x
        self.__y = y

        #Allows is_occupied to have no initial value
        if is_occupied == None:
            self.__is_occupied = False #default value, if none given
        else:
            self.__is_occupied = is_occupied

    @property #Getter for x
    def x(self):
        return self.__x

    @x.setter #Setter for x, int only
    def x(self, value):
        if type(value) == int: #int checker
            self.__x = value
        else:
            return print("A wrong x value was entered into a position") #error

    @property #Getter for y
    def y(self):
        return self.__y

    @y.setter  #Setter for y int only
    def y(self, value):
        if type(value) == int: #int checker
            self.__y = value
        else:
            return print("A wrong x value was entered into a position") #error

    @property #Getter for is_occupied
    def is_occupied(self):
        return self.__is_occupied

    @is_occupied.setter  #Setter for is_occupied, boolean only
    def is_occupied(self, value):
        if type(value) == bool:  #boolean checker
            self.__is_occupied = value
        else:
            return print("A wrong is_occupied value was entered into a position") #error


class State:
    goal = [1,2,3,4,5,6,7,8,0]

    greedy_evaluation = None

    heuristic = None
    def __init__(self,state,parent,direction,depth,cost):
        self.state = state
        self.parent = parent
        self.direction = direction
        self.depth = depth

        if parent:
            self.cost = parent.cost + cost

        else:
            self.cost = cost

    def test(self):
        if self.state == self.goal:
            return True
        return False

    def Misplaced_Tiles(self,n):
        counter = 0
        self.heuristic = 0
        for i in range(n*n):
            for j in range(n*n):
                if(self.state[i] != self.goal[j]):
                    counter += 1
                self.heuristic = self.heuristic + counter
        self.greedy_evaluation = self.heuristic

        return(self.greedy_evaluation)

    @staticmethod

    def available_moves(x,n):
        moves = ['Left','Right','Up','Down']
        if x%n == 0:
            moves.remove('Left')
        if x%n == n-1:
            moves.remove('Right')
        if x-n<0:
            moves.remove('Up')
        if x+n>n*n-1:
            moves.remove('Down')

        return moves

    def expand(self,n):
        x=self.state.index(0)
        moves=self.available_moves(x,n)

        children=[]
        for direction in moves:
            temp=self.state.copy()
            if direction=='Left':
                temp[x],temp[x-1]=temp[x-1],temp[x]
            elif direction=='Right':
                temp[x],temp[x+1]=temp[x+1],temp[x]
            elif direction=='Up':
                temp[x],temp[x-n]=temp[x-n],temp[x]
            elif direction=='Down':
                temp[x],temp[x+n]=temp[x+n],temp[x]

            children.append(State(temp,self,direction,self.depth+1,1))
        return children

    def solution(self):
        solution = []
        solution.append(self.direction)
        path = self
        while path.parent != None:
            path = path.parent
            solution.append(path.direction)
        solution = solution[:-1]
        solution.reverse()
        return solution


from sys import stdin
from collections import deque

N, M = map(int, stdin.readline().split())
check = [[[False for _ in range(2)] for _ in range(M)] for _ in range(N)]
Map = [list(stdin.readline().strip()) for _ in range(N)]

Que = deque([(0, 0, 0)])
check[0][0][0] = 1
check[0][0][1] = 1

dy = [0, 0, 1, -1]
dx = [1, -1, 0, 0]

output = -1

if N == 1 and M == 1:
    output = 1

while len(Que):
    cur_y, cur_x, chance = Que.popleft()
    for i in range(4):
        ny = cur_y + dy[i]
        nx = cur_x + dx[i]
        if 0 <= ny < N and 0 <= nx < M:
            if ny == N-1 and nx == M-1:
                output = check[cur_y][cur_x][chance] + 1
                Que.clear()
                break

            elif Map[ny][nx] == '0' and check[ny][nx][chance] is False:
                Que.append((ny, nx, chance))
                check[ny][nx][chance] = check[cur_y][cur_x][chance] + 1

            elif Map[ny][nx] == '1' and chance == 0:
                Que.append((ny, nx, 1))
                check[ny][nx][1] = check[cur_y][cur_x][chance] + 1

print(output)

6.연습/벽부수고이동하기.py


from django.http import HttpResponse
from django.test import RequestFactory
from djblets.cache.backend import cache_memoize
from kgb import SpyAgency

from reviewboard.diffviewer.errors import UserVisibleError
from reviewboard.diffviewer.models import FileDiff
from reviewboard.diffviewer.renderers import DiffRenderer
from reviewboard.diffviewer.settings import DiffSettings
from reviewboard.testing import TestCase

class DiffRendererTests(SpyAgency, TestCase):
    """Unit tests for DiffRenderer."""

    def test_construction_with_invalid_chunks(self):
        """Testing DiffRenderer construction with invalid chunks"""
        diff_file = {
            'chunks': [{}],
            'filediff': None,
            'interfilediff': None,
            'force_interdiff': False,
            'chunks_loaded': True,
        }

        diff_settings = DiffSettings.create()

        renderer = DiffRenderer(diff_file, chunk_index=-1,
                                diff_settings=diff_settings)
        self.assertRaises(UserVisibleError,
                          lambda: renderer.render_to_string_uncached(None))

        renderer = DiffRenderer(diff_file, chunk_index=1,
                                diff_settings=diff_settings)
        self.assertRaises(UserVisibleError,
                          lambda: renderer.render_to_string_uncached(None))

    def test_construction_with_valid_chunks(self):
        """Testing DiffRenderer construction with valid chunks"""
        diff_file = {
            'chunks': [{}],
            'chunks_loaded': True,
        }

        # Should not assert.
        renderer = DiffRenderer(diff_file, chunk_index=0,
                                diff_settings=DiffSettings.create())
        self.spy_on(renderer.render_to_string, call_original=False)
        self.spy_on(renderer.make_context, call_original=False)

        renderer.render_to_string_uncached(None)
        self.assertEqual(renderer.num_chunks, 1)
        self.assertEqual(renderer.chunk_index, 0)

    def test_construction_with_setting_syntax_highlighting_true(self):
        """Testing DiffRenderer construction with
        DiffSettings.syntax_highlighting=True
        """
        diff_file = {
            'chunks': [{}],
            'chunks_loaded': True,
        }

        diff_settings = DiffSettings.create(syntax_highlighting=True)

        renderer = DiffRenderer(diff_file,
                                chunk_index=0,
                                diff_settings=diff_settings)
        self.assertTrue(renderer.highlighting)

    def test_construction_with_setting_syntax_highlighting_false(self):
        """Testing DiffRenderer construction with
        DiffSettings.syntax_highlighting=False
        """
        diff_file = {
            'chunks': [{}],
            'chunks_loaded': True,
        }

        diff_settings = DiffSettings.create(syntax_highlighting=False)

        renderer = DiffRenderer(diff_file,
                                chunk_index=0,
                                diff_settings=diff_settings)
        self.assertFalse(renderer.highlighting)

    def test_render_to_response(self):
        """Testing DiffRenderer.render_to_response"""
        diff_file = {
            'chunks': [{}]
        }

        renderer = DiffRenderer(diff_file, diff_settings=DiffSettings.create())
        self.spy_on(renderer.render_to_string,
                    call_fake=lambda self, request: 'Foo')

        request_factory = RequestFactory()
        request = request_factory.get('/')
        response = renderer.render_to_response(request)

        self.assertTrue(renderer.render_to_string.called)
        self.assertTrue(isinstance(response, HttpResponse))
        self.assertEqual(response.content, b'Foo')

    def test_render_to_string(self):
        """Testing DiffRenderer.render_to_string"""
        diff_file = {
            'chunks': [{}]
        }

        renderer = DiffRenderer(diff_file, diff_settings=DiffSettings.create())
        self.spy_on(renderer.render_to_string_uncached,
                    call_fake=lambda self, request: 'Foo')
        self.spy_on(renderer.make_cache_key,
                    call_fake=lambda self: 'my-cache-key')
        self.spy_on(cache_memoize)

        request_factory = RequestFactory()
        request = request_factory.get('/')
        response = renderer.render_to_response(request)

        self.assertEqual(response.content, b'Foo')
        self.assertTrue(renderer.render_to_string_uncached.called)
        self.assertTrue(renderer.make_cache_key.called)
        self.assertTrue(cache_memoize.spy.called)

    def test_render_to_string_uncached(self):
        """Testing DiffRenderer.render_to_string_uncached"""
        diff_file = {
            'chunks': [{}]
        }

        renderer = DiffRenderer(diff_file, lines_of_context=[5, 5],
                                diff_settings=DiffSettings.create())
        self.spy_on(renderer.render_to_string_uncached,
                    call_fake=lambda self, request: 'Foo')
        self.spy_on(renderer.make_cache_key,
                    call_fake=lambda self: 'my-cache-key')
        self.spy_on(cache_memoize)

        request_factory = RequestFactory()
        request = request_factory.get('/')
        response = renderer.render_to_response(request)

        self.assertEqual(response.content, b'Foo')
        self.assertTrue(renderer.render_to_string_uncached.called)
        self.assertFalse(renderer.make_cache_key.called)
        self.assertFalse(cache_memoize.spy.called)

    def test_make_context_with_chunk_index(self):
        """Testing DiffRenderer.make_context with chunk_index"""
        diff_file = {
            'newfile': True,
            'interfilediff': None,
            'filediff': FileDiff(),
            'chunks': [
                {
                    'lines': [],
                    'meta': {},
                    'change': 'insert',
                },
                {
                    # This is not how lines really look, but it's fine for
                    # current usage tests.
                    'lines': range(10),
                    'meta': {},
                    'change': 'replace',
                },
                {
                    'lines': [],
                    'meta': {},
                    'change': 'delete',
                }
            ],
        }

        renderer = DiffRenderer(diff_file, chunk_index=1,
                                diff_settings=DiffSettings.create())
        context = renderer.make_context()

        self.assertEqual(context['standalone'], True)
        self.assertEqual(context['file'], diff_file)
        self.assertEqual(len(diff_file['chunks']), 1)

        chunk = diff_file['chunks'][0]
        self.assertEqual(chunk['change'], 'replace')


import sys
class Solution():
    """_summary_

    1. You are given a number n, representing the number of rows.
    2. You are given a number m, representing the number of columns.
    3. You are given n*m numbers, representing elements of 2d array a, which represents a gold mine.
    4. You are standing in front of left wall and are supposed to dig to the right wall. You can start from
     any row in the left wall.
    5. You are allowed to move 1 cell right-up (d1), 1 cell right (d2) or 1 cell right-down(d3).
    """
    def find_max_gold(self,gold_bag):
        dp = [[0 for _ in gold] for gold in gold_bag]
        j = len(dp[0])-1
        while j>=0:
            i = len(dp)-1
            while i>=0:
                if j == len(dp[0])-1:
                    dp[i][j]=gold_bag[i][j]
                elif i==0:
                    dp[i][j]=gold_bag[i][j]+max(dp[i][j+1],dp[i+1][j+1])
                elif i==len(dp)-1:
                    dp[i][j]=gold_bag[i][j]+max(dp[i-1][j+1],dp[i][j+1])
                else:
                    dp[i][j] = gold_bag[i][j] + max(dp[i][j+1],dp[i-1][j+1],dp[i+1][j+1])
                i =i-1
            j=j-1

        maxi = sys.maxsize*-1
        i=len(dp)-1
        while i>=0:
            if maxi < dp[i][0]:
                maxi = dp[i][0]
            i =i-1
        return maxi

n = int(input())
m = int(input())

gold_bag = []
for i in range(0, n):
    ar = []
    l = input()
    for j in range(0, m):
        lst = l.split(" ")
        val = int(lst[j])
        ar.append(val)
    gold_bag.append(ar)

print(Solution().find_max_gold(gold_bag))


# -*- coding: utf-8 -*-
"""
Created on Fri Dec  2 11:09:43 2022

@author: utilisateur
"""

import os
import gzip
import shutil

def ExtractGz(directory,
              extract_dir,
              verbose = 0):
    if not os.path.exists(extract_dir):
        os.mkdir(extract_dir)
    list_files = os.listdir(directory)
    list_gz = []
    for file in list_files:
        if file.split('.')[-1] == 'gz':
            list_gz.append(file)
    for file_in_name in list_gz:
        assert file_in_name.split('.')[-1] == 'gz'
        file_out_name = extract_dir + '/' + file_in_name.replace('.gz', '')
        file_in_name = directory + '/' + file_in_name
        with gzip.open(file_in_name, 'rb') as f_in:
            with open(file_out_name, 'wb') as f_out:
                try:
                    shutil.copyfileobj(f_in, f_out)
                except:
                    print(file_in_name)
                    raise

if __name__ == "__main__":
    directory = 'C:/Users/utilisateur/Desktop/Guerledan/Bouees_GNSS/DATA/data_2022_2023/BoueeV2/testLog23102022/NMEA'
    extract_dir = directory + '/extract'
    ExtractGz(directory, extract_dir)


from operator import itemgetter

def items_anal(data: list) -> int:
    backpack_volume = data[0][1]
    del data[0]

    # Finding price per 1 weight point

    for i in range(len(data)):
        data[i].insert(0, float(data[i][0] / data[i][1]))
    data = sorted(data, key=itemgetter(0), reverse=True)
    # print(f"data {data}")

    # Calculating optimal backpack set

    total_price = float()
    remaining_volume = backpack_volume
    i = 0
    while remaining_volume > 0 and i < len(data):
        if data[i][2] <= remaining_volume:
            total_price += data[i][1]
            remaining_volume -= data[i][2]
        else:
            total_price += float(remaining_volume * data[i][0])
            break
        i += 1
        # print(f'total_price = {total_price}')
        # print(f'remaining_volume = {remaining_volume}')
    return total_price

def get_input_data() -> list:
    data_set = []
    data_set.append(list(map(int, input().split())))
    for i in range(data_set[0][0]):
        data_set.append(list(map(int, input().split())))
    return data_set

# def get_test_data(filename: str) -> list:
#   data_set = []
#   with open(filename) as data:
#       for line in data:
#           data_set.append(list(map(int, line.split())))
#   assert 1 <= data_set[0][0] <= 1e3, 'Wrong amount of items'
#   assert 0 <= data_set[0][1] <= 2e6, 'Wrong volume for backpack'
#   for i in range(1, len(data_set)):
#       for j in data_set[i]:
#           assert 0 <= j <= 2e6, f'Wrong values for {j} in {data_set[i]}'
#   return data_set

def main():
    print(f"{items_anal(get_input_data()):.3f}")
    # print(f"{items_anal(get_test_data('4_1_2_data.txt')):.3f}")

if __name__ == "__main__":
    main()


# Faça um programa que leia 10 números inteiros e separe os mesmos em pares e ímpares. Mostre
# quantos pares foram lidos, bem como o maior e o menor número par. Faça o mesmo para os ímpares.

list_numero = []
list_par = []
list_impar = []

for i in range(10):
    numero = int(input(f"Digite o {i+1}º número inteiro: "))
    list_numero.append(numero)
    if (numero % 2 == 0):
        list_par.append(numero)
    else:
        list_impar.append(numero)

tam_par = len(list_par)
tam_impar = len(list_impar)

if tam_par > 0:
    maior_par = max(list_par)
    menor_par = min(list_par)
    print(f"Quantidade de números pares: {tam_par}")
    print(f"Maior número par: {maior_par}")
    print(f"Menor número par: {menor_par}")
else:
    print("Nenhum número par foi digitado!")

if tam_impar > 0:
    maior_impar = max(list_impar)
    menor_impar = min(list_impar)
    print(f"Quantidade de números ímpares: {tam_impar}")
    print(f"Maior número ímpar: {maior_impar}")
    print(f"Menor número ímpar: {menor_impar}")
else:
    print("Nenhum número ímpar foi digitado!")


"""This module contains random functions used by the other modules."""

from sys import stdout
from time import sleep

def type_effect(text, newline=True, speed=0.05):
    """Prints strings one character at a time for a typing effect."""
    for char in text:
        stdout.write(char)
        stdout.flush()
        sleep(speed)
    if newline:
        print()

def print_line(length=50, before=False, after=False):
    """Print line of specified size using type effect."""
    if before:
        print()
    type_effect("-" * length, speed=0.02)
    if after:
        print()

def prompt_str(question, true, false, newline=True):
    """Ask user to input string. Check input validity."""
    while True:
        type_effect(question, newline=newline)
        resp = input()

        # Checks if input has non-letter characters
        if resp == '' or any(not c.isalpha() for c in resp):
            type_effect("Invalid response.")
        else:
            if resp.lower() == true:
                return True
            if resp.lower() == false:
                return False
            type_effect("Invalid response.")

def prompt_int(question, less_than, greater_than, newline=True):
    """Ask user to input integer value. Check input validity."""
    while True:
        type_effect(question, newline=newline)
        val = input()

        # Check if input has any non-digit characters
        if val == '' or any(not c.isdigit() for c in val):
            type_effect("\nInvalid value entered.")
        else:
            val = int(val)

            # Check if inputted numbers are outside of range
            if val < less_than or val > greater_than:
                type_effect("\nThis value is out of range.")

            # Input is valid
            else:
                return val


#!/usr/bin/env python

from base_filter import BaseFilter
import re

class RegexFilter(BaseFilter):

    def __init__(self, conf):
        self.regexps = []
        self.compiled = False

    def compile(self, force=False):
        if not self.compiled or force:
            for regex in self.regexps:
                regex["regexc"] = re.compile(regex["regex"])

    def parse(self, message):
        if not self.compiled:
            self.compile()
        return [(m.groupdict() or m.groups()) for regex in self.regexps for m in regex["regexc"].finditer(message)]

    def compact_field_value(self, dict_):
        if "field" in dict_:
            for v in [dict_.pop(k, None) for k in ["value", "value1", "value2"]]:
                if not v is None:
                    dict_[dict_.pop("field")] = v
                    return dict_
        return dict_

    def add_fields(self, one, other):
        for k, v in other.iteritems():
            if k in one:
                if not isinstance(one[k], list):
                    one[k] = [one[k]]
                one[k] = one[k] + v if isinstance(v, list) else one[k] + [v]
            else:
                one[k] = v
        return one


from PyQt5.QtWidgets import *
from include.marver_r.RMLOracle import RMLOracle
from include.marver_r.TLOracle import TLOracle
from src.marver_r.GuiLog import GuiLog
from include.marver_r.Monitor import Monitor
from include.marver_r.Property import Property
from bin.UI_MARVer import Ui_MainWindow
from include.marver_r.Verifier import Verifier
from include.marver_r.XmlParser import XmlParser
import json

class GuiVerifier:
    def __init__(self, ui: Ui_MainWindow = None, logger: GuiLog = None, monitor: [Monitor] = [],
                 rmlOracle: RMLOracle = None, tlOracle: TLOracle = None):
        self.__rmlOracle = rmlOracle
        self.__ui = ui
        self.__monitor = monitor
        self.__tlOracle = tlOracle
        self.__logger = logger

        self.initComponents()
        # self.test()

    def initComponents(self):
        self.__ui.btnPropertyDefineDelete.setEnabled(False)
        self.__ui.btnPropertyDefineUpdate.setEnabled(False)
        self.__ui.btnPropertyDefineCreate.setEnabled(True)

    def getProperties(self) -> [Property]:
        temp = []
        temp.extend(self.__rmlOracle.getProperties())
        temp.extend(self.__tlOracle.getProperties())
        return temp

    def addProperty(self):
        if not self.checkMonitorIsExist():
            self.__logger.printLog("Please create a monitor first ! ", "red")
            return

        if self.__ui.txtPropertyDefineName.text() == "" or \
                self.__ui.txtPropertyDefineDescription.toPlainText() == "" \
                or self.__ui.txtPropertyDefineFormula.text() == "" \
                or not self.__ui.lwPropertyDefineNodes.selectedItems():
            self.__logger.printLog(message="Please fill in all fields !!", color="red")
            return

        if self.__ui.cbxPropertyDefineType.currentText() == "TL Oracle":
            if self.__tlOracle.isExist(self.__ui.txtPropertyDefineName.text())[0] or \
                    self.__rmlOracle.isExist(self.__ui.txtPropertyDefineName.text())[0]:
                self.__logger.printLog(message="The name of the property is not unique. Change the name !!",
                                       color="red")
                return
            else:
                self.__tlOracle.setProperties(Property(name=self.__ui.txtPropertyDefineName.text(),
                                                       description=self.__ui.txtPropertyDefineDescription.toPlainText(),
                                                       formula=self.__ui.txtPropertyDefineFormula.text(),
                                                       nodeNames=[item.text() for item in
                                                                  self.__ui.lwPropertyDefineNodes.selectedItems()]))
                self.__logger.printLog(message="The property is added successfully", color="green")
        else:
            if self.__rmlOracle.isExist(self.__ui.txtPropertyDefineName.text())[0] or \
                    self.__tlOracle.isExist(self.__ui.txtPropertyDefineName.text())[0]:
                self.__logger.printLog(message="The name of the property is not unique. Change the name !!",
                                       color="red")
                return
            else:
                self.__rmlOracle.setProperties(Property(name=self.__ui.txtPropertyDefineName.text(),
                                                        description=self.__ui.txtPropertyDefineDescription.toPlainText(),
                                                        formula=self.__ui.txtPropertyDefineFormula.text(),
                                                        nodeNames=[item.text() for item in
                                                                   self.__ui.lwPropertyDefineNodes.selectedItems()]))
                self.__logger.printLog(message="The property is added successfully", color="green")
        self.__ui.txtPropertyDefineName.clear()
        self.__ui.txtPropertyDefineDescription.clear()
        self.__ui.txtPropertyDefineFormula.clear()
        self.__ui.lwPropertyDefineNodes.clearSelection()
        self.updateVerifierDefineCbx()
        self.updateVerifierSaveCbx()

    def editProperty(self):
        property = self.__tlOracle.getPropertyByName(self.__ui.cbxPropertyDefineVerifier.currentText())
        if property:
            self.__tlOracle.deletePropertyByName(property.getName())
        else:
            property = self.__rmlOracle.getPropertyByName(self.__ui.cbxPropertyDefineVerifier.currentText())
            if property:
                self.__rmlOracle.deletePropertyByName(property.getName())
        self.addProperty()

    def deleteProperty(self):
        propertyName = self.__ui.cbxPropertyDefineVerifier.currentText()
        if self.__tlOracle.isExist(propertyName)[0]:
            self.__tlOracle.getProperties().pop(self.__tlOracle.isExist(propertyName)[1])
        else:
            self.__rmlOracle.getProperties().pop(self.__rmlOracle.isExist(propertyName)[1])

        self.__ui.txtPropertyDefineName.clear()
        self.__ui.txtPropertyDefineDescription.clear()
        self.__ui.txtPropertyDefineFormula.clear()
        self.__ui.lwPropertyDefineNodes.clearSelection()
        self.updateVerifierDefineCbx()
        self.updateVerifierSaveCbx()

    def importProperty(self):
        filePath = self.openFileDialogWindow('json')
        if not filePath:
            return
        properties = self.getJSONFileContent(filePath=filePath)
        for property in properties["properties"]:
            if self.__ui.cbxPropertyImportType.currentText() == "TL Oracle":
                self.__tlOracle.setProperties(Property(name=property["name"],
                                                       description=property["description"],
                                                       formula=property["formula"],
                                                       nodeNames=property["nodeNames"]))
                self.__logger.printLog(message="TL properties imported successfully", color="green")
            else:
                self.__rmlOracle.setProperties(Property(name=property["name"],
                                                        description=property["description"],
                                                        formula=property["formula"],
                                                        nodeNames=property["nodeNames"]))
                self.__logger.printLog(message="RML properties imported successfully", color="green")
        self.updateVerifierDefineCbx()
        self.updateVerifierSaveCbx()

    def openFileDialogWindow(self, ext) -> str:
        try:
            filePath, check = QFileDialog.getOpenFileName(None, "Open File", "3rdparty/rosmonitoring/oracle",
                                                          "Text Files (*." + ext + ")")
            if filePath:
                self.__logger.printLog(message="File selection completed successfully", color="green")
                return filePath
            else:
                raise IOError(f"An error occurred while opening the file")
        except IOError:
            self.__logger.printLog(message=f"An error occurred while opening the file", color="red")
        except:
            self.__logger.printLog(message="ERROR in openFileDialogWindow()", color="red")

    def getJSONFileContent(self, filePath: str):
        try:
            with open(filePath) as file:
                if not file:
                    raise IOError(f"An error occurred while reading the file")
                self.__logger.printLog(message="File content read successfully", color="green")
                return json.load(file)
        except IOError:
            self.__logger.printLog(message=f"An error occurred while reading the file", color="red")
        except:
            self.__logger.printLog(message="ERROR in getJSONFileContent()", color="red")

    def saveProperty2File(self):
        fileName = self.__ui.txtPropertySaveFileName.text()
        if fileName:
            items = self.__ui.lwPropertySaveSelect.selectedItems()
            if items:
                try:
                    if self.__ui.cbxPropertySaveType.currentText() == "TL Oracle":
                        with open(f'3rdparty/rosmonitoring/oracle/TLOracle/properties/{fileName}.json', 'w') as f:
                            f.write(self.preparePropertiesJSON(
                                self.__tlOracle.getPropertiesByName(names=[item.text() for item in items])))
                    else:
                        with open(f'3rdparty/rosmonitoring/oracle/RMLOracle/rml/properties/{fileName}.json',
                                  'w') as f:
                            f.write(self.preparePropertiesJSON(
                                self.__rmlOracle.getPropertiesByName(names=[item.text() for item in items])))

                    self.__ui.txtPropertySaveFileName.clear()
                    self.__logger.printLog(message="File content saved successfully", color="green")
                except IOError:
                    self.__logger.printLog(message=f"An error occurred while writing to the file", color="red")
                except:
                    self.__logger.printLog(message="ERROR in saveProperty2File()", color="red")

            else:
                self.__logger.printLog(message="Please select the properties", color="red")
        else:
            del fileName
            self.__logger.printLog(message="Please fill the file name", color="red")

    @staticmethod
    def preparePropertiesJSON(properties: [Verifier]) -> str:
        content = {"properties": []}
        for property in properties:
            content["properties"].append(
                {"name": property.getName(), "description": property.getDescription(), "formula": property.getFormula(),
                 "nodeNames": property.getNodeNames()})

        return json.dumps(content, indent=4)

    def setVerifierComponentsStatus(self):
        if self.__ui.cbxPropertyDefineVerifier.currentText() == "New Property":
            self.__ui.btnPropertyDefineDelete.setEnabled(False)
            self.__ui.btnPropertyDefineUpdate.setEnabled(False)
            self.__ui.btnPropertyDefineCreate.setEnabled(True)
        else:
            verifier = self.__tlOracle.getPropertyByName(self.__ui.cbxPropertyDefineVerifier.currentText())
            if verifier:
                self.__ui.cbxPropertyDefineType.setCurrentIndex(0)
            else:
                self.__ui.cbxPropertyDefineType.setCurrentIndex(1)
                verifier = self.__rmlOracle.getPropertyByName(self.__ui.cbxPropertyDefineVerifier.currentText())

            self.__ui.txtPropertyDefineName.setText(verifier.getName())
            self.__ui.txtPropertyDefineDescription.setPlainText(verifier.getDescription())
            self.__ui.txtPropertyDefineFormula.setText(verifier.getFormula())
            self.__ui.lwPropertyDefineNodes.clear()

            for name in verifier.getNodeNames():
                self.__ui.lwPropertyDefineNodes.addItem(name)

            self.__ui.btnPropertyDefineDelete.setEnabled(True)
            self.__ui.btnPropertyDefineUpdate.setEnabled(True)
            self.__ui.btnPropertyDefineCreate.setEnabled(False)

    def updateVerifierDefineCbx(self):
        self.__ui.cbxPropertyDefineVerifier.clear()
        self.__ui.cbxPropertyDefineVerifier.addItem("New Property")
        for tlVerifier in self.__tlOracle.getProperties():
            self.__ui.cbxPropertyDefineVerifier.addItem(tlVerifier.getName())
        for rmlVerifier in self.__rmlOracle.getProperties():
            self.__ui.cbxPropertyDefineVerifier.addItem(rmlVerifier.getName())

        self.__ui.cbxPropertyDefineVerifier.setCurrentIndex(0)
        self.__ui.btnPropertyDefineDelete.setEnabled(False)
        self.__ui.btnPropertyDefineUpdate.setEnabled(False)
        self.__ui.btnPropertyDefineCreate.setEnabled(True)

        self.__ui.lwPropertyDefineNodes.clear()
        if self.checkMonitorIsExist():
            for node in self.__monitor[0].getNodes():
                self.__ui.lwPropertyDefineNodes.addItem(node.getName())

    def updateVerifierSaveCbx(self):
        self.__ui.lwPropertySaveSelect.clear()
        if self.__ui.cbxPropertySaveType.currentText() == "TL Oracle":
            for tlVerifier in self.__tlOracle.getProperties():
                self.__ui.lwPropertySaveSelect.addItem(tlVerifier.getName())
        else:
            for rmlVerifier in self.__rmlOracle.getProperties():
                self.__ui.lwPropertySaveSelect.addItem(rmlVerifier.getName())
        self.__ui.cbxPropertyDefineVerifier.setCurrentIndex(0)

    def checkMonitorIsExist(self) -> bool:
        if not self.__monitor:
            return False
        return True

    def clearVerifierComponents(self):
        self.__ui.cbxPropertyDefineVerifier.clear()
        self.__ui.cbxPropertyDefineVerifier.addItem("New Property")
        self.__ui.cbxPropertyDefineVerifier.setCurrentIndex(0)
        self.__ui.txtPropertyDefineName.clear()
        self.__ui.txtPropertyDefineDescription.clear()
        self.__ui.lwPropertyDefineNodes.clear()
        self.__ui.lwPropertySaveSelect.clear()
        self.__ui.txtPropertySaveFileName.clear()
        self.__ui.txtPropertyDefineFormula.clear()

        self.__ui.btnPropertyDefineDelete.setEnabled(False)
        self.__ui.btnPropertyDefineUpdate.setEnabled(False)
        self.__ui.btnPropertyDefineCreate.setEnabled(True)

    def importUppaalModel(self):
        f = self.openFileDialogWindow('xml')
        file = XmlParser(f)

        for formula in file.getQueries():
            formula=formula.strip()
            if self.tctl2Reelay(formula):
                self.__ui.cbxPropertyDefineFormula.addItem(self.tctl2Reelay(formula))

        self.__ui.cbxPropertyDefineFormula.setEnabled(True)
        print()

    def tctl2Reelay(self,formula: str) -> str:
        # check str is blank or not
        if not formula or "deadlock" in formula:
            return None

        temp = ""
        # Eliminate E<> or A[]
        for f in formula.split(" ")[1:]:
            if "&&" in f:
                temp += " and "
            elif "||" in f:
                temp += " or "
            elif "." in f:
                temp += str(f.split(".")[0]) + "_state: " + str(f.split(".")[1])
            else:
                temp += f

        return "{" + temp + "}"