import os
import joblib
import xarray as xr
import matplotlib.pyplot as plt
import cmocean
import ffmpeg

shapes = ("Gaussian", "Square")
schemes = ("CenteredSecondOrder", "CenteredFourthOrder", "WENO")
Ns = (32, 256)
CFLs = (0.05, 0.30)

def plot_tracer_advection_2d_frame(shape, scheme, N, CFL, n):
    dir = f"stommel_gyre_{shape}_{scheme}_N{N:d}_CFL{CFL:.2f}"
    filename = dir + ".nc"
    ds = xr.open_dataset(filename)
    c = ds.c.isel(time=n).squeeze()

    print(f"{dir} frame {n}/{len(ds.time)}")

    fig, ax = plt.subplots(figsize=(9, 9))
    c.plot.pcolormesh(vmin=-1, vmax=1, cmap=cmocean.cm.balance, extend="both")
    ax.set_title(f"{shape} {scheme} N={N:d} CFL={CFL:.2f}")
    ax.set_xlabel("y")
    ax.set_ylabel("z")
    ax.set_aspect("equal")

    plt.savefig(f"{dir}/{dir}_c_{n:03d}.png")
    plt.close()

for shape in shapes:
    for scheme in schemes:
        for N in Ns:
            for CFL in CFLs:
                dir = f"stommel_gyre_{shape}_{scheme}_N{N:d}_CFL{CFL:.2f}"
                if not os.path.exists(dir):
                    os.mkdir(dir)

                filename = dir + ".nc"
                ds = xr.open_dataset(filename)

                joblib.Parallel(n_jobs=-1)(
                    joblib.delayed(plot_tracer_advection_2d_frame)(shape, scheme, N, CFL, n)
                    for n in range(ds.time.size)
                )

                (
                    ffmpeg
                    .input(f"{dir}/{dir}_c_%03d.png", framerate=30)
                    .output(f"{dir}/{dir}_c.mp4", crf=15, pix_fmt='yuv420p')
                    .overwrite_output()
                    .run()
                )


season = input()
type_group = input()
students_qty = int(input())
nights_qty = int(input())
sport = ""
night_price = 0

#nights price
if season == "Winter" :
    if type_group == "boys" or type_group == "girls" :
        night_price = students_qty * (nights_qty * 9.60)
    elif type_group == "mixed" :
        night_price = students_qty * (nights_qty * 10.00)
elif season == "Spring" :
    if type_group == "boys" or type_group == "girls" :
        night_price = students_qty * (nights_qty * 7.20)
    elif type_group == "mixed" :
        night_price = students_qty * (nights_qty * 9.50)
elif season == "Summer" :
    if type_group == "boys" or type_group == "girls" :
        night_price = students_qty * (nights_qty * 15.00)
    elif type_group == "mixed" :
        night_price =students_qty * (nights_qty * 20.00)

#type of sport
if season == "Winter" :
    if type_group == "girls":
        sport = "Gymnastics"
    elif type_group == "boys":
        sport = "Judo"
    elif type_group == "mixed" :
        sport = "Ski"
elif season == "Spring" :
    if type_group == "girls":
        sport = "Athletics"
    elif type_group == "boys":
        sport = "Tennis"
    elif type_group == "mixed" :
        sport = "Cycling"
elif season == "Summer" :
    if type_group == "girls":
        sport = "Volleyball"
    elif type_group == "boys":
        sport = "Football"
    elif type_group == "mixed" :
        sport = "Swimming"

#Calculation
if students_qty >= 50 :
    night_price -= night_price * 0.50
elif students_qty >= 20 and students_qty < 50:
    night_price -= night_price * 0.15
elif students_qty >= 10 and students_qty < 20 :
    night_price -= night_price * 0.05

#Output
print(f'{sport} {night_price :.2f} lv.')

PB_Python_Feb2023/More Exercise's/Conditional Statements Advanced - More Exercises/07. School Camp.py


import numpy as np
import csv

AA = ['A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y']

f1 = open('E:/Study/Bioinformatics/DeepAVP/train.fasta')
line = f1.readlines()

n_protein = int(len(line) / 2)
print(n_protein)

ASDC = np.zeros((n_protein, 400))

def get_ASDC(seq):
    Mat = np.zeros(400)
    sum = 0
    index = 0
    for i in range(20):
        for j in range(20):
            X = AA[i]
            Y = AA[j]
            cnt_pair = 0
            m = 0
            l = len(seq)
            while m < l:
                n = m + 1
                if seq[m] == X:
                    while n < l and n != m:
                        if seq[n] == Y:
                            cnt_pair = cnt_pair + 1
                        n = n + 1
                m = m + 1
            sum = sum + cnt_pair
            Mat[index] = cnt_pair
            index = index + 1
    for p in range(400):
        Mat[p] = Mat[p] / sum
    return Mat

x = 0
for line_list in line:
    if not line_list.startswith('>'):
        line_new = line_list.strip('/n')
        ASDC[x] = get_ASDC(line_new)
        x = x + 1
print(ASDC)

with open('E:/Study/Bioinformatics/DeepAVP/ASDC/train_ASDC.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    for row in ASDC:
        writer.writerow(row)

f1.close()
csvfile.close()


import io
import json
import random
import threading
import numpy as np
import sys
import os
import tensorflow as tf
from datetime import datetime

from collections import Counter
from collections import namedtuple
#recommened train_shards: 256
tf.flags.DEFINE_integer("train_shards", 1,
                        "Number of shards in training TFRecord files.")
tf.flags.DEFINE_integer("val_shards", 4,
                        "Number of shards in validation TFRecord files.")
tf.flags.DEFINE_integer("test_shards", 8,
                        "Number of shards in testing TFRecord files.")
tf.flags.DEFINE_integer("num_threads", 4,
                        "Number of threads to preprocess the images.")
tf.flags.DEFINE_string("output_dir", "/Users/KYD/Downloads/tfrecord", "Output data directory.")
tf.flags.DEFINE_string("train_image_dir", "/Users/KYD/Downloads/30_collected_train2014",
                       "Training image directory.")

FLAGS = tf.flags.FLAGS

ImageMetadata = namedtuple("ImageMetadata",["image_id", "filename", "captions"])

class Vocabulary(object):
    """Simple vocabulary wrapper."""

    def __init__(self, vocab, unk_id):
        """Initializes the vocabulary.

        Args:
          vocab: A dictionary of word to word_id.
          unk_id: Id of the special 'unknown' word.
        """
        self._vocab = vocab
        self._unk_id = unk_id

    def word_to_id(self, word):
        """Returns the integer id of a word string."""
        if word in self._vocab:
            return self._vocab[word]
        else:
            return self._unk_id

class ImageDecoder(object):
    """Helper class for decoding images in TensorFlow."""

    def __init__(self):
    # Create a single TensorFlow Session for all image decoding calls.
        self._sess = tf.Session()

        # TensorFlow ops for JPEG decoding.
        self._encoded_jpeg = tf.placeholder(dtype=tf.string)
        self._decode_jpeg = tf.image.decode_jpeg(self._encoded_jpeg, channels=3)

    def decode_jpeg(self, encoded_jpeg):
        image = self._sess.run(self._decode_jpeg,
                               feed_dict={self._encoded_jpeg: encoded_jpeg})
        assert len(image.shape) == 3
        assert image.shape[2] == 3
        return image

def _int64_feature(value):
    """Wrapper for inserting an int64 Feature into a SequenceExample proto."""
    return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))

def _bytes_feature(value):
    """Wrapper for inserting a bytes Feature into a SequenceExample proto."""
    if type(value) == str:
        return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value.encode()]))
    else:
        return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

def _int64_feature_list(values):
    """Wrapper for inserting an int64 FeatureList into a SequenceExample proto."""
    return tf.train.FeatureList(feature=[_int64_feature(v) for v in values])

def _bytes_feature_list(values):
    """Wrapper for inserting a bytes FeatureList into a SequenceExample proto."""
    return tf.train.FeatureList(feature=[_bytes_feature(v) for v in values])

def to_sequence_example(image, decoder, vocab):
    """Builds a SequenceExample proto for an image-caption pair.

    Args:
    image: An ImageMetadata object.
    decoder: An ImageDecoder object.
    vocab: A Vocabulary object.

    Returns:
    A SequenceExample proto.
    """
    filename = output_file = os.path.join(FLAGS.train_image_dir, image.filename)
    if tf.gfile.Exists(filename):
        with tf.gfile.FastGFile(filename, "rb") as f:
            encoded_image = f.read()
    else:
        return

    try:
        decoder.decode_jpeg(encoded_image)
    except (tf.errors.InvalidArgumentError, AssertionError):
        print("Skipping file with invalid JPEG data: %s" % image.filename)
        return

    context = tf.train.Features(feature={
      "image/image_id": _int64_feature(image.image_id),
      "image/data": _bytes_feature(encoded_image),
    })

    assert len(image.captions) == 1
    caption = image.captions[0]
    caption_ids = [vocab.word_to_id(word) for word in caption]
    feature_lists = tf.train.FeatureLists(feature_list={
      "image/caption": _bytes_feature_list(caption),
      "image/caption_ids": _int64_feature_list(caption_ids)
    })
    sequence_example = tf.train.SequenceExample(
      context=context, feature_lists=feature_lists)

    return sequence_example

def process_image_files(thread_index, ranges, name, images, decoder, vocab,
                         num_shards):
    """Processes and saves a subset of images as TFRecord files in one thread.

    Args:
    thread_index: Integer thread identifier within [0, len(ranges)].
    ranges: A list of pairs of integers specifying the ranges of the dataset to
      process in parallel.
    name: Unique identifier specifying the dataset.
    images: List of ImageMetadata.
    decoder: An ImageDecoder object.
    vocab: A Vocabulary object.
    num_shards: Integer number of shards for the output files.
    """
    # Each thread produces N shards where N = num_shards / num_threads. For
    # instance, if num_shards = 128, and num_threads = 2, then the first thread
    # would produce shards [0, 64).
    num_threads = len(ranges)
    assert not num_shards % num_threads
    num_shards_per_batch = int(num_shards / num_threads)

    shard_ranges = np.linspace(ranges[thread_index][0], ranges[thread_index][1],
                             num_shards_per_batch + 1).astype(int)
    num_images_in_thread = ranges[thread_index][1] - ranges[thread_index][0]

    counter = 0
    for s in range(num_shards_per_batch):
        # Generate a sharded version of the file name, e.g. 'train-00002-of-00010'
        shard = thread_index * num_shards_per_batch + s
        output_filename = "%s-%.5d-of-%.5d" % (name, shard, num_shards)
        output_file = os.path.join(FLAGS.output_dir, output_filename)
        writer = tf.python_io.TFRecordWriter(output_file)

        shard_counter = 0
        images_in_shard = np.arange(shard_ranges[s], shard_ranges[s + 1], dtype=int)
        for i in images_in_shard:
          image = images[i]

          sequence_example = to_sequence_example(image, decoder, vocab)
          if sequence_example is not None:
            writer.write(sequence_example.SerializeToString())
            shard_counter += 1
            counter += 1

          if not counter % 1000:
            print("%s [thread %d]: Processed %d of %d items in thread batch." %
                  (datetime.now(), thread_index, counter, num_images_in_thread))
            sys.stdout.flush()

        writer.close()
        print("%s [thread %d]: Wrote %d image-caption pairs to %s" %
              (datetime.now(), thread_index, shard_counter, output_file))
        sys.stdout.flush()
        shard_counter = 0
    print("%s [thread %d]: Wrote %d image-caption pairs to %d shards." %
        (datetime.now(), thread_index, counter, num_shards_per_batch))
    sys.stdout.flush()

def process_dataset(name, images, vocab, num_shards):
    """Processes a complete data set and saves it as a TFRecord.

    Args:
    name: Unique identifier specifying the dataset.
    images: List of ImageMetadata.
    vocab: A Vocabulary object.
    num_shards: Integer number of shards for the output files.
    """
    # Break up each image into a separate entity for each caption.
    images = [ImageMetadata(image[0], image[1], [caption])
            for image in images for caption in image[2]]

    # Shuffle the ordering of images. Make the randomization repeatable.
    random.seed(12345)
    random.shuffle(images)

    # Break the images into num_threads batches. Batch i is defined as
    # images[ranges[i][0]:ranges[i][1]].
    num_threads = min(num_shards, FLAGS.num_threads)
    spacing = np.linspace(0, len(images), num_threads + 1).astype(np.int)
    ranges = []
    threads = []
    for i in range(len(spacing) - 1):
        ranges.append([spacing[i], spacing[i + 1]])

    # Create a mechanism for monitoring when all threads are finished.
    coord = tf.train.Coordinator()

    # Create a utility for decoding JPEG images to run sanity checks.
    decoder = ImageDecoder()

    # Launch a thread for each batch.
    print("Launching %d threads for spacings: %s" % (num_threads, ranges))
    for thread_index in range(len(ranges)):
        args = (thread_index, ranges, name, images, decoder, vocab, num_shards)
        t = threading.Thread(target=process_image_files, args=args)
        t.start()
        threads.append(t)

    # Wait for all the threads to terminate.
    coord.join(threads)
    print("%s: Finished processing all %d image-caption pairs in data set '%s'." %
        (datetime.now(), len(images), name))

def main(argv):
    image_metadata = []
    with io.open('/Users/KYD/Dropbox/논문/MSCOCO/captions_train-val2014/annotations/img_metadata_train.json') as f:
        image_metadata = json.loads(f.read())

    word2id = dict()
    with io.open('/Users/KYD/Dropbox/논문/MSCOCO/captions_train-val2014/annotations/word_to_index_dict.json') as f:
        word2id = json.loads(f.read())

    process_dataset('train', image_metadata, Vocabulary(word2id, len(word2id)), FLAGS.train_shards)

if __name__ == "__main__":
  tf.app.run()


from Maix import FPIOA

class fm:
  fpioa = FPIOA()

  def help():
    __class__.fpioa.help()

  def get_pin_by_function(function):
    return __class__.fpioa.get_Pin_num(function)

  def register(pin, function, force=False):
    pin_used = __class__.get_pin_by_function(function)
    if pin_used == pin:
      return
    if None != pin_used:
      info = "[Warning] function is used by %s(pin:%d)" % (
          fm.str_function(function), pin_used)
      if force == False:
        raise Exception(info)
      else:
        print(info)
    __class__.fpioa.set_function(pin, function)

  def unregister(pin):
    __class__.fpioa.set_function(pin, fm.fpioa.RESV0)

  def str_function(function):
    if fm.fpioa.GPIOHS0 <= function and function <= fm.fpioa.GPIO7:
      if fm.fpioa.GPIO0 <= function:
        return 'fm.fpioa.GPIO%d' % (function - fm.fpioa.GPIO0)
      return 'fm.fpioa.GPIOHS%d' % (function - fm.fpioa.GPIOHS0)
    return 'unknown'

  def get_gpio_used():
    return [(__class__.str_function(f), __class__.get_pin_by_function(f)) for f in range(fm.fpioa.GPIOHS0, fm.fpioa.GPIO7 + 1)]

if __name__ == "__main__":
  import time
  print('check register')
  for item in fm.get_gpio_used():
    print(item)
  print('test unregister')
  for pin in range(8, 48):
    fm.unregister(pin)
  print('check register')
  for item in fm.get_gpio_used():
    print(item)
  # gpio test
  from Maix import GPIO

  def gpio_test():
    for i in range(5):
      led_b.value(1)
      led_g.value(1)
      time.sleep_ms(100)
      print('woking...')
      led_b.value(0)
      led_g.value(0)
      time.sleep_ms(100)
      print('woking...')
  print('register...')
  fm.register(12, fm.fpioa.GPIO0)
  fm.register(13, fm.fpioa.GPIOHS0)
  led_b = GPIO(GPIO.GPIO0, GPIO.OUT)
  led_g = GPIO(GPIO.GPIOHS0, GPIO.OUT)
  gpio_test()
  print('unregister...')
  fm.unregister(12)
  fm.unregister(13)
  gpio_test()
  print('register...')
  fm.register(12, fm.fpioa.GPIO0)
  fm.register(13, fm.fpioa.GPIOHS0)
  gpio_test()
  fm.unregister(12)
  fm.unregister(13)
  # register Coverage test
  fm.register(12, fm.fpioa.GPIO0)
  time.sleep_ms(500)
  try:
    fm.register(13, fm.fpioa.GPIO0)  # fail
  except Exception as e:
    print('Exception')
    print(e)
  time.sleep_ms(500)
  fm.register(12, fm.fpioa.GPIOHS0)  # pass
  time.sleep_ms(500)
  print('Warning')
  fm.register(13, fm.fpioa.GPIOHS0, force=True)  # pass
  time.sleep_ms(500)
  fm.unregister(12)
  fm.unregister(13)


from ray.rllib.utils.framework import try_import_torch

torch, nn = try_import_torch()
if torch:
    import torch.nn.functional as F
    from torch import Tensor
    import kornia.augmentation as K
    import torch

class Augmentation(torch.nn.Module):
    def __init__(
            self,
            strong: bool,
            consistent: bool,
            pad: int = 4,
            image_size: int = 64
    ) -> None:
        super().__init__()
        self.random_crop = K.VideoSequential(
            K.RandomCrop((image_size, image_size), padding=pad, padding_mode='replicate'))
        self.strong_transform = None
        if strong:
            self.strong_transform = [
                K.RandomRotation(5, p=1 / 8),
                K.RandomSharpness((0, 1.0), p=1 / 8),
                K.RandomPosterize((3, 8), p=1 / 8),
                K.RandomSolarize(0.1, p=1 / 8),
                K.RandomEqualize(p=1 / 8),
                K.ColorJiggle(brightness=(0.4, 1.4), p=1 / 8),
                K.ColorJiggle(saturation=(0.4, 1.4), p=1 / 8),
                K.ColorJiggle(contrast=(0.4, 1.4), p=1 / 8),
            ]
            # Strong augmentations are always consistent across timesteps
            self.strong_transfom_fn = K.VideoSequential(*self.strong_transform, same_on_frame=True)
        self.consistent_crop = consistent

    def forward(self, X: Tensor) -> Tensor:
        X = (X + 0.5) * 255.0
        orig_shape = X.shape
        if len(orig_shape) == 4:
            print("STUPID RLLIB TEST USELESS - NOT AUGMENTING")
            return X
        if self.consistent_crop:
            X = self.random_crop(X.view(orig_shape[0], 1, orig_shape[1] * orig_shape[2], *orig_shape[3:])).view(
                orig_shape)
        else:
            X = self.random_crop(X)
        if self.strong_transform:
            X = self.strong_transfom_fn(X / 255.0)
        X = X - 0.5
        return X

class RandomShiftsAug(nn.Module):
    def __init__(self, pad=4, consistent=False):
        super().__init__()
        self.pad = pad
        self.consistent = consistent

    def forward(self, x):
        orig_size = x.size()
        if len(orig_size) > 4:
            x = x.permute(1, 0, 2, 3, 4)
            orig_size = x.size()
            t, n, c, h, w = x.size()
        else:
            n, c, h, w = x.size()

        assert h == w

        padding = tuple([self.pad] * 4 + [0, 0])  # len(x.size()))
        x = F.pad(x, padding, 'replicate')
        eps = 1.0 / (h + 2 * self.pad)
        arange = torch.linspace(-1.0 + eps,
                                1.0 - eps,
                                h + 2 * self.pad,
                                device=x.device,
                                dtype=x.dtype)[:h]
        arange = arange.unsqueeze(0).repeat(h, 1).unsqueeze(2)
        base_grid = torch.cat([arange, arange.transpose(1, 0)], dim=2)
        base_grid = base_grid[None, None, ...].repeat(t, n, 1, 1, 1) if len(x.size()) > 4 else base_grid.unsqueeze(
            0).repeat(n, 1, 1, 1)

        if self.consistent:
            shift = torch.randint(0,
                                  2 * self.pad + 1,
                                  size=(n, 1, 1, 2),
                                  device=x.device,
                                  dtype=x.dtype)
            shift = shift.repeat(t, 1, 1, 1, 1) if len(orig_size) > 4 else shift
        else:
            shift = torch.randint(0,
                                  2 * self.pad + 1,
                                  size=(t, n, 1, 1, 2) if len(orig_size) > 4 else (n, 1, 1, 2),
                                  device=x.device,
                                  dtype=x.dtype)

        shift *= 2.0 / (h + 2 * self.pad)

        grid = base_grid + shift
        if len(orig_size) > 4:
            x = x.view((-1, *x.size()[2:]))
            grid = grid.view((-1, *grid.size()[2:]))

        samples = F.grid_sample(x,
                                grid,
                                padding_mode='zeros',
                                align_corners=False)
        # samples = samples.view(orig_size)
        if len(orig_size) > 4:
            samples = samples.view(orig_size)
            samples = samples.permute(1, 0, 2, 3, 4)
        else:
            return samples

        return samples


import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
import torchvision
import torch.optim as optim
from torchvision import transforms, utils, datasets
from torch.utils.data import Dataset, DataLoader, Subset
import torch.nn.functional as F
import numpy as np
import random
import gc
from collections import deque
from itertools import chain

class Student:
    def __init__(self, data_size, device):
        #Store dataset so we have access
        self.data_size = data_size
        self.device = device
        #Create ConvNetwork
        self.network = ConvNetwork(data_size).to(device)
        #Use Cross Entropy Loss function
        self.objective = nn.CrossEntropyLoss()
        #Use Adam optimizer
        self.optimizer = optim.Adam(self.network.parameters(), lr=1e-3)

    def reset(self):
        #Reinstantiate new ConvNetwork
        self.network = ConvNetwork(self.data_size).to(self.device)
        #Zero Gradients of optimizer
        self.optimizer.zero_grad()

    def train(self, batch):
        x, y_truth = batch[0].to(self.device), batch[1].to(self.device)
        self.network.train()
        #Zero optimizer gradient
        self.optimizer.zero_grad()
        #Get network predictions
        y_hat = self.network(x)
        #Compute Loss, call .backward()
        loss = self.objective(y_hat, y_truth)
        loss.backward()
        #optimizer step
        self.optimizer.step()

    def compute_accuracy(self, y_hat, y_truth):
        return (y_hat.argmax(1) == y_truth).float().mean()

    def eval(self, validation_set):
        #dim x should len x channels x h x w
        x = torch.cat([x[0] for x in validation_set], dim=0).to(self.device).unsqueeze(1)
        #y_truth should be len
        y_truth = torch.tensor([x[1] for x in validation_set], dtype=torch.long, device=self.device)

        self.network.eval()
        y_hat = self.network(x)
        accuracy = self.compute_accuracy(y_hat, y_truth)

        return y_hat, accuracy

class ConvNetwork(nn.Module):
    def __init__(self, data_size):
        super(ConvNetwork, self).__init__()
        c, h, w = data_size
        self.linear_in = h * w * 10
        output = 10

        self.conv = nn.Sequential(
                nn.Conv2d(c, 10, (3,3), padding=(1,1)),
                nn.BatchNorm2d(10),
                nn.ReLU(),
                nn.Conv2d(10, 10, (3,3), padding=(1,1)),
                nn.BatchNorm2d(10),
                nn.ReLU(),
                nn.Conv2d(10, 10, (3,3), padding=(1,1)),
                nn.BatchNorm2d(10),
                nn.ReLU(),
                nn.Conv2d(10, 10, (3,3), padding=(1,1)),
                nn.BatchNorm2d(10),
                nn.ReLU(),
                nn.Dropout(.2)
        )

        self.linear = nn.Linear(self.linear_in, output)

    def forward(self, x):
        conv_out = self.conv(x).view(-1, self.linear_in)
        return self.linear(conv_out)


# -*- Mode: Python -*-

# test persistent version of the aa-tree multimap.

import unittest
from aatree import PersistentMap
import random

class TestPersistentMap (unittest.TestCase):

    def test_persistence (self):
        t0 = PersistentMap()
        random.seed (3141)
        for i in range (100):
            x = random.randint (0, 100)
            y = random.choice ('abcdefghijklmnopqrstuvwxyz')
            t0[x] = y

        t_orig = t0.copy()
        l_orig = [x.key for x in t_orig]

        as_list = [x.key for x in t0]
        for i in range (20):
            k = random.choice (as_list)
            t1 = t0.copy()
            del t0[k]
            as_list.remove (k)
            self.assertEqual ([x.key for x in t0], as_list)
            # make sure the key is still in the previous version
            self.assertTrue (k in t1)
            t1.verify()

        # verify that our original tree is unmangled.
        self.assertEqual ([x.key for x in t_orig], l_orig)

    def test_to_empty (self):
        t0 = PersistentMap()
        random.seed (3141)
        l = []
        for i in range (1000):
            k = random.randint (0, 1000000)
            t0[k] = None
            l.append (k)
        t0.verify()
        random.shuffle (l)
        size = len(t0)
        self.assertEqual (size, 1000)
        for k in l:
            del t0[k]
            size -= 1
            self.assertEqual (len(t0), size)

    def test_levels (self):
        t0 = PersistentMap()
        random.seed (3141)
        for i in range (1000):
            k = random.randint (0, 100000)
            t0[k] = None
            t0.verify()

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


# -*- coding: utf-8 -*-
"""
Created on Mon May  4 22:24:56 2020

@author: phamk
"""

from __future__ import print_function
import numpy as np
# confusion matrix to precision + recall
def cm2pr_binary(cm):
    p = cm[0,0]/np.sum(cm[:,0])
    r = cm[0,0]/np.sum(cm[0])
    return (p, r)

# example of a confusion matrix for binary classification problem
cm = np.array([[100., 10], [20, 70]])
p,r = cm2pr_binary(cm)
print("precition = {0:.2f}, recall = {1:.2f}".format(p, r))

tp1, fp1, fn1 = 10, 5, 3
tp2, fp2, fn2 = 17, 7, 10
tp3, fp3, fn3 = 25, 2, 4

def PR(tp, fp, fn):
    P = float(tp)/(tp + fp)
    R = float(tp)/(tp + fn)
    return (P, R)

(P1, R1) = PR(tp1, fp1, fn1)
(P2, R2) = PR(tp2, fp2, fn2)
(P3, R3) = PR(tp3, fp3, fn2)

print('(P1, R1) = (%.2f, %.2f)'%(P1, R1))
print('(P2, R2) = (%.2f, %.2f)'%(P2, R2))
print('(P3, R3) = (%.2f, %.2f)'%(P3, R3))

total_tp = tp1 + tp2 + tp3
total_fp = fp1 + fp2 + fp3
total_fn = fn1 + fn2 + fn3
micro_ap = float(total_tp)/(total_tp + total_fp)
micro_ar = float(total_tp)/(total_tp + total_fn)
print('(micro_ap, micro_ar) = (%.2f, %.2f)' % (micro_ap, micro_ar))

macro_ap = (P1 + P2 + P3)/3
macro_ar = (R1 + R2 + R3)/3
print('(micro_ap, micro_ar) = (%.2f, %.2f)' % (macro_ap, macro_ar))


# 99 VIP P40
import logging

# 定义一个类封装自定义日志流程
class LogClass():
    def get_log(self):
        # 1、日志收集器
        logger = logging.getLogger("log_test40")

        # 2、设置日志收集器的级别
        logger.setLevel(logging.WARN)

        # 3、设置日志输出的渠道，一个是控制台输出，一个是在后台形成文件
        handle1 = logging.StreamHandler()
        handle2 = logging.FileHandler(filename="log_demo.log",encoding="utf-8")

        # 可选步骤
        # 设置输出渠道的日志级别（注意要大于前面收集器设置的级别）
        handle1.setLevel(logging.ERROR)

        # 4、设置日志输出的格式
        fmt = "%(asctime)s %(name)s %(levelname)s %(filename)s %(lineno)d %(message)s) "
        formt = logging.Formatter(fmt)

        # 5、需要让控制台输出的渠道格式为刚刚定义好的格式：formt
        handle1.setFormatter(formt)

        # 6、日志收集器添加需要的日志输出渠道
        logger.addHandler(handle1)
        logger.addHandler(handle2)

        # 测试日志生成打印
        # logger.warning("运行失败警告")
        # logger.error("运行出错")
        return logger

def sum_data(a,b):
    try:
        return a + b
    except Exception as e:
        LogClass().get_log().error("这个计算参数有问题，这是报错信息")

if __name__ == '__main__':
    # LogClass().get_log().error("报错信息")
    print(sum_data(1,2))
    print(sum_data(1,"2"))


# wap to find the largest no in a list
class LargestNoInList:
    def findLargest(self,l):
        l.sort()
        print("The largest No: ",l[-1])
        for i in reversed(l):
            print(i)
ob=LargestNoInList()
l=[45,65,78,52,98]
ob.findLargest(l)


def ruch(plansza, gracz, kolumna, wiersz):
    if kolumna > 2 or wiersz > 2 or plansza[wiersz][kolumna] != '[ ]':
        print("Błędny ruch. Spróbuj ponownie.")
        return gracz
    plansza[wiersz][kolumna] = f'[{gracz}]'
    gracz = zmianaGracza(gracz)
    return gracz

def zmianaGracza(gracz):
    if gracz == 'X':
        gracz = 'O'
    elif gracz =='O':
        gracz = 'X'
    return gracz


import numpy as np

with open("input8.txt", "r") as f:
    grid = []
    for line in f:
        line = line.strip()
        grid.append(list(map(int, line)))

grid = np.array(grid, dtype=int)

height, width = grid.shape

score = np.ones_like(grid)

for i in range(height):
    for j in range(width):
        value = grid[i, j]
        # top
        index = i
        while True:
            if index == 0:
                break
            index -= 1
            if grid[index, j] >= value:
                break
        score[i, j] *= (i - index)
        #  down
        index = i
        while True:
            if index == height-1:
                break
            index += 1
            if grid[index, j] >= value:
                break
        score[i, j] *= (index - i)
        #  left
        index = j
        while True:
            if index == 0:
                break
            index -= 1
            if grid[i, index] >= value:
                break
        score[i, j] *= (j - index)
        # right
        index = j
        while True:
            if index == width - 1:
                break
            index += 1
            if grid[i, index] >= value:
                break
        score[i, j] *= (index - j)

print(score.max().max())


import numpy as np
import matplotlib.pyplot as plt

def get_windows(image):
    """Display the given image and record user selected points.

    Parameters
    ----------

    image : M,N,3 ndarray
        The image to be displayed.

    Returns
    -------

    array : n_points,2
        An array of coordinates in the image. Each row corresponds to the x, y
        coordinates of one point. If an odd number of points are specified, the
        last one will be discarded.

    """
    plt.interactive(True)
    plt.imshow(image)
    plt.show()
    crop = plt.ginput(0)
    plt.close()
    plt.interactive(False)
    # remove last point if an odd number selected
    crop = crop[:-1] if np.mod(len(crop), 2) else crop
    return np.vstack(crop).astype('int')[:, [1, 0]]


import asyncio
import os
from config import OWNER_ID
import time
import requests
import aiohttp
from pyrogram import filters
from pyrogram import Client
from pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardMarkup
from strings.filters import command
from AnonX import (Apple, Resso, SoundCloud, Spotify, Telegram, YouTube, app)
from AnonX import app
from asyncio import gather
from pyrogram.errors import FloodWait
from pyrogram.enums import ParseMode, ChatMemberStatus

@app.on_message(command(["المالك"]) & filters.group)
async def gak_owne(client: Client, message: Message):
      if len(message.command) >= 2:
         return
      else:
            chat_id = message.chat.id

            async for member in client.get_chat_members(chat_id):
               if member.status == ChatMemberStatus.OWNER:
                 id = member.user.id
                 key = InlineKeyboardMarkup([[InlineKeyboardButton(member.user.first_name, user_id=id)]])
                 m = await client.get_chat(id)
                 if m.photo:
                       photo = await app.download_media(m.photo.big_file_id)
                       return await message.reply_photo(photo, caption=f"**✧ ¦معلومات مالك القروب \n\n ✧ ¦ اسمه ← {m.first_name} \n ✧ ¦ معرفه ← @{m.username} \n ✧ ¦ البايو ← {m.bio}**",reply_markup=key)
                 else:
                    return await message.reply("• " + member.user.mention)

@app.on_message(command(["اسمي", "شن اسمي"]) & filters.group )
async def vgdg(client: Client, message: Message):
    await message.reply_text(
        f"""❤🔥 اسمك هو »»  {message.from_user.mention()}""")

array = []
@app.on_message(command(["@all", "تاغ","تاغ للكل"]) & ~filters.private)
async def nummmm(client: app, message):
  if message.chat.id in array:
     return await message.reply_text(f"**تم بدأ التاق الجماعي \n\n بواسطة ← ✧ ¦{message.from_user.mention}**")

  dev = (OWNER_ID)
  haya = (6275847466,6195765774)
  get = await client.get_chat_member(message.chat.id, message.from_user.id)
  if message.from_user.id in haya:
         rotba= "مّمٌَـبـ ـࢪمـج السوࢪس"
  elif message.from_user.id in dev:
         rotba = "مطور اساسي"
  elif get.status in [ChatMemberStatus.OWNER]:
         rotba = "المالك"
  elif get.status in [ChatMemberStatus.ADMINISTRATOR]:
         rotba = "الادمن"
  chek = await client.get_chat_member(message.chat.id, message.from_user.id)
  if not chek.status in  [ChatMemberStatus.OWNER, ChatMemberStatus.ADMINISTRATOR]:
    await message.reply(f"**انت لست مشرفا يا {message.from_user.mention}**")
    return
  await message.reply_text(f"**تم بدأ التاق الجماعي \n\n بواسطة ← {rotba}✧ ¦{message.from_user.mention} \n\n للايقاف اكتب وقف منشن او خلاص**")
  i = 0
  txt = ""
  zz = message.text
  if message.photo:
          photo_id = message.photo.file_id
          photo = await client.download_media(photo_id)
          zz = message.caption
  try:
   zz = zz.replace("@all","").replace("تاغ","").replace("كلمهم","")
  except:
    pass
  array.append(message.chat.id)
  async for x in client.get_chat_members(message.chat.id):
      if message.chat.id not in array:
        return
      if not x.user.is_deleted:
       i += 1
       txt += f" {x.user.mention} ،"
       if i == 5:
        try:
              if not message.photo:
                    await client.send_message(message.chat.id, f"{zz}\n{txt}")
              else:
                    await client.send_photo(message.chat.id, photo=photo, caption=f"{zz}\n{txt}")
              i = 0
              txt = ""
              await asyncio.sleep(2)
        except FloodWait as e:
                    flood_time = int(e.x)
                    if flood_time > 200:
                        continue
                    await asyncio.sleep(flood_time)
        except Exception:
              array.remove(message.chat.id)
  array.remove(message.chat.id)

@app.on_message(command(["وقف منشن", "/cancel","خلاص"]))
async def stop(client, message):
  dev = (OWNER_ID)
  haya = (6275847466,6195765774)
  get = await client.get_chat_member(message.chat.id, message.from_user.id)
  if get.status in [ChatMemberStatus.ADMINISTRATOR]:
         rotba = "الادمن"
  elif get.status in [ChatMemberStatus.OWNER]:
         rotba = "المالك"
  elif message.from_user.id in haya:
         rotba= "مّمٌَـبـ ـࢪمـج السوࢪس"
  elif message.from_user.id in dev:
         rotba = "مطور اساسي"
  chek = await client.get_chat_member(message.chat.id, message.from_user.id)
  if not chek.status in  [ChatMemberStatus.OWNER, ChatMemberStatus.ADMINISTRATOR]:
    await message.reply(f"**انت لست مشرفا يا {message.from_user.mention}**")
    return
  if message.chat.id not in array:
     await message.reply(f"**التاق متوقف فالاصل \n\n يا {message.from_user.mention}**")
     return
  if message.chat.id in array:
    array.remove(message.chat.id)
    await message.reply(f"**تم ايقاف التاق الجماعي \n\n بواسطة ← {rotba}✧ ¦{message.from_user.mention}**")
    return


import math

import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange

class SelfAttentionPose(nn.Module):
    def __init__(self, ni, pose_dim, img_seq_dim, attn_chans, transpose=True):
        super().__init__()
        self.nheads = ni // attn_chans
        self.scale = math.sqrt(ni / self.nheads)
        self.norm = nn.LayerNorm(ni)
        self.x_pose_norm = nn.LayerNorm(ni + 2)
        self.pose_embed_layer = nn.Linear(pose_dim, img_seq_dim)
        self.q_layer = nn.Linear(ni, ni)
        self.k_layer = nn.Linear(ni + 2, ni)
        self.v_layer = nn.Linear(ni + 2, ni)
        self.proj = nn.Linear(ni, ni)
        self.transpose = transpose

    def forward(self, x, pose_embed):
        n, c, h, w = x.shape
        x = x.view(n, c, -1)  # n, c, s # pose_embed.shape = n, 2, pd
        pose_embed = self.pose_embed_layer(pose_embed)  # pose_embed.shape = n,2,s
        if self.transpose:
            x = x.transpose(1, 2)  # x.shape = n, s, c
            pose_embed = pose_embed.transpose(1, 2)  # n,s,1

        print(f"SelfAttentionPose - x.shape = {x.shape}, pose_embed.shape = {pose_embed.shape}")
        x_pose = torch.cat((x, pose_embed), dim=2)  # n, s, c+1
        x = self.norm(x)
        x_pose = self.x_pose_norm(x_pose)

        q, k, v = self.q_layer(x), self.k_layer(x_pose), self.v_layer(x_pose)  # n, s, c
        x = torch.cat((q, k, v), dim=-1)  # n,s,c
        x = rearrange(x, "n s (h d) -> (n h) s d", h=self.nheads)
        q, k, v = torch.chunk(x, 3, dim=-1)  # 16*n, s, c/16

        s = (q @ k.transpose(1, 2)) / self.scale
        x = s.softmax(dim=-1) @ v
        x = rearrange(x, "(n h) s d -> n s (h d)", h=self.nheads)
        x = self.proj(x)
        if self.transpose:
            x = x.transpose(1, 2)
        return x.reshape(n, c, h, w)

class CrossAttention(nn.Module):
    def __init__(self, ni, attn_chans, transpose=True):
        super().__init__()
        self.nheads = ni // attn_chans
        self.scale = math.sqrt(ni / self.nheads)
        self.q = nn.Sequential(nn.LayerNorm(ni), nn.Linear(ni, ni))
        self.kv = nn.Sequential(nn.LayerNorm(ni), nn.Linear(ni, ni * 2))
        self.proj = nn.Linear(ni, ni)
        self.transpose = transpose

    def forward(self, x, query_x):
        print(f"CrossAttention x = {x.shape}, query_x = {query_x.shape}")
        n, c, h, w = x.shape
        x = x.view(n, c, -1)
        query_x = query_x.view(n, c, -1)
        n, c, s = x.shape

        if self.transpose:
            x = x.transpose(1, 2)  # n,s,c
            query_x = query_x.transpose(1, 2)

        query_x = self.q(query_x)

        # repeat if there is single channel. Useful since this is also used as pool attention for clip embeddings.
        if not self.transpose and query_x.shape[1] == 1:
            query_x = query_x.repeat(1, 3, 1)

        x = self.kv(x)
        x = torch.cat((query_x, x), dim=-1)
        x = rearrange(x, "n s (h d) -> (n h) s d", h=self.nheads)
        q, k, v = torch.chunk(x, 3, dim=-1)
        s = (q @ k.transpose(1, 2)) / self.scale
        x = s.softmax(dim=-1) @ v
        x = rearrange(x, "(n h) s d -> n s (h d)", h=self.nheads)
        x = self.proj(x)

        if self.transpose:
            x = x.transpose(1, 2)
        return x.reshape(n, c, h, w)

class MultiHeadAttention(nn.Module):
    def __init__(self, ni, attn_chans):
        super().__init__()
        self.nheads = ni // attn_chans
        self.scale = math.sqrt(ni / self.nheads)
        self.q_proj = nn.Linear(ni, ni)
        self.k_proj = nn.Linear(ni, ni)
        self.v_proj = nn.Linear(ni, ni)
        self.c_proj = nn.Linear(ni, ni)
        # self.transpose = transpose

    def forward(self, x):
        x = x.permute(1, 0, 2)
        x, _ = F.multi_head_attention_forward(
            query=x[:1],
            key=x,
            value=x,
            embed_dim_to_check=x.shape[-1],
            num_heads=self.nheads,
            q_proj_weight=self.q_proj.weight,
            k_proj_weight=self.k_proj.weight,
            v_proj_weight=self.v_proj.weight,
            in_proj_weight=None,
            in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
            bias_k=None,
            bias_v=None,
            add_zero_attn=False,
            dropout_p=0,
            out_proj_weight=self.c_proj.weight,
            out_proj_bias=self.c_proj.bias,
            use_separate_proj_weight=True,
            training=self.training,
            need_weights=False,
        )
        return x.permute(1, 0, 2)


#!/usr/bin/python

__author__ = 'scukonick'

import os
import re
import select
import socket
import logging

result = {}

configname = '/etc/pyeximer'
filename = '/var/log/exim4/mainlog'
logfile = '/var/log/pyeximer/pyeximer.log'
pidfile = '/var/run/pyeximer.pid'

interface = '0.0.0.0'
port = 8083

EOL1 = b'\n'

# Configuring logging
log = logging.getLogger()
ch = logging.FileHandler(logfile)

log.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
log.addHandler(ch)

pid = str(os.getpid())
if os.path.isfile(pidfile):
    log.error ("%s already exists, exiting" % pidfile)
    exit()
else:
    open(pidfile, 'w').write(pid)
log.info('Configname is: '+configname)
log.info('Exim log filename is: '+filename)

regex = '(?P<date>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}).*=>.* T=(?P<transport>\S+)'

transports = []
# Config
try:
    with open(configname) as config:
        for line in config:
            result[line.rstrip('\n')]=0
            transports.append(line.rstrip('\n'))
except Exception:
    log.fatal("Couldn't open config, exiting")
    exit (2)

log.debug('Result at start is: '+str(result))
log.debug('Transports are: '+str(transports))

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serversocket.bind((interface, port))
serversocket.listen(1)
serversocket.setblocking(0)

log.info('Listening on: '+interface + ':' + str(port))

epoll = select.epoll()
epoll.register(serversocket.fileno(), select.EPOLLIN)

connections = {}; requests = {}; responses = {}

def openFile(filename):
    for x in range(0,3): # Let's try to open file 3 times
        try:
            file = open(filename)
            return file
        except Exception:
            log.debug ("Try "+str(x)+": Could not open file: "+filename)
            #sleep(1)
    log.fatal ("Failed opening file")
    exit(1)

file = openFile(filename)
inode = os.stat(filename).st_ino
file.seek(0,2)
i = 0

while True:
    # check if file replaced
    if inode != os.stat(filename).st_ino:
        log.info("File changed, reopening")
        file = openFile(filename)
        inode = os.stat(filename).st_ino
    newline = file.readline()
    # check if we can read new line
    if newline:
        log.debug("Read line")
        match = re.search(regex,newline)
        if match:
            log.debug ("Matched with regexp")
            date = match.group('date')
            transport = match.group('transport')
            log.debug ("Received msg to transport: "+transport)
            if transport in transports:
                result[transport] = result[transport] + 1
                log.debug ('Increased result for transport: '+str(result))
    else:
        log.debug('Sleeping')

    events = epoll.poll(.1)
    for fileno, event in events:
        if fileno == serversocket.fileno():

            connection, address = serversocket.accept()
            connection.setblocking( 0)
            epoll.register(connection.fileno(), select.EPOLLIN)
            connections[connection.fileno()] = connection
            requests[connection.fileno()] = b''
            log.debug("Socket: "+str(connection.fileno())+": Connected somebody")
        elif event & select.EPOLLIN:
            log.debug("Socket: "+str(connection.fileno())+": Got something to read")
            requests[fileno] += connections[fileno].recv(1024)
            log.debug ("Socket: "+str(connection.fileno())+":We read: "+requests[fileno].decode())
            if EOL1 in requests[fileno]:
                log.debug("Socket: "+str(connection.fileno())+": Received EOL")
                epoll.modify(fileno, select.EPOLLOUT)
                log.info ("Received request: "+requests[fileno].decode()[:-2])
                asked_transport = requests[fileno].decode()[:-2]
                try:
                    responses[fileno] = str(result[asked_transport])
                    result[asked_transport] = 0
                    log.info('Answering with: '+responses[fileno])
                except KeyError:
                    log.info('Wrong key')
                    responses[fileno] = b'Wrong key\n'

        elif event & select.EPOLLOUT:
            byteswritten = connections[fileno].send(responses[fileno])
            responses[fileno] = responses[fileno][byteswritten:]
            if len(responses[fileno]) ==  0:
                epoll.modify(fileno,  0)
                log.debug('Sent response')
                connections[fileno].shutdown(socket.SHUT_RDWR)
        elif event & select.EPOLLHUP:
            log.debug('Disconnecting')
            epoll.unregister(fileno)
            connections[fileno].close()
            del connections[fileno]

log.info ("Ok")
os.unlink(pidfile)


# RBE 500 Group Assignment #3
# Group 2 - Joshua Gross, Arjan Gupta, Melissa Kelly

import sys
import rclpy
from rclpy.node import Node
from rclpy.task import Future
from rbe500_custom_interfaces.srv import CalcScaraJointVelRefs
from sensor_msgs.msg import JointState
from std_msgs.msg import Float64MultiArray
from controller_manager_msgs.srv import SwitchController
import numpy as np
import time
from matplotlib import pyplot as plt

# Node for subscriber, publisher, service, and client
class ScaraVelocityController(Node):

    def __init__(self):
        # Initialize superclass
        super().__init__('scara_velocity_controller')

        # --- Initialize member variables for reference velocities ---
        self.received_ref_vels: bool = False
        self.end_effector_ref_vel = 1.1 # arbitrarily chosen
        self.ref_v1: float = 0
        self.ref_v2: float = 0
        self.graph_ref_v1: float = self.ref_v1
        self.graph_ref_v2: float = self.ref_v2
        self.ref_v3: float = 0.0
        self.ref_q1 = 1.5708
        self.ref_q2 = 0.0
        # --- Initialize member variables for joint_states subscription ---
        self.awating_ref_vel_count: int = 0
        # --- Initialize member variables for run_controller method ---
        # Define gains for v1
        self.Kp1:float = 0.35
        self.Kd1:float = 0.3
        # Define gains for v2
        self.Kp2:float = -0.35
        self.Kd2:float = -0.15
        # Define gains for v3
        self.Kp3:float = 5
        self.Kd3:float = 5
        self.num_values_received: int = 0
        self.accel_approx_last_time = time.time()
        # Store the last known velocities
        self.last_v1: float = 0.0
        self.last_v2: float = 0.0
        self.last_v3: float = 0.0
        # --- Initialize member variables for clients ---
        self.switch_controller_req = SwitchController.Request()
        self.convert_end_effector_velocity_req: CalcScaraJointVelRefs.Request() = CalcScaraJointVelRefs.Request()
        # --- Initialize member variables for timing/graphing ---
        self.time_array = np.arange(0, 10, .01)
        self.curr_time_iterator = 0
        self.joint1_data_array = np.array([])
        self.joint2_data_array = np.array([])
        self.joint3_data_array = np.array([])
        self.plot_data_last_time = time.time()
        self.graph_generated = False

        # Create the client that will activate the required controller.
        self.switch_controller_client = self.create_client(SwitchController, '/controller_manager/switch_controller')
        # If we find that we had to wait for the service, it means Gazebo is not
        # running. We exit the program in this case because trying to call the service
        # while Gazebo is starting up causes errors. This Node needs to be started
        # after Gazebo is already running.
        if not self.switch_controller_client.wait_for_service(timeout_sec=0.5):
            print('The /controller_manager/switch_controller service is not available. Please launch Gazebo before running this package, or simply try running this package again.')
            sys.exit()
        # Activate the Gazebo effort controller
        self.activate_effort_controller()

        # Create another client that will get the joint velocity references from our other ROS Node
        self.velocity_reference_client = self.create_client(CalcScaraJointVelRefs, 'velocity_inv_kin_service')
        self.get_target_velocities()

        # Create the subscriber that receives the joint state information, with a queue of 50 since it is very fast
        self.subscription = self.create_subscription(JointState, '/joint_states', self.joint_states_callback, 100)
        print("Done creating subscription that receives joint-state information.")

        # Create the publisher that will send the joint efforts
        self.efforts_publisher = self.create_publisher(Float64MultiArray, '/forward_effort_controller/commands', 10)
        print("Done creating the publisher for sending joint efforts.")

    def joint_states_callback(self, joint_state_msg):
        # Only take action if we have a reference/goal velocity to work against
        if self.received_ref_vel:
            # Record the current velocitys for graphing
            self.dump_graph_data(joint_state_msg)
            # Perform the work for the PD controller
            self.run_controller(joint_state_msg)
        elif self.awating_ref_vel_count >= 100:
            print("Receiving joint state info. Awaiting a reference end effector velocity to be given.")
            self.awating_ref_vel_count = 0
        else:
            self.awating_ref_vel_count += 1
        # Update the time captured for the last set of velocities we received
        self.accel_approx_last_time = time.time()

    def dump_graph_data(self, joint_state_msg):
        # Collect graphing data
        if (self.curr_time_iterator < len(self.time_array)) and (time.time() - self.plot_data_last_time >= 0.01):
            # Show elapsed time difference
            if self.curr_time_iterator % 50 == 0:
                print(f"Collecting data for plotting...")
            # Get joint velocity values
            v1 = joint_state_msg.velocity[0]
            v2 = joint_state_msg.velocity[1]
            v3 = joint_state_msg.velocity[2]
            # Append values to joint data arrays
            self.joint1_data_array = np.append(self.joint1_data_array, v1)
            self.joint2_data_array = np.append(self.joint2_data_array, v2)
            self.joint3_data_array = np.append(self.joint3_data_array, v3)
            # Increment iterator, update the last time data was dumped
            self.curr_time_iterator += 1
            self.plot_data_last_time = time.time()

        # Plot graph if we are done sampling
        if (self.curr_time_iterator >= len(self.time_array)) and not self.graph_generated:
            # Create subplot 1
            plt.subplot(2, 1, 1)
            plt.plot(self.time_array, self.joint1_data_array, label="Current velocity")
            plt.plot(self.time_array, np.full((len(self.time_array), 1), self.graph_ref_v1), label="Reference velocity")
            plt.legend()
            plt.title("Joint 1 Velocity vs Time")
            plt.xlabel("Time (seconds)")
            plt.ylabel("Velocity (Radians/s)")

            # Create subplot 2
            plt.subplot(2, 1, 2)
            plt.plot(self.time_array, self.joint2_data_array, label="Current velocity")
            plt.plot(self.time_array, np.full((len(self.time_array), 1), self.graph_ref_v2), label="Reference velocity")
            plt.legend()
            plt.title("Joint 2 Velocity vs Time")
            plt.xlabel("Time (seconds)")
            plt.ylabel("Velocity (Radians/s)")

            # Size the plots better for better visual appearance
            plt.subplots_adjust(bottom=0.05,
                                top=.95,
                                wspace=0.6,
                                hspace=0.6)
            plt.show()

            # Mark that we have generated this graph so that we don't continuously generate it
            self.graph_generated = True

    def run_controller(self, joint_state_msg):
        """
        This function runs our velocity PD controller. It grabs the current
        velocities of all three joints of our SCARA robot, applies the
        proportional and derivative gains for the error and derivative error,
        and computes the output efforts that need to be applied to the
        corresponding joints.
        """
        # # Get joint position values
        p1 = joint_state_msg.position[0]
        p2 = joint_state_msg.position[1]
        # Get joint velocity values
        v1 = joint_state_msg.velocity[0]
        v2 = joint_state_msg.velocity[1]
        v3 = joint_state_msg.velocity[2]

        # Conditional printing so that we're not printing continuously
        if self.num_values_received >= 100:
            print("Controller is running!")
            print(f"Current joint velocities are v1:{v1}, v2:{v2}, v3:{v3}")
            self.num_values_received = 0
        else:
            self.num_values_received += 1

        # ----- Implement controller ------
        # Find errors
        err_v1 = self.ref_v1 - v1
        err_v2 = (self.ref_v2 * -1) - v2
        err_v3 = self.ref_v3 - v3
        # Approximate the acceleration by using the derivative
        # approximation technique shown in Week 8 lecture
        accel1 = (v1 - self.last_v1)/(time.time() - self.accel_approx_last_time)
        accel2 = (v2 - self.last_v2)/(time.time() - self.accel_approx_last_time)
        accel3 = (v3 - self.last_v3)/(time.time() - self.accel_approx_last_time)
        # Update the last velocities
        self.last_v1 = v1
        self.last_v2 = v2
        self.last_v3 = v3
        # Find error dots
        err_dot_v1 = -1 * accel1
        err_dot_v2 = -1 * accel2
        err_dot_v3 = -1 * accel3
        # The modeled controller for each joint
        # (as described in our report) is
        # F = K_p*E - K_d*v
        output_effort_v1: float = self.Kp1*err_v1 + self.Kd1*err_dot_v1
        output_effort_v2: float = self.Kp2*err_v2 + self.Kd2*err_dot_v2
        output_effort_v3: float = self.Kp3*err_v3 + self.Kd3*err_dot_v3
        # For v3, there is also a force of gravity acting upon it
        output_effort_v3 += -9.8
        # Cut off the efforts if we're in position range
        if abs(1.57 - p1) <= 0.01:
            self.ref_v1 = 0.0
            output_effort_v1 = 0.0
        if abs(0 - p2) <= 0.01:
            self.ref_v2 = 0.0
            output_effort_v2 = 0.0
        # Show efforts
        print(f"effort1 is {output_effort_v1} and effort2 is {output_effort_v2}")
        # Publish the output efforts
        efforts_arr: Float64MultiArray = Float64MultiArray()
        efforts_arr.data = [output_effort_v1, output_effort_v2, 0.0]
        self.efforts_publisher.publish(efforts_arr)

    def get_target_velocities(self):
        """
        This function calls our inverse velocity kinematics node to return our reference joint velocities.
        """
        # Send another client request to convert the end effector velocity to joint velocities
        while not self.velocity_reference_client.wait_for_service(timeout_sec=1.0):
            print("The velocity kinematics services are not online, waiting...")
        # Send the request and get the conversion
        self.convert_end_effector_velocity_req.end_effector_ref_vel = self.end_effector_ref_vel

        # Start an asynchronous call and then block until it is done
        future: Future = self.velocity_reference_client.call_async(self.convert_end_effector_velocity_req)
        print("About to spin until future complete.")
        rclpy.spin_until_future_complete(node=self, future=future, timeout_sec=5)

        # Capture the result
        self.ref_v1 = future.result().joint1_velocity
        self.ref_v2 = future.result().joint2_velocity
        self.ref_v3 = future.result().joint3_velocity
        self.graph_ref_v1 = self.ref_v1
        self.graph_ref_v2 = self.ref_v2

        # Report the result
        print(f"Obtained reference velocities for joints - v1: {self.ref_v1} v2: {self.ref_v2} v3: {self.ref_v3}")

        # Set flag that we've received the goal velocities
        self.received_ref_vel = True
        print("We're ready to start our controller!")

        # Reset the timer iterator and graphing flag
        self.curr_time_iterator = 0
        self.graph_generated = False
        # Reset joint data arrays
        self.joint1_data_array = np.array([])
        self.joint2_data_array = np.array([])
        self.joint3_data_array = np.array([])

    def activate_effort_controller(self):
        # Set the controller we want to activate
        self.switch_controller_req.activate_controllers = ["forward_effort_controller"]
        # Set the controllers we want to deactivate
        self.switch_controller_req.deactivate_controllers = ["forward_position_controller", "forward_velocity_controller"]
        # Start an asynchronous call and then block until it is done
        future = self.switch_controller_client.call_async(self.switch_controller_req)
        rclpy.spin_until_future_complete(self, future)
        # Report the result
        print(f"The result of the attempt to activate the effort controller is ok: {future.result().ok}")

def main():
    rclpy.init()

    scara_velocity_controller = ScaraVelocityController()

    rclpy.spin(scara_velocity_controller)

    rclpy.shutdown()

if __name__ == '__main__':
    main()


import numpy as np

from typing import Optional

from automl.components.transformers.category_coalescer import CategoryCoalescer

from ..stage import AutoMLStage
from ...problems.problem_type import ProblemType
from ...components.flow import (
    ColumnTransformer,
    TopPipeline,
)
from ...components.transformers import *
from ...components.estimators import *
from ...components.component import Component, ComponentLevel, ComponentConfig
from ...components.estimators.linear_model.linear_model_estimator import (
    LinearModelEstimator,
)
from ...components.estimators.neural_network.neural_network_estimator import (
    NeuralNetworkEstimator,
)
from ...components.estimators.knn.knn_estimator import KNNEstimator
from ...utils import validate_type

from automl_models.components.flow.column_transformer import make_column_selector

def _scaler_passthrough_condition(config, stage) -> bool:
    return config.estimator is None or not isinstance(
        config.estimator, (LinearModelEstimator, KNNEstimator, NeuralNetworkEstimator)
    )

def _column_is_binary_condition(column) -> bool:
    return len(column.cat.categories) <= 2

categorical_selector = make_column_selector(dtype_include="category")
numeric_selector = make_column_selector(dtype_exclude=["category", "bool"])

categorical_binary_selector = make_column_selector(
    _column_is_binary_condition, dtype_include="category"
)
categorical_not_binary_selector = make_column_selector(
    _column_is_binary_condition, dtype_include="category", negate_condition=True
)

def create_pipeline_blueprint(
    problem_type: ProblemType,
    X=None,
    y=None,
    categorical_columns: Optional[list] = None,
    numeric_columns: Optional[list] = None,
    level: ComponentLevel = ComponentLevel.COMMON,
    is_secondary: bool = False,
) -> TopPipeline:
    validate_type(problem_type, "problem_type", ProblemType)
    validate_type(level, "level", ComponentLevel)

    # steps in [] are tunable
    # there are three possible states for a step depending on an estimator:
    # - none of the components are valid
    # - one component is valid
    # - all components are valid
    # make sure that is the case!

    passthrough = {
        "Passthrough": Passthrough(),
        "Passthrough_Scaler": Passthrough(
            validity_condition=_scaler_passthrough_condition
        ),
    }
    unknown_categories = {"UnknownCategoriesDropper": UnknownCategoriesDropper()}
    category_coalescers = {"CategoryCoalescer": CategoryCoalescer()}
    imbalance = {"AutoSMOTE": AutoSMOTE()}
    imputers = {
        "CombinedSimpleImputer": CombinedSimpleImputer(),
        "IterativeImputer": IterativeImputer(),
    }
    scalers_normalizers = {
        "CombinedScalerTransformer": CombinedScalerTransformer(),
        "MinMaxScaler": MinMaxScaler(),
    }
    target_transformers = {"QuantileTransformer": QuantileTargetTransformer()}
    binary_encoders = {
        "BinaryEncoder": BinaryEncoder(),
    }
    categorical_encoders = {
        "OneHotEncoder": OneHotEncoder(),
        "CatBoostEncoderBinary": CatBoostEncoderBinary(),
        "CatBoostEncoderMulticlass": CatBoostEncoderMulticlass(),
        "CatBoostEncoderRegression": CatBoostEncoderRegression(),
        # "BayesianTargetEncoderBinary": BayesianTargetEncoderBinary(),
        # "BayesianTargetEncoderMulticlass": BayesianTargetEncoderMulticlass(),
        # "BayesianTargetEncoderRegression": BayesianTargetEncoderRegression(),
    }
    oridinal_encoder = {"OrdinalEncoder": OrdinalEncoder()}
    feature_selectors = {
        # "BorutaSHAPClassification": BorutaSHAPClassification(),
        # "BorutaSHAPRegression": BorutaSHAPRegression(),
        "SHAPSelectFromModelClassification": SHAPSelectFromModelClassification(),
        "SHAPSelectFromModelRegression": SHAPSelectFromModelRegression(),
    }
    svm_kernels = {
        "NystroemRBF": NystroemRBF(),
        "PolynomialCountSketch": PolynomialCountSketch(),
        "NystroemSigmoid": NystroemSigmoid(),
    }
    knn_transformers = {
        "KNNTransformer": KNNTransformer(),
        # "NCATransformer": NCATransformer(),
    }
    estimators = {
        # "DecisionTreeClassifier": DecisionTreeClassifier(),
        # "DecisionTreeRegressor": DecisionTreeRegressor(),
        "LogisticRegression": LogisticRegression(),
        # "LogisticRegression_L1": LogisticRegression(l1_ratio=1),
        "LogisticRegression_EN": LogisticRegression(l1_ratio=0.15, alpha=0.01),
        "LinearRegression": LinearRegression(),
        "ElasticNet": ElasticNet(),
        "ElasticNet_EN": ElasticNet(l1_ratio=0.15, alpha=0.01),
        "LGBMClassifier": LGBMClassifier(),
        "LGBMClassifier_UnBalanced": LGBMClassifier(class_weight=None),
        "LGBMRegressor": LGBMRegressor(),
        "CatBoostClassifierBinary": CatBoostClassifierBinary(),
        "CatBoostClassifierMulticlass": CatBoostClassifierMulticlass(),
        "CatBoostRegressor": CatBoostRegressor(),
        "CatBoostClassifierBinary_UnBalanced": CatBoostClassifierBinary(
            auto_class_weights=None
        ),
        "CatBoostClassifierMulticlass_UnBalanced": CatBoostClassifierMulticlass(
            auto_class_weights=None
        ),
        "RandomForestClassifier": RandomForestClassifier(),
        "RandomForestRegressor": RandomForestRegressor(),
        "ExtraTreesClassifier": RandomForestClassifier(randomization_type="et"),
        "ExtraTreesRegressor": RandomForestRegressor(randomization_type="et"),
        "RandomForestClassifier_UnBalanced": RandomForestClassifier(
            class_weight=None
        ),
        "ExtraTreesClassifier_UnBalanced": RandomForestClassifier(
            randomization_type="et", class_weight=None
        ),
        "LinearSVC": LinearSVC(),
        "LinearSVR": LinearSVR(),
        "KNeighborsClassifier": KNeighborsClassifier(),
        "KNeighborsRegressor": KNeighborsRegressor(),
        "FTTransformerClassifier": FTTransformerClassifier(),
        "FTTransformerRegressor": FTTransformerRegressor(),
        "FastAINNClassifier": FastAINNClassifier(),
        "FastAINNRegressor": FastAINNRegressor(),
        "GaussianNB": GaussianNB(),
        "QuadraticDiscriminantAnalysis": QuadraticDiscriminantAnalysis(),
    }
    components = {
        **passthrough,
        **unknown_categories,
        **category_coalescers,
        **imbalance,
        **imputers,
        **scalers_normalizers,
        **binary_encoders,
        **categorical_encoders,
        **oridinal_encoder,
        **feature_selectors,
        **svm_kernels,
        **knn_transformers,
        **estimators,
    }

    pipeline_steps = [
        (
            "target_pipeline__TransformTarget",
            [components["Passthrough"]] + list(target_transformers.values()),
        ),
        ("UnknownCategories", list(unknown_categories.values())),
        ("Imputer", list(imputers.values())),
        (
            "CategoryCoalescer",
            list(category_coalescers.values()),
        ),
        (
            "FeatureSelector",
            [components["Passthrough"]] + list(feature_selectors.values()),
        ),
        ("Imbalance", [components["Passthrough"]] + list(imbalance.values())),
        (
            "ColumnOrdinal",
            ColumnTransformer(
                transformers=[
                    (
                        "OrdinalEncoder",
                        [components["OrdinalEncoder"]],
                        categorical_selector,
                    ),
                ],
            ),
        ),
        (
            "ColumnEncoding",
            ColumnTransformer(
                transformers=[
                    (
                        "BinaryEncoder",
                        [components["BinaryEncoder"]],
                        categorical_binary_selector,
                    ),
                    (
                        "CategoricalEncoder",
                        list(categorical_encoders.values()),
                        categorical_not_binary_selector,
                    ),
                ],
            ),
        ),
        (
            "ColumnScaling",
            ColumnTransformer(
                transformers=[
                    (
                        "ScalerNormalizer",
                        list(scalers_normalizers.values()),
                        numeric_selector,
                    ),
                ],
            ),
        ),
        (
            "SVMKernelApproximation",
            list(svm_kernels.values()),
        ),
        (
            "KNNTransformer",
            list(knn_transformers.values()),
        ),
        (
            "Estimator",
            list(estimators.values()),
        ),
    ]

    pipeline = TopPipeline(
        steps=pipeline_steps,
        # preset_configurations=[d, d2]
    )
    config = ComponentConfig(
        level=level,
        problem_type=problem_type,
        categorical_columns=categorical_columns,
        numeric_columns=numeric_columns,
        X=X,
        y=y,
    )
    # TODO: move to trainer
    pipeline.call_tuning_grid_funcs(config=config, stage=AutoMLStage.PREPROCESSING)
    pipeline.convert_duplicates_in_steps_to_extra_configs()
    pipeline.remove_invalid_components(
        pipeline_config=config,
        current_stage=AutoMLStage.PREPROCESSING,
    )
    return pipeline


import sqlite3

conn = sqlite3.connect('database.db')

from datetime import datetime

conn.execute("""CREATE TABLE IF NOT EXISTS books (
                title TEXT,
                author TEXT,
                pages INTEGER,
                published INTEGER
                )""")

values = ('Deep Learning',
          'Ian Goodfellow et al.',
          775,
          datetime(2016, 11, 18).timestamp())

conn.execute("""INSERT INTO books VALUES (?, ?, ?, ?)""", values)

r = conn.execute("""SELECT * FROM books""")
print(r.fetchall())


from acre.loops import Loops
from acre.ast_to_json import file_to_dict

import pytest

def test_while_single():
	ast_dict = file_to_dict('tests/c_files/single_while.c')
	l = Loops(ast_dict)
	assert l.get_nested_level('While') == 1

def test_while_nested():
	ast_dict = file_to_dict('tests/c_files/nested_while.c')
	l = Loops(ast_dict)
	assert l.get_nested_level('While') == 4

def test_while_complex():
	ast_dict = file_to_dict('tests/c_files/complex_while.c')
	l = Loops(ast_dict)
	assert l.get_nested_level('While') == 5


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

## This file is part of fb-archive.

## fb-archive is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.

## fb-archive is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.

## You should have received a copy of the GNU General Public License
## along with fb-archive.  If not, see <http://www.gnu.org/licenses/>.

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from constants import *

class ConcertsTableModel(QAbstractTableModel):
    def __init__(self, parent, headerdata):
        super(QAbstractTableModel, self).__init__()
        self.parent = parent
        self.headerdata = headerdata
        self.data = []

    def flags(self, index):
        return Qt.ItemIsEnabled | Qt.ItemIsSelectable

    def data(self, index, role):
        if not index.isValid():
            return QVariant()
        if role == Qt.DisplayRole:
            if index.column() in [COLUMN_DATE_FROM, COLUMN_DATE_TO]:
                return QVariant(self.data[index.row()][index.column()].strftime('%d.%m.%Y'))
            # Show multiline note as one line with 3 dots
            elif index.column() == COLUMN_NOTE:
                text = self.data[index.row()][index.column()]
                if (text != None) and (text.count('\n') > 0):
                    text = text[:text.find('\n')] + '...'
                return QVariant(text)
            else:
                return QVariant(self.data[index.row()][index.column()])
        if role == Qt.ToolTipRole:
            if index.column() in [COLUMN_WORKS, COLUMN_SOLOISTS, COLUMN_DIRIGENTS, COLUMN_CHOIRS]:
                text = self.data[index.row()][index.column()]
                if text != None:
                    QToolTip.showText(self.parent.cursor().pos(), text.replace(', ', '\n'))
            elif index.column() == COLUMN_NOTE:
                text = self.data[index.row()][index.column()]
                if text != None:
                    QToolTip.showText(self.parent.cursor().pos(), text)
        return QVariant()

    def headerData(self, col, orientation, role):
        # horizontal
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            return QVariant(self.headerdata[col])
        else:
            return QVariant()

    def rowCount(self, parent=QModelIndex()):
        return len(self.data)

    def columnCount(self, parent=QModelIndex()):
        return len(self.headerdata)

    def addRow(self, row):
        self.data.append(row)

    def clear(self):
        self.beginResetModel()
        self.data = []
        self.endResetModel()

    def get_item_data(self, index, column):
        return self.data[index.row()][column]

    def removeRow(self, row, parent=QModelIndex()):
        """
        Remove just one row
        """
        self.beginRemoveRows(parent, row, row)
        self.data.pop(row)
        self.endRemoveRows()

# End of concertstablemodel.py


import sys
input = sys.stdin.readline
def n_int():
    return int(input())

def n_str():
    return input()

def map_int():
    return map(int, input().split())

def n_list():
    return list(map(int, input().split()))

def n_lislis(n):
    a = []
    for _ in range(n):
        a.append(list(map(int, input().split())))
    return a

import sys
sys.setrecursionlimit(10**7)
h, w= map_int()

c = []
for _ in range(h):
    c.append(input())

for i in range(h):
    for j in range(w):
        if c[i][j] =='S':
            y0, x0 = (i,j)
            break

visited = [[-1]*w for _ in range(h)]
from collections import deque
def bfs(y0, x0):
    visited = [[-1]*w for _ in range(h)]
    visited[y0][x0] = 0
    q =deque()
    q.append([y0,x0])

    while(len(q) > 0):
        y, x = q.popleft()
        for dy, dx in [[-1, 0], [1, 0], [0,-1], [0,1]]:
            ny , nx = y + dy, x+dx
            if ny < 0 or ny >=h or nx<0 or nx >=w:
                continue
            if visited[ny][nx] != -1 or c[ny][nx] == '#' or c[ny][nx] == 'S':
                continue
            visited[ny][nx] = visited[y][x] + 1
            q.append([ny,nx])

    return visited

for dy1, dx1 in [[-1, 0], [1, 0], [0,-1], [0,1]]:
    for dy2, dx2 in [[-1, 0], [1, 0], [0,-1], [0,1]]:
        if (dy1 == dy2) and (dx1 == dx2):
            continue
        ny1, nx1 = y0 + dy1, x0 + dx1
        ny2, nx2 = y0 + dy2, x0 + dx2
        if ny1 < 0 or ny1 >=h or nx1 < 0 or nx1 >= w or ny2 < 0 or ny2 >=h or nx2 < 0 or nx2 >= w:
            continue
        if c[ny1][nx1] =='#' or c[ny2][nx2] == '#':
            continue
        visited = bfs(ny1, nx1)
        if visited[ny1][nx1] != -1 and visited[ny2][nx2] != -1:
            print('Yes')
            exit()
print('No')


"""
显示二维表数据(QTableView控件)

对于QTableView控件，它的数据源是Model

需要创建QTableView实例和一个数据源(Model),然后将两者关联
MVC：Model  Viewer  Controller
MVC的目的是将后端的数据和前端页面的耦合度降低

"""
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

class TableView(QWidget):
    def __init__(self):
        super(TableView, self).__init__()
        # 设置窗口标题
        self.setWindowTitle("QTableView表格视图控件演示")
        # 设置窗口尺寸
        self.resize(500,300)
        # 创建QStandardItemModel对象  4行3列
        self.model = QStandardItemModel(4,3)
        # 设置字段
        self.model.setHorizontalHeaderLabels(['id','姓名','年龄'])

        # 创建QTableView控件
        self.tableview = QTableView()

        # 关联模型
        self.tableview.setModel(self.model)

        # 添加数据

        item11 = QStandardItem('10')
        itme12 = QStandardItem('杰克')
        item13 = QStandardItem('18')
        #  第一行第一列
        self.model.setItem(0,0,item11)
        #  第一行第二列
        self.model.setItem(0,1,itme12)
        #  第一行第三列
        self.model.setItem(0,2,item13)

        item31 = QStandardItem('99')
        itme32 = QStandardItem('酒桶')
        item33 = QStandardItem('21')
        #  第一行第一列
        self.model.setItem(2, 0, item31)
        #  第一行第二列
        self.model.setItem(2, 1, itme32)
        #  第一行第三列
        self.model.setItem(2, 2, item33)

        # 创建垂直布局
        layout = QVBoxLayout()

        # 把控件添加到布局里
        layout.addWidget(self.tableview)

        # 应用于垂直布局
        self.setLayout(layout)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    table = TableView()
    table.show()
    sys.exit(app.exec_())


input_file = open('C:\\Users\\shenyou\\Desktop\\bioinfo\\krother-python-for-biologists-e47cf55735c7\\sequence.gb')
output_file = open('C:\\Users\\shenyou\\Desktop\\bioinfo\\krother-python-for-biologists-e47cf55735c7\\gbout.fasta', 'w')
flag = 0
for line in input_file:
	if line[:9] == 'ACCESSION':
		AC = line.split()[1].strip()
		print(AC)
	if line[:6] == 'SOURCE':
		sp1 = line.split()[1].strip()
		sp2 = line.split()[2].strip()
		output_file.write('>' + sp1 + ' ' + sp2 + '|' + AC + '\n')
	elif line[:6] == 'ORIGIN':
		flag = 1
	elif flag == 1:
		fields = line.split()
		if fields !=[]:
			seq = ''.join(fields[1:])
			output_file.write(seq.upper() + '\n')
input_file.close()
output_file.close()


from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
import time

class Googlesearch:
    def __init__(self):
        self.PATH = "./chromedriver"
        self.driver = webdriver.Chrome(self.PATH)
        self.driver.get("https://google.com")
        self.search_company = "Google search"

        # ACTION
        time.sleep(3)
        self._close_google_privacy_modal()

    def _close_google_privacy_modal(self):
        """Close initial Google privacy modal window
        """
        WebDriverWait(self.driver, 5).until(
            EC.frame_to_be_available_and_switch_to_it((By.XPATH, "//iframe"))
        )
        WebDriverWait(self.driver, 5).until(
            EC.element_to_be_clickable(
                (By.XPATH, "//*[@id='introAgreeButton']/span"))
        ).click()

    def _search(self, search_phrase):
        """Search initial page or later one

        Args:
            search_keywords (string): Keywords to search
        """
        input_element = WebDriverWait(self.driver, 5).until(
            EC.visibility_of_element_located((By.NAME, "q")))
        input_element.clear()
        input_element.send_keys(search_phrase)
        input_element.send_keys(Keys.RETURN)
        assert "No results found." not in self.driver.page_source
        self.driver.implicitly_wait(10)

    def _scroll_to_bottom(self):
        """Scrolls the page to the bottom by pressing down key.
        """
        time.sleep(2)
        body = self.driver.find_element_by_css_selector('body')
        while self.driver.execute_script('return ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight - 2);') == False:
            body.send_keys(Keys.PAGE_DOWN)
        time.sleep(2)

    def _paginate(self):
        """Paginate to the next page

        Returns:
            boolean: True if paginated, False if there was no next pagination button and didn't paginate
        """
        try:
            next_button = WebDriverWait(self.driver, 5).until(
                EC.visibility_of_element_located((By.ID, "pnnext")))
            next_button.click()
            return True
        except:
            return False

    def _button_link(self):
        """Get the link to the button of the website (my chromedriver browser is in Polish, change "Strona" for your language)

        Returns:
            string: link to the website
        """
        try:
            details_buttons = WebDriverWait(self.driver, 5).until(
                EC.presence_of_all_elements_located((By.CLASS_NAME, "ab_button")))

            for item in details_buttons:
                if item.text == "Strona":
                    return item.get_attribute("href")
        except:
            return None

        return None

    def _get_lite_search_results(self):
        """Get all the results in the page for particular search in the form of titles and links

        Returns:
            list: list of selenium objects. None if no results
        """
        try:
            self._scroll_to_bottom()
            full_results_list = WebDriverWait(self.driver, 5).until(
                EC.presence_of_all_elements_located((By.CLASS_NAME, "rc")))
            return full_results_list
        except:
            return None

    def _get_full_search_results(self):
        try:
            self._scroll_to_bottom()
            full_results_list = WebDriverWait(self.driver, 5).until(
                EC.presence_of_all_elements_located((By.CLASS_NAME, "g")))
            return full_results_list
        except:
            return None

    def _convert_lite_search_results_to_dict(self, full_results_list):
        """Converts results to a list of dictionaries

        Args:
            full_results_list (list): List of selenium objects

        Returns:
            list: List of dictionaries with links and titles of the search results
        """
        if full_results_list != None:
            list_link_title = []
            for result in full_results_list:
                link = result.find_element_by_tag_name("a")
                title = result.find_element_by_tag_name("h3")
                result_output = {
                    "link": link.get_attribute("href"),
                    "title": title.text
                }
                list_link_title.append(result_output)
            return list_link_title
        else:
            return None

    def get_search_results(self, search_phrase, pages=1):
        """Search a phrase and get it's results in the form of dictionary

        Args:
            search_phrase (string): Search phrase to insert in Google search bar. Don't need to be Google start page.
            pages (int, optional): Number of pages (pagination) to handle. Defaults to 1.

        Returns:
            dictionary: dictionary of results with titles and links
        """

        search_results = {
            "search-phrase": search_phrase,
            "search-result-list": []
        }

        self._search(search_phrase)

        for page in range(0, pages):
            result_temp = self._get_lite_search_results()
            result = self._convert_lite_search_results_to_dict(result_temp)
            search_results["search-result-list"].extend(result)
            if page < pages - 1:
                if self._paginate() == False:
                    break

        return search_results

    def get_website_link(self):
        """Get link to the company website

        Returns:
            string: Link to the website
        """
        button_link = self._button_link()
        return button_link

    def get_full_page_in_text(self, search_phrase, pages=1):
        """Search for an item, paginate if you wish and get the text from the search results.

        Args:
            search_phrase (string): Search phrase to insert in Google search bar. Don't need to be Google start page.
            pages (int, optional): Number of pages (pagination) to handle. Defaults to 1.

        Returns:
            string: Text from all the pages paginated.
        """
        result_text = ""
        self._search(search_phrase)
        for page in range(0, pages):
            self._scroll_to_bottom()
            site_html = self.driver.find_element_by_tag_name("html")
            result_text += site_html.text
            if page < pages - 1:
                if self._paginate() == False:
                    break

        return result_text

    def get_page_source(self, search_phrase, pages=1):
        """Search for an item, paginate if you wish and get the source of all pages in the form of the text (it also includes JavaScript files).

        Args:
            search_phrase (string): Search phrase to insert in Google search bar. Don't need to be Google start page.
            pages (int, optional): Number of pages (pagination) to handle. Defaults to 1.

        Returns:
            string: Text of cource code of all the pages.
        """
        page_source_string = ""
        self._search(search_phrase)
        for page in range(0, pages):
            self._scroll_to_bottom()
            page_source_string += self.driver.page_source
            if page < pages - 1:
                if self._paginate() == False:
                    break

        return page_source_string

    def close(self):
        """Close Selenium driver
        """
        self.driver.quit()


from pprint import pprint
#from oslo.config import cfg
from oslo_config import cfg
#import oslo.messaging as om
import oslo_messaging as om
import time

##Invoke "get_transport". This call will set default Configurations required to Create Messaging Transport
#transport = om.get_transport(cfg.CONF)

##Set/Override Configurations required to Create Messaging Transport
#cfg.CONF.set_override('rabbit_host', '192.168.56.101')
#cfg.CONF.set_override('rabbit_port', 5672)
#cfg.CONF.set_override('username', 'admin')
#cfg.CONF.set_override('password', 'hpinvent')
#cfg.CONF.set_override('rabbit_login_method', 'AMQPLAIN')
#cfg.CONF.set_override('rabbit_virtual_host', '/')
#cfg.CONF.set_override('rpc_backend', 'rabbit')

##Check the Configurations
#res = [{k:v} for k, v in cfg.CONF.iteritems()]
#pprint(res)

##Create Messaging Transport
transport = om.get_transport(cfg.CONF)
##Create Target (Exchange, Topic and Server to listen on)
target = om.Target(topic='testme', server='127.0.0.1')

##Create EndPoint
class TestEndpoint(object):
    def test_method1(self, ctx, arg):
        res = "Result from test_method1 " + str(arg)
        print(res)
        return res
    def test_method2(self, ctx, arg):
        res = "Result from test_method2 " + str(arg)
        print(res)
        return res

##Create EndPoint List
endpoints = [TestEndpoint(),]

##Create RPC Server
server = om.get_rpc_server(transport, target, endpoints, executor='blocking')
##Start RPC Server
try:
    server.start()
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    print("Stopping server")

server.stop()
server.wait()


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

from collections import OrderedDict

from brainpy import backend
from brainpy.backend import ops
from brainpy.simulation import utils
from .dynamic_system import DynamicSystem
from .neu_group import NeuGroup
from .syn_conn import SynConn

__all__ = [
    'Network',
]

class Network(object):
    """The main simulation controller in ``BrainPy``.

    ``Network`` handles the running of a simulation. It contains a set
    of objects that are added with `add()`. The `run()` method actually
    runs the simulation. The main loop runs according to user add orders.
    The objects in the `Network` are accessible via their names, e.g.
    `net.name` would return the `object`.
    """

    def __init__(self, *args, show_code=False, **kwargs):
        # record the current step
        self.t_start = 0.
        self.t_end = 0.

        # store all nodes
        self.all_nodes = OrderedDict()

        # store the step function
        self.run_func = None
        self.show_code = show_code

        # add nodes
        self.add(*args, **kwargs)

        # driver
        self.driver = backend.get_net_driver()(target=self)

    def __getattr__(self, item):
        if item in self.all_nodes:
            return self.all_nodes[item]
        else:
            return super(Network, self).__getattribute__(item)

    def _add_obj(self, obj, name=None):
        # 1. check object type
        if not isinstance(obj, DynamicSystem):
            raise ValueError(f'Unknown object type "{type(obj)}". '
                             f'Currently, Network only supports '
                             f'{NeuGroup.__name__} and {SynConn.__name__}.')
        # 2. check object name
        name = obj.name if name is None else name
        if name in self.all_nodes:
            raise KeyError(f'Name "{name}" has been used in the network, '
                           f'please change another name.')
        # 3. add object to the network
        self.all_nodes[name] = obj

    def add(self, *args, **kwargs):
        """Add object (neurons or synapses) to the network.

        Parameters
        ----------
        args
            The nameless objects.
        kwargs
            The named objects, which can be accessed by `net.xxx`
            (xxx is the name of the object).
        """
        for obj in args:
            self._add_obj(obj)
        for name, obj in kwargs.items():
            self._add_obj(obj, name)

    def run(self, duration, inputs=(), report=False, report_percent=0.1):
        """Run the simulation for the given duration.

        This function provides the most convenient way to run the network.
        For example:

        Parameters
        ----------
        duration : int, float, tuple, list
            The amount of simulation time to run for.
        inputs : list, tuple
            The receivers, external inputs and durations.
        report : bool
            Report the progress of the simulation.
        report_percent : float
            The speed to report simulation progress.
        """
        # preparation
        start, end = utils.check_duration(duration)
        dt = backend.get_dt()
        ts = ops.arange(start, end, dt)

        # build the network
        run_length = ts.shape[0]
        format_inputs = utils.format_net_level_inputs(inputs, run_length)
        self.run_func = self.driver.build(duration=duration,
                                          formatted_inputs=format_inputs,
                                          show_code=self.show_code)

        # run the network
        res = utils.run_model(self.run_func, times=ts, report=report, report_percent=report_percent)

        # end
        self.t_start, self.t_end = start, end
        for obj in self.all_nodes.values():
            if obj.mon.num_item > 0:
                obj.mon.ts = ts
        return res

    @property
    def ts(self):
        """Get the time points of the network.
        """
        return ops.arange(self.t_start, self.t_end, backend.get_dt())

    def schedule(self):
        """Network scheduling in a network.
        """
        for node in self.all_nodes.values():
            for key in node.schedule():
                yield f'{node.name}.{key}'


import math
from collections import deque

class Solution(object):
    @staticmethod
    def oranges_rotting(grid):
        rotting_time = 0
        m, n = len(grid), len(grid[0])
        direction_list = [0, 1, 0, -1, 0]  # up, right, down, left

        r_list = []
        r_apple = deque([])
        count_flesh_apple = 0
        for r in range(m):
            for c in range(n):
                if grid[r][c] == 2:
                    r_apple.append((r, c))
                elif grid[r][c] == 0:
                    continue
                else:
                    grid[r][c] = -1  # Marked as not processed yet!
                    count_flesh_apple += 1
        r_list.append(r_apple)

        # check is have rotten apple
        how_many_rotten = len(r_apple)
        if how_many_rotten == 0 and count_flesh_apple == 0:
            return 0

        for r_q in r_list:
            rotting_time += 1
            temp_q = deque([])
            while r_q:
                r, c = r_q.popleft()
                for i in range(4):
                    # check this block surrounding value
                    nr = r + direction_list[i]
                    nc = c + direction_list[i + 1]

                    # check is in matrix and already process
                    if nr < 0 or nr == m or nc < 0 or nc == n or grid[nr][nc] != -1:
                        continue

                    # deal with block
                    grid[nr][nc] = 2
                    count_flesh_apple -= 1

                    # append not process block index into queue
                    temp_q.append((nr, nc))
            if len(temp_q) >= 1:
                r_list.append(temp_q)

        if count_flesh_apple >= 1:
            return -1
        else:
            return rotting_time - 1

if __name__ == '__main__':
    run_test = Solution()
    """
    input_grid = [
        [2, 1, 1],
        [1, 1, 0],
        [0, 1, 2]
    ]
    """
    """
    input_grid = [
        [2, 0]
    ]
    """

    input_grid = [[1]]

    print(run_test.oranges_rotting(input_grid))