"""Tests for Gaussian process models."""
from math import isclose

import numpy as np
import pytest
from mlapp_models.gaussian_process import (
    GaussianProcessClassifier,
    GaussianProcessRegressor,
)
from numpy import testing

from .utils import AbstractTestCase

class TestGaussianProcessRegressor(AbstractTestCase):
    """Test gaussian process regressor."""

    def test_no_noise(self):
        """Test that the model behaves as expected when there is no noise."""
        X = np.array([[0], [1], [2]])
        y = np.array([1, 2, 3])
        model = GaussianProcessRegressor(var_eps=0, var0=1, ell=0.5)
        model.fit(X, y)
        preds_mean, preds_covar = model.predict(X)
        preds_var = np.diag(preds_covar)
        testing.assert_allclose(preds_mean, y)
        testing.assert_allclose(preds_var, np.zeros_like(preds_var), atol=1e-8)

        preds_mean, preds_var = model.predict(np.array([[0.5]]))
        assert 1 < preds_mean[0] < 2
        assert preds_var[0, 0] > 1e-2

        # fitting different y with same x should give error
        X = np.array([[0, 1], [0, 1], [2, 0]])
        y = np.array([1, 2, 3])
        with pytest.raises(np.linalg.LinAlgError) as excinfo:
            model.fit(X, y)
        assert "singular" in excinfo.value.args[0].lower()

    def test_some_noise(self):
        """Test that adding some noise to the model makes it behave as expected."""
        X = np.array([[0], [1], [2]])
        y = np.array([1, 2, 3])
        var_eps = 0.001
        var0 = 1
        model = GaussianProcessRegressor(var_eps=var_eps, var0=var0, ell=0.5)
        model.fit(X, y)
        preds_mean, preds_covar = model.predict(X)
        preds_var = np.diag(preds_covar)
        testing.assert_allclose(preds_mean, y, atol=1e-2)
        testing.assert_allclose(preds_var, np.ones_like(preds_var) * 0.002, atol=1e-2)

        # Stack points
        X = np.array([[0], [0]])
        y = np.array([1, 2])
        model.fit(X, y)
        preds_mean, preds_var = model.predict(np.array([[0]]))
        assert isclose(preds_mean[0], 1.5, abs_tol=1e-2)
        assert 0 < preds_var[0, 0] < 0.002

        # predict some far off point
        preds_mean, preds_var = model.predict(np.array([[9999999]]))
        assert isclose(preds_mean[0], 0)
        assert isclose(preds_var[0, 0], var0, abs_tol=1e-2)

class TestGaussianProcessClassifier(AbstractTestCase):
    """Test for GP classifier."""

    def test_fit(self):
        """Test that the model can fit to some data."""
        model = GaussianProcessClassifier(var0=0.001, ell=4)
        self.assert_classifier_fit_blobs(
            model,
            blob_kwargs={"centers": np.array([[5, 0], [0, -5]])},
            zero_one_labels=False,
            min_accuracy=1,
        )
        model = GaussianProcessClassifier(var0=0.001, ell=0.1)
        self.assert_classifier_fit_moons(model, zero_one_labels=False, min_accuracy=1)
        model = GaussianProcessClassifier(var0=0.001, ell=0.1)
        self.assert_classifier_fit_circles(model, zero_one_labels=False, min_accuracy=1)

    def test_easy_data(self):
        """The model should perform as expected on easy data."""
        model = GaussianProcessClassifier(var0=0.01, ell=0.5)

        n = 10
        X = np.array([[1, 1], [-1, -1]])
        y = np.array([1, -1])
        model.fit(X, y)

        X = np.ones((n, 2)) * np.linspace(-1, 1, n).reshape(-1, 1)
        means = model.predict_mean(X)
        assert list(means) == sorted(means)
        assert (means[: n // 2] < 0).all()
        assert (means[n // 2 :] > 0).all()
        variances = np.diag(model.predict_var(X))
        assert list(variances[: n // 2]) == sorted(variances[: n // 2])
        assert list(variances[n // 2 :]) == sorted(variances[n // 2 :], reverse=True)


import json
from collections import OrderedDict

from djblets.testing.testcases import TestCase
from djblets.webapi.encoders import (JSONEncoderAdapter, WebAPIEncoder,
                                     XMLEncoderAdapter)

class EncoderAdapterTests(TestCase):
    """Tests encoding correctness of WebAPIEncoder adapters"""

    @classmethod
    def setUpClass(cls):
        super(EncoderAdapterTests, cls).setUpClass()

        data = OrderedDict()
        data['string_val'] = 'foobar'
        data['none_val'] = None
        data['dict_val'] = {'foo': 'bar'}
        data['bool_val'] = True
        data['scientific_val'] = 2.75e-15
        data['int_val'] = 42
        data['float_val'] = 3.14159
        data['list_val'] = [10, 'baz']

        cls.data = data

    def test_json_encoder_adapter(self):
        """Testing JSONEncoderAdapter.encode"""
        encoder = WebAPIEncoder()
        adapter = JSONEncoderAdapter(encoder)

        content = adapter.encode(self.data)
        self.assertEqual(content, json.dumps(self.data, sort_keys=True))

    def test_xml_encoder_adapter(self):
        """Testing XMLEncoderAdapter.encode"""
        encoder = WebAPIEncoder()
        adapter = XMLEncoderAdapter(encoder)

        expected = (
            '<?xml version="1.0" encoding="utf-8"?>\n'
            '<rsp>\n'
            ' <string_val>foobar</string_val>\n'
            ' <none_val>\n'
            ' </none_val>\n'
            ' <dict_val>\n'
            '  <foo>bar</foo>\n'
            ' </dict_val>\n'
            ' <bool_val>1</bool_val>\n'
            ' <scientific_val>2.75e-15</scientific_val>\n'
            ' <int_val>42</int_val>\n'
            ' <float_val>3.14159</float_val>\n'
            ' <list_val>\n'
            '  <array>\n'
            '   <item>10</item>\n'
            '   <item>baz</item>\n'
            '  </array>\n'
            ' </list_val>\n'
            '</rsp>'
        )

        content = adapter.encode(self.data)
        self.assertEqual(content, expected)


import time
import torch as th
import torchbox as tb
import torchsar as ts
from torch.nn.parameter import Parameter
from collections import OrderedDict
from dataset import saveimage
import matplotlib.pyplot as plt

class Focuser(th.nn.Module):

    def __init__(self, Na, Nr, mas, convp=[[16, 17, 1]], xa=None, ftshift=True):
        r"""Focuser

        Focuser

        Parameters
        ----------
        Na : {number}
            [description]
        Nr : {number}
            1 or the number of range cells
        mas : {list}
            [description]
        ftshift : {bool}, optional
            [description] (the default is True, which [default_description])
        """

        super(Focuser, self).__init__()

        self.Na = Na
        self.Nr = Nr
        self.mas = mas
        self.ftshift = ftshift
        self.Ma = len(mas)
        self.nconvs = len(convp)

        FD = OrderedDict()
        FD['conv1'] = th.nn.Conv2d(2, convp[0][0], convp[0][1:3], stride=convp[0][3:5], padding=convp[0][5:7], dilation=convp[0][7:9], groups=convp[0][9])
        FD['in1'] = th.nn.InstanceNorm2d(convp[0][0])
        FD['relu1'] = th.nn.LeakyReLU()
        for n in range(1, self.nconvs):
            FD['conv' + str(n + 1)] = th.nn.Conv2d(convp[n - 1][0], convp[n][0], convp[n][1:3], stride=convp[n][3:5],
                                                   padding=convp[n][5:7], dilation=convp[n][7:9], groups=convp[n][9])
            FD['in' + str(n + 1)] = th.nn.InstanceNorm2d(convp[n][0])
            FD['relu' + str(n + 1)] = th.nn.LeakyReLU()
        FD['gapool'] = th.nn.AdaptiveAvgPool2d((1, 1))  # N-1-Na-1

        self.features = th.nn.Sequential(FD)
        self.coefs = th.nn.Sequential(OrderedDict([
            ('fc1', th.nn.Linear(convp[-1][0], 128)),
            ('relu1', th.nn.LeakyReLU()),
            # ('relu1', th.nn.LeakyReLU(0.5)),
            ('drop1', th.nn.Dropout(p=0.5, inplace=True)),
            ('fc2', th.nn.Linear(128, self.Ma)),
            # ('relu2', th.nn.LeakyReLU(0.5)),
        ]))

        if xa is None:
            xa = ts.ppeaxis(Na, norm=True, shift=ftshift, mode='fftfreq')
        xa = xa.reshape(1, Na)

        xas = th.tensor([])
        for ma in mas:
            xas = th.cat((xas, xa ** ma), axis=0)
        self.xa = Parameter(xa, requires_grad=False)  # 1-Na
        self.xas = Parameter(xas, requires_grad=False)  # Ma-Na

    def forward(self, X):
        d = X.dim()

        # Y = th.stack((X.pow(2).sum(-1).sqrt(), th.atan2(X[..., 1], X[..., 0])), dim=1)
        Y = th.stack((X[..., 0], X[..., 1]), dim=1)
        Y = self.features(Y)

        Y = Y.view(Y.size(0), -1)  # N-Na
        ca = self.coefs(Y)  # N-Ma
        pa = th.matmul(ca, self.xas)  # N-Ma x Ma-Na

        sizea = [1] * d
        sizea[0], sizea[-3], sizea[-2], sizea[-1] = pa.size(0), pa.size(1), 1, 2
        epa = th.stack((th.cos(pa), -th.sin(pa)), dim=-1)
        epa = epa.reshape(sizea)

        X = tb.fft(X, n=None, cdim=-1, dim=-3, keepcdim=True, norm=None, shift=self.ftshift)
        X = tb.ematmul(X, epa, cdim=-1)
        X = tb.ifft(X, n=None, cdim=-1, dim=-3, keepcdim=True, norm=None, shift=self.ftshift)

        return X, ca

def weights_init(m):
    if isinstance(m, th.nn.Conv2d):
        th.nn.init.orthogonal_(m.weight.data, th.nn.init.calculate_gain('leaky_relu'))
        m.bias.data.zero_()
        # print(m.weight.data.shape, m.weight.data[0, 0])
    if isinstance(m, th.nn.Linear):
        th.nn.init.orthogonal_(m.weight.data, th.nn.init.calculate_gain('leaky_relu'))
        m.bias.data.zero_()
        # print(m.weight.data.shape, m.weight.data[0, 0])

class PAFnet(th.nn.Module):

    def __init__(self, Na, Nr, Mas=[[2, 3]], Mrs=None, lpaf=[[[32, 11, 1]]], lprf=None, xa=None, ftshift=True, seed=None):
        super(PAFnet, self).__init__()
        self.Na = Na
        self.Nr = Nr
        self.Mas = Mas
        self.ftshift = ftshift
        self.seed = seed
        self.focusers = []

        if self.seed is not None:
            th.manual_seed(seed)

        self.Ma = 0
        for mas, convp in zip(Mas, lpaf):
            focusern = Focuser(Na, Nr, mas, convp, xa, ftshift)
            focusern.apply(weights_init)  # init weight
            self.Ma += len(mas)
            self.focusers.append(focusern)

        self.focusers = th.nn.ModuleList(self.focusers)
        self.Nf = len(self.focusers)

    def forward(self, X, isfft=True):

        cas = th.tensor([], device=X.device)
        for n in range(self.Nf):
            X, ca = self.focusers[n](X)
            cas = th.cat((cas, ca), axis=1)  # N-Ma

        return X, cas

    def visual_features(self, X, idx, device='cpu'):

        if self.Nf != 1:
            raise ValueError("Only support 1 Focuser now!")

        d = X.dim()

        X = th.stack((X[..., 0], X[..., 1]), dim=1)
        for i, j in enumerate(idx):
            for n in range(self.Nf):
                Xi = X[[i]].to(device)
                layers = self.focusers[n].features
                for k in range(len(layers) - 1):
                    Xi = layers[k](Xi)
                C = Xi.shape[1]
                tb.imshow([tb.mapping(Xi[0, c, :, :].detach().cpu().abs()) for c in range(C)], outfile='FeaturesOfFocuser%dOfImage%d.svg' % (n, j))

    def train_epoch(self, X, sizeBatch, loss_ent_func, loss_cts_func, loss_fro_func, loss_type, epoch, optimizer, scheduler, device):
        self.train()

        tstart = time.time()
        numSamples = X.shape[0]

        numBatch = int(numSamples / sizeBatch)
        idx = tb.randperm(0, numSamples, numSamples)
        lossENTv, lossCTSv, lossFROv, lossvtrain = 0., 0., 0., 0.
        # t1, t2, t3 = 0., 0., 0.
        for b in range(numBatch):
            # tstart1 = time.time()
            i = idx[b * sizeBatch:(b + 1) * sizeBatch]
            xi = X[i]
            xi = xi.to(device)

            optimizer.zero_grad()

            fi, casi = self.forward(xi)
            # tend1 = time.time()

            # tstart2 = time.time()
            lossENT = loss_ent_func(fi)
            lossCTS = loss_cts_func(fi)
            lossFRO = loss_fro_func(fi)
            # tend2 = time.time()

            if loss_type == 'Entropy':
                loss = lossENT
            if loss_type == 'Entropy+LogFro':
                loss = lossENT + lossFRO
            if loss_type == 'Contrast':
                loss = lossCTS
            if loss_type == 'Entropy/Contrast':
                loss = lossENT / lossCTS

            loss.backward()

            # tstart3 = time.time()
            lossvtrain += loss.item()
            lossCTSv += lossCTS.item()
            lossENTv += lossENT.item()
            lossFROv += lossFRO.item()
            # tend3 = time.time()

            optimizer.step()

            if scheduler is not None:
                scheduler.step()

            # t1 += tend1 - tstart1
            # t2 += tend2 - tstart2
            # t3 += tend3 - tstart3

        tend = time.time()

        lossvtrain /= numBatch
        lossCTSv /= numBatch
        lossENTv /= numBatch
        lossFROv /= numBatch
        # print(t1, t2, t3)
        print("--->Train epoch: %d, loss: %.4f, entropy: %.4f, l1norm: %.4f, contrast: %.4f, time: %ss" %
              (epoch, lossvtrain, lossENTv, lossFROv, lossCTSv, tend - tstart))
        return lossvtrain

    def valid_epoch(self, X, sizeBatch, loss_ent_func, loss_cts_func, loss_fro_func, loss_type, epoch, device):
        self.eval()

        tstart = time.time()
        numSamples = X.shape[0]

        numBatch = int(numSamples / sizeBatch)
        idx = list(range(numSamples))
        lossENTv, lossCTSv, lossFROv, lossvvalid = 0., 0., 0., 0.
        with th.no_grad():
            for b in range(numBatch):
                i = idx[b * sizeBatch:(b + 1) * sizeBatch]
                xi = X[i]
                xi = xi.to(device)

                fi, casi = self.forward(xi)

                lossENT = loss_ent_func(fi)
                lossCTS = loss_cts_func(fi)
                lossFRO = loss_fro_func(fi)

                if loss_type == 'Entropy':
                    loss = lossENT
                if loss_type == 'Entropy+LogFro':
                    loss = lossENT + lossFRO
                if loss_type == 'Contrast':
                    loss = lossCTS
                if loss_type == 'Entropy/Contrast':
                    loss = lossENT / lossCTS

                lossvvalid += loss.item()
                lossCTSv += lossCTS.item()
                lossENTv += lossENT.item()
                lossFROv += lossFRO.item()

        tend = time.time()

        lossvvalid /= numBatch
        lossCTSv /= numBatch
        lossENTv /= numBatch
        lossFROv /= numBatch

        print("--->Valid epoch: %d, loss: %.4f, entropy: %.4f, l1norm: %.4f, contrast: %.4f, time: %ss" %
              (epoch, lossvvalid, lossENTv, lossFROv, lossCTSv, tend - tstart))

        return lossvvalid

    def test_epoch(self, X, sizeBatch, loss_ent_func, loss_cts_func, loss_fro_func, loss_type, epoch, device):
        self.eval()

        tstart = time.time()
        numSamples = X.shape[0]

        numBatch = int(numSamples / sizeBatch)
        idx = list(range(numSamples))
        lossENTv, lossCTSv, lossFROv, lossvtest = 0., 0., 0., 0.
        with th.no_grad():
            for b in range(numBatch):
                i = idx[b * sizeBatch:(b + 1) * sizeBatch]
                xi = X[i]
                xi = xi.to(device)

                fi, casi = self.forward(xi)

                lossENT = loss_ent_func(fi)
                lossCTS = loss_cts_func(fi)
                lossFRO = loss_fro_func(fi)

                if loss_type == 'Entropy':
                    loss = lossENT
                if loss_type == 'Entropy+LogFro':
                    loss = lossENT + lossFRO
                if loss_type == 'Contrast':
                    loss = lossCTS
                if loss_type == 'Entropy/Contrast':
                    loss = lossENT / lossCTS

                lossvtest += loss.item()
                lossCTSv += lossCTS.item()
                lossENTv += lossENT.item()
                lossFROv += lossFRO.item()

        tend = time.time()

        lossvtest /= numBatch
        lossCTSv /= numBatch
        lossENTv /= numBatch
        lossFROv /= numBatch

        print("--->Test epoch: %d, loss: %.4f, entropy: %.4f, l1norm: %.4f, contrast: %.4f, time: %ss" %
              (epoch, lossvtest, lossENTv, lossFROv, lossCTSv, tend - tstart))

        return lossvtest

    def visual_epoch(self, X, sizeBatch, loss_ent_func, loss_cts_func, device):
        self.eval()

        numSamples = X.shape[0]

        numBatch = int(numSamples / sizeBatch)
        idx = list(range(numSamples))
        Y = th.zeros_like(X)
        with th.no_grad():
            for n in range(self.Nf):
                tstart = time.time()
                for b in range(numBatch):
                    i = idx[b * sizeBatch:(b + 1) * sizeBatch]
                    xi = X[i]
                    xi = xi.to(device)

                    pyi, _ = self.focusers[n](xi)
                    Y[i] = pyi.detach().cpu()

                tend = time.time()
                lossentv = loss_ent_func(Y).item()
                lossctsv = loss_cts_func(Y).item()
                X = Y

                print('Focuser: %d, Entropy: %.4f, Contrast: %.4f, Time: %.2fs' % (n, lossentv, lossctsv, tend - tstart))
                saveimage(X, X, [0, 1, 2], prefixname='visual%d' % n, outfolder='snapshot/')

    def plot(self, xi, cai, cri, xa, idx, prefixname, outfolder, device):

        self.eval()
        with th.no_grad():
            xi, cai, cri = xi.to(device), cai.to(device), cri.to(device)

            fi, casi = self.forward(xi)

        saveimage(xi, fi, idx, prefixname=prefixname, outfolder=outfolder + '/images/')

        pai = ts.polype(c=cai, x=xa)
        ppai = ts.polype(c=casi, x=xa)
        pai = pai.detach().cpu().numpy()
        ppai = ppai.detach().cpu().numpy()

        for i, ii in zip(range(len(idx)), idx):
            plt.figure()
            plt.plot(pai[i], '-b')
            plt.plot(ppai[i], '-r')
            plt.legend(['Real', 'Estimated'])
            plt.grid()
            plt.xlabel('Aperture time (samples)')
            plt.ylabel('Phase (rad)')
            plt.title('Estimated phase error (polynomial degree ' + str(self.Ma) + ')')
            plt.savefig(outfolder + '/images/' + prefixname + '_phase_error_azimuth' + str(ii) + '.png')
            plt.close()

if __name__ == '__main__':

    seed = 2020
    device = 'cuda:0'
    N, Na, Nr = 4, 25, 26

    th.random.manual_seed(seed)
    X = th.randn(N, Na, Nr, 2)

    net = Focuser(Na, Nr, mas=[2, 3], convp=[[16, 11, 1, 1, 1, 0, 0, 1, 1, 1]])
    net = net.to(device)
    X = X.to(device)
    Y, ca = net.forward(X)

    print(Y.shape)
    # print(ca)

    net = PAFnet(Na, Nr, Mas=[[2, 3], [4, 5], [6, 7]], lpaf=[[[8, 11, 1, 1, 1, 0, 0, 1, 1, 1]], [[16, 7, 1, 1, 1, 0, 0, 1, 1, 1]], [[32, 5, 1, 1, 1, 0, 0, 1, 1, 1]]], seed=2020)
    net = net.to(device)

    # print(net)

    Y, cas = net.forward(X)
    print(Y.shape, cas.shape)
    print(Y[0, 0, 0])
    # print(net.cas)


def r1():
    from PIL import Image, ImageFilter
    from pathlib import Path

    current_dir = ''
    filenames = Path(current_dir).glob('*')
    Path('new_dir').mkdir(parents=True, exist_ok=True)

    for file in filenames:
        if file.suffix in ['.jpg', '.png']:
            with Image.open(file) as img:
                img.load()
                new_img = img.filter(ImageFilter.EMBOSS)
                new_img.save(Path("new_dir", file))

def r3():
    import csv
    file = open("l9.csv", 'r')
    l = list(csv.reader(file, delimiter=','))
    summ = 0
    for i in l:
        summ = summ + (int(i[1]) * int(i[2]))
    for i in l:
        i.insert(1, ' - ')
        i.insert(3, ' шт. за ')
        i.insert(5, ' руб. ')
        print(*i)

    print('Итоговая сумма:', summ, 'руб.')

r1()
r3()


##counting a character using dictionary
##convert a dictionary to a string and then print the number of occurences
d=dict()
def count(word):
      for i in word:
            d[i]=word.count(i)

word=input("Enter Word: ")
print("The Word is: ",word)
n=(input("Enter Alphabet whose count you need to find: "))
count(word.lower())
print(d.get(n.lower()))
print("Full dictionary is : \n",d)


import math
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method
from sqlalchemy import func

db = SQLAlchemy()

class FoodTruck(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100))
    facility_type = db.Column(db.String(20))
    address = db.Column(db.String(200))
    food_items = db.Column(db.Text)
    latitude = db.Column(db.Float)
    longitude = db.Column(db.Float)
    schedule = db.Column(db.String(200))

    def __init__(self, name, facility_type, address, food_items, latitude, longitude, schedule):
        self.name = name
        self.facility_type = facility_type
        self.address = address
        self.food_items = food_items
        self.latitude = latitude
        self.longitude = longitude
        self.schedule = schedule

    # from http://stackoverflow.com/a/11884806
    def as_dict(self):
      return {c.name: getattr(self, c.name) for c in self.__table__.columns}

    # calculate distance (in km) between food truck and geolocation
    # adapted from http://www.movable-type.co.uk/scripts/latlong.html
    @hybrid_method
    def distance(self, latitude, longitude):
        earth_radius = 6371
        dlat = math.radians(latitude - self.latitude)
        dlon = math.radians(longitude - self.longitude)
        lat1 = math.radians(self.latitude)
        lat2 = math.radians(latitude)
        haversine = math.sin(dlat/2) * math.sin(dlat/2) + math.sin(dlon/2) * math.sin(dlon/2) * math.cos(lat1) * math.cos(lat2)
        return earth_radius * 2 * math.atan2(math.sqrt(haversine), math.sqrt(1-haversine))

    # converted distance function for use in SQL query
    @distance.expression
    def distance(cls, latitude, longitude):
        earth_radius = 6371
        pi_converter = func.pi() / 180
        dlat = (latitude - cls.latitude) * pi_converter
        dlon = (longitude - cls.longitude) * pi_converter
        lat1 = (cls.latitude) * pi_converter
        lat2 = (latitude) * pi_converter
        haversine = func.sin(dlat/2) * func.sin(dlat/2) + func.sin(dlon/2) * func.sin(dlon/2) * func.cos(lat1) * func.cos(lat2)
        return earth_radius * 2 * func.atan2(func.sqrt(haversine), func.sqrt(1-haversine))


from VEX_Magnetosphere import *
import _pickle as cPickle

def map_plots(start_date,end_date,append=None,slicedir=None,pres='off',v='off',E='off'):
    #print time range plotted
    print(start_date + ' TO ' + end_date)
    #create title string for date range
    title_yr = str(start_date) + ' TO ' + str(end_date)
    dimtick = 0
    #for each projection
    for dim in [['YSC','ZSC'],['XSC','ZSC'],['XSC','YSC']]:
        print(dimtick)

        #grab names of pkl files
        x_pkl_name = start_date[0:10]+'_'+end_date[0:10]+'_Bx_'+dim[0]+'_'+dim[1]+"_"+append
        y_pkl_name = start_date[0:10]+'_'+end_date[0:10]+'_By_'+dim[0]+'_'+dim[1]+"_"+append
        z_pkl_name = start_date[0:10]+'_'+end_date[0:10]+'_Bz_'+dim[0]+'_'+dim[1]+"_"+append
        b_pkl_name = start_date[0:10]+'_'+end_date[0:10]+'_B_'+dim[0]+'_'+dim[1]+"_"+append

        if pres!='off':
            x_pkl_name += '_p'
            y_pkl_name += '_p'
            z_pkl_name += '_p'
            b_pkl_name += '_p'
        if v!='off':
            x_pkl_name += '_v'
            y_pkl_name += '_v'
            z_pkl_name += '_v'
            b_pkl_name += '_v'
        if E!='off':
            x_pkl_name += '_E'
            y_pkl_name += '_E'
            z_pkl_name += '_E'
            b_pkl_name += '_E'

        print(x_pkl_name,y_pkl_name,z_pkl_name)
        #grab full file paths
        x_pkl_name2D = "./VEX_data_files/VSE/VEX_bin_" + x_pkl_name + "_2D.pkl"
        y_pkl_name2D = "./VEX_data_files/VSE/VEX_bin_" + y_pkl_name + "_2D.pkl"
        z_pkl_name2D = "./VEX_data_files/VSE/VEX_bin_" + z_pkl_name + "_2D.pkl"
        b_pkl_name2D = "./VEX_data_files/VSE/VEX_bin_" + b_pkl_name + "_2D.pkl"

        #load pickle files 2D
        xpkl = open(x_pkl_name2D,"rb")
        ypkl = open(y_pkl_name2D,"rb")
        zpkl = open(z_pkl_name2D,"rb")
        bpkl = open(b_pkl_name2D,"rb")
        X = cPickle.load(xpkl)
        Y = cPickle.load(ypkl)
        Z = cPickle.load(zpkl)
        B = cPickle.load(bpkl)

        #set plot directory path
        #plot_dir = r'C:/Users/Elysia/Pictures/VEX Plots/gif/'
        #plot_dir = r'/Users/ellu2839/Pictures/VEX_Plots/'
        plot_dir = "/Volumes/VEX_Data/VEX_Plots/"
        if pres!='off':
            plot_dir += r'Pressure/'
        if v!='off':
            plot_dir += r'Velocity/'
        if E!='off':
            plot_dir += r'Electric/'

        #depending on projection, plot the binned data
        if dimtick == 0:
            bin_3d(X,Y,Z,dim='x',v_toggle='on',save=True,name=plot_dir+x_pkl_name,title=title_yr,bs='on')
        elif dimtick == 1:
            bin_3d(Y,X,Z,dim='y',v_toggle='on',save=True,name=plot_dir+y_pkl_name,title=title_yr,bs='on')
        elif dimtick == 2:
            bin_3d(Z,X,Y,dim='z',v_toggle='on',save=True,name=plot_dir+z_pkl_name,title=title_yr,bs='on')

        #pick projection of slice
        if slicedir=='XSC' and dimtick==0:
            bin_3d(B,Y,Z,dim='x',v_toggle='on',save=True,name=plot_dir+b_pkl_name,title=title_yr,bs='on',magB=True)
        elif slicedir=='YSC' and dimtick==1:
            bin_3d(B,X,Z,dim='y',v_toggle='on',save=True,name=plot_dir+b_pkl_name,title=title_yr,bs='on',magB=True)
        if slicedir=='ZSC' and dimtick==2:
            bin_3d(B,X,Y,dim='z',v_toggle='on',save=True,name=plot_dir+b_pkl_name,title=title_yr,bs='on',magB=True)

        dimtick += 1

    xpkl.close()
    ypkl.close()
    zpkl.close()
    bpkl.close()


#!/usr/bin/env python

import pika
import queue
import random
import time
from Request import *

""" constants """
BROADCAST_EXCHANGE = 'BROADCAST'
REQUEST_MSG = 'REQUEST'
RESPONSE_MSG = 'RESPONSE'
RELEASE_MSG = 'RELEASE'
NETWORK_SIZE_REQ_MSG = 'NETWORK_SIZE_REQ'
NETWORK_SIZE_ACK_MSG = 'NETWORK_SIZE_ACK'

""" global varaibles """
req_list = queue.PriorityQueue()
clock = 0
network_size = 1
nbr_acknowledgement = 1
queue_name = ''

def increment_clock():
	global clock
	clock += 1
	print(f'[increment clock] new clock value: {clock}')

def update_clock(sender_clock):
	global clock
	clock = max(clock, sender_clock)
	print(f'[update clock] new clock value: {clock}')

def send_msg(msg_type, routing_key, is_broadcast = False):
	props = pika.BasicProperties(reply_to=queue_name, timestamp=clock)
	exchange_name = BROADCAST_EXCHANGE if is_broadcast else ''
	routing_name = routing_key if exchange_name == '' else ''
	if msg_type == REQUEST_MSG:
		increment_clock()
		request = Request(queue_name, clock)
		req_list.put_nowait(request)
	channel.basic_publish(exchange=exchange_name, routing_key=routing_name, body=msg_type, properties=props)

def process_request_msg(properties):
	req_list.put_nowait(Request(properties.reply_to, properties.timestamp))
	first_req_in_queue = req_list.get()
	if first_req_in_queue.timestamp == properties.timestamp:
		send_msg(RESPONSE_MSG, properties.reply_to, False)

	req_list.put_nowait(first_req_in_queue)

def process_permission_msg():
	global nbr_acknowledgement
	nbr_acknowledgement += 1
	if nbr_acknowledgement == network_size:
		first_req_in_queue = req_list.get()
		if queue_name == first_req_in_queue.queue_name:
			enter_critical_section(first_req_in_queue)
		else:
			req_list.put(first_req_in_queue)

def simulate_critcal_section():
	print('[critical_Secton]: made it to the critical section')
	time.sleep(random.randint(5,10))

def enter_critical_section(request):
	global nbr_acknowledgement
	nbr_acknowledgement = 0
	simulate_critcal_section()
	send_msg(RELEASE_MSG, queue_name, True)
	process_next_requests_in_queue()

def process_next_requests_in_queue():
	if req_list.empty():
		return
	req = req_list.get()
	if req.queue_name == queue_name and nbr_acknowledgement == network_size:
		enter_critical_section(req)
		return
	if req.queue_name != queue_name:
		send_msg(RESPONSE_MSG, queue_name, False)
	req_list.put(req)

# callback function, called whenever a message is received
def callback(ch, method, properties, body):
	global network_size
	global nbr_acknowledgement
	sender_name = properties.reply_to
	sender_timestamp = properties.timestamp
	msg_type = body.decode('UTF-8')

	update_clock(sender_timestamp)
	increment_clock()
	if sender_name == queue_name:
		return

	print(f'[MSG] msg type: {msg_type}')

	if msg_type == NETWORK_SIZE_REQ_MSG:
		network_size += 1
		send_msg(NETWORK_SIZE_ACK_MSG, sender_name, False)
		print("[NETWORK_SIZE] New client joined the network:", network_size, "clients")
	elif msg_type == NETWORK_SIZE_ACK_MSG:
		network_size += 1
		print("[NETWORK_SIZE] client already in the network:", network_size, "clients")
	elif msg_type == REQUEST_MSG:
		process_request_msg(properties)
	elif msg_type == RESPONSE_MSG:
		process_permission_msg()
	elif msg_type == RELEASE_MSG:
		process_next_requests_in_queue()

	else:
		print(f"[error] msg type is unknown {msg_type}")

if __name__ == '__main__':
	# start connection
	connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
	channel = connection.channel()

	# connect to the broadcast exchange
	channel.exchange_declare(exchange=BROADCAST_EXCHANGE, exchange_type='fanout')
	# The exclusive flag is used so once the client connection is closed, the queue is deleted
	result = channel.queue_declare('', exclusive=True)
	queue_name = result.method.queue

	# Bind the queue with the exchange to get messages from all clients
	channel.queue_bind(exchange=BROADCAST_EXCHANGE, queue=queue_name)
	print("[CLIENT] client name: %r" %queue_name)

	time.sleep(random.randint(5,10))

	# send message to check for other clients in the network
	send_msg(NETWORK_SIZE_REQ_MSG, queue_name, True)
	# send request to enter the critical section
	send_msg(REQUEST_MSG, 'queue_name', True)

	channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True)
	channel.start_consuming()


from will.plugin import WillPlugin
from will.decorators import respond_to, periodic, hear, randomly, route, rendered_template, require_settings
import random

class VocalControlPlugin(WillPlugin):

    @respond_to("(?:(?:no|stop) talking$|don'?t (?:talk|speak))|(?:(?:turn |set )?voice off|turn off voice|(?:set )?voice disabled?|disable voice)")
    def stop_talking(self, message):
        """stop talking|turn off voice|voice off: I know how to stop speaking!"""
        try:
            self.save("use_voice", False)
        except Exception as e:
            self.reply(message, "I wasn't able to turn my voice off!", color="red", notify=True)
            self.reply(message, "/code "+str(e), color="red", notify=True)
            return
        rand_reply = random.choice(["Alright, I won't talk anymore.", "Turned off my voice.", "I won't talk anymore.", "I won't say a thing.", "Voice Disabled."])
        self.reply(message, rand_reply, color="green")

    @respond_to("(?:(?:you (?:can|may) )?(?:talk|speak) (?:again)?|voice (?:enabled?|on)|turn on voice)")
    def start_talking(self, message):
        """you can speak again|turn on voice|voice on: I know how to start speaking!"""
        try:
            self.save("use_voice", True)
        except Exception as e:
            self.reply(message, "I wasn't able to turn my voice on!", color="red", notify=True)
            self.reply(message, "/code "+str(e), color="red", notify=True)
            return
        rand_reply = random.choice(["Okay, I'll talk again.", "Alright, I'll start talking again.", "Voice Enabled.", "Ready to talk!"])
        self.reply(message, rand_reply, color="green")


import re
n=int(input())
for _ in range(n):
    uid=input()
    if len(uid)==10:
        if re.search(r"[0-9]{3,}[a-zA-Z]{2,}", uid):
            if re.search(r'(a-zA-Z)\1', uid):
                print('Invalid1')
            else:
                print('Valid')
        else:
            print("Invalid3")
    else:
        print("Invalid4")

# u="abcdefaabbcd"
# s=re.search(r".*(.)\1.*",u)
# print(s)


"""plotting cfd run results"""
import os

from functions_plotting import cf_plotter, read_cfd_data, read_ref_data, append_kinematics_array

#-------------input plot control----------
cfd_data_list = ['cfd']
# ref_data_lst = ['exp_cl', 'impulse_cl']
ref_data_lst = []
#-----------------------------------------
data_to_plot = ['cfd']
#---------------------------------------
time_to_plot = 'all'
coeffs_show_range = 'all'
# time_to_plot = [0, 1500]
# coeffs_show_range = [-0.5, 3]
#---------------------------------------
cwd = os.getcwd()
image_out_path = cwd
#---------------------------------------
cf_array = []
for cfi in cfd_data_list:
    cfd_datai = os.path.join(cwd, cfi)
    cf_arrayi = read_cfd_data(cfd_datai)

    # cfd_kinematics_datai = os.path.join(cwd, 'kinematics/' + cfi + '.dat')
    # cf_arrayi = append_kinematics_array(cf_arrayi, cfd_kinematics_datai)

    cf_array.append(cf_arrayi)

ref_array = []
for refi in ref_data_lst:
    ref_datai = os.path.join(cwd, refi + '.csv')
    ref_arrayi = read_ref_data(ref_datai)

    ref_array.append(ref_arrayi)

data_array = [cf_array, ref_array]
legends = [cfd_data_list, ref_data_lst]
#---------------------------------------

cf_plotter(data_array, legends, data_to_plot, time_to_plot, coeffs_show_range,
           image_out_path, 'against_t')


# imports
import xbee, time
import micropython
from sys import stdin, stdout
def rx_callback(packet):
    micropython.kbd_intr(-1 )
    if(packet != None):

        stdout.buffer.write(packet["payload"])
    micropython.kbd_intr(3)
        #for i in range(0,3):
        #    print("{}".format(packet["payload"][i]))
        #stdout.buffer.write(data.encode("utf-8"));
        #print("{}".format(packet["payload"]))
# set name
xbee.atcmd("NI","XBee B");
# configure network
network_settings = {"CE": 0, "ID": 0x0, "EE": 0, "NT":0x20}
for command, value in network_settings.items():
	print("SET {}: {}".format(command, value))
	xbee.atcmd(command, value)
xbee.atcmd("AC") # apply changes
time.sleep(1)
# wait for success
print("Connecting to network, please wait...")
while xbee.atcmd("AI") != 0:
    time.sleep(0.1)
print("Connected to Network")
xbee.receive_callback(None)
# print network parameters
operating_network = ["OI", "OP", "CH"]
print("Operating network parameters:")
for cmd in operating_network:
	print("{}: {}".format(cmd, xbee.atcmd(cmd)))
xbee.receive_callback(rx_callback)
# loops
while True:
    time.sleep(0.01)
    #vals = xbee.receive()
    #rx_callback(vals)


#not ortalamasi hesaplama için ilk önce yapılış sıralamasını yapmamız lazım.
#1*notlar girilecek                                                            yapıldı.
#2*notlarin ortalamasi alınacak                                                yapıldı.
#3*notların geçip geçmediğini göreceğiz.                                       yapılmadı.

sayi = input("Virgül ile sayilari giriniz.: ")

print("Girdiginiz Sayilar: {0}".format(sayi))

ortalama=sayi.split(",")                                                                #split(",") komutu ile virgülleri sileriz.
toplam = 0
for n in ortalama:
   toplam = toplam + int(n)                                                             #sayilarin toplamini hesaplar.

print("GIRDIGINIZ SAYILARIN NOT ORTALAMASI:{0:.2f} ".format(toplam / len(ortalama)))    #len(ortalama) ile kaç adet sayi olduğunu hesaplariz.
#format(toplam / len(ortalama)) ile sayilarin toplamini sayi adetine bölerek ortalamayi hesaplariz.


# This code was motivated by:
# https://stackoverflow.com/questions/30227466/combine-several-images-horizontally-with-python
# and discussions on plotnine github to combine image

import io
from PIL import Image
import plotnine as p9
import warnings
import numpy as np

def gg2img(gg):
    """
    Convert plotnine ggplot figure to PIL Image and return it

    Arguments:
    ----------
    gg: plotnine ggplot object

    Returns:
    --------
    PIL.Image coversion of the ggplot object

    Details:
    --------
    Associated with the stackoverflow question here: https://stackoverflow.com/questions/8598673/how-to-save-a-pylab-figure-into-in-memory-file-which-can-be-read-into-pil-image/8598881
    """

    buf = io.BytesIO()
    gg.save(buf, format= "png")
    buf.seek(0)
    img = Image.open(buf)
    return img

def h_concat(img_list, reshape = True):
    """
    Horizontally concat PIL.Image images

    Arguments:
    ----------
    img_list: list of PIL.Image images
    reshape: boolean, if we should reshape images to be the same size

    Returns:
    --------
        single PIL.Image image that has the original images in a horizontal row

    Example:
    -------
    test_list = [my_img, my_img, my_img]

    h_concat(test_list)
    """
    if reshape:
        min_shape = sorted( [(np.sum(i.size), i.size ) for i in img_list])[0][1]
        imgs_comb = np.hstack( [np.asarray( i.resize(min_shape) ) for i in img_list] )
    else:
        imgs_comb = np.hstack(img_list)
    imgs_comb = Image.fromarray( imgs_comb)
    return imgs_comb

def v_concat(img_list, reshape = True):
    """
    Vertically concat PIL.Image images

    Arguments:
    ----------
    img_list: list of PIL.Image images
    reshape: boolean, if we should reshape images to be the same size

    Returns:
    --------
        single PIL.Image image that has the original images in a vertically col

    Example:
    -------
    test_list = [my_img, my_img, my_img]

    v_concat(test_list)
    """
    if reshape:
        min_shape = sorted( [(np.sum(i.size), i.size ) for i in img_list])[0][1]
        imgs_comb = np.vstack( [np.asarray( i.resize(min_shape) ) for i in img_list] )
    else:
        imgs_comb = np.vstack(img_list)
    imgs_comb = Image.fromarray( imgs_comb)
    return imgs_comb

def vh_concat(img_list_2d, reshape = True):
    """
    contact a list "matrix" of PIL.Image images

    Arguments:
    ----------
    img_list_2d: 2d list of PIL.Image images (similar to the structure that
        would make a 2d numpy array)
    reshape: boolean, if we should reshape images to be the same size

    Returns:
    --------
        single PIL.Image image that has the original images in the matrix form

    Example:
    -------
    test_list = [[my_img, my_img, my_img],
                 [my_img, my_img, my_img]]

    vh_concat(test_list)
    """
    nrow = len(img_list_2d)
    ncol = len(img_list_2d[0])

    assert np.all([len(row) == ncol for row in img_list_2d]), \
        "img_list_2d should have matrix structure"

    if reshape:
        global_min_shape = [np.Inf, np.Inf]
        for r_idx in range(nrow):
            inner_list = img_list_2d[r_idx]
            inner_min_shape = sorted( [(np.sum(i.size), i.size ) for i in inner_list])[0][1]
            #ipdb.set_trace()
            global_min_shape[0] = np.min([global_min_shape[0], inner_min_shape[0]])
            global_min_shape[1] = np.min([global_min_shape[1], inner_min_shape[1]])

        global_list = []
        for r_idx in range(nrow):
            inner_list = img_list_2d[r_idx]
            global_list.append(
                np.hstack([np.asarray( i.resize(global_min_shape) )
                           for i in inner_list])
            )

        imgs_comb = Image.fromarray(np.vstack(global_list))

    else:
        global_list = []
        for r_idx in range(nrow):
            inner_list = img_list_2d[r_idx]
            global_list.append(np.hstack(inner_list))

        imgs_comb = Image.fromarray(np.vstack(global_list))

    return imgs_comb

def _check_dimensions(n_grobs, nrow = None, ncol = None):
    """
    Internal function to provide non-Null nrow and ncol numbers
    given a n_number of images and potentially some information about the
    desired nrow/ncols.

    Arguments:
    ----------
    n_grobs: int, number of images to be organized
    nrow: int, number of rows user wants (Default is None)
    ncol: int, number of columns user wants (Default is None)

    Returns:
    --------
        (nrow, ncol) tuple that meets user desires or errors if cannot meet
        users expectation
    """
    if nrow is None and ncol is None:
        nrow = int(np.ceil(np.sqrt(n_grobs)))
        ncol = int(np.ceil(n_grobs/nrow))
    if nrow is None:
        nrow = int(np.ceil(n_grobs/ncol))
    if ncol is None:
        ncol = int(np.ceil(n_grobs/nrow))

    assert n_grobs <= nrow * ncol, \
        "nrow * ncol < the number of grobs, please correct"

    return nrow, ncol

def _match_ids(nrow, ncol):
    """
    Internal fucntion to create the a list of images rows and column ids

    Arguments:
    ----------
    nrow: int, number of rows to have
    ncol: int, number of columns to have

    Returns:
    --------
    tuple with:
        row_id: numpy array (nrow*ncol,) with row indices
        col_id: numpy array (nrow*ncol,) with column indices

    """
    row_id = np.repeat(np.arange(nrow, dtype = int),ncol)
    col_id = np.tile(np.arange(nrow, dtype = int),ncol)

    return row_id, col_id

def arrangegrob(grobs, nrow = None, ncol = None, reshape = True,
                suppressWarnings = True):
    """
    Arranges a list of ggplot objects into a set number of rows and columns

    Arguments:
    ----------
    grobs: list of plotnine ggplot objects
    nrow: int, number of rows user wants (Default is None)
    ncol: int, number of columns user wants (Default is None)
    reshape: boolean, if we should reshape images to be the same size
    suppressWarnings: boolean, if we should suppressWarnings from ggplot
        conversion to image

    Returns:
    --------
    single PIL.Image image that has the original images in the matrix form

    Details:
    --------
    Similar to a basic version of R library gridExtra::arrangeGrob function

    """
    # initial setup -----------

    n_grobs = len(grobs)
    nrow, ncol = _check_dimensions(n_grobs, nrow, ncol)
    row_id, _ = _match_ids(nrow, ncol)

    if n_grobs < nrow * ncol:
        n_diff = nrow * ncol - n_grobs
        grobs = grobs + [p9.ggplot(pd.DataFrame()) + p9.theme_void() for _ in range(n_diff)]

    # converting to images -----------
    if suppressWarnings:
        with warnings.catch_warnings():
            warnings.simplefilter('ignore')
            img_list = [gg2img(gg) for gg in grobs]
    else:
        img_list = [gg2img(gg) for gg in grobs]
    # reshape if necessary ----------

    if reshape:
        min_shape = sorted( [(np.sum(i.size), i.size ) for i in img_list])[0][1]
        img_list = [i.resize(min_shape)  for i in img_list]

    # combining

    global_list = []
    for r_idx in range(nrow):
        inner_img_id = np.ix_(row_id == r_idx)[0]
        inner_img_list = [img_list[good_i] for good_i in inner_img_id]
        global_list.append(np.hstack(inner_img_list))

    single_image = Image.fromarray(np.vstack(global_list))

    return single_image


"""
This module has an simple implementation of DDPG, which is described in
- Continuous control with deep reinforcement learning
  - https://arxiv.org/abs/1509.02971
"""
from copy import deepcopy
from typing import Optional

import numpy as np
import torch
from torch import Tensor
from torch.nn import functional as F

from ..config import Config
from ..envs import ParallelEnv
from ..prelude import Action, Array, State
from ..replay import DQNReplayFeed
from .base import DQNLikeAgent, Netout

class DDPGAgent(DQNLikeAgent):
    SAVED_MEMBERS = "net", "target_net", "actor_opt", "critic_opt", "explorer", "replay"
    SUPPORT_PARALLEL_ENV = True

    def __init__(self, config: Config) -> None:
        super().__init__(config)
        self.net = config.net("ddpg")
        self.target_net = deepcopy(self.net)
        self.actor_opt = config.optimizer(self.net.actor_params(), key="actor")
        self.critic_opt = config.optimizer(self.net.critic_params(), key="critic")
        self.explorer = config.explorer()
        self.eval_explorer = config.explorer(key="eval")
        self.replay = config.replay_buffer()
        self.batch_indices = config.device.indices(config.replay_batch_size)

    def set_mode(self, train: bool = True) -> None:
        self.net.train(mode=train)

    @torch.no_grad()
    def eval_action(self, state: Array, net_outputs: Optional[Netout] = None) -> Action:
        action = self.net.action(state)
        if net_outputs is not None:
            net_outputs["action"] = action
        return self.eval_explorer.add_noise(action).cpu().numpy()

    def action(self, state: State) -> Action:
        if self.train_started:
            with torch.no_grad():
                action = self.net.action(state)
            action = self.explorer.add_noise(action).cpu().numpy()
        else:
            action = self.env._spec.random_action()
        return self.env._spec.clip_action(action)

    def batch_actions(self, states: Array[State], penv: ParallelEnv) -> Array[Action]:
        if self.train_started:
            states = penv.extract(states)
            with torch.no_grad():
                action = self.net.action(states)
            action = self.explorer.add_noise(action).cpu().numpy()
        else:
            action = self.env._spec.random_actions(states.shape[0])
        return self.env._spec.clip_action(action)

    @torch.no_grad()
    def _q_next(self, next_states: Array) -> Tensor:
        actions = self.target_net.action(next_states)
        return self.target_net.q_value(next_states, actions)

    def train(self, replay_feed: DQNReplayFeed) -> None:
        obs = [ob.to_array(self.env.extract) for ob in replay_feed]
        states, actions, next_states, rewards, done = map(np.asarray, zip(*obs))
        q_next = self._q_next(next_states)
        q_next = self._q_next(next_states).squeeze_().mul_(self.tensor(1.0 - done))
        q_target = self.tensor(rewards).add_(q_next.mul_(self.config.discount_factor))
        action, q_current = self.net(states, actions)

        #  Backward critic loss
        critic_loss = F.mse_loss(q_current.squeeze_(), q_target)
        self._backward(critic_loss, self.critic_opt, self.net.critic_params())

        #  Backward policy loss
        policy_loss = -self.net.q_value(states, action).mean()
        self._backward(policy_loss, self.actor_opt, self.net.actor_params())

        #  Update target network
        self.target_net.soft_update(self.net, self.config.soft_update_coef)


from django import template

register = template.Library()

@register.filter
def has_lock(user, obj):
    if getattr(obj, "is_locked", None):
        return obj.is_locked() and obj.locked_by == user
    elif getattr(obj, "related_lock_object", None):
        # things that are not lockable themselves like original texts
        # but who can be edited if a related object is locked e.g. fragment
        return has_lock(user, obj.related_lock_object())

@register.filter
def lock_request(from_user, obj):
    try:
        return (
            obj.get_object_lock()
            .objectlockrequest_set.filter(from_user=from_user)
            .order_by("created")
            .last()
        )
    except AttributeError:
        return None


import unittest
from unittest import mock
from copy import deepcopy
import py.test
from coreapis.groups.adhoc_backend import query_match, format_membership, AdHocGroupBackend
from coreapis.adhocgroups.tests.data import \
    user1, user2, user3, \
    groupid1, group1, \
    groupid2, group2, \
    public_userinfo

GROUP1_VIEW = {
    "id": 'adhoc:' + str(groupid1),
    "displayName": "pre update",
    "description": "some data",
    "type": "voot:ad-hoc",
    "membership": {
        "basic": "member",
    }
}

GROUP2_VIEW = {
    "id": 'adhoc:' + str(groupid2),
    "displayName": "pre update",
    "description": "some data",
    "type": "voot:ad-hoc",
    "public": True,
    "membership": {
        "basic": "admin",
    }
}

GROUPS = {
    groupid1: group1,
    groupid2: group2
}

MEMBERSHIP1 = {
    'groupid': groupid1,
    'userid': user1,
    'status': 'normal',
    'type': 'normal',
}

class TestQueryMatch(unittest.TestCase):
    def test_no_query(self):
        assert query_match(None, {})

    def test_match_displayName(self):
        assert query_match('foo', {'displayName': 'a foo group'})

    def test_match_description(self):
        assert query_match('foo', {'displayName': 'test group', 'description': 'a foo group'})

    def test_no_description(self):
        assert not query_match('foo', {'displayName': 'test group'})

    def test_no_match(self):
        assert not query_match('foo', {'displayName': 'no match', 'description': 'no match'})

class TestFormatMembership(unittest.TestCase):
    def test_owner_admin(self):
        assert format_membership(group1, {'userid': user1, 'type': 'admin'}) == {'basic': 'owner'}

    def test_owner_member(self):
        assert format_membership(group1, {'userid': user1, 'type': 'admin'}) == {'basic': 'owner'}

    def test_member(self):
        assert format_membership(group1, {'userid': user2, 'type': 'member'}) == {'basic': 'member'}

    def test_admin(self):
        assert format_membership(group1, {'userid': user2, 'type': 'admin'}) == {'basic': 'admin'}

class TestAdHocBackendBase(unittest.TestCase):
    @mock.patch('coreapis.middleware.cassandra_client.Client')
    def setUp(self, Client):
        self.session = Client()
        self.backend = AdHocGroupBackend('adhoc', 100, mock.Mock())

class TestAdHocBackend(TestAdHocBackendBase):
    def test_get_member_groups(self):
        self.session.get_group_memberships.return_value = iter([
            {
                'groupid': groupid1,
                'status': 'normal',
                'type': 'member',
                'userid': user3
            },
            {
                'groupid': groupid2,
                'status': 'normal',
                'type': 'admin',
                'userid': user3
            },
        ])
        self.session.get_group.side_effect = GROUPS.get
        res = self.backend.get_member_groups(dict(userid=user3), False)
        assert res == [GROUP1_VIEW, GROUP2_VIEW]

# pylint: disable=protected-access
class TestAdHocBackendGet(TestAdHocBackendBase):
    def test_normal(self):
        self.session.get_group.return_value = group1
        self.session.get_membership_data.return_value = MEMBERSHIP1
        assert self.backend._get(user1, 'fc:adhoc:{}'.format(groupid1)) == (group1, MEMBERSHIP1)

    def test_not_member(self):
        group = deepcopy(group1)
        self.session.get_group.return_value = group
        self.session.get_membership_data.side_effect = KeyError
        with py.test.raises(KeyError):
            self.backend._get(user2, 'fc:adhoc:{}'.format(groupid1))

    def test_not_member_but_owner(self):
        group = deepcopy(group1)
        self.session.get_group.return_value = group
        self.session.get_membership_data.side_effect = KeyError
        assert self.backend._get(user1, 'fc:adhoc:{}'.format(groupid1)) == (group1, None)

    def test_not_member_but_public(self):
        group = deepcopy(group1)
        group['public'] = True
        self.session.get_group.return_value = group
        self.session.get_membership_data.side_effect = KeyError
        assert self.backend._get(user2, 'fc:adhoc:{}'.format(groupid1)) == (group, None)
# pylint: enable=protected-access

class TestAdHocBackendGetMembership(TestAdHocBackendBase):
    def test_normal(self):
        with mock.patch('coreapis.groups.adhoc_backend.AdHocGroupBackend._get') as _get:
            _get.return_value = group1, MEMBERSHIP1
            assert self.backend.get_membership({'userid': user1},
                                               'fc:adhoc:{}'.format(groupid1)) == {'basic': 'owner'}

    def test_not_member(self):
        with mock.patch('coreapis.groups.adhoc_backend.AdHocGroupBackend._get') as _get:
            _get.return_value = group1, None
            with py.test.raises(KeyError):
                self.backend.get_membership({'userid': user1}, 'fc:adhoc:{}'.format(groupid1))

class TestAdHocBackendGetGroup(TestAdHocBackendBase):
    def test_normal(self):
        with mock.patch('coreapis.groups.adhoc_backend.AdHocGroupBackend._get') as _get:
            _get.return_value = group1, None
            res = self.backend.get_group({'userid': user1}, 'fc:adhoc:{}'.format(groupid1))
            expected = deepcopy(GROUP1_VIEW)
            del expected['membership']
            assert res == expected

class TestAdHocBackendGetMembers(TestAdHocBackendBase):
    def test_normal(self):
        members = [{'userid': user1, 'type': 'member', 'status': 'normal'}]
        self.session.get_group_members.return_value = iter(members)
        self.session.get_user_by_id.return_value = public_userinfo
        with mock.patch('coreapis.groups.adhoc_backend.AdHocGroupBackend._get') as _get:
            _get.return_value = group1, MEMBERSHIP1
            res = self.backend.get_members({'userid': user1},
                                           'fc:adhoc:{}'.format(groupid1), False, False)
            assert res == [{'membership': {'basic': 'owner'}, 'name': 'foo'}]

    def test_bad_member(self):
        members = [{'userid': user1, 'type': 'member', 'status': 'normal'}]
        self.session.get_group_members.return_value = iter(members)
        self.session.get_user_by_id.side_effect = KeyError
        with mock.patch('coreapis.groups.adhoc_backend.AdHocGroupBackend._get') as _get:
            _get.return_value = group1, MEMBERSHIP1
            res = self.backend.get_members({'userid': user1},
                                           'fc:adhoc:{}'.format(groupid1), False, False)
            assert res == []

    def test_bad_status(self):
        members = [{'userid': user1, 'type': 'member', 'status': 'hacked'}]
        self.session.get_group_members.return_value = iter(members)
        self.session.get_user_by_id.return_value = public_userinfo
        with mock.patch('coreapis.groups.adhoc_backend.AdHocGroupBackend._get') as _get:
            _get.return_value = group1, MEMBERSHIP1
            res = self.backend.get_members({'userid': user1},
                                           'fc:adhoc:{}'.format(groupid1), False, False)
            assert res == []

    def test_not_member(self):
        members = []
        self.session.get_group_members.return_value = iter(members)
        self.session.get_user_by_id.return_value = public_userinfo
        with mock.patch('coreapis.groups.adhoc_backend.AdHocGroupBackend._get') as _get:
            _get.return_value = group1, None
            with py.test.raises(KeyError):
                self.backend.get_members({'userid': user1},
                                         'fc:adhoc:{}'.format(groupid1), False, False)


from PyQt5 import QtWidgets, QtCore
from pyqtgraph import PlotWidget, plot
import pyqtgraph as pg
import sys  # We need sys so that we can pass argv to QApplication
import os
from random import randint

class MainWindow(QtWidgets.QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        self.graphWidget = pg.PlotWidget()
        self.setCentralWidget(self.graphWidget)

        self.x = list(range(100))  # 100 time points
        self.y = [randint(0,100) for _ in range(100)]  # 100 data points

        # plot data: x, y values
        #color = self.palette().color(QtGui.QPalette.Window)  # Get the default window background,
        #self.graphWidget.setBackground(color)                # and make it the background color for the graph
        self.graphWidget.setBackground('w') # Background color
        self.graphWidget.setTitle("Thermocouple", color="k", size="10pt") # Graph title
        styles = {'color':'k', 'font-size':'17px'} # Labels
        self.graphWidget.setLabel('left', 'Temperature [°C]', **styles)
        self.graphWidget.setLabel('bottom', 'Hour [H]', **styles)
        self.graphWidget.showGrid(x=True, y=True) # Grid
        self.graphWidget.addLegend() # Legend. Name must be provided in .plot() in order for legend to work
        pen = pg.mkPen(color=(255, 0, 0), width=2, style=QtCore.Qt.SolidLine) # Line style
        self.data_line = self.graphWidget.plot(self.x, self.y, name = "Sensor 1", pen=pen)

        self.timer = QtCore.QTimer()
        self.timer.setInterval(100)
        self.timer.timeout.connect(self.update_plot_data)
        self.timer.start()

    def update_plot_data(self):

        self.x = self.x[1:]  # Remove the first y element.
        self.x.append(self.x[-1] + 1)  # Add a new value 1 higher than the last.

        self.y = self.y[1:]  # Remove the first
        self.y.append( randint(0,100))  # Add a new random value.

        self.data_line.setData(self.x, self.y)  # Update the data

def main():
    app = QtWidgets.QApplication(sys.argv)
    main = MainWindow()
    main.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()


"""Represents a feature discovery disclosure message."""

from typing import Mapping

from marshmallow import fields, Schema
from marshmallow.validate import OneOf

from ...agent_message import AgentMessage, AgentMessageSchema
from ..message_types import DISCLOSE

HANDLER_CLASS = (
    "aries_cloudagent.messaging.discovery.handlers.disclose_handler.DiscloseHandler"
)

class Disclose(AgentMessage):
    """Represents a feature discovery disclosure, the response to a query message."""

    class Meta:
        """Disclose metadata."""

        handler_class = HANDLER_CLASS
        message_type = DISCLOSE
        schema_class = "DiscloseSchema"

    def __init__(self, *, protocols: Mapping[str, Mapping] = None, **kwargs):
        """
        Initialize disclose message object.

        Args:
            protocols: A mapping of protocol names to a dictionary of properties
        """
        super(Disclose, self).__init__(**kwargs)
        self.protocols = list(protocols) if protocols else []

class ProtocolDescriptorSchema(Schema):
    """Schema for an entry in the protocols list."""

    pid = fields.Str(required=True)
    roles = fields.List(
        fields.Str(
            description="Role: requester or responder",
            example="requester",
            validate=OneOf(["requester", "responder"]),
        ),
        required=False,
        allow_none=True,
        description="List of roles",
    )

class DiscloseSchema(AgentMessageSchema):
    """Disclose message schema used in serialization/deserialization."""

    class Meta:
        """DiscloseSchema metadata."""

        model_class = Disclose

    protocols = fields.List(
        fields.Nested(ProtocolDescriptorSchema()),
        required=True,
        description="List of protocol descriptors",
    )


# coding: utf-8
import os
import tkinter
import tkinter.filedialog as fd
from tkinter import *
from tkinter import ttk
from tkinter import messagebox as MessageBox
from tkinter.filedialog import askopenfilenames
from tkinterdnd2 import DND_FILES, TkinterDnD
from miagepackage.testing_tabula import check_presence
from miagepackage.testing_tabula import preprocessing
from miagepackage.handw_ext import trating_text

current_dir = os.getcwd()
sep = os.path.sep

TITRE_FENETRE = 'Lecteur de feuilles d\'abscence'
TEXTE_AIDE = 'Cliquez sur \'Déposer un fichier\' pour ajouter un fichier à la liste d\'attente d\'analyse.\nPassez la ' \
             'souris sur un fichier dans la liste d\'attente.\nCliquez sur la croix pour retirer un fichier de la ' \
             'liste d\'attente.\nCliquez sur \'Analiser\' pour Commencer l\'analise des fichiers déposés dans la ' \
             'liste d\'attente.\nCliquez n\'importe ou sur le texte de l\'aide pour la cacher ou la faire apparaitre'
TAILLE_FENETRE = "700x650"
CHEMIN_ICONE_PDF = f'{current_dir}{sep}views{sep}img{sep}icone_pdf.png'
CHEMIN_ICONE_CROIX = f'{current_dir}{sep}views{sep}img{sep}croix_cercle.png'
TYPES_FICHIERS = [('pdf files', '.pdf')]
NB_LIGNES_DEPOS = 3
APP_ICON = f'{current_dir}{sep}views{sep}img{sep}logo.png'

fenetre = TkinterDnD.Tk()
lst_fichiers = []
icone_pdf = tkinter.PhotoImage(file=CHEMIN_ICONE_PDF).subsample(7, 7)
# icone random recup sur https://icon-icons.com/fr/
# TODO voir licence ; subsample a addapter si changement d'icone
icone_croix = tkinter.PhotoImage(file=CHEMIN_ICONE_CROIX)  # idem

def analyserFichiers():
    """
    Fonction qui lance l'analyse de chaque fichiers dans la liste d'attente
    """
    if(len(lst_fichiers) == 0):
        MessageBox.showinfo("Aucun fichier", "Veuillez déposer au moins un fichier")
    else:
        for fichier in lst_fichiers:
            nom_du_fichier = nom_fichier(fichier)[:-4]
            preprocessing(fichier, nom_du_fichier)
            file_info = trating_text(nom_du_fichier + '.jpg')
            nom_du_fichier_json = file_info[-1]
            path = file_info[0] + sep + file_info[1] + sep + file_info[2] + sep + file_info[3] + sep + file_info[4] + sep
            check_presence(nom_du_fichier + '.pdf', nom_du_fichier_json, path)

        MessageBox.showinfo("Analyse terminée", "L'analyse des fichiers a été terminée")

def apparaitre_aide(event):
    """
    Faire apparaitre l'aide dans la fenetre
    """
    label_aide = event.widget

    label_aide.winfo_children()[0].pack(side=LEFT)
    label_aide.configure(text="Aide")

def cacher_aide(event):
    """
    Fait disparaitre le texte d'aide de la fenetre
    """
    label_aide = event.widget.master

    event.widget.pack_forget()
    label_aide.configure(text="Cliquez pour faire apparaitre l'aide", height=25)

def sortie_souris_frame(event):
    """
    Suppression de la croix d'une frame quand la souris sort de celle-ci
    """
    event.widget.winfo_children()[1].winfo_children()[0].destroy()

def click_souris_sur_image(event, label_vide):
    """
    Supprimer un fichier de la liste d'attente et retire l'affichage du fichier de l'interface
    """
    frame_depos = event.widget.master.master.master.master
    colonne_depos = event.widget.master.master.master
    frame_fichier = event.widget.master.master

    numero_colonne = 0
    numero_fichier_dans_colonne = 0
    for colonne in frame_depos.winfo_children():
        numero_colonne += 1
        if colonne == colonne_depos:
            for fichier in colonne.winfo_children():
                numero_fichier_dans_colonne += 1
                if fichier == frame_fichier:
                    break
            break
    numero_fichier = numero_colonne * NB_LIGNES_DEPOS - (NB_LIGNES_DEPOS - numero_fichier_dans_colonne)

    # supprimer le fichier dans lst fichier
    lst_fichiers.pop(numero_fichier - 1)
    # supprimer les affichages
    for colonne in frame_depos.winfo_children():
        colonne.destroy()
    # refaire tout les affichages
    cpt = 1
    for chemin in lst_fichiers:
        ajouter_un_label(nom_fichier(chemin), cpt, label_vide, frame_depos)
        cpt += 1

def passage_souris_sur_frame(event,label_vide):
    """
    Indications au passage de la souris sur une image
    """
    # label_depos = Label(event, text="cliquer sur l'icone pour supprimer")
    # ajouter la croix de suppression
    image_label_suppression = ttk.Label(event.widget.winfo_children()[1], image=icone_croix, padding=5)
    image_label_suppression.pack(anchor=NE)

    # ajout des evenements surlabel supression
    image_label_suppression.bind("<Button-1>", lambda eff: click_souris_sur_image(eff, label_vide))

def ajouter_un_label(nom, index_nom, label_vide, frame_depos):
    # TODO si aucun fichier replacer label vide
    """
    Afficher le nom d'un fichier et l'iconne de pdf à l'écran
    -----Variables-----
        nom : str
              nom du fichier à ajouter
        ligne : int
                index du nom dans la liste des fichiers (pas tout fait mais vus que c'est le dernier elem de la liste ça passe)
    """
    # détruire l'indication 'aucun fichier déposé'
    detruire_label_vide(label_vide)

    # créer une frame la précedente est remplie sinon recup la derniere frame de frame depos
    frame = recuperer_frame_de_depos(index_nom,frame_depos)
    frame.pack(expand=True, fill=BOTH, side=LEFT, padx=5, pady=5)

    # jout dans la Frame récupérée
    frame_fichier = Frame(frame)
    label_depos = Label(frame_fichier, text=nom)
    label_depos.pack(side=BOTTOM)
    image_label = ttk.Label(frame_fichier, image=icone_pdf, padding=10)
    image_label.pack(side=BOTTOM)
    image_label.propagate(False)
    frame_fichier.pack()

    # ajout des evenements sur frame_fichier
    #frame_fichier.bind("<Enter>", passage_souris_sur_frame(label_vide))
    frame_fichier.bind("<Enter>", lambda eff: passage_souris_sur_frame(eff, label_vide))
    frame_fichier.bind("<Leave>", sortie_souris_frame)

def detruire_label_vide(label_vide):
    if len(lst_fichiers) != 0:
        label_vide.destroy()

def recuperer_frame_de_depos(index_nom,frame_depos):
    if index_nom % NB_LIGNES_DEPOS == 1 or NB_LIGNES_DEPOS == 1:
        return Frame(frame_depos, border=False)
    else:
        return frame_depos.winfo_children()[-1]  # recupère le dernier enfant

def nom_fichier(chemin):
    """
    Donne le nom d'un fichier a partir de son chemin
    :param chemin: (str) le chemin vers un fichier
    :return: (str) le nom du fichier
    """
    return chemin.split("/")[-1]

def drop(event, label_vide, frame_depos):
    file_paths = event.data.split(" ")
    print(event.data)
    for file_path in file_paths:
        if not file_path.endswith(".pdf"):
            MessageBox.showerror("Erreur", "Un ou plusieurs fichiers ne sont pas au format pdf")
            break
        else:
            lst_fichiers.append(file_path)
            ajouter_un_label(nom_fichier(file_path), len(lst_fichiers), label_vide, frame_depos)

def ajouter_fichier_a_liste_attente(canva_depos, label_vide, frame_depos):
    """
    Ouvre une fenetre de recherche de fichier pdf
    Ajoute un fichier à la liste d'attente
    Ajoute l'icone d'un pdf et le chemin du fichier ajouté
    """

    canva_depos.configure(scrollregion=canva_depos.bbox("all"))
    chemins = askopenfilenames(title="Ouvrir une image", filetypes=TYPES_FICHIERS)

    for chemin in chemins:
        if len(chemin) != 0:
            lst_fichiers.append(chemin)
            ajouter_un_label(nom_fichier(chemin), len(lst_fichiers), label_vide, frame_depos)

            # MAJ taille scrolling
            # https://openclassrooms.com/forum/sujet/taille-d-une-frame-tkinter
            canva_depos.update_idletasks()
            # Ligne à ajouter sinon thinker considere qu'on veut màj la taille avant que le dépos ne soit fait
            canva_depos.configure(scrollregion=canva_depos.bbox("all"))


import gi
import requests
import os
import glob
import subprocess
import simpleaudio as sa

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, GdkPixbuf

class Janela_Main(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="Papelinator 1.0")

        self.builder = Gtk.Builder()
        self.builder.add_from_file("menu.glade")

        self.window = self.builder.get_object("janela")
        self.image = self.builder.get_object("imagem")
        self.entry = self.builder.get_object("entrada")
        self.bt_download = self.builder.get_object("bt_dl")
        self.bt_mudar = self.builder.get_object("bt_md")

        self.bt_download.connect("clicked", self.botao_dl)
        self.bt_mudar.connect("clicked", self.botao_muda)

        self.window.connect("destroy", Gtk.main_quit)

        self.window.show_all()

        self.link_invalido = sa.WaveObject.from_wave_file("sadtrombone.wav")
        self.nova_img = sa.WaveObject.from_wave_file("yoda.wav")

    def dados(self):
        url = self.entry.get_text()

        pasta_downloads = os.path.expanduser('~/Downloads')
        local_dl = max(glob.glob(os.path.join(pasta_downloads, '*')), key=os.path.getctime)
        diretorio = os.path.dirname(local_dl)

        output_link = None
        try:
            output_link = requests.get(url)
        except requests.exceptions.InvalidSchema:
            self.trombone_triste()

        nome_img = os.path.basename(url)

        diretorio_imgs = os.path.join(diretorio, nome_img)

        return output_link, diretorio_imgs

    def botao_muda(self, button):
        _, diretorio_imgs = self.dados()
        subprocess.run(['gsettings', 'set', 'org.gnome.desktop.background', 'picture-uri', 'file://' + diretorio_imgs])

        self.yoda_img()

    def botao_dl(self, button):
        output_link, diretorio_imgs = self.dados()

        if output_link is None:
            return

        if output_link.status_code != 200:
            self.trombone_triste()
            return

        with open(diretorio_imgs, 'wb') as file:
            file.write(output_link.content)

        pixbuf = GdkPixbuf.Pixbuf.new_from_file(diretorio_imgs)
        pixbuf = pixbuf.scale_simple(500, 300, GdkPixbuf.InterpType.BILINEAR)
        self.image.set_from_pixbuf(pixbuf)

    def trombone_triste(self):
        play_obj = self.link_invalido.play()
        play_obj.wait_done()

    def yoda_img(self):
        play_obj = self.nova_img.play()
        play_obj.wait_done()

janela = Janela_Main()
Gtk.main()


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

# Scrapy settings for jiujiu project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://docs.scrapy.org/en/latest/topics/settings.html
#     https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://docs.scrapy.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'jiujiu'

SPIDER_MODULES = ['jiujiu.spiders']
NEWSPIDER_MODULE = 'jiujiu.spiders'

GENRE = "Young" # Chuanyue, Young, chongshengxiaoshuo, Lsjs

"""
########### SeleniumConfig START ###########
"""
SELENIUM_TIMEOUT = 25           # selenium浏览器的超时时间，单位秒
EXECUTABLE_PATH = "/usr/local/share/"
HEADLESS = True # 浏览器不提供可视化页面

"""
########### SpidersConfig START ###########
"""
# 随机沉睡秒数范围，如果启用了 DOWNLOAD_DELAY，总DELAY时长为 RANDOM_DELAY + DOWNLOAD_DELAY
RANDOM_DELAY = 0

# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
# DOWNLOAD_DELAY = 3

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

# Configure maximum concurrent requests performed by Scrapy (default: 16)
CONCURRENT_REQUESTS = 16

# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16

# Disable cookies (enabled by default)
#COOKIES_ENABLED = False
REDIRECT_ENABLED = False

# Override the default request headers:
DEFAULT_REQUEST_HEADERS = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language':'en-GB,en;q=0.9,en-US;q=0.8,zh-CN;q=0.7,zh;q=0.6,ja;q=0.5,it;q=0.4,el;q=0.3,tr;q=0.2,zh-TW;q=0.1',
    'Cache-Control':'max-age=0',
    'Connection': 'keep-alive',
    # 'Cookie':r'xxxxxxxxx这里换成你的cookiexxxxxxxx这里换成你的cookiexxxxxxxxx这里换成你的cookiexxxxxxx',
    'Host': 'www.jjxsw.la',
    'Upgrade-Insecure-Requests': 1,
}

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {
    'jiujiu.middlewares.UserAgentDownloaderMiddleware': 50,
    'jiujiu.middlewares.SeleniumDownloaderMiddleware': 100,
    'jiujiu.middlewares.RandomDelayDownloaderMiddleware': 150,
}


class Solution:
    def earliestFullBloom(self, plantTime: List[int], growTime: List[int]) -> int:
        l=[]
        for i in range(len(plantTime)):
            l.append([plantTime[i],growTime[i]])
        l.sort(key=lambda x:x[1],reverse=True)
        # print(l)
        ans=0
        f=0
        for i in range(len(l)):
            f+=l[i][0]
            ans=max(ans,f+l[i][1])

        return ans


#!/usr/bin/python3
#coding: utf-8

import re, sys, subprocess

# python3 WichWithFile.py Archivo_ip.txt

if len(sys.argv) != 2:
    print("\n[!] Uso: python3 " + sys.argv[0] + "Archivo_ip.txt\n")
    sys.exit(1)

def get_ttl(line):

    proc = subprocess.Popen(["/usr/bin/ping -c 1 %s" % line, ""], stdout=subprocess.PIPE, shell=True)
    (out,err) = proc.communicate()

    out = out.split()
    out = out[12].decode('utf-8')

    ttl_value = re.findall(r"\d{1,3}", out)[0]

    return ttl_value

def get_os(ttl):

    ttl = int(ttl)

    if ttl >= 0 and ttl <= 64:
        return "Linux"
    elif ttl >= 65 and ttl <= 128:
        return "Windows"
    else:
        return "Not Found"

if __name__ == '__main__':

    filename = sys.argv[1]

    with open(filename) as f_obj:
        lines = f_obj.readlines()
    for line in lines:

     ttl = get_ttl(line)

     os_name = get_os(ttl)

     print("%s (ttl -> %s): %s" % (line.rstrip(), ttl, os_name))


from django import forms
from django.core.exceptions import ValidationError

from .models import *

class CreateRoom(forms.ModelForm):
    c = []

    try:
        types = RoomType.objects.all()
        for t in types:
            c.append((t.pk, t.type_name))
    except:
        pass
    type = forms.ChoiceField(choices=c, widget=forms.Select(attrs = {'class': 'creating_inputs', 'id': 'select_inp'}))
    class Meta:
        model = Rooms
        fields = ['room_name', 'type']
        widgets = {
            'room_name': forms.TextInput(attrs = {'class': 'creating_inputs'}),
        }

    def clean_type(self):
        return RoomType.objects.get(pk=int(self.cleaned_data['type']))

class Search(forms.Form):
    search_inp = forms.CharField(label='', widget=forms.TextInput(attrs={'style': 'width: 70%'}))


"""Fibonacci number"""
"""
Fibonacci sequence is a sequence of numbers in which each number is the sum of two preceding ones and
the sequence starts from zero and one.
0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89...
      .        .
      .        .
     0+1      3+5
 f(n) = f(n-1) + f(n-2)

"""
def fibonacci(n):
    assert n >=0 and int(n) == n , 'the number must be positive integer only!'
    if n in [0,1]:
        return n
    else:
        return fibonacci(n-1) + fibonacci(n-2)


# This gives the sentence most similar to the inputted sentence. Different from what we are trying to do but this
    # is what gave me the idea for the sentence classification convolutional neural network

import tensorflow as tf
import tensorflow_hub as hub
import numpy as np
import os, sys
from sklearn.metrics.pairwise import cosine_similarity

# get cosine similarity matrix
def cos_sim(input_vectors):
    similarity = cosine_similarity(input_vectors)
    return similarity

# get topN similar sentences
def get_top_similar(sentence, sentence_list, similarity_matrix, topN):
    # find the index of sentence in list
    index = sentence_list.index(sentence)
    # get the corresponding row in similarity matrix
    similarity_row = np.array(similarity_matrix[index, :])
    # get the indices of top similar
    indices = similarity_row.argsort()[-topN:][::-1]
    return [sentence_list[i] for i in indices]

module_url = "https://tfhub.dev/google/universal-sentence-encoder/2" #@param ["https://tfhub.dev/google/universal-sentence-encoder/2", "https://tfhub.dev/google/universal-sentence-encoder-large/3"]

# Import the Universal Sentence Encoder's TF Hub module
embed = hub.Module(module_url)

# Reduce logging output.
tf.logging.set_verbosity(tf.logging.ERROR)

sentences_list = [
    # starting an exercise
    'getting ready',
    'starting with',
    'getting right into it',
    'join me',
    "first we're",
    "start off",
    "push up first",
    "going to start",
    "first exercise",
    "start with",
    "are you ready",
    "you ready here we go",
    "you ready",

    # stopping
    'we are done',
    "we're done",
    "it's over",
    "press pause",

    # duration
    'halfway done',
    'not much left',
    'second',
    "minute",
    "more seconds",
    "seconds left",
    "second break",
    "seconds here",
    "almost done",
    "few more seconds",
    "last round",
    "almost halfway",
    "almost there",

    "Nice work nice work not much left."
]

with tf.Session() as session:
  session.run([tf.global_variables_initializer(), tf.tables_initializer()])
  sentences_embeddings = session.run(embed(sentences_list))

similarity_matrix = cos_sim(np.array(sentences_embeddings))

sentence = "Nice work nice work not much left."
top_similar = get_top_similar(sentence, sentences_list, similarity_matrix, 4)

# printing the list using loop
for x in range(len(top_similar)):
    print(top_similar[x])


import numpy as np

def wrap(x: float, l: float = 1.0) -> float:
    '''
    Map/wrap x into the interval [0.0, l) with 0.0 and l identified.

    Args:
        x: number to map.
        l: length of mod interval.

    Returns:
        The image of x in [0.0, l).
    '''
    return float(np.mod(x, l))

def wrap_0_to_2pi(x: float) -> float:
    '''
    Map/wrap an angle x into the interval [0.0, 2.0*np.pi) with 0.0 and
    2.0*np.pi identified.

    Args:
        x: angle in radians.

    Returns:
        Angle radians in [0.0, 2.0*np.pi).
    '''
    return wrap(x, 2.0*np.pi)

def wrap_mpi_to_pi(x: float) -> float:
    '''
    Map/wrap an angle x into the interval [-np.pi, np.pi) with -np.pi and
    np.pi identified.

    Args:
        x: angle in radians.

    Returns:
        Angle radians in [0.0, 2.0*np.pi).
    '''
    y = wrap(x, 2.0*np.pi)
    if y <= np.pi:
        return y
    return float(y - 2.0*np.pi)  # y > np.pi

def geodesic_difference(a: float, b: float) -> float:
    '''
    Geodesic difference on the circle between angles in radians.

    Args:
        a: angle in radians.
        b: angle in radians.

    Returns:
        Geodesic difference in radians.
    '''
    a_wrapped = wrap_0_to_2pi(a)
    b_wrapped = wrap_0_to_2pi(b)

    d = a_wrapped - b_wrapped
    d_magnitude = abs(d)
    d_alternate_magnitude = abs(2.0*np.pi - d_magnitude)

    if d_alternate_magnitude < d_magnitude:
        return float(-np.sign(d)*d_alternate_magnitude)
    return d

def geodesic_distance(a: float, b: float) -> float:
    '''
    Geodesic distance on the circle between angles in radians.

    Args:
        a: angle in radians.
        b: angle in radians.

    Returns:
        Geodesic distance in radians.
    '''
    a_wrapped = wrap_0_to_2pi(a)
    b_wrapped = wrap_0_to_2pi(b)

    d = a_wrapped - b_wrapped
    d_magnitude = abs(d)
    d_alternate_magnitude = abs(2.0*np.pi - d_magnitude)

    return min(d_magnitude, d_alternate_magnitude)


import logging
from flask_restplus import Namespace, Resource
from stellar_base.utils import account_xdr_object

from app.base.base import get_coin_types
from app.utils.code_msg import create_response, CodeMsg
from app.utils.cover_resource import CoverRequestParser
from app.models import Order

order_ns = Namespace("orders", description="order查询接口")

@order_ns.route('/')
class Orders(Resource):
    @order_ns.doc(
        params={
            "stellar_account": "stellar账户",
            "coin_name": "币种类型",
            "order_type": "订单类型:1=充值 2=提现 3=归集",
            "chain_type": "链类型 1=链内 2=链外",
        },
        description=u'订单查询返回订单信息'
    )
    def get(self):
        parser_ = CoverRequestParser()
        parser_.add_argument("stellar_account", type=str, required=True)
        parser_.add_argument("coin_name", type=str, required=False)
        parser_.add_argument("order_type", type=int, required=False)
        parser_.add_argument("chain_type", type=int, required=False)
        params = parser_.parse_args()

        user_address = params.get('stellar_account')
        coin_name = params.get('coin_name')
        order_type = params.get('order_type')
        chain_type = params.get('chain_type')
        try:
            account_xdr_object(user_address)
        except Exception as e:
            return create_response(CodeMsg.CM(1031, '账户地址错误'))
        try:
            coin_types = get_coin_types()
        except Exception as e:
            logging.error('find coin_types error:{}'.format(e))
            return create_response(CodeMsg.CM(1030, '查询失败'))
        if coin_name is not None and coin_name not in coin_types:
            return create_response(CodeMsg.CM(1031, '币种名错误'))
        if order_type is not None and int(order_type) not in (1, 2, 3):
            return create_response(CodeMsg.CM(1031, '订单类型错误'))
        if chain_type is not None and int(chain_type) not in (1, 2):
            return create_response(CodeMsg.CM(1031, '链类型错误'))

        params_dict = dict(stellar_account=user_address,
                           coin_name=coin_name,
                           order_type=order_type,
                           chain_type=chain_type,
                           )
        filter = {}
        for param in params_dict:
            if params_dict[param] is not None:
                filter[param] = params_dict[param]
        # print(filter)
        ret_list = []
        try:
            query_dict = Order.query.filter_by(**filter).all()
            for query in query_dict:
                ret_dict = {}
                ret_dict["user_id"] = query.user_id
                ret_dict["order_from"] = query.order_from
                ret_dict["order_to"] = query.order_to
                ret_dict["amount"] = str(query.amount)
                ret_dict["fee"] = str(query.fee)
                ret_dict["status"] = str(query.status)
                ret_dict["add_time"] = str(query.add_time)
                ret_dict["coin_name"] = query.coin_name

                ret_list.append(ret_dict)
        except Exception as e:
            logging.error('Db query order error:{}'.format(e))
            return create_response(CodeMsg.CM(1030, '查询错误'))

        return create_response(CodeMsg.CM(200, '查询成功'), data=ret_list)


'''
XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP(S) as a transport. With it, a client can call methods with parameters on a remote server (the server is named by a URI) and get back structured data.

'''
#Importamos la libreria del lado del cliente
import xmlrpc.client

#Solicitamos los datos al usuario
a =eval(input(str('Ingrese el primer numero: ')))
b=eval(input(str('Ingrese el segundo numero: ')))

#A ServerProxy instance is an object that manages communication with a remote XML-RPC server.The required first argument is a URI
proxy = xmlrpc.client.ServerProxy("http://localhost:8001/")

#invocamos la funcion "suma_remota" con el alias de "suma" desde el cliente y le pasamos los parametros a y b para mostrar el resultado en pantalla
print("La suma es: " +str(proxy.suma(a,b)))


text ='Python'

for stp in text:
    print("-", stp)

#zadanie 1
#Stwórz listę przedmiotów, które zabierzesz na samotną wyprawę w góry.
#Wyświetl nazwę właśnie spakowanego przedmiotu, po ostatnim przedmiocie pokaż informację: “Great, we are ready!”

adventure = ['lina', 'siekiera', 'wifi']
for a in adventure:
    print(a)
print('Great, we are ready!')

#zadanie 2
#Utwórz listę, która zawiera składniki na ulubione danie. Wyświetl komunikaty co należy pokolei dodać. Poza pętlą umieść pozostałe instrukcje np. “Wrzuć do pierkanika”, “Podawaj schłodzone”.

ingridients = ['pyszne', 'uber', 'pizzeria']
for b in ingridients:
    print(b, 'czekaj na dostawę')

#zadanie 3
#Napisz program, który dla 10 kolejnych liczb naturalnych wyświetli sumę poprzedników. Oczekiwany wynik: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55

suma = 0

for i in range(1, 11):
    suma = suma + i
    print(suma)

#alternatywa

suma = 0
for i in range(1, 11):
    suma += i
    if i == 10:
        print(suma)
    else:
        print(suma, end=",  ")

#zadanie 4
#Napisz program, który wyświetli kolejne wyniki dla silni liczby naturalnej N (N podane przez użytkownika, ale nie większe niż 8).
podaj = int(input("Podaj liczbę do 8: "))
silnia = 1

for s in range(1, podaj + 1):
    silnia = silnia * s
    if s == podaj:
        print(s, '=', silnia)
    else:
        print(s, end=' * ')
print('Silnia z', podaj, 'wynosi', silnia)


# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

import os
import subprocess

from mach.decorators import Command, SubCommand

# IMPORTANT: Please Request review from a DOM peer before
# committing to using UniFFI. There are other ways to consume Rust from
# JavaScript that might fit your use case better.
UDL_FILES = [
    "third_party/rust/tabs/src/tabs.udl",
]

FIXTURE_UDL_FILES = [
    "third_party/rust/uniffi-example-geometry/src/geometry.udl",
    "third_party/rust/uniffi-example-arithmetic/src/arithmetic.udl",
    "third_party/rust/uniffi-example-rondpoint/src/rondpoint.udl",
    "third_party/rust/uniffi-example-sprites/src/sprites.udl",
    "third_party/rust/uniffi-example-todolist/src/todolist.udl",
    "toolkit/components/uniffi-fixture-callbacks/src/callbacks.udl",
    "toolkit/components/uniffi-example-custom-types/src/custom-types.udl",
    "toolkit/components/uniffi-fixture-external-types/src/external-types.udl",
]
CPP_PATH = "toolkit/components/uniffi-js/UniFFIGeneratedScaffolding.cpp"
JS_DIR = "toolkit/components/uniffi-bindgen-gecko-js/components/generated"
FIXTURE_CPP_PATH = "toolkit/components/uniffi-js/UniFFIFixtureScaffolding.cpp"
FIXTURE_JS_DIR = "toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated"

def build_uniffi_bindgen_gecko_js(command_context):
    uniffi_root = crate_root(command_context)
    print("Building uniffi-bindgen-gecko-js")
    cmdline = [
        "cargo",
        "build",
        "--release",
        "--manifest-path",
        os.path.join(command_context.topsrcdir, "Cargo.toml"),
        "--package",
        "uniffi-bindgen-gecko-js",
    ]
    subprocess.check_call(cmdline, cwd=uniffi_root)
    print()
    return os.path.join(
        command_context.topsrcdir, "target", "release", "uniffi-bindgen-gecko-js"
    )

@Command(
    "uniffi",
    category="devenv",
    description="Generate JS bindings using uniffi-bindgen-gecko-js",
)
def uniffi(command_context, *runargs, **lintargs):
    """Run uniffi."""
    command_context._sub_mach(["help", "uniffi"])
    return 1

@SubCommand(
    "uniffi",
    "generate",
    description="Generate/regenerate bindings",
)
def generate_command(command_context):
    binary_path = build_uniffi_bindgen_gecko_js(command_context)
    cmdline = [
        binary_path,
        "--js-dir",
        JS_DIR,
        "--fixture-js-dir",
        FIXTURE_JS_DIR,
        "--cpp-path",
        CPP_PATH,
        "--fixture-cpp-path",
        FIXTURE_CPP_PATH,
    ]
    if UDL_FILES:
        cmdline += ["--udl-files"] + UDL_FILES
    if FIXTURE_UDL_FILES:
        cmdline += ["--fixture-udl-files"] + FIXTURE_UDL_FILES
    subprocess.check_call(cmdline, cwd=command_context.topsrcdir)
    return 0

def crate_root(command_context):
    return os.path.join(
        command_context.topsrcdir, "toolkit", "components", "uniffi-bindgen-gecko-js"
    )


from PySide2.QtWidgets import QApplication
from PySide2.QtWidgets import QDialog, QMessageBox, QVBoxLayout
from PySide2.QtWidgets import QPushButton, QLineEdit

class Dialog(QDialog):
    def __init__(self, parent = None):
        super(Dialog, self).__init__()

        self.text_field = QLineEdit()
        self.alert_button = QPushButton('Alert')
        self.quit_button = QPushButton('Quit')

        layout = QVBoxLayout()
        layout.addWidget(self.text_field)
        layout.addWidget(self.alert_button)
        layout.addWidget(self.quit_button)
        self.setLayout(layout)

        self.alert_button.clicked.connect(self.alert)
        self.quit_button.clicked.connect(quit)

    def alert(self):
        alert = QMessageBox()
        alert.setText(self.text_field.text())
        alert.exec_()

if __name__ == '__main__':
    app = QApplication([])
    dialog = Dialog()
    dialog.show()
    app.exec_()