import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import time
import torch.utils.model_zoo as model_zoo
import numpy as np
import torch.utils.data as data_utils

import math
from collections import OrderedDict

def train(trainloader, net, criterion, optimizer, device):
    for epoch in range(10):  # loop over the dataset multiple times
        start = time.time()
        running_loss = 0.0
        for i, (images, labels) in enumerate(trainloader):
            images = images.to(device)
            labels = labels.view(-1, 1).to(device)
            optimizer.zero_grad()
            outputs = net(images)
            loss = criterion(outputs, labels)
            loss.backward()
            optimizer.step()
            # print statistics
            running_loss += loss.item()
            if i % 5 == 4:    # print every 2000 mini-batches
                end = time.time()
                print('[epoch %d, iter %5d] loss: %.3f eplased time %.3f' %
                      (epoch + 1, i + 1, running_loss / 100, end-start))
                start = time.time()
                running_loss = 0.0
    print('Finished Training')

def test(testloader, net, device):
    correct = 0
    total = 0
    with torch.no_grad():
        for data in testloader:
            images, labels = data
            images = images.to(device)
            labels = labels.view(-1, 1).to(device)
            outputs = net(images)
            predicted = (outputs.data > 0).float()
            total += labels.size(0)
            correct += (predicted == labels).sum().item()
    print('Accuracy of the network on the test images: %d %%' % (
        100 * correct / total))

def main():
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
#    device = torch.device('cpu')
    model_urls = {
        'alexnet': 'https://download.pytorch.org/models/alexnet-owt-4df8aa71.pth',
    }
    data_control = np.load('data.npy')
    data_control = data_control[:, 4:7, :, :]
    data_control = torch.from_numpy(data_control.astype(float)).float()
    y_control = torch.zeros(data_control.size(0), dtype=torch.float)
    data_control_train = data_control[0:int(data_control.size(0)*0.8)]
    data_control_test =  data_control[int(data_control.size(0)*0.8):]
    y_control_train = y_control[0:int(data_control.size(0)*0.8)]
    y_control_test = y_control[int(data_control.size(0)*0.8):]
    data_pd = np.load('PD_data.npy')
    data_pd = data_pd[:, 4:7, :, :]
    data_pd = torch.from_numpy(data_pd.astype(float)).float()
    y_pd = torch.ones(data_pd.size(0), dtype=torch.float)
    data_pd_train = data_pd[0:int(data_pd.size(0)*0.8)]
    data_pd_test =  data_pd[int(data_pd.size(0)*0.8):]
    y_pd_train = y_pd[0:int(data_pd.size(0)*0.8)]
    y_pd_test = y_pd[int(data_pd.size(0)*0.8):]
    data_train = torch.cat((data_control_train, data_pd_train), 0)
    y_train = torch.cat((y_control_train, y_pd_train), 0)
    data_test = torch.cat((data_control_test, data_pd_test), 0)
    y_test = torch.cat((y_control_test, y_pd_test), 0)

    trainset = data_utils.TensorDataset(data_train, y_train)
    trainloader = torch.utils.data.DataLoader(trainset, batch_size=10,
                                              shuffle=True)

    testset = data_utils.TensorDataset(data_test, y_test)
    testloader = torch.utils.data.DataLoader(testset, batch_size=10, shuffle=False)

    net = torchvision.models.alexnet(pretrained=False, num_classes=1)
    net = net.to(device)
#    net.load_state_dict(model_zoo.load_url(model_urls['alexnet']), strict=False)

    criterion = nn.BCEWithLogitsLoss()
    optimizer = optim.Adam(net.parameters(), lr=0.001)

    train(trainloader, net, criterion, optimizer, device)
    test(testloader, net, device)

if __name__ == "__main__":
    main()


"""
    Service class includes functionalities for implementing program features
"""

from src.domain.entity import complexNumber
import random
#import sys

class complexNumbersList:
    """
    Functionalities for the (list of) complex numbers
    """

    def __init__(self):
        """
        Creates a list of complex numbers and initialize it with 10 random complex numbers
        """
        self._listOfComplexNumbers = []
        self.initial_numbers()

    def __getitem__(self, position):
        """
        Get an element from the list of complex numbers
        :param position: the position of the element that needs to be returned
        :return: the element from the given position
        """
        return self._listOfComplexNumbers[position]

    @property
    def list_of_complex_numbers(self):
        """
        :return: the list of complex numbers
        """
        return self._listOfComplexNumbers

    @list_of_complex_numbers.setter
    def list_of_complex_numbers(self, givenList):
        """
        Set the list of complex numbers
        :param givenList: the list attributed to the list of complex numbers
        """
        self._listOfComplexNumbers = list(givenList)

    def add_complex_number_to_list(self, complexNumberToAdd):
        """
        Adds a complex numbers to the list
        :param complexNumberToAdd: the complex number that will be added
        """
        self._listOfComplexNumbers.append(complexNumberToAdd)

    def filter_list(self, startPosition, endPosition):
        """
        Filter the list so that it contains only the numbers between <startPosition> and <endPosition>
        :param startPosition: the position from where we begin to keep the elements
        :param endPosition: the position where we stop keeping the elements
        """
        if startPosition < 0 or startPosition > len(self._listOfComplexNumbers) - 1 or startPosition > endPosition:
            raise IndexError("The start position should be greater than 0 and smaller than the end position which need to be smaller than " + str(len(self._listOfComplexNumbers) - 1) + '!')
        if endPosition < startPosition or endPosition > len(self._listOfComplexNumbers) - 1:
            raise IndexError("The final position should be bigger than " + str(startPosition) + " and smaller than " + str(len(self._listOfComplexNumbers) - 1) + '!')

        auxiliaryList = []

        for index in range(startPosition, endPosition + 1):
            auxiliaryList.append(self._listOfComplexNumbers[index])

        self._listOfComplexNumbers = auxiliaryList

    def __len__(self):
        """
        :return: the length of the list of complex numbers
        """
        return len(self._listOfComplexNumbers)

    def initial_numbers(self):
        """
        Adds 10 random complex numbers to the list at program startup
        """
        complexNumber1 = complexNumber(random.randint(-100, 100), random.randint(-100, 100))
        self.add_complex_number_to_list(complexNumber1)
        complexNumber2 = complexNumber(random.randint(-100, 100), random.randint(-100, 100))
        self.add_complex_number_to_list(complexNumber2)
        complexNumber3 = complexNumber(random.randint(-100, 100), random.randint(-100, 100))
        self.add_complex_number_to_list(complexNumber3)
        complexNumber4 = complexNumber(random.randint(-100, 100), random.randint(-100, 100))
        self.add_complex_number_to_list(complexNumber4)
        complexNumber5 = complexNumber(random.randint(-100, 100), random.randint(-100, 100))
        self.add_complex_number_to_list(complexNumber5)
        complexNumber6 = complexNumber(random.randint(-100, 100), random.randint(-100, 100))
        self.add_complex_number_to_list(complexNumber6)
        complexNumber7 = complexNumber(random.randint(-100, 100), random.randint(-100, 100))
        self.add_complex_number_to_list(complexNumber7)
        complexNumber8 = complexNumber(random.randint(-100, 100), random.randint(-100, 100))
        self.add_complex_number_to_list(complexNumber8)
        complexNumber9 = complexNumber(random.randint(-100, 100), random.randint(-100, 100))
        self.add_complex_number_to_list(complexNumber9)
        complexNumber10 = complexNumber(random.randint(-100, 100), random.randint(-100, 100))
        self.add_complex_number_to_list(complexNumber10)

        """
        #OR
        for index in range(10):
            myComplexNumber = complexNumber(random.randint(-sys.maxsize - 1, sys.maxsize), random.randint(-sys.maxsize - 1, sys.maxsize))
            self.add_complex_number_to_list(myComplexNumber)
        """

class historyList:
    """
    Functionalities for the history of lists
    """

    def __init__(self):
        """
        Creates a list which will contain all the modified lists
        """
        self._historyOfLists = []

    def __getitem__(self, position):
        """
        Get an element(list) from the list of all the modified lists
        :param position: the position of the element(list) that needs to be returned
        :return: the element(list) from the given position
        """
        return self._historyOfLists[position]

    @property
    def history_list(self):
        """
        :return: the list of all the modified lists
        """
        return self._historyOfLists

    def __len__(self):
        """
        :return: the length of the list of all the modified lists
        """
        return len(self._historyOfLists)

    def add_to_history(self, listOfComplexNumbers):
        """
        Adds a list of complex numbers to the history of modified lists
        :param listOfComplexNumbers: the list that will be added
        """
        self._historyOfLists.append(list(listOfComplexNumbers))

    def remove_at_position(self, position):
        """
        Remove the list from the given position from the history of modified lists
        :param position: the position from which we need to delete the list
        """
        self._historyOfLists.pop(position)

        #OR del self._historyOfLists[position]

    def undo_operation(self, listOfComplexNumbers):
        """

        :return:
        """
        if len(self._historyOfLists) < 2:
            raise ValueError('There is nothing to undo!')

        listOfComplexNumbers.clear()
        self.remove_at_position(-1)
        for number in self._historyOfLists[-1]:
            listOfComplexNumbers.append(number)

class testFunctionsService:

    @staticmethod
    def test_init():
        listOfComplexNumbers = complexNumbersList()
        assert len(listOfComplexNumbers) == 10

    @staticmethod
    def test_add_complex_number_to_list():
        listOfComplexNumbers = complexNumbersList()
        listOfComplexNumbers.add_complex_number_to_list(complexNumber(2, 3))
        assert  len(listOfComplexNumbers) == 11
        print(listOfComplexNumbers[0])

    @staticmethod
    def test_filter_list():
        listOfComplexNumbers = complexNumbersList()
        listOfComplexNumbers.filter_list(2,5)
        assert len(listOfComplexNumbers) == 4
        listOfComplexNumbers.filter_list(0,0)
        assert len(listOfComplexNumbers) == 1

    @staticmethod
    def test_add_to_history():
        historyOfLists = historyList()
        listOfComplexNumbers = complexNumbersList()
        historyOfLists.add_to_history(listOfComplexNumbers.list_of_complex_numbers)
        assert len(historyOfLists) == 1

    @staticmethod
    def test_remove_at_position():
        historyOfLists = historyList()
        listOfComplexNumbers = complexNumbersList()
        historyOfLists.add_to_history(listOfComplexNumbers.list_of_complex_numbers)
        assert len(historyOfLists) == 1
        historyOfLists.remove_at_position(0)
        assert len(historyOfLists) == 0

    @staticmethod
    def run_all_service_tests():
        testFunctionsService.test_init()
        testFunctionsService.test_add_complex_number_to_list()
        testFunctionsService.test_filter_list()
        testFunctionsService.test_add_to_history()
        testFunctionsService.test_remove_at_position()


import functools

from test_framework import generic_test
import math

MAPPING = {'A':1,'B':2,'C':3,'D':4,'E':5,'F':6,'G':7,'H':8,'I':9,'J':10,'K':11,'L':12,'M':13,'N':14,'O':15,
           'P':16,'Q':17,'R':18,'S':19,'T':20,'U':21,'V':22,'W':23,'X':24,'Y':25,'Z':26}
MULTIPLIER = 26

def ss_decode_col_id(col):
    if len(col) == 1:
        return MAPPING[col]
    col_list = list(col)
    running_total = 0
    power = len(col_list)-1
    for i in range(len(col_list)-1):
        key = col_list[i]
        running_total += ((MULTIPLIER**power)*MAPPING[key])
        power -= 1

    key = col_list[-1]
    running_total += MAPPING[key]
    return running_total

if __name__ == '__main__':
    exit(
        generic_test.generic_test_main("spreadsheet_encoding.py",
                                       'spreadsheet_encoding.tsv',
                                       ss_decode_col_id))


# # # # # # # # # # # # # #
# CAPTAINHOOK IDENTIFIER  #
# # # # # # # # # # # # # #
import os
import sys
from contextlib import contextmanager
from os.path import join

from .utils import filter_python_files, get_config_file

try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO

DEFAULT = 'on'
CHECK_NAME = 'flake8'
NO_FLAKE_MSG = ("flake8 is required for the flake8 plugin.\n"
                "`pip install flake8` or turn it off in your {} "
                "file.".format(get_config_file()))
REQUIRED_FILES = [get_config_file()]

@contextmanager
def redirected(out=sys.stdout, err=sys.stderr):
    saved = sys.stdout, sys.stderr
    sys.stdout, sys.stderr = out, err
    try:
        yield
    finally:
        sys.stdout, sys.stderr = saved

@contextmanager
def change_folder(folder):
    old_dir = os.curdir
    os.chdir(folder)
    try:
        yield
    finally:
        os.chdir(old_dir)

def run(files, temp_folder):
    "Check flake8 errors in the code base."
    try:
        import flake8  # NOQA
    except ImportError:
        return NO_FLAKE_MSG
    try:
        from flake8.engine import get_style_guide
    except ImportError:
        # We're on a new version of flake8
        from flake8.api.legacy import get_style_guide

    py_files = filter_python_files(files)
    if not py_files:
        return
    DEFAULT_CONFIG = join(temp_folder, get_config_file())

    with change_folder(temp_folder):
        flake8_style = get_style_guide(config_file=DEFAULT_CONFIG)
        out, err = StringIO(), StringIO()
        with redirected(out, err):
            flake8_style.check_files(py_files)
    return out.getvalue().strip() + err.getvalue().strip()


import queue
import sys
import datetime
import time
from scipy.stats import poisson
    # event = Event(bus, eventData)
class Event(object):
    def __init__( self, bus, eventData ):
        self.bus=bus
        self.timestamp = bus.timestamp
        self.route = bus.route
        self.eventType = eventData.eventType
        self.componentType = eventData.component.componentType
        self.id = eventData.component.id
        self.numAtQ = eventData.component.numAtQ
        # self.next = next
        return

    def printSelf(self):
        print( 'its timestamp is %s ' % (self.timestamp) )
        print( 'its eventType is %s ' % (self.eventType))
        print( 'its componentType is %s ' % (self.componentType) )
        # print('its next is %s ' % (self.next))

#compare with others??
    def __lt__(self, other):
        return self.timestamp < other.timestamp
    def __eq__(self, other):
        return self.timestamp == other.timestamp

# eventData = EventData('arrival', comp)
class EventData(object):
    def __init__(self, eventType, Component):
        self.eventType = eventType
        self.component = Component

# usage: comp = Component(34, 'station', 12, 0)
# ???
class Component(object):
    def __init__(self, id, componentType, processingTime, numAtQ ):
        self.id = id
        self.componentType = componentType
        self.processingTime = processingTime
        self.numAtQ = numAtQ

class Scheduler():
    def __init__(self):
        self.time = 0
        self.FEL = queue.PriorityQueue()

    def schedule(self, event ):
        # self.FEL.put( Event( bus, eventData ) )
        self.FEL.put( event )
# change the bus off the input, taken from nextevent
    def runSim(self, eventHandler, endTime):
        while not self.FEL.empty():

            # print(self.FEL.queue)
            nextEvent = self.FEL.get()
            bus=nextEvent.bus
            now = nextEvent.timestamp
            if now > endTime:
                break

            eventHandler.handle( nextEvent, bus )
            # print( nextEvent )
            # print( 'current timestamp is %s ' % (nextEvent.timestamp) )
            timeArray = time.localtime(nextEvent.timestamp)
            StyleTime = time.strftime("%Y-%b-%d %a %H:%M:%S", timeArray)
            print('current timestamp is  ',StyleTime)
            print('current route is %s ' % (nextEvent.route))
            print('current eventType is %s ' % (nextEvent.eventType))
            print('current componentType is %s ' % (nextEvent.componentType))
            print( )

            # self.time = nextEvent.timestamp
#?????
class EventHandeler(object):
    def __init__(self):
        pass

    def handle(self, event, bus):
        if event.eventType == 'generate':
            bus.busGenerate()

        elif event.eventType == 'arrival':
            bus.busArrival()

        else:
            bus.busDepature()

t=0
#usage: bus = Bus(23, 1255, stopImpl, 50, scheduler)
class Bus(object):
    def __init__(self, route, timestamp, stop, capacity, scheduler):
        self.route = route
        self.timestamp = timestamp
    #numAtStop is the number of bus
        self.numAtStop = stop.busAtQ
        self.numOnRoad = 0
        self.capacity = capacity
        self.peopleOnBus = 0
        #busy time or station
        #data_poisson = poisson.rvs(mu=5, size=5)
        #peopleOnBus = sum(data_poisson)
        #normal time or station
        #data_poisson = poisson.rvs(mu=5, size=5)
        #peopleOnBus = sum(data_poisson)
        self.scheduler = scheduler
    def busGenerate(self):
        global t
        self.numOnRoad += 1
#interval is a RV
        if t==0:
            self.timestamp +=1800
        elif t%39==0:
            self.timestamp +=18000
        else:
            self.timestamp +=1800
        t+=1
#temporary setting
        stop = BusStop(12,10)
        #component __init__(self, id, componentType, processingTime, numAtQ ):
#need to change the component id 34 here
        self.scheduler.schedule( Event( self, EventData( 'generate' ,Component(34, 'Generator', 10, 0)) ) )

        # print('number of the bus on the road: %i' % (self.numOnRoad) )

    def busArrival(self):
        self.numAtStop += 1

    def busDeparture(self):
        self.numAtStop -= 1

# people
class BusStop(object):
    def __init__(self, stopId,peoplecount):
        self.id = stopId
        self.peopleInStop = peoplecount
        self.busAtQ = 0

if __name__ == '__main__':
#set up all bus stops
    stopImpl = BusStop(455,10)

    scheduler = Scheduler()

    #20190905
    bus = Bus(94, 1567675500, stopImpl, 50, scheduler)
    # bus.busGenerate()
    # bus.busGenerate()

    comp = Component(34, 'station', 12, 0)
    eventData = EventData('generate', comp)
    event = Event(bus, eventData)

    scheduler.schedule(event)

    eventHandler = EventHandeler()
    # eventHandler.handle( event, bus )

    # scheduler = Scheduler()
    # scheduler.schedule(event)
    #20190908
    scheduler.runSim( eventHandler, 1567975500 )

    # bus = Bus(23, 1255, stopImpl, 50, scheduler)
    # bus.busGenerate()
    # bus.busGenerate()
    #
    # comp = Component(34, 'station', 12, 0)
    # eventData = EventData('arrival', comp)
    # event = Event(bus, eventData)
    #
    # # scheduler = Scheduler()
    # scheduler.schedule(event)
    # # scheduler.runSim()
    #
    #
    #
    # bus = Bus(24, 2155, stopImpl, 50, scheduler)
    # bus.busGenerate()
    # bus.busGenerate()
    #
    # comp = Component(34, 'station', 12, 0)
    # eventData = EventData('arrival', comp)
    # event = Event(bus, eventData)
    #
    #
    # # scheduler = Scheduler()
    # scheduler.schedule( event )
    # scheduler.runSim()

    # pq = queue.PriorityQueue()
    # pq.put((2, 'a'))
    # pq.put((1, 'b'))
    # print(pq.queue ) # output: [(1, 'b'), (2, 'a')]
    # print(pq.get())  # output: (1, 'b')
    # print(pq.queue)  # output: [(1, 'b'), (2, 'a')]
    # pq.queue  # output: [(2, 'a')]

    # bus = Bus(23)
    # bus.busGenerate()
    # bus.busGenerate()

    # event.printSelf()


import warnings
from typing import Tuple

import geopandas as gpd
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd

# Use codes as defined by the [codebook](https://www.mass.gov/files/documents/2016/08/wr/classificationcodebook.pdf)

USE_CODES = {
    "101": "Single Family",
    "102": "Condominium",
    "103": "Mobile Home",
    "104": "Two-Family",
    "105": "Three-Family",
    "106": "Accessory Land with Improvement - garage,etc.",
    "109": "Multiple Houses on one parcel (for example, a single and a two-family on one parcel)",
    "132": "Undevelopable Land",
    "930": "Municipal, Vacant, Selectmen or City Council",
    "130": "Vacant Land in a Residential Zone or Accessory to Residential Parcel, Developable Land",
    "343": "Office Building",  # There is no code 343 in the cited reference, but prefix 34 indicates office buildings.
    "131": "Vacant Land in a Residential Zone or Accessory to Residential Parcel, Potentially Developable Land",
    "945": "Educational Private, Affilliated Housing",
    "942": "Educational Private, College or University",
    "920": "Department of Conservation and Recreation, Division of Urban Parks and Recreation",
    "340": "General Office Buildings",
    "931": "Municipal, Improved, Selectmen or City Council",
    "960": "Church, Mosque, Synagogue, Temple, etc",
    "325": "Small Retail and Services stores (under 10,000 sq. ft.)",
    "337": "Parking Lots - a commercial open parking lot for motor vehicles",
    "932": "Municipal, Vacant, Conservation",
    "013": "Multiple-Use, primarily Residential",
    "031": "Multiple-Use, primarily Commercial",
    "950": "Charitable, Vacant, Conservation Organizations",
}

# Currently only need mappings for Milton and Quincy. Expand to add more municipalities.
TOWN_IDS = {
    189: "Milton",
    243: "Quincy",
}

RESIDENTIAL_USE_CODES = ["101", "102", "103", "104", "105", "109", "013"]

PUBLIC_ACCESS_CODES = {
    "Y": "Yes (open to public)",
    "N": "No (not open to public)",
    "L": "Limited (membership only)",
    "X": "Unknown",
}

LEVEL_OF_PROTECTION_CODES = {
    "P": "In Perpetuity",
    "T": "Temporary",
    "L": "Limited",
    "N": "None",
}

PRIMARY_PURPOSE_CODES = {
    "R": "Recreation (activities are facility based)",
    "C": "Conservation (activities are non-facility based)",
    "B": "Recreation and Conservation",
    "H": "Historical/Cultural",
    "A": "Agricultural",
    "W": "Water Supply Protection",
    "S": "Scenic (official designation only)",
    "F": "Flood Control",
    "U": "Site is underwater",
    "O": "Other (explain)",
    "X": "Unknown",
}

def transform_use_codes(use_codes: pd.Series) -> pd.Series:
    """
    Standardizes use codes by extracting first three digits and looking up description

    USE_CODE – state three-digit use code with optional extension digit to accommodate the four-digit codes commonly used
    by assessors. If the codes contain a four-digit use code, because the meaning of the fourth digit varies from community-to-community,
    the standard requires a lookup table. See the end of this Section for more details on this look-up table.

    """

    def use_codes_map(use_code):
        try:
            use_description = USE_CODES[use_code]
        except KeyError:
            use_description = "Other"
        return use_description

    use_code_descriptions = use_codes.str[:3].map(use_codes_map)
    return use_code_descriptions

def plot_map(
    gdf: gpd.GeoDataFrame,
    column: str,
    categorical: bool = True,
    axis_scale: float = 1,
    legend_shift: float = 1,
    figsize: Tuple[int, int] = (20, 20),
    markersize: float = 0.01,
    legend: bool = True,
    title: str = None,
    cmap: str = "gist_earth",
    fig=None,
    ax=None,
    **style_kwds,
):
    """Generic function to plot maps from GeoDataFrame.

    Args:
        gdf (geopandas.GeoDataFrame): the GeoDataFrame we want to plot map from.
        column (str): column name that we want to use in the plot.
        categorical (bool): ``True`` if the column should be treated as a categorical variable,`False`` if not. Defaults to ``True``.
        axis_scale (float): the scale to enlarge or shrink the axis. Defaults to ``1`` (no size adjustments).
        legend_shift (float): how much to shift the legend box to the right. Defaults to ``1``. Larger number will shift the legend box further to the right. This parameter is used to prevent overlap of the legend box and the map.
        figsize (tuple): the size of the figure. Defaults to ``(20, 20)``.
        markersize (float): the size of the marker, only useful for GeoDataFrame that contains point geometries. Defaults to ``0.01``.
        title (str): the title of the figure. Defaults to ``None``, in which case no title will be set.
        cmap (str): the color map to use in the map plot. Defaults to ``'gist_earth'``. The color maps available in matplotlib can be found here: https://matplotlib.org/3.1.0/tutorials/colors/colormaps.html
        ax: (matplotlib.axes._subplots.AxesSubplot) matplotlib axis object to add plot to

    Returns:
        matplotlib.axes._subplots.AxesSubplot: matplotlib plot.
    """
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        units = gdf.crs.to_dict()["units"]

    if units != "m":
        raise ValueError(
            f"coordinate units can only be meters (m). Instead, the crs was: {gdf.crs.to_dict()}"
        )

    if not ax:
        fig, ax = plt.subplots(1, figsize=figsize)
    ax.grid()
    gdf.plot(
        ax=ax,
        column=column,
        categorical=categorical,
        legend=legend,
        markersize=markersize,
        cmap=cmap,
        **style_kwds,
    )

    # Shrink current axis by `axis_scale`
    box = ax.get_position()
    ax.set_position([box.x0, box.y0, box.width * axis_scale, box.height * axis_scale])

    if legend:
        leg = ax.get_legend()
        if leg is not None:
            leg.set_bbox_to_anchor((legend_shift, 1))

    if units == "m":
        ax.set(xlabel="distance_x (meters)", ylabel="distance_y (meters)")
    # elif coord == 'latlong':
    #     ax.set(xlabel='longitude (deg)', ylabel='latitude (deg)')

    if isinstance(title, str):
        ax.set_title(title)

    return ax

def make_choropleth_style_function(
    df: pd.DataFrame, attr: str, colormap: str, navalue="None"
):
    cmap = matplotlib.cm.get_cmap(colormap)
    attr_values = list(df[attr].fillna(navalue).unique())
    colormap_dict = {
        attr_values[i]: matplotlib.colors.rgb2hex(cmap(i))
        for i in range(len(attr_values))
    }

    def stylefunc(x):
        val = x["properties"][attr]
        if val is None:
            val = navalue
        return {
            "fillColor": colormap_dict[val],
            "color": colormap_dict[val],
        }

    return stylefunc, colormap_dict

def html_legend(cmap_dict):
    table_html = (
        """

    Value
    Color

"""
        + "\n".join(
            f'
{code}	 ████████
'
            for code, color in cmap_dict.items()
        )
        + "
"
    )

    return table_html

# def add_basemap(ax, zoom, url=ctx.sources.ST_TONER_LITE):
#     xmin, xmax, ymin, ymax = ax.axis()
#     basemap, extent = ctx.bounds2img(xmin, ymin, xmax, ymax, zoom=zoom, source=url)
#     ax.imshow(basemap, extent=extent, interpolation='bilinear')
#     # restore original x/y limits
#     ax.axis((xmin, xmax, ymin, ymax))


import pickle
import numpy as np
import tensorflow as tf
import os

def load_label_names(path):

    # Load data
    with open(path + "batches.meta", mode='rb') as file:
        data = pickle.load(file, encoding='bytes')

    # Load label names
    label_names = data[b'label_names']

    # Convert from binary strings
    label_names = [i.decode('utf-8') for i in label_names]

    return label_names

def load_batch(path, filename):
    img_width = 32
    img_height = 32
    img_depth = 3
    number_of_classes = 10

    # Load data
    with open(path + filename, mode='rb') as file:
        data = pickle.load(file, encoding='bytes')

    # Images
    images = data[b'data'].reshape([-1, img_depth, img_width, img_height])
    images = images.transpose([0, 2, 3, 1])

    # Classifiers
    classif = np.array(data[b'labels'])

    # Onehot classifiers
    classif_onehot = np.eye(number_of_classes)[classif]

    return images, classif_onehot, classif


import pytest
from werkzeug.exceptions import NotFound, BadRequest

from app import api
from app.models import Camera

def test_get_query_string_params(application):
    with application.test_request_context('/?foo=bar&life=42'):
        assert api.get_query_string_params() == {'foo': 'bar', 'life': '42'}

def test_get_resource_empty(session, application):
    with application.test_request_context('/api/cameras'):
        resources = api.get_resource(Camera, None)
        assert isinstance(resources, list)
        assert not resources

def test_get_resource_single_item(session):
    session.add(Camera(Name='foo'))
    session.commit()
    resource = api.get_resource(Camera, 1)
    assert isinstance(resource, dict)
    assert resource['Name'] == 'foo'
    assert resource['ID'] == 1

def test_get_resource_not_found(session):
    with pytest.raises(NotFound):
        api.get_resource(Camera, 2)

def test_get_resource_multiple_items(session, application):
    session.add(Camera(Name='foo'))
    session.commit()
    session.add(Camera(Name='bar'))
    session.commit()

    with application.test_request_context('/api/cameras/1'):
        resource = api.get_resource(Camera, 1)
        assert isinstance(resource, dict)
        assert resource['Name'] == 'foo'
        assert resource['ID'] == 1

    with application.test_request_context('/api/cameras'):
        resources = api.get_resource(Camera, None)
        assert isinstance(resources, list)
        assert resources[0]['Name'] == 'foo'
        assert resources[0]['ID'] == 1
        assert resources[1]['Name'] == 'bar'
        assert resources[1]['ID'] == 2

def test_get_data_from_json(application):
    with pytest.raises(BadRequest):
        with application.test_request_context(json=None):
            api.get_data_from_json()
    with application.test_request_context(json={'foo': 'bar'}):
        assert api.get_data_from_json() == {'foo': 'bar'}

def test_create_resource(session, application):
    # We need the session object so the item can be added to the db
    with application.test_request_context(json={'Name': 'foo'}):
        cam = api.create_resource(Camera)
    assert isinstance(cam, dict)
    assert cam['Name'] == 'foo'
    assert cam['ID'] == 1
    with pytest.raises(BadRequest):
        with application.test_request_context(json={'Name': 'foo'}):
            cam = api.create_resource(Camera)
    with pytest.raises(BadRequest):
        with application.test_request_context(json=None):
            cam = api.create_resource(Camera)

def test_update_resource(session, application):
    session.add(Camera(Name='foo'))
    session.commit()
    og_cam = Camera.query.first()

    url = "/api?Name=bar"

    with pytest.raises(NotFound):
        api.update_resource(Camera, 2)
    with pytest.raises(NotFound):
        with application.test_request_context(url):
            api.update_resource(Camera)
    with pytest.raises(BadRequest):
        with application.test_request_context(json=None):
            api.update_resource(Camera, 1)
    with application.test_request_context(json={'Name': 'bar'}):
        cam = api.update_resource(Camera, 1)
    assert cam['Name'] == 'bar'
    assert cam['Created'] == og_cam.Created.isoformat()
    assert cam['Updated'] != og_cam.Updated.isoformat()
    up1_cam = Camera.query.first()
    assert up1_cam.Name == 'bar'
    assert up1_cam.Updated.isoformat() == cam['Updated']

    with application.test_request_context(url, json={'Name': 'foo'}):
        cam = api.update_resource(Camera)
    assert cam['Name'] == 'foo'
    assert cam['Created'] == og_cam.Created.isoformat()
    assert cam['Updated'] != og_cam.Updated.isoformat()
    assert cam['Updated'] != up1_cam.Updated.isoformat()
    up2_cam = Camera.query.first()
    assert up2_cam.Name == 'foo'
    assert up2_cam.Updated.isoformat() == cam['Updated']

def test_delete_resource(session):
    session.add(Camera(Name='foo'))
    session.commit()

    og_cam = Camera.query.first()
    assert og_cam.Active

    cam = api.delete_resource(Camera, 1)
    assert not cam['Active']
    assert not Camera.query.first().Active

    with pytest.raises(BadRequest):
        api.delete_resource(Camera, None)
    with pytest.raises(NotFound):
        api.delete_resource(Camera, 2)

def test_get_create_update_or_delete(session, application):
    client = application.test_client()
    # Test create
    r = client.post('/api/cameras', json={'Name': 'foo'})
    assert r.status_code == 201
    cam1 = r.json
    r = client.post('/api/cameras', json={'Name': 'bar'})
    assert r.status_code == 201
    cam2 = r.json
    assert cam1['Name'] == 'foo'
    assert cam1['ID'] == 1
    assert cam2['Name'] == 'bar'
    assert cam2['ID'] == 2

    r = client.post('/api/product_types', json={'Name': 'EDR'})
    assert r.status_code == 201
    pt = r.json
    pt['Name'] == 'EDR'

    r = client.post(
        '/api/images',
        json={
            'Name': 'im1',
            'URL': 'url',
            'DetatchedLabel': False,
            'Sol': 42,
            'CameraID': 1,
            'ProductTypeID': 1,
        }
    )
    assert r.status_code == 201
    im = r.json
    im['Name'] == 'im1'

    # Test Update
    r = client.put('/api/cameras/2', json={'Name': 'baz'})
    assert r.status_code == 200
    assert r.json['Name'] == 'baz'

    # Test Get
    r = client.get('/api/cameras/1')
    assert r.status_code == 200
    assert r.json['Name'] == 'foo'
    r = client.get('/api/cameras')
    assert r.status_code == 200
    assert isinstance(r.json, list)
    assert len(r.json) == 2
    r = client.get('/api/cameras?Name=foo')
    assert isinstance(r.json, list)
    assert len(r.json) == 1

    # Test Delete
    r = client.delete('/api/cameras/2')
    assert r.status_code == 200
    assert not r.json['Active']


from utils.datasets import *
import cv2

# dataset = MDFA(base_dir='MDFA/')
dataset = SIRST(base_dir='sirst/')

for i in range(dataset.__len__()):
    img, mask = dataset.__getitem__(i)

    if img.shape == mask.shape:
        continue
    else:
        print(i)
        print(img.shape)
        print(mask.shape)
        break

# mask = cv2.imread(r'sirst\masks/Misc_111_pixels0.png', 0)
# print(mask.shape)
#
# mask_new = cv2.resize(mask, (325 ,220))
# print(mask_new.shape)
# cv2.imwrite('Misc_111_pixels0.png', mask_new)


from limite.tela_coordenador import TelaCoordenador
from entidades.coordenador import Coordenador
from entidades.organizador import Organizador
from persistencia.coordenadordao import CoordenadorDAO
from persistencia.organizadordao import OrganizadorDAO

class ControladorCoordenador:
    def __init__(self, controlador_sistema):
        self.__coordenadordao = CoordenadorDAO()
        self.__tela_coordenador = TelaCoordenador()
        self.__controlador_sistema = controlador_sistema
        self.__continua_nesse_menu = True

    def abre_tela(self):
        lista_opcoes = {'btn_voltar': self.voltar, 'btn_organizadores': self.organizadores,
                        'btn_locais': self.locais, 'btn_agendamentos': self.agendamentos,
                        'btn_cad_entidade': self.cadastra_entidade, 'btn_cad_organizador': self.cadastra_organizador,
                        'btn_cad_local': self.cadastra_local}
        self.__continua_nesse_menu = True
        while self.__continua_nesse_menu:
            lista_opcoes[self.__tela_coordenador.open()]()
            self.__tela_coordeador.close()

    def organizadores(self):
        if len(self.organizadores()) == 0:
            self.__tela_cadastro.show_message("Aviso!", "Não existem organizadores cadastrados.")
        else:
            lista_organizadores = list()
            for organizador in self.organizadores():
                lista_organizadores.append("\nNome do organizador: " + organizador.nome +
                                      "\nEmail do organizador: " + organizador.email)
            self.__tela_organizador.show_message("Listagem de Organizadores" + "\nTotal de organizadores "
                                             "cadastrados: " + str(len(self.organizadores())),
                                             "\n".join(lista_organizadores))

    @property
    def organizadores(self):
        return self.__organizadordao.get_all()


# Recode By @mrismanaziz
# FROM Man-Userbot <https://github.com/mrismanaziz/Man-Userbot>
# t.me/SharingUserbot & t.me/Lunatic0de

import importlib
import logging
import os
import sys
from pathlib import Path

from userbot import CMD_HELP, DEVS, LOGS, TEMP_DOWNLOAD_DIRECTORY, bot
from userbot.events import register
from userbot.utils import edit_or_reply

DELETE_TIMEOUT = 5
thumb_image_path = os.path.join(TEMP_DOWNLOAD_DIRECTORY, "thumb_image.jpg")

async def reply_id(event):
    reply_to_id = None
    if event.sender_id in DEVS:
        reply_to_id = event.id
    if event.reply_to_msg_id:
        reply_to_id = event.reply_to_msg_id
    return reply_to_id

def load_module(shortname):
    if shortname.startswith("__"):
        pass
    elif shortname.endswith("_"):
        path = Path(f"userbot/modules/{shortname}.py")
        name = "userbot.modules.{}".format(shortname)
        spec = importlib.util.spec_from_file_location(name, path)
        mod = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(mod)
        LOGS.info("Successfully imported " + shortname)
    else:

        path = Path(f"userbot/modules/{shortname}.py")
        name = "userbot.modules.{}".format(shortname)
        spec = importlib.util.spec_from_file_location(name, path)
        mod = importlib.util.module_from_spec(spec)
        mod.bot = bot
        mod.LOGS = LOGS
        mod.CMD_HELP = CMD_HELP
        mod.logger = logging.getLogger(shortname)
        spec.loader.exec_module(mod)
        # for imports
        sys.modules["userbot.modules." + shortname] = mod
        LOGS.info("Successfully imported " + shortname)

@register(outgoing=True, pattern=r"^\.install$")
async def _(event):
    if event.fwd_from:
        return
    if event.reply_to_msg_id:
        try:
            await event.edit("`Installing Modules...`")
            downloaded_file_name = (
                await event.client.download_media(  # pylint:disable=E0602
                    await event.get_reply_message(),
                    "userbot/modules/",  # pylint:disable=E0602
                )
            )
            if "(" not in downloaded_file_name:
                path1 = Path(downloaded_file_name)
                shortname = path1.stem
                load_module(shortname.replace(".py", ""))
                await event.edit(
                    "**Plugin** `{}` **Berhasil di install**".format(
                        os.path.basename(downloaded_file_name)
                    )
                )
            else:
                os.remove(downloaded_file_name)
                await event.edit("**Error!** Plugin ini sudah terinstall di userbot.")
        except Exception as e:
            await event.edit(str(e))
            os.remove(downloaded_file_name)

@register(outgoing=True, pattern=r"^\.psend ([\s\S]*)")
async def send(event):
    reply_to_id = await reply_id(event)
    thumb = thumb_image_path if os.path.exists(thumb_image_path) else None
    input_str = event.pattern_match.group(1)
    the_plugin_file = f"./userbot/modules/{input_str}.py"
    if os.path.exists(the_plugin_file):
        caat = await event.client.send_file(
            event.chat_id,
            the_plugin_file,
            force_document=True,
            allow_cache=False,
            reply_to=reply_to_id,
            thumb=thumb,
            caption=f"➠ **Nama Plugin:** `{input_str}`",
        )
        await event.delete()
    else:
        await edit_or_reply(event, "**ERROR: Modules Tidak ditemukan**")

CMD_HELP.update(
    {
        "core": "**Plugin : **`core`\
        \n\n  •  **Syntax :** `.install` <reply ke file module>\
        \n  •  **Function : **Untuk Menginstall plugins userbot secara instan.\
        \n\n  •  **Syntax :** `.psend` <nama module>\
        \n  •  **Function : **Untuk Mengirim module userbot secara instan.\
    "
    }
)


import cv2
from cv2 import UMat

def crop_and_resize(frame:UMat,width:int,height:int)->UMat:
  aspect=float(height)/float(width)
  [original_height,original_width]=frame.shape[0:2]
  original_aspect=float(original_height)/float(original_width)
  if aspect < original_aspect:
    # 高さが不要
    temporary_height=int(original_width * aspect)
    y=int((original_height - temporary_height)/2)
    cropped_frame=frame[y:temporary_height,0:original_width]
  else:
    # 幅が不要
    temporary_width=int(original_height / aspect)
    x=int((original_width - temporary_width)/2)
    cropped_frame=frame[0:original_height,x:temporary_width]
  resized_frame=cv2.resize(cropped_frame, (width,height),interpolation=cv2.INTER_NEAREST)
  return resized_frame


from rest_framework.response import Response
from rest_framework import status, mixins, generics, viewsets
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from rest_framework.exceptions import NotFound

from .models import Drop
from .renderers import DropJSONRenderer
from .serializers import DropSerializer

# class DropListCreateAPIView(generics.ListCreateAPIView):
#
#     renderer_classes = (DropJSONRenderer,)
#     queryset = Drop.objects.all()
#     serializer_class = DropSerializer
#
#     def list(self, request, *args, **kwargs):
#         queryset = self.get_queryset()
#         serializer = DropSerializer(queryset, many=True)
#         return Response(serializer.data)
#
#     def post(self, request, *args, **kwargs):
#
#         serializer = DropSerializer(data=request.data)
#         serializer.is_valid(raise_exception=True)
#         serializer.save()
#         return Response(serializer.data, status=status.HTTP_201_CREATED)

class DropViewSet(mixins.CreateModelMixin,
                  mixins.ListModelMixin,
                  mixins.RetrieveModelMixin,
                  mixins.DestroyModelMixin,
                  viewsets.GenericViewSet):

    queryset = Drop.objects.select_related('agent', 'agent__user')
    permission_classes = (IsAuthenticatedOrReadOnly,)
    renderer_classes = (DropJSONRenderer,)
    serializer_class = DropSerializer
    lookup_field = 'id'

    def _check_exists(self, id):
        try:
            serializer_instance = self.queryset.get(id=id)
            return serializer_instance

        except Drop.DoesNotExist:
            raise NotFound('A drop with this id does not exist.')

    def create(self, request, *args, **kwargs):

        serializer_context = {'agent': request.user.profile}
        serializer_data = request.data.get('drop', {})

        serializer = self.serializer_class(
            data=serializer_data,
            context=serializer_context
        )
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)

    def update(self, request, id):

        serializer_instance = self._check_exists(id)

        serializer_data = request.data.get('drop', {})
        serializer = self.serializer_class(serializer_instance, serializer_data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)

    def retrieve(self, request, id):

        serializer_instance = self._check_exists(id)
        serializer = self.serializer_class(serializer_instance)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def destroy(self, request, id, *args, **kwargs):
        drop = self._check_exists(id)
        drop.delete()
        return Response(None, status=status.HTTP_204_NO_CONTENT)


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('behavior_subjects', '0007_auto_20151119_1117'),
    ]

    operations = [
        migrations.AddField(
            model_name='session',
            name='exh_inh_delay',
            field=models.IntegerField(blank=True, verbose_name='Exh-inh delay', default=-1),
        ),
    ]


import plotly.offline as py
import plotly.graph_objs as go
import sensor_input
import random
from pandas import Series

def plot_spectrum_from_files(name,files):
    spectrums = []
    for file in files:
        spectrums.append(sensor_input.read_spectrum_from_file(file))
    plot_spectrums(name,spectrums)

def plot_data_from_pandas(pandas):
    data = []
    for panda in pandas:
        data.append(go.Scatter(
            x=panda,
            y=spectrum["power"],
            marker = dict(
                color = 'rgba(10, 10, 240, .9)'
            )))
    return data

def get_plot_data(name, spectrums):
    data = []
    r = random.randrange(0, 255)
    g = random.randrange(0, 255)
    b = random.randrange(0, 255)
    for spectrum in spectrums:
        data.append(go.Scatter(
            x=spectrum["wavelength"],
            y=spectrum["power"],
            name=name,
            marker = dict(
                color = 'rgba(%s, %s, %s, .9)'%(r,g,b)
            )
        ))
    return data

def read_plot_data_from_files(name,files):
    spectrums = []
    for file in files:
        spectrums.append(sensor_input.read_spectrum_from_file(file))
    return get_plot_data(name,spectrums)

def plot_spectrum_from_files_group(file_groups):
    data = []
    for key in file_groups.keys():
        for plot_data in read_plot_data_from_files(key,file_groups[key]):
            data.append(plot_data)

    py.plot(data, filename="all_ploted")

def plot_spectrums(name,spectrums):
    data = get_plot_data(name,spectrums)
    py.plot(data, filename=name)


#!/usr/bin/python3

# runs VK modules in correct way
""" Developer and Author: Thomas Fire https://github.com/thomasfire (Telegram: @Thomas_Fire)
### Main manager: Uliy Bee
"""

from logging import exception
from os import getpid

import getmsg
import makeseq
import sendtovk
import updatemedia

def get_last_msg():
    f = open('files/msgshistory.db', 'r')
    num = int(f.read().strip('@ ').strip(' ;').split(' ;\n@ ')[-1].split(' :: ')[0])
    print(num)
    f.close()
    return num

def run_vk_bot(vk, chatid, albumid, userid, msgshistory, tl_msgs, list_of_alles, list_of_imnts, list_of_cmds,
               iterations_vk, curr_stat):
    userdic = getmsg.get_user_dict()
    keywords = makeseq.load_keywords()
    lastid = get_last_msg()
    updatemedia.main(vk, albumid, userid)
    curr_stat['PID_VK'] = str(getpid())
    print('VK is ready to start...PID_VK: {0}'.format(curr_stat['PID_VK']))

    cycles = 0

    while True:
        try:
            # getting messages
            lastid, userdic, messages = getmsg.getmain(vk, chatid, msgshistory, userdic, lastid)

            # update list of available media every 1000th iterarion. It is about every 8-20th minute if you have non-server connection
            if cycles >= 1000:
                # clearsent(sent_msgs)
                updatemedia.main(vk, albumid, userid)
                cycles = 0

            # running retranslation to TL only if there are new messages from VK
            for x in messages:
                makeseq.mkmain(x, keywords, list_of_alles, list_of_imnts, list_of_cmds)

            # processing commands and retranslation_from_TL in VK
            sendtovk.stvmain(vk, chatid, list_of_cmds, tl_msgs)

            cycles += 1
            iterations_vk.value += 1
        except ConnectionResetError:  # there are often this type of errors, but it is not my fault
            continue
        except Exception as exp:
            exception("Something gone wrong in vk_bot:\n")


from django.urls import path
from app1.views import *

urlpatterns = [
    path('', inicio, name="Inicio"),
    path('vuelo/', vuelo),
    path('personal/', personal),
    path('pasajero/', pasajero),

    path('formulario1/', formulariovuelo, name="Crear Vuelos"),
    path('formulario2/', formulariopersonal, name="Crear Personal"),
    path('formulario3/', formulariopasajero, name="Crear Pasajeros"),

    path('buscarVuelos/', busquedaVuelos, name="Buscar Vuelos"),
    path('buscarPersonal/', busquedaPersonal, name="Buscar Personal"),
    path('buscarPasajero/', busquedaPasajero, name="Buscar Pasajeros"),

    path('buscar_pasa/',buscar_pasa),
    path('buscar_per/',buscar_per),
    path('buscar/',buscar),
    ]


import pandas as pd
from silx.gui.qt import QMessageBox
from datetime import datetime

def save_csv(self):
    filepath = self.imagepath
    q_choice = self.q_combo.currentText()
    loadedlist = self.loadedlistwidget
    curvelist = [item.text() for item in loadedlist.selectedItems()]
    curvenames = []
    for curve in curvelist:
        if '.nxs' in curve:
            curvenames.append(curve)
        else:
            curvenames.append(curve.split('.')[0])
    if curvelist == []:
        msg = QMessageBox()
        msg.setWindowTitle("Error")
        msg.setText("Please Select Integrated Curve to Save")
        x = msg.exec_()
    else:
        for curve in curvenames:
            df = pd.read_csv(r'{}/{}.dat'.format(filepath, curve), header=None, sep=",", skiprows=2)
            df.to_csv(filepath + '/{}_csv.csv'.format(curve), index=False,header=False)

def save_dat(filename,filepath,res,q_choice):
    now = datetime.now()
    # dd/mm/YY H:M:S
    dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
    date_time = 'DAT file by SAXSII - Timestamp: {}'.format(dt_string)
    res_to_save=res.copy()
    res_to_save.columns = [f'radial-{q_choice}' if x == 'radial' else x for x in res_to_save.columns]
    save_path='{}/{}.dat'.format(filepath, filename)
    with open(save_path, 'w') as f:
       # f.write('# List of Vars\n')
        f.write('#{}\n'.format(date_time))
    res_to_save.to_csv(save_path, mode='a',index=False)
    f.close()


def test_add_group(app):
    old_list = app.groups.get_group_list()
    groups_from_excel = app.groups.\
        get_groups_from_excel("C:\\Users\\AleksandrKoygerov\\PycharmProjects\\python-gui-tests\\groups.xlsx")
    if len(groups_from_excel) == 0:
        print("NO GROUPS LIST, CHECK EXCEL FILE")
        assert False
    for group_to_add in groups_from_excel:
        app.groups.add_new_group(group_to_add)
        old_list.append(group_to_add)
    new_list = app.groups.get_group_list()
    assert sorted(old_list) == sorted(new_list)


import copy
import logging
from typing import Optional

import requests
from ocean_provider.utils.basics import get_web3
from ocean_provider.utils.consumable import ConsumableCodes
from ocean_provider.utils.credentials import AddressCredential
from ocean_provider.utils.data_nft import get_data_nft_contract
from ocean_provider.utils.services import Service

logger = logging.getLogger(__name__)

class Asset:
    def __init__(self, asset_dict: dict) -> None:
        ad = copy.deepcopy(asset_dict)
        self.did = ad.pop("id", None)
        self.version = ad.pop("version", None)
        self.nftAddress = ad.pop("nftAddress", None)
        self.chain_id = ad.pop("chainId", None)
        self.metadata = ad.pop("metadata", None)
        self.services = [
            Service.from_json(index, service_dict)
            for index, service_dict in enumerate(ad.pop("services", []))
        ]
        self.credentials = ad.pop("credentials", None)
        self.nft = ad.pop("nft", None)
        self.datatokens = ad.pop("datatokens", None)
        self.event = ad.pop("event", None)
        self.stats = ad.pop("stats", None)

    def get_service_by_index(self, index: int) -> Service:
        """Return the first Service with the given index"""
        return next((service for service in self.services if service.index == index))

    def get_service_by_id(self, service_id: str) -> Service:
        """Return the Service with the matching id"""
        try:
            return next(
                (service for service in self.services if service.id == service_id)
            )
        except StopIteration:
            return None

    @property
    def requires_address_credential(self) -> bool:
        """Checks if an address credential is required on this asset."""
        manager = AddressCredential(self)
        return manager.requires_credential()

    @property
    def allowed_addresses(self) -> list:
        """Lists addresses that are explicitly allowed in credentials."""
        manager = AddressCredential(self)
        return manager.get_addresses_of_class("allow")

    @property
    def denied_addresses(self) -> list:
        """Lists addresesses that are explicitly denied in credentials."""
        manager = AddressCredential(self)
        return manager.get_addresses_of_class("deny")

    @property
    def is_disabled(self) -> bool:
        return not self.metadata or (self.nft and self.nft["state"] not in [0, 5])

    def is_consumable(
        self,
        credential: Optional[dict] = None,
        with_connectivity_check: bool = True,
        provider_uri: Optional[str] = None,
    ) -> ConsumableCodes:
        """Checks whether an asset is consumable and returns a ConsumableCode."""
        if self.is_disabled:
            return ConsumableCodes.ASSET_DISABLED

        manager = AddressCredential(self)

        if manager.requires_credential():
            return manager.validate_access(credential)

        return ConsumableCodes.OK

def get_asset_from_metadatastore(metadata_url, document_id) -> Optional[Asset]:
    """
    :return: `Asset` instance or None
    """
    url = f"{metadata_url}/api/aquarius/assets/ddo/{document_id}"
    response = requests.get(url)

    return Asset(response.json()) if response.status_code == 200 else None

def check_asset_consumable(asset, consumer_address, logger, custom_url=None):
    if not asset.nft or "address" not in asset.nft or not asset.chain_id:
        return False, "Asset malformed or disabled."

    web3 = get_web3(asset.chain_id)
    nft_contract = get_data_nft_contract(web3, asset.nft["address"])

    if nft_contract.functions.getMetaData().call()[2] not in [0, 5]:
        return False, "Asset is not consumable."

    code = asset.is_consumable({"type": "address", "value": consumer_address})

    if code == ConsumableCodes.OK:  # is consumable
        return True, ""

    message = f"Error: Access to asset {asset.did} was denied with code: {code}."
    logger.error(message, exc_info=1)

    return False, message


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep  7 17:53:40 2023

@author: mingjunsun

This code is an example of solving LASSO-like optimization problems.
"""

import cvxpy as cp
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import os

from sklearn import linear_model
#from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score
from sklearn.linear_model import LassoCV, RidgeCV, ElasticNetCV

#SET WORKING DIRECTORY
os.chdir('/Users/mingjunsun/Library/CloudStorage/Dropbox/23 Summer/Data/')
data = pd.read_csv("Characteristics/usa.csv")

#define start date and end date of training set
train_start = 19900000
train_end = 20000000

#define start date and end date of test set
test_start = 20000000
test_end = 20220000

#exclude data that's not during the period
data = data[(data["date"] > train_start) & (data["date"] < test_end)]

#exclude observations with missing market equity in month t and missing return in month t+1
data = data.dropna(subset=['me', 'ret_exc_lead1m'])

#exclude nano caps
data = data.loc[data['size_grp'] != 'nano']

#delete observation with more than 5 out of the 21 characteristics missing
cols = ["be_me", "ret_12_1", "market_equity", "ret_1_0", "rvol_252d", "beta_252d", "qmj_safety", "rmax1_21d", "chcsho_12m",
        "ni_me", "eq_dur", "ret_60_12", "ope_be", "gp_at", "ebit_sale", "at_gr1", "sale_gr1", "at_be","cash_at", "age", "z_score"]

data["missing_num"] = data[cols].isna().sum(1)
data = data.loc[data['missing_num'] <= 5]

#impute the missing characteristics by replacing them with the cross-sectional median
for i in cols:
    data[i] = data[i].astype(float)
    data[i] = data[i].fillna(data.groupby('date')[i].transform('median'))

cols1 = ["permno","date","ret_exc_lead1m", "be_me", "ret_12_1", "market_equity", "ret_1_0", "rvol_252d", "beta_252d",
"qmj_safety", "rmax1_21d", "chcsho_12m","ni_me", "eq_dur", "ret_60_12", "ope_be", "gp_at", "ebit_sale", "at_gr1", "sale_gr1",
"at_be","cash_at", "age", "z_score"]

data1 = data[cols1]
data1 = data1.dropna()

#rank transformation
#each characteristics is transformed into the cross-sectional rank
for i in cols:
    data1[i] = data1.groupby("date")[i].rank(pct=True)

#use df, store data1
df = data1
df.sort_values(by=['date', 'permno'], inplace=True)

# lists of months
train_month_list = df.date.unique()

df_test = df[(df["date"] > test_start) & (df["date"] < test_end)]
obj_month_list = df_test.date.unique()

#optimization part
def regularizer(beta):
    return cp.norm1(beta)

def loss_fn(X, Y, beta, intercept):
    return (1.0 / X.shape[0]) *(cp.norm2(X @ beta + intercept - Y)**2)

#objective function 1 - L1 penalty on the coefficient
def objective_fn_initial(X, Y, beta, intercept, lambda1):
    return loss_fn(X, Y, beta, intercept) + lambda1 * cp.norm1(beta)

#coefficients, intercepts and objective values
beta_list = np.zeros((len(cols), 3))
intercept_list = np.zeros(3)
objective_list = np.zeros(3)

#set your own penalty parameters
lambda1_value = 0.0005

index = list(train_month_list).index(obj_month_list[0])
data_train = df[(df["date"] < train_month_list[index]) & (df["date"] >=train_month_list[index-5])]
X_train = data_train[cols].to_numpy()
Y_train = data_train["ret_exc_lead1m"].to_numpy()

#sklearn
model_lasso = linear_model.Lasso(alpha=lambda1_value/2)
model_lasso.fit(X_train, Y_train)
beta_list[:,0] = model_lasso.coef_
intercept_list[0] = model_lasso.intercept_
objective_list[0] = np.linalg.norm(model_lasso.coef_, ord=1)

#cvx with objective function 1
beta = cp.Variable(len(cols))
intercept = cp.Variable(1)
problem = cp.Problem(cp.Minimize(objective_fn_initial(X_train, Y_train, beta, intercept, lambda1_value)))
problem.solve(solver = cp.SCS)
#beta_list[:,2] = beta.value
#Choose your own threshold here. I chose 0.0001.
beta_list[:,1] = np.where(abs(beta.value) < 0.0001, 0, beta.value)
intercept_list[1] = intercept.value
objective_list[1] = problem.value
objective_list[1] = np.linalg.norm(beta.value, ord=1)

#The estimates in each column should be very close. Because there are the same model when lambda2_value = 0
#Feel free to try different penalty parameters and write your own optimization problems.


"""
The RAD record format defines what a flat record should look like. It's
an unifying format that is used through out the application.

This record is passed around the different components of the application
to keep a consistent data format. Also it is a good model for other people
in the team looking for data. It gives our data collection some backbone.

For example a scraper is ran, it returns a list of "RadRecord"s, some
middleware takes these records and calls a function that accepts "RadRecord"s
and creates and saves database records from them. That way the scraper doesn't
know about the database and the database models aren't structured around the
scrapers.

Use the rad_record function to create new records. It allows you to create
objects without specifying all of the fields.

>>> r = rad_record('Some Hospital')
>>> r.city is None # True
>>> r2 = rad_record('Other Hospital', city='Chicago', state='Illinois')
>>> r2.city is None # False

The rad_record function will return an instance of RadRecord.

>>> r3 = rad_record('Vida Sida')
>>> r3.is_valid() # True
>>> r4 = rad_record(None)
>>> r4.is_valid() # False

To be valid, all records must have a name. In addition, if a
date_verified value is provided, it must be successfully
parsed into a date using 'YYYY-MM-DD' format.
"""

from datetime import datetime
from collections import namedtuple

"""
A record contains the following fields.
The procedure type and category name are
optional. They are transformed by middleware
into relationships at the database.

The one field that is completely necessary is
`name`. This might be an institutions name, or
a doctor to name some examples.

Underneath the hood a RadRecord is a Python named
tuple, read it's documentation if you aren't familiar
with it. It is a very nice and slick data structure.

"""
RadRecord = namedtuple('RadRecord', [
    'name',
    'organization',
    'description',
    'address',
    'street',
    'city',
    'state',
    'country',
    'zipcode',
    'email',
    'phone',
    'fax',
    'url',
    'source',
    'category_name',
    'category_names',
    'population_names',
    'population_tags',
    'procedure_type',
    'is_icath',
    'is_wpath',
    'wheelchair_accessible',
    'sliding_scale',
    'hospital_affiliation',
    'hours',
    'npi',
    'visible',
    'notes',
    'date_verified'])

def is_valid(record):
    """
    A function to help validate RadRecords.
    A RadRecord's name should not be None, an empty string,
    or consist entirely of whitespace. In addition, if
    date_verified is provided, it must parse into a date
    using the 'YYYY-MM-DD' format.

    Args:
        record: The record to validate.

    Returns:
        A boolean indicating whether the provided record is valid.
    """
    # First validate name
    if record.name is None or \
        len(record.name) == 0 or \
        record.name.isspace():
        return False

    # Validate date_verified if provided
    if record.date_verified is not None and \
        len(record.date_verified) > 0 and \
        not record.date_verified.isspace():
        # Try to parse it out using 'YYYY-MM-DD'
        try:
            datetime.strptime(record.date_verified, '%Y-%m-%d')
        except ValueError:
            # Parsing error, return false
            return False

    # Fall-through case
    return True

def parse_delimited_list(liststr):
    """
    Parses the provided string, which is assumed
    to be a semicolon-delimited list of items,
    into the corresponding unique list of strings.

    Args:
        liststr: The delimited string to parse.

    Returns:
        The resulting unique list of strings.
    """
    # Handle null/empty/whitespace values
    if liststr is None or \
        len(liststr) == 0 or \
        liststr.isspace():
        return list()

    # Split on semicolons, filter out blank entries,
    # turn the transformed list into a set (to ensure
    # duplicates don't go in), and then convert it
    # back to a list.
    return list(set((cat.strip() for cat \
        in liststr.split(';')
        if cat is not None and \
            len(cat) > 0 and \
            not cat.isspace())))

# Store some lowercase sets for true/false strings
true_values = set([u'true', u't', u'yes', u'y', u'1'])
false_values = set([u'false', u'f', u'no', u'n', u'0'])

def convert_boolean(boolVal):
    """
    Coerces the provided value to a Boolean value, falling back to
    None if the value could not be converted.

    Args:
        boolVal: The value to convert.

    Returns:
        True, False, or None depending on the result of the conversion.
    """
    # Handle None types
    if boolVal is None:
        return None

    # Handle Boolean types
    if isinstance(boolVal, bool):
        return boolVal

    # Handle strings
    if isinstance(boolVal, str) or isinstance(boolVal, unicode):
        # Handle empty values
        if len(boolVal) == 0 or boolVal.isspace():
            return None

        # Normalize the string to Unicode, trim it, and lowercase it
        boolVal = unicode(boolVal).strip().lower()

        # Now look for it in our sets, falling back to None if
        # we don't find anything
        if boolVal in true_values:
            return True
        elif boolVal in false_values:
            return False
        else:
            return None

    # Handle integer/float types
    if isinstance(boolVal, int) or isinstance(boolVal, float):
        if boolVal == 1:
            return True
        elif boolVal == 0:
            return False
        else:
            return None

    # Fall-through case
    return None

def convert_category_name(record):
    """
    Converts a RadRecord's category_name field to
    a list of category_names (separated by semicolons)
    and returns the updated RadRecord.

    Will bypass processing if category_names is already
    populated with data.

    Args:
        record: The record to convert.

    Returns:
        An updated version of the RadRecord with category_names
        set appropriately.
    """
    if record is None:
        return record

    # Don't bother if we already have category_names
    if record.category_names is not None and \
        len(record.category_names) > 0:
        return record

    new_category_names = parse_delimited_list(record.category_name)

    # Replace the category_names field in the tuple
    return record._replace(category_names=new_category_names)

def convert_population_names(record):
    """
    Converts a RadRecord's population_names field to
    a list of population_tags (separated by semicolons)
    and returns the updated RadRecord.

    Will bypass processing if population_tags is already
    populated with data.

    Args:
        record: The record to convert.

    Returns:
        An updated version of the RadRecord with population_tags
        set appropriately.
    """
    if record is None:
        return record

    # Don't bother if we already have population_tags
    if record.population_tags is not None and \
        len(record.population_tags) > 0:
        return record

    new_population_tags = parse_delimited_list(record.population_names)

    # Replace the population_tags field in the tuple
    return record._replace(population_tags=new_population_tags)

def normalize_record(record):
    """
    Normalizes all fields on the provided RadRecord.

    Args:
        record: The RadRecord to normalize.

    Returns:
        A normalized verion of the RadRecord.
    """
    if record is None:
        return None

    # Normalize values of "None" on visible - that shouldn't be null.
    if record.visible is None:
        record = record._replace(visible=False)

    # Convert names to delimited strings and normalize
    # all Boolean values.
    return record.convert_category_name(). \
        convert_population_names(). \
        _replace(is_wpath=convert_boolean(record.is_wpath),
            is_icath=convert_boolean(record.is_icath),
            wheelchair_accessible=convert_boolean(record.wheelchair_accessible),
            sliding_scale=convert_boolean(record.sliding_scale),
            visible=convert_boolean(record.visible))

# Give every RadRecord a method to help with validation.
RadRecord.is_valid = is_valid

# Also attach the conversion functions.
RadRecord.convert_category_name = convert_category_name
RadRecord.convert_population_names = convert_population_names
RadRecord.normalize_record = normalize_record

def rad_record(name, organization=None, description=None,
    address=None, street=None, city=None, state=None, zipcode=None, country=None,
    email=None, phone=None, fax=None, url=None,
    source=None, category_name=None, category_names=None,
    population_names=None, population_tags=None, procedure_type=None,
    is_icath=None, is_wpath=None, wheelchair_accessible=None, sliding_scale=None,
    hospital_affiliation=None, hours=None, npi=None, visible=True,
    notes=None, date_verified=None):
    """
    Convenience method to create RadRecords with optional fields.
    Use this instead of the class constructor so you don't have to
    specify all of the fields.
    """
    return RadRecord(name, organization, description,
        address, street, city, state, country, zipcode,
        email, phone, fax, url,
        source, category_name, category_names,
        population_names, population_tags, procedure_type,
        is_icath, is_wpath, wheelchair_accessible, sliding_scale,
        hospital_affiliation, hours, npi, visible, notes, date_verified)


import os
import sys
import torch
import torch.utils.data as data
import numpy as np
from PIL import Image
import glob
import random
from torchvision import transforms
import matplotlib.pyplot as plt
import scipy.misc

class SALICON(data.Dataset):

    def __init__(self, stimuli_train_path, stimuli_val_path, gt_train_path, gt_val_path, augment=None, transform_h=None, transform_l=None, target=None, mode='train'):
        self.gt_train_path = gt_train_path
        self.gt_val_path = gt_val_path
        self.mode = mode
        self.augment = augment
        self.transform_h = transform_h
        self.transform_l = transform_l
        self.target = target

        if (mode == 'train'):
            self.data_list = sorted(glob.glob(stimuli_train_path + '*'))
            self.gt_list = sorted(glob.glob(gt_train_path + '*'))
            print('Total training samples are {}'.format(len(self.data_list)))
        else:
            self.data_list = sorted(glob.glob(stimuli_val_path + '*'))
            self.gt_list = sorted(glob.glob(gt_val_path + '*'))
            print('Total validating samples are {}'.format(len(self.data_list)))

    def __getitem__(self, idx):
        data_stimuli_path = self.data_list[idx]
        data_gt_path = self.gt_list[idx]

        data_stimuli = Image.open(data_stimuli_path)
        data_gt = Image.open(data_gt_path)

        if (self.augment != None):
            data_stimuli, data_gt = self.augment(data_stimuli, data_gt)

        if (self.transform_h != None):
            data_stimuli_h = self.transform_h(data_stimuli)

        if (self.transform_l != None):
            data_stimuli_l = self.transform_l(data_stimuli)

        if (self.target != None):
            data_gt = self.target(data_gt)

        return data_stimuli_h, data_stimuli_l, data_gt

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


import os
import boto3
import time
import copy
import subprocess
import threading
import multiprocessing

MAX_WORKERS    = 1
SRC_ACCESS_KEY = os.environ['SRC_ACCESS_KEY']
SRC_SECRET_KEY = os.environ['SRC_SECRET_KEY']
SRC_REGION     = os.environ['SRC_REGION']
DST_ACCESS_KEY = os.environ['DST_ACCESS_KEY']
DST_SECRET_KEY = os.environ['DST_SECRET_KEY']
DST_REGION     = os.environ['DST_REGION']
DST_REPO_URI   = os.environ['DST_REPO_URI']

class Repository:
    def __init__(self, name, uri, images):
        self.name = name
        self.uri = uri
        self.images = images

def create_dst_tag(repoName, imageTag):
    return '{0}/{1}:{2}'.format(DST_REPO_URI, repoName, imageTag)

def get_catalog(client):
    catalog = {}

    repos = client.describe_repositories()
    for repo in repos['repositories']:
        name = repo['repositoryName']
        uri = repo['repositoryUri']

        images = []
        paginator = client.get_paginator('list_images')
        for output in paginator.paginate(repositoryName=name, filter={'tagStatus': 'TAGGED'}):
            images = images + output['imageIds']

        catalog[name] = Repository(name, uri, images)

    return catalog

def calculate_catalog_diff(src, dst):
    diff = {}

    for name, repo in src.iteritems():
        if not name in dst:
            diff[name] = repo
            continue

        image_diff = copy.deepcopy(repo.images)
        for src_image in repo.images:
            src_tag = src_image['imageTag']
            for dst_image in dst[name].images:
                dst_tag = dst_image['imageTag']

                if src_tag == dst_tag:
                    image_diff.remove(src_image)
                    break

        if len(image_diff) > 0:
            diff[name] = Repository(repo.name, repo.uri, image_diff)

    return diff

def migrate(repos, src, dst):
    for repo in repos:
        print('Migrating {0} images(s) for repo {1}'.format(len(repo.images), repo.name))

        try:
            dst.create_repository(repositoryName=repo.name)
        except:
            pass

        for image in repo.images:
            src_tag = '{0}:{1}'.format(repo.uri, image['imageTag'])
            dst_tag = create_dst_tag(repo.name, image['imageTag'])

            subprocess.call(['docker', 'pull', src_tag])
            subprocess.call(['docker', 'tag', src_tag, dst_tag])
            subprocess.call(['docker', 'push', dst_tag])

def split_work(repos, size):
    return [repos[i::size] for i in xrange(size)]

def main():
    src_client = boto3.client('ecr',
        region_name=SRC_REGION,
        aws_access_key_id=SRC_ACCESS_KEY,
        aws_secret_access_key=SRC_SECRET_KEY)

    dst_client = boto3.client('ecr',
        region_name=DST_REGION,
        aws_access_key_id=DST_ACCESS_KEY,
        aws_secret_access_key=DST_SECRET_KEY)

    print('Fetching source catalog')
    src_catalog = get_catalog(src_client)

    print('Fetching destination catalog')
    dst_catalog = get_catalog(dst_client)

    # Migrate repos will least amount of images first
    print('Calculating difference')
    diff = calculate_catalog_diff(src_catalog, dst_catalog).values()
    diff = sorted(diff, key=lambda r: len(r.images))

    print('Migrating the following repositories:')
    for repo in diff:
        print('{0} ({1} images)'.format(repo.name, len(repo.images)))

    threads = []
    for repos in split_work(diff, min(multiprocessing.cpu_count(), MAX_WORKERS)):
        thread = threading.Thread(target=migrate, args=(repos, src_client, dst_client))
        thread.daemon = True
        threads.append(thread)

    print('Migrating {0} repos between {1} thread(s)'.format(len(diff), len(threads)))
    time.sleep(2)

    for thread in threads:
        thread.start()

    for thread in threads:
        thread.join()

if __name__ == '__main__':
    main()


import copy

dr=[-1,1,0,0]
dc=[0,0,-1,1]

N,M = map(int,input().split())
pan=[]
for _ in range(N):
    pan.append(list(map(int,input().split())))
zero_list=[]
virus_list=[]
visited=[[0]*M for _ in range(N)]
for r in range(N):
    for c in range(M):
        if pan[r][c]==0:
            zero_list.append((r,c))
        if pan[r][c]==2:
            virus_list.append((r,c))
## 이제 제로리스트 세개 뽑기 하고 1로 바꾸고 퍼뜨리면 댐
combi=[]
max_cnt=0
for i in range(len(zero_list)-2):
    for j in range(i+1,len(zero_list)-1):
        for k in range(j+1,len(zero_list)):
            combi1=[]
            combi1.append(zero_list[i])
            combi1.append(zero_list[j])
            combi1.append(zero_list[k])
            combi.append(combi1)
# print("~")
while len(combi)!=0:
    wall = combi.pop()
    tmp_pan=copy.deepcopy(pan)
    for w in range(3):
        a1,b1 = wall[w]
        tmp_pan[a1][b1]=1
    ## 여기서 bfs
    for v in range(len(virus_list)):
        sr,sc = virus_list[v]
        togo=[(sr,sc)]
        while togo !=[]:
            ssr,ssc = togo.pop()
            for a in range(4):
                newr= ssr + dr[a]
                newc = ssc + dc[a]
                if 0<=newr<N and 0<=newc<M and tmp_pan[newr][newc]==0:
                    togo.append((newr,newc))
                    tmp_pan[newr][newc]=2
    cnt=0
    for r in range(N):
        for c in range(M):
            if tmp_pan[r][c]==0:
                cnt+=1
    if max_cnt<cnt:
        max_cnt=cnt
print(max_cnt)

코로나 기간 알고/백준연구소.py


import random as r
import math
import numpy as np
import tkinter as tk
import heapq
import itertools
import random

class Player:
    polygons = []
    n = None

    def __init__(self, n, score=0):
        self.n = n
        self.polygons = []
        self.score = 0

    def add_pol(self, pol):
        self.polygons.append(pol)

class Point:
    x = 0.0
    y = 0.0

    def __init__(self, x, y, player=None):
        self.x = x
        self.y = y
        self.player = player

    def distance(self, p):
        return math.sqrt((self.x-p.x)**2 + (self.y-p.y)**2)

class Event:
    x = 0.0
    p = None
    a = None
    valid = True

    def __init__(self, x, p, a, p0, p1):
        self.x = x
        self.p = p
        self.a = a
        self.p0 = p0
        self.p1 = p1
        self.valid = True

class Arc:
    p = None
    pprev = None
    pnext = None
    e = None
    s0 = None
    s1 = None

    def __init__(self, p, player=None, a=None, b=None):
        self.player = player
        self.p = p
        self.pprev = a
        self.pnext = b
        self.e = None
        self.s0 = None
        self.s1 = None
# Arc(p) définit la parabole associé au point p

class Segment:
    start = None
    end = None
    done = False
    p1 = None
    p2 = None
    score1 = False
    score2 = False

    def __init__(self, p, p1=None, p2=None):
        self.start = p
        self.end = None
        self.done = False
        self.p1 = p1
        self.p2 = p2

    def finish(self, p, edge=False):
        if not edge:
            if self.done:
                return
            self.end = p
            self.done = True
        else:
            self.end = p
            self.done = True

    def point(self, p1, p2):
        self.p1 = p1
        self.p2 = p2

    def hauteur(self, p):
        if self.end.x - self.start.x == 0:
            p_inter = Point(self.start.x, p.y)
        if self.end.y - self.start.y == 0:
            p_inter = Point(p.x, self.start.y)
        elif self.end.x - self.start.x != 0:
            a1 = (self.end.y - self.start.y) / (self.end.x - self.start.x)
            # pente d'une droite perpendiculaire à self
            a2 = -1/a1
            # abscisse du point d'intersection des deux droites
            x0 = (-a1*(self.start.x) + a2*(p.x) - (p.y) + (
                self.start.y))/(a2 - a1)
            y0 = a2*(x0 - p.x) + p.y
            p_inter = Point(x0, y0)

        return p.distance(p_inter)

    def actu_score(self):
        if self.p1 is not None and not self.score1:
            self.p1.player.score += self.hauteur(self.p1)*(
                self.start.distance(self.end))/2
            self.score1 = True
        if self.p2 is not None and not self.score1:
            self.p2.player.score += self.hauteur(self.p2)*(
                self.start.distance(self.end))/2
            self.score2 = True

    def p_edge(self, p):
        # renvoie l'intersection du Segment self avec le bord qui est dépassé par le segment
        if self.start.x - self.end.x != 0:
            a = (self.end.y - self.start.y)/(self.end.x - self.start.x)
            x2 = 500
            y2 = a*(500 - self.start.x) + self.start.y
            if 0 < y2 < 500 and p.x > self.p1.x:
                return Point(x2, y2)

            x2 = 0
            y2 = a*(0 - self.start.x) + self.start.y
            if 0 < y2 < 500 and p.x < self.p1.x:
                return Point(x2, y2)

            y2 = 500
            x2 = (500)/a - self.start.y/a + self.start.x
            if 0 < x2 < 500 and p.y > self.p1.y:
                return Point(x2, y2)

            y2 = 0
            x2 = (-self.start.y)/a + self.start.x
            if 0 < x2 < 500 and p.y < self.p1.y:
                return Point(x2, y2)
        elif p.y > 500:
            return Point(p.x, 500)
        else:
            return Point(p.x, 0)

    def inter_edge(self):
        # regarde si un Segment dépasse un bord, si oui remet son extrémité sur le bord du canvas
        if self.start.x < 0 or self.start.x > 500 or self.start.y < 0 or self.start.y > 500:
            self.start = self.p_edge(self.start)

        if self.end.x < 0 or self.end.x > 500 or self.end.y < 0 or self.end.y > 500:
            self.end = self.p_edge(self.end)

class PriorityQueue:
    def __init__(self):
        self.pq = []
        self.entry_finder = {}
        self.counter = itertools.count()

    def push(self, item):
        # check for duplicate
        if item in self.entry_finder:
            return
        count = next(self.counter)
        # use x-coordinate as a primary key (heapq in python is min-heap)
        entry = [item.x, count, item]
        self.entry_finder[item] = entry
        heapq.heappush(self.pq, entry)

    def remove_entry(self, item):
        entry = self.entry_finder.pop(item)
        entry[-1] = 'Removed'

    def pop(self):
        while self.pq:
            priority, count, item = heapq.heappop(self.pq)
            if item != 'Removed':
                del self.entry_finder[item]
                return item
        raise KeyError('pop from an empty priority queue')

    def top(self):
        while self.pq:
            priority, count, item = heapq.heappop(self.pq)
            if item != 'Removed':
                del self.entry_finder[item]
                self.push(item)
                return item
        raise KeyError('top from an empty priority queue')

    def empty(self):
        return not self.pq


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

# external
import numpy as np
import matplotlib.pyplot as plt
import pandas

# local
from dtk import walk

obinna = pandas.read_csv('../data/obinna-walking.txt', delimiter='\t',
                         index_col="TimeStamp", na_values='0.000000')

# change the degrees to radians
for col in obinna.columns:
    if col.endswith('.Ang'):
        obinna[col] = np.deg2rad(obinna[col])

start = 500
stop = 3000

data = walk.WalkingData(obinna.iloc[start:stop].copy())

angles = ['RKneeFlexion.Ang',
          'LKneeFlexion.Ang']

rates = ['RKneeFlexion.Rate',
         'LKneeFlexion.Rate']

data.time_derivative(angles, rates)

data.grf_landmarks('FP2.ForY', 'FP1.ForY', threshold=28.0)

right_steps = data.split_at('right', num_samples=15)
data.plot_steps('FP2.ForY', 'RKneeFlexion.Ang', 'RKneeFlexion.Rate',
                'RKneeFlexion.Mom', linestyle='-', marker='o')
data.plot_steps('FP2.ForY', 'RKneeFlexion.Ang', 'RKneeFlexion.Rate',
                'RKneeFlexion.Mom', mean=True)

controls = ['RKneeFlexion.Mom',
            'LKneeFlexion.Mom']

sensors = ['RKneeFlexion.Ang',
           'RKneeFlexion.Rate',
           'LKneeFlexion.Ang',
           'LKneeFlexion.Rate']

solver = walk.SimpleControlSolver(right_steps, sensors, controls)

gain_omission_matrix = np.ones((len(controls), len(sensors))).astype(bool)
gain_omission_matrix[0, 2:] = False
gain_omission_matrix[1, :2] = False
#gain_omission_matrix = None

gains, controls, variance, gain_var, control_var, estimated_controls = \
    solver.solve(gain_omission_matrix=gain_omission_matrix)

solver.plot_gains(gains, gain_var)

solver.plot_estimated_vs_measure_controls(estimated_controls, variance)

solver.plot_control_contributions(estimated_controls)

plt.show()


import cv2

print(cv2.__version__)

cam = cv2.VideoCapture(0)

while True:
    output1, frame = cam.read()

    greyFrame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)

    cv2.imshow("CameraWindow", greyFrame)
    cv2.moveWindow("CameraWindow", 500,0)

    if cv2.waitKey(1) & 0xff == ord("q"):
        break

cam.release()


# -*- coding: utf-8 -*-

"""
*******************
tests.conftest
*******************

Utility functions that are used to configure Py.Test context.

"""

import os
import pytest

def pytest_addoption(parser):
    """Define options that the parser looks for in the command-line.

    Pattern to use::

      parser.addoption("--cli-option",
                       action="store",
                       default=None,
                       help="cli-option: help text goes here")

    """
    parser.addoption("--inputs",
                     action="store",
                     default="/home/travis/build/highcharts-for-python/highcharts-core/tests/input_files",
                     help=("inputs: the absolute path to the directory where input"
                           " files can be found"))
    parser.addoption("--downloads",
                     action="store",
                     default="true",
                     help=("downloads: set to 'false' to disable tests of chart export "
                           "via the Highsoft-provided Export Server."))
    parser.addoption("--create-output-directory",
                     action = "store",
                     default = "true",
                     help=("create-output-directory: set to 'false' to error if the output "
                           "directory does not exist, otherwise creates it."))
    parser.addoption("--pyspark",
                     action="store",
                     default="false",
                     help=("pyspark: set to 'false' to disable tests of pyspark-related"
                           " functionality, or 'true' to enable those tests. Defaults to"
                           " 'false'"))

def pytest_runtest_makereport(item, call):
    """Connect current incremental test to its preceding parent."""
    # pylint: disable=W0212
    if "incremental" in item.keywords:
        if call.excinfo is not None:
            parent = item.parent
            parent._previousfailed = item

def pytest_runtest_setup(item):
    """Fail test if preceding incremental test failed."""
    if "incremental" in item.keywords:
        previousfailed = getattr(item.parent, "_previousfailed", None)
        if previousfailed is not None:
            pytest.xfail(
                "previous test failed (%s) for reason: %s" % (previousfailed.name,
                                                              previousfailed))


class Base:

    def __init__(self, *specs, **kwargs):

        for spec in specs:
            try:
                spec_dict = dict(spec)
                self.digest(spec_dict)
            except ValueError:
                print(f'Element cannot be cast into dict, and is being discarded: {type(spec)} {spec}')

        self.digest(kwargs)

    def digest(self, data):
        for field in data:
            setattr(self, field, data[field])

    def __repr__(self):
        return f'{self.__class__.__name__} {list(vars(self).keys())}'

class Recursive(Base):

    def __init__(self, *specs, **kwargs):
        super(Recursive, self).__init__(*specs, **kwargs)

    def digest(self, data):
        for field in data:
            if isinstance(data[field], dict):
                setattr(self, field, Recursive(data[field]))
            else:
                setattr(self, field, data[field])

class RecursiveFiltered(Recursive):

    _exclude      = None
    _include_only = None

    def __init__(self, *specs, **kwargs):

        if '_exclude' in kwargs and not '_include_only' in kwargs:
            self._exclude = self._allow_single_element(kwargs.pop('_exclude'))
        elif '_include_only' in kwargs and not '_exclude' in kwargs:
            self._include_only = self._allow_single_element(kwargs.pop('_include_only'))
        elif '_exclude' in kwargs and '_include_only' in kwargs:
            raise Exception('The parameters _exclude and _include_only may not be used together.')

        super(RecursiveFiltered, self).__init__(*specs, **kwargs)

    def digest(self, data):

        if self._include_only:
            digestible = (k for k, v in data.items() if k in self._include_only)
            print(f' Included only: {self._include_only}')
        elif self._exclude:
            digestible = (k for k, v in data.items() if k not in self._exclude)
            print(f' Excluded: {self._exclude}')
        else:
            digestible = data

        for field in data:
            if isinstance(data[field], dict) and field in digestible:
                setattr(self, field, RecursiveFiltered(data[field]))
            else:
                setattr(self, field, data[field])

    def _allow_single_element(self, data):

        if isinstance(data, str):
            t = [data]
        else:
            t = data

        return t


"""
__author__: Jiaming Shen
__description__: extract entity pair document level co-occurrence features
    Input: 1) the sentence.json
    Output: 1) eidDocPairCounts.txt, 2) eidDocPairPPMI.txt
"""
import sys
import json
import itertools
import math
from collections import defaultdict
import mmap
from tqdm import tqdm

def get_num_lines(file_path):
  fp = open(file_path, "r+")
  buf = mmap.mmap(fp.fileno(), 0)
  lines = 0
  while buf.readline():
    lines += 1
  return lines

if __name__ == "__main__":
  if len(sys.argv) != 2:
    print('Usage: python3 extractEidDocPairFeature.py -data')
    exit(1)
  corpusName = sys.argv[1]

  outfilename= '../../data/' + corpusName + '/intermediate/eidDocPairCount.txt'
  outfilename2 = '../../data/' + corpusName + '/intermediate/eidDocPairPPMI.txt'
  infilename = '../../data/' + corpusName + '/intermediate/sentences.json'

  articeID2eidlist = defaultdict(list)
  eid2freq = defaultdict(int)
  with open(infilename, 'r') as fin:
    for line in tqdm(fin, total=get_num_lines(infilename), desc="Generate document-level cooccurrence features (pass 1)"):
      sentInfo = json.loads(line)
      articleId = sentInfo['articleId']
      eidlist = [em['entityId'] for em in sentInfo['entityMentions']]
      articeID2eidlist[articleId].extend(eidlist)
      for eid in eidlist:
        eid2freq[eid] += 1

  eidPair2count = defaultdict(int)
  eidTotalCount = 0
  eidPairTotalCount = 0
  for articleId in tqdm(articeID2eidlist, desc="Generate document-level coocurrence features (pass 2)"):
    eidlist = articeID2eidlist[articleId]
    eidTotalCount += len(eidlist)
    for pair in itertools.combinations(eidlist,2):
      eidPairTotalCount += 1
      if pair[0] == pair[1]:
        continue
      eidPair2count[frozenset(pair)] += 1

  with open(outfilename, 'w') as fout:
    for ele in eidPair2count:
      count = eidPair2count[ele]
      ele = list(ele)
      fout.write(str(ele[0]) + "\t" + str(ele[1]) + "\t" + str(count) + "\n")

  with open(outfilename2, 'w') as fout:
    for ele in eidPair2count:
      p_x_y =  eidPair2count[ele] / eidPairTotalCount
      ele = list(ele)
      p_x = 1.0 * eid2freq[ele[0]] / eidTotalCount
      p_y = 1.0 * eid2freq[ele[1]] / eidTotalCount
      raw_pmi = math.log(p_x_y / (p_x * p_y) )
      if raw_pmi >= 0:
        ppmi = raw_pmi
      else:
        ppmi = 0.0
      fout.write(str(ele[0]) + "\t" + str(ele[1]) + "\t" + str(ppmi) + "\n")


from python_graphql_client import GraphqlClient
import feedparser
import httpx
import json
import pathlib
import re
import os
import datetime

root = pathlib.Path(__file__).parent.resolve()
client = GraphqlClient(endpoint="https://api.github.com/graphql")

TOKEN = os.environ.get("GH_TOKEN", "")

def replace_chunk(content, marker, chunk, inline=False):
    r = re.compile(
        r"<!\-\- {} starts \-\->.*<!\-\- {} ends \-\->".format(marker, marker),
        re.DOTALL,
    )
    if not inline:
        chunk = "\n{}\n".format(chunk)
    chunk = "{}".format(marker, chunk, marker)
    return r.sub(chunk, content)

def formatGMTime(timestamp):
    GMT_FORMAT = '%a, %d %b %Y %H:%M:%S GMT'
    dateStr = datetime.datetime.strptime(timestamp, GMT_FORMAT) + datetime.timedelta(hours=8)
    return dateStr.date()

def make_query(after_cursor=None):
    return """
query {
  viewer {
    repositories(first: 100, privacy: PUBLIC, after:AFTER) {
      pageInfo {
        hasNextPage
        endCursor
      }
      nodes {
        name
        description
        url
        releases(last:1) {
          totalCount
          nodes {
            name
            publishedAt
            url
          }
        }
      }
    }
  }
}
""".replace(
        "AFTER", '"{}"'.format(after_cursor) if after_cursor else "null"
    )

def fetch_blog_entries():
    entries = feedparser.parse("http://feed.cnblogs.com/blog/u/678190/rss/")["entries"]
    return [
        {
            "title": entry["title"],
            "url": entry["link"].split("#")[0],
            "published": entry["published"].split("T")[0],
        }
        for entry in entries
    ]

if __name__ == "__main__":
    readme = root / "README.md"
    readme_contents = readme.open().read()

    entries = fetch_blog_entries()[:5]
    entries_md = "\n".join(
        ["* {title} - {published}".format(**entry) for entry in entries]
    )
    rewritten = replace_chunk(readme_contents, "blog", entries_md)
    readme.open("w").write(rewritten)


import discogs_client
import config
import pandas as pd

#Connect using auth token
d = discogs_client.Client('discogsAnalytics', user_token=config.discogs_token)
me=d.identity()

collection_data = []

for album in me.collection_folders[1].releases:
    formatlist = album.release.formats[0]
    format_desc = formatlist['descriptions']
    media_type = format_desc[0]

    data = [
    album.release.artists[0].name,
    album.release.title,
    album.release.genres[0],
    media_type,
    album.release.year,
   # album.release.community.have
    ]
    collection_data.append(data)

df = pd.DataFrame(collection_data, columns=['Artists','Title','Genre','Format','Year'])
print(df)


import os
import shutil
from typing import List

def main(source_dir: str, des_dir: str, ext: str):
    files = list_file_with_ext(source_dir, ext)
    for file in files:
        shutil.copy(file, des_dir)

# List all music files with path. Get file type by extension name.
def list_file_with_ext(file_path: str, ext_list: List[int]):
    result = []
    for home, dirs, files in os.walk(file_path):
        for file in files:
            if (os.path.splitext(file)[1] in ext_list):
                file_path = os.path.join(home, file)
                result.append(file_path)

    return result

source_dir = './'
des_dir = './0_new_folder'
ext_list = ['.wav', '.mp3', '.flac', '.ape']
os.makedirs(des_dir)
main(source_dir, des_dir, ext_list)


#your code needs the ability to take different actions
#based on different conditions
price = float(input('enter the price: '))

if price >= 1.00:
    tax = .07
    print(tax)
else:
    tax = 0
    print(tax)
# > greater
# < less
# >= greater than or EQUAL
# <= less than or equal
# == is equal to
# != not equal to


import tweepy

from app.models.twitter import auth
from app.models.twitter import utils

def get_friends(username):
    api = auth.get_api()
    return api.friends(screen_name=username, include_user_entities='false',
                       skip_status='true')

def screen_names_of_friends(username):
    friends = get_friends(username)
    return [user.screen_name for user in friends]

def search(query, count, sinceId=None):
    api = auth.get_api()
    results = []
    print(query)
    for tweet in tweepy.Cursor(api.search, q=query).items(40):
        result = {}
        result['screen_name'] = tweet.user.screen_name
        result['created_at'] = tweet.created_at
        result['text'] = tweet.text
        result['id'] = tweet.id_str
        result['video'] = (tweet.entities.get('urls') or [{}])[0].get('expanded_url')
        results.append(result)
    return results


## Top 5 restaurant types
from pymongo import MongoClient
def get_node(db):
    return list(db.OSMLagny.aggregate([{"$match":{"amenity":{"$exists":1}, "amenity":"restaurant"}},
                   {"$group":{"_id":"$cuisine", "count":{"$sum":1}}},{"$sort":{"count":-1}}, {"$limit":5}]))
def get_db():
    client = MongoClient('localhost:27017')
    db = client.mongData
    return db

if __name__ == "__main__":
    db = get_db()
    pprint.pprint(get_node(db))

Python Scripts Queries/Top 5 Restaurants.py


piada = input()

piadas_boas = 0
piadas_ruins = 0

bom = True
ruim = True
mediano = True

while (piada != 'Fim do Show!'):
    reacao = input()
    piada = input()

    if (reacao == 'BAZINGA!'):
        piadas_boas += 1
    elif (reacao != 'BAZINGA!'):
        piadas_ruins += 1

if ((piadas_boas/(piadas_boas + piadas_ruins)) > 0.6):
    ruim = False
    mediano = False
elif ((piadas_ruins/(piadas_boas + piadas_ruins)) > 0.6):
    bom = False
    mediano = False
else:
    ruim = False
    bom = False

if (bom):
    print('BAZINGA! O senso de humor dele é muito bom, Amy, parece com o meu!')
elif (mediano):
    print('Esse stand up foi bastante mediano, Amy. Parece a carreira do Leonard!')
elif (ruim):
    print ('Amy, acredito que acabei de perder 60 de QI ouvindo essas piadas!')


def main():
  gsn = 9445
  powerGrid = createPowerGrid(gsn)

  maxPower = 0
  coords = []
  for l in range(1,30): # Part1: l = 3
    print(l)
    for r in range(len(powerGrid) - l):
      row = powerGrid[r]
      for c in range(len(row) - l):
        squareSum = 0
        for i in range(l):
          for j in range(l):
            squareSum += powerGrid[r + i][c + j]

        if squareSum > maxPower:
          maxPower = squareSum
          coords = [c + 1, r + 1, l]

  print(coords, maxPower)

def createPowerGrid(gsn):
  powerGrid = []
  for y in range(1,301):
    row = []
    for x in range(1,301):
      rackID = x + 10
      powerLevel = rackID * y
      powerLevel += gsn
      powerLevel = powerLevel * rackID
      powerLevel = str(powerLevel)[-3]
      powerLevel = int(powerLevel) - 5
      row.append(powerLevel)

    powerGrid.append(row)

  return powerGrid

if __name__ == "__main__":
  main()


# MAGIC CODEFORCES PYTHON FAST IO
import atexit
import io
import sys

_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER

@atexit.register
def write():
    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
# END OF MAGIC CODEFORCES PYTHON FAST IO

def solve():
    INF = 10**20

    x,n = map(int,input().split())
    d = list(map(int,input().split()))
    d.sort()
    d.append(INF)

    q = []
    a = b = 0
    ret = 0
    for steps in range(n-1):
        newElement = 0
        for items in range(2):
            if b == len(q) or d[a] < q[b]:
                newElement += d[a]
                a += 1
            else:
                newElement += q[b]
                b += 1
        ret += newElement
        q.append(newElement)
    print(ret)

solve()


#!/bin/python3

import sys

# x1 + v1 * t = x2 + v2 * t
# x1 - x2 = ( v2 - v1 ) * t
# (x1 - x2) / ( v2 - v1 ) = t
def kangaroo(x1, v1, x2, v2):
    if v1 == v2:
        if x1 == x2:
            return 'YES';
        else:
            return 'NO';

    t = (x1 - x2) / ( v2 - v1 )
    if t < 0:
        return 'NO';
    if t == int(t):
            return 'YES'
    return 'NO'

x1, v1, x2, v2 = input().strip().split(' ')
x1, v1, x2, v2 = [int(x1), int(v1), int(x2), int(v2)]
result = kangaroo(x1, v1, x2, v2)
print(result)