import ast
import importlib
import os
import sys
import uuid

from tensorflow.python.platform import flags
from tensorflow.python.util import tf_inspect

FLAGS = flags.FLAGS
flags.DEFINE_string(
    'wrapped_tpu_test_module_relative', None,
    'The Python-style relative path to the user-given test. If test is in same '
    'directory as BUILD file as is common, then "test.py" would be ".test".')
flags.DEFINE_string('test_dir_base',
                    os.environ.get('TEST_UNDECLARED_OUTPUTS_DIR'),
                    'GCS path to root directory for temporary test files.')
flags.DEFINE_string(
    'bazel_repo_root', 'tensorflow/python',
    'Substring of a bazel filepath beginning the python absolute import path.')

# List of flags which all TPU tests should accept.
REQUIRED_FLAGS = ['tpu', 'zone', 'project', 'model_dir']

def maybe_define_flags():
  """Defines any required flags that are missing."""
  for f in REQUIRED_FLAGS:
    try:
      flags.DEFINE_string(f, None, 'flag defined by test lib')
    except flags.DuplicateFlagError:
      pass

def set_random_test_dir():
  """Pick a random GCS directory under --test_dir_base, set as --model_dir."""
  path = os.path.join(FLAGS.test_dir_base, uuid.uuid4().hex)
  FLAGS.set_default('model_dir', path)

def calculate_parent_python_path(test_filepath):
  """Returns the absolute import path for the containing directory.

  Args:
    test_filepath: The filepath which Bazel invoked
      (ex: /filesystem/path/tensorflow/tensorflow/python/tpu/tpu_test)

  Returns:
    Absolute import path of parent (ex: tensorflow.python.tpu).

  Raises:
    ValueError: if bazel_repo_root does not appear within test_filepath.
  """
  # We find the last occurrence of bazel_repo_root, and drop everything before.
  split_path = test_filepath.rsplit(FLAGS.bazel_repo_root, 1)
  if len(split_path) < 2:
    raise ValueError(
        f'Filepath "{test_filepath}" does not contain repo root "{FLAGS.bazel_repo_root}"'
    )

  path = FLAGS.bazel_repo_root + split_path[1]

  # We drop the last portion of the path, which is the name of the test wrapper.
  path = path.rsplit('/', 1)[0]

  # We convert the directory separators into dots.
  return path.replace('/', '.')

def import_user_module():
  """Imports the flag-specified user test code.

  This runs all top-level statements in the user module, specifically flag
  definitions.

  Returns:
    The user test module.
  """
  return importlib.import_module(FLAGS.wrapped_tpu_test_module_relative,
                                 calculate_parent_python_path(sys.argv[0]))

def _is_test_class(obj):
  """Check if arbitrary object is a test class (not a test object!).

  Args:
    obj: An arbitrary object from within a module.

  Returns:
    True iff obj is a test class inheriting at some point from a module
    named "TestCase". This is because we write tests using different underlying
    test libraries.
  """
  return (tf_inspect.isclass(obj)
          and 'TestCase' in (p.__name__ for p in tf_inspect.getmro(obj)))

module_variables = vars()

def move_test_classes_into_scope(wrapped_test_module):
  """Add all test classes defined in wrapped module to our module.

  The test runner works by inspecting the main module for TestCase classes, so
  by adding a module-level reference to the TestCase we cause it to execute the
  wrapped TestCase.

  Args:
    wrapped_test_module: The user-provided test code to run.
  """
  for name, obj in wrapped_test_module.__dict__.items():
    if _is_test_class(obj):
      module_variables['tpu_test_imported_%s' % name] = obj

def run_user_main(wrapped_test_module):
  """Runs the "if __name__ == '__main__'" at the bottom of a module.

  TensorFlow practice is to have a main if at the bottom of the module which
  might call an API compat function before calling test.main().

  Since this is a statement, not a function, we can't cleanly reference it, but
  we can inspect it from the user module and run it in the context of that
  module so all imports and variables are available to it.

  Args:
    wrapped_test_module: The user-provided test code to run.

  Raises:
    NotImplementedError: If main block was not found in module. This should not
      be caught, as it is likely an error on the user's part -- absltest is all
      too happy to report a successful status (and zero tests executed) if a
      user forgets to end a class with "test.main()".
  """
  tree = ast.parse(tf_inspect.getsource(wrapped_test_module))

  # Get string representation of just the condition `__name == "__main__"`.
  target = ast.dump(ast.parse('if __name__ == "__main__": pass').body[0].test)

  # `tree.body` is a list of top-level statements in the module, like imports
  # and class definitions. We search for our main block, starting from the end.
  for expr in reversed(tree.body):
    if isinstance(expr, ast.If) and ast.dump(expr.test) == target:
      break
  else:
    raise NotImplementedError(
        f'Could not find `if __name__ == "main":` block in {wrapped_test_module.__name__}.'
        )

  # expr is defined because we would have raised an error otherwise.
  new_ast = ast.Module(body=expr.body, type_ignores=[])  # pylint:disable=undefined-loop-variable
  exec(  # pylint:disable=exec-used
      compile(new_ast, '<ast>', 'exec'),
      globals(),
      wrapped_test_module.__dict__,
  )

if __name__ == '__main__':
  # Partially parse flags, since module to import is specified by flag.
  unparsed = FLAGS(sys.argv, known_only=True)
  # Test filters from bazel's --test_filter flag are passed via the
  # TESTBRIDGE_TEST_ONLY environment variable. This wrapper script is typically
  # run from within another test case handler that doesn't actually hold the
  # user test cases. So, in oder to make --test_filter work correctly, the
  # outer test case needs to hide TESTBRIDGE_TEST_ONLY and we need to re-expose
  # it here. To do this, the outer test case stores the value in
  # SAVED_TESTBRIDGE_TEST_ONLY which we can use to set TESTBRIDGE_TEST_ONLY in
  # this local context.
  # The same holds for test sharding which is enabled through the num_shards
  # attribute in the test rule. For test sharding, the two key variables are
  # TEST_SHARD_INDEX and TEST_TOTAL_SHARDS.
  saved_test_filter = os.getenv('SAVED_TESTBRIDGE_TEST_ONLY')
  existing_test_filter = os.getenv('TESTBRIDGE_TEST_ONLY')
  if saved_test_filter and not existing_test_filter:
    os.environ['TESTBRIDGE_TEST_ONLY'] = saved_test_filter
  user_module = import_user_module()
  saved_shard_index = os.getenv('SAVED_TEST_SHARD_INDEX')
  existing_shard_index = os.getenv('TEST_SHARD_INDEX')
  if saved_shard_index and not existing_shard_index:
    os.environ['TEST_SHARD_INDEX'] = saved_shard_index
  saved_total_shards = os.getenv('SAVED_TEST_TOTAL_SHARDS')
  existing_total_shards = os.getenv('TEST_TOTAL_SHARDS')
  if saved_total_shards and not existing_total_shards:
    os.environ['TEST_TOTAL_SHARDS'] = saved_total_shards
  maybe_define_flags()
  # Parse remaining flags.
  FLAGS(unparsed, known_only=True)
  set_random_test_dir()

  move_test_classes_into_scope(user_module)
  run_user_main(user_module)


from flask import Flask, jsonify, request
from test import  test

app = Flask(__name__)

def get_prediction(image_bytes):
    prediction = test(image_path=image_bytes, deploy=True)
    return prediction

@app.route('/predict', methods=['POST'])
def predict():
    if request.method == 'POST':
        file = request.files['file']
        img_bytes = file.read()
        prediction = get_prediction(image_bytes=img_bytes)
        return jsonify({'Pokemon': prediction})

if __name__ == '__main__':
    app.run()


#!/usr/bin/env python
# encoding: utf-8
"""
Creates a new sound table from random chunks of a soundfile.

"""
from pyo import *
import random, os

s = Server(duplex=0).boot()

path = "../snds/baseballmajeur_m.aif"
dur = sndinfo(path)[1]

t = SndTable(path, start=0, stop=1)
amp = Fader(fadein=0.005, fadeout=0.005, dur=0, mul=0.4).play()
a = Looper(t, pitch=[1.,1.], dur=t.getDur(), xfade=5, mul=amp).out()

def addsnd():
    start = random.uniform(0, dur*0.7)
    duration = random.uniform(.1, .3)
    pos = random.uniform(0.05, t.getDur()-0.5)
    cross = random.uniform(0.04, duration/2)
    t.insert(path, pos=pos, crossfade=cross, start=start, stop=start+duration)

def delayed_generation():
    start = random.uniform(0, dur*0.7)
    duration = random.uniform(.1, .3)
    t.setSound(path, start=start, stop=start+duration)
    for i in range(10):
        addsnd()
    a.dur = t.getDur()
    a.reset()
    amp.play()

caller = CallAfter(function=delayed_generation, time=0.005).stop()
def gen():
    amp.stop()
    caller.play()

gen()

s.gui(locals())


# Get json files from train.txt and test.txt from MJ Dataset
import os
import random
import argparse
import json

'''
Get new train/test lists from original one

Args:
    txt_file: path to the annotation txt file of the original mjdataset
    num: number of trainging/test images you want to use
    prob: probability to continue

Return:
    A list contains the paths to the images/data you select.
    The length of the list is the same with the number parameter.
'''
def get_selected_list(txt_file, num, prob):
    path_list = []
    cnt = 0
    with open(txt_file, 'r', encoding='ascii') as f:
        line = f.readline()
        while line:
            lines = line.split(' ')
            t = random.randint(0, 100)
            if t <= 100*prob:
                line = f.readline()
                continue
            cnt += 1
            if cnt >= num:
                break
            path_list.append(lines[0][2:])

            line = f.readline()
    return path_list

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--datadir', required=True, help='path to dataset')
    parser.add_argument('--train_num', required=True, help='train data number')
    parser.add_argument('--test_num', required=True, help='test data number')
    parser.add_argument('--prob', default=0.5, help='probability for data selection method to continue')
    opt = parser.parse_args()

    img_pathlist_train = get_selected_list(os.path.join(opt.datadir,'annotation_train.txt'), int(opt.train_num), float(opt.prob))
    img_pathlist_test = get_selected_list(os.path.join(opt.datadir,'annotation_test.txt'), int(opt.test_num), float(opt.prob))
#     print(len(img_pathlist_train))
#     print(len(img_pathlist_test))
    with open(os.path.join(opt.datadir,'train_new.json'), 'w') as file:
        json.dump(img_pathlist_train, file)
    with open(os.path.join(opt.datadir, 'test_new.json'), 'w') as file:
        json.dump(img_pathlist_test, file)

if __name__ == '__main__':
    main()


'''
All the functions necessary to parse and store to the BD
'''
from tqdm import tqdm
import pandas as pd
import numpy as np
import sys

import sqlite3 as sql
import time
from datetime import datetime

def c_geo_point_2d_FLOAT(x):
	out = []
	for i in x.split(','):
	    try:
	        out.append(float(i))
	    except ValueError:
	        return [np.nan,np.nan]
	        raise(ValueError(' x='+str(x)))
	return out

'''
read the file of geo positions of sensors
and create a BD SQLite maned Traffic.db
'''
def modeBD():
	conn = sql.connect('Traffic.db')
	converters = {'geo_point_2d':c_geo_point_2d_FLOAT }
	positions = pd.read_csv('data/referentiel-comptages-routiers.csv',delimiter=';',converters=converters,chunksize=50000)

	for chunk in tqdm(positions):
		try:
			chunk=chunk.assign(id_arc_tra=chunk.id_arc_tra.apply(lambda x: 0 if np.isnan(x) else int(x)))
			chunk=chunk.assign(lat=chunk.geo_point_2d.apply(lambda x:x[0]))
			chunk=chunk.assign(lon=chunk.geo_point_2d.apply(lambda x:x[1]))
			chunk=chunk[['id_arc_tra','lat','lon']]
			chunk.to_sql('Capteur',con=conn,if_exists='replace')
		except ValueError:
			print("Erreur:Database")
			break
	conn.commit()
	#verifBD(conn)

'''
print the content of the traffic sensors BD
'''
def verifBD(conn):
	cur = conn.cursor()
	cur.execute('SELECT * FROM Capteur')
	for i in cur.fetchall():
	    print(i)
'''
print the content of the traffic sensors BD without nul values
'''
def verifBD_NULL(conn):
	cur = conn.cursor()
	#Que faire des capteur qui n'ont pas de position?
	cur.execute('SELECT * FROM Capteur WHERE lat is NULL or lon is NULL')

	#print(cur.description)
	for i in cur.fetchall():
	    print(i)

'''
return the str of the file correspondig to the Year , month gived
'''
def getPathFile(name ,year ,month):
	strYearMonth=""
	if(month<10):
		strYearMonth=str(year)+str(0)+str(month)
	else:
		strYearMonth=str(year)+str(month)

	folderName = str(year)+"_paris_donnees_trafic_capteurs"
	fileName = name+strYearMonth+'.txt'

	pathName = 'traffic/'+folderName+'/'+fileName

	return pathName

FLAG_BLACK =4
FLAG_RED =3
FLAG_YELLOW =2
FLAG_GREEN =1

def getStrColor(color):
	if(color==FLAG_BLACK):
		return "BLACK"
	elif(color==FLAG_RED):
		return "RED"
	elif(color==FLAG_YELLOW):
		return "YELLOW"
	else:
		return "GREEN"

'''
cluster values of debit and taux
'''
def findFlag(debit,taux):

	if(taux>35):
		return FLAG_BLACK
	elif(taux>25):
		return FLAG_RED
	elif(taux>10):
		return FLAG_YELLOW
	else:
		return FLAG_GREEN

'''
return the value of the year inside the x :str   | 2017-10-15   -> 2015
'''
def parseYear(x):
	return int(x.split('-')[0])

'''
return the value of the hour inside the x :str   | 23-01-12   -> 23
'''
def parseHour(x):
	return int(x.split(':')[0])
	'''
	tab= x.split(':')
	try:
		return int(tab[0])
	except ValueError:
		return np.nan
	'''

'''
return number of the day in the week , monday=0 ...
'''
def getDay_DATE(date):
	tab= date.split("-")
	year = int(tab[0])
	month = int(tab[1])
	day = int(tab[2])
	return datetime(year,month,day).weekday()

'''
return number of the week in the year
'''
def getWeek_DATE(date):
	tab= date.split("-")
	year = int(tab[0])
	month = int(tab[1])
	day = int(tab[2])
	return  datetime(year,month,day).isocalendar()[1]

'''
return a tuple of number of day and number of week  | date is a str of date : 2017-04-29
'''
def getTupleWeek_Day(date):
	tab= date.split("-")
	year = int(tab[0])
	month = int(tab[1])
	day = int(tab[2])
	mydate = datetime(year,month,day)
	return (mydate.weekday() , mydate.isocalendar()[1])


import zipfile
import os

folder_path = 'C:\\Users\\qw2\\Desktop\\Fire_Scars_Archive'
save_path = 'C:\\Users\\qw2\\Desktop\\Fire_Scars_Archive\\shapefiles'

for file in os.scandir(folder_path):
    if file.name.split('.')[-1] == 'zip':
        zip_path = os.path.join(folder_path, file.name)
        with zipfile.ZipFile(zip_path,"r") as zip_ref:
            zip_ref.extractall(save_path)


import os
import torch
import re
import time
import argparse
from transformers import AutoModelForCausalLM, GPT2Config, AutoTokenizer, GPT2LMHeadModel
from transformers_neuronx.module import save_pretrained_split
from transformers_neuronx.gpt2.model import GPT2ForSampling
from transformers_neuronx.config import NeuronConfig, QuantizationConfig

os.environ['NEURON_CC_FLAGS'] = '--model-type=transformer-inference'
parser = argparse.ArgumentParser()
parser.add_argument("--bs", type=int, default=8)
parser.add_argument("--seqlen", type=int, default=64)
parser.add_argument("--tp", type=int, default=2)
args = parser.parse_args()

model_name = 'gpt2-ft'

print('Creating the Neuron model ...')
model_neuron = GPT2ForSampling.from_pretrained(
    f'./{model_name}-split',
    batch_size=args.bs,
    tp_degree=args.tp,
    n_positions=args.seqlen,
    amp='f32',
)
print(f"Compiling the Neuron model for batch_size={args.bs}, sequence_length={args.seqlen}, tp_degree={args.tp} ...")
model_neuron.to_neuron()

tokenizer = AutoTokenizer.from_pretrained('gpt2')
tokenizer.pad_token_id = tokenizer.eos_token_id

def sample(model_neuron, text, seqlen):
    encoded_input = tokenizer(text, return_tensors='pt', padding="longest")
    input_ids = encoded_input.input_ids
    input_length = input_ids.shape[1]
    new_tokens = seqlen - input_length

    print(f'input prompt length: {input_length}')
    print(f'generated tokens: {new_tokens}')

    start = time.time()
    model_neuron.reset()
    sample_output = model_neuron.sample(
        input_ids,
        sequence_length=seqlen,
        top_k=20
    )
    end = time.time()

    print('\nGenerated outputs:\n')
    for result in [tokenizer.decode(tok, skip_special_tokens=True) for tok in sample_output]:
        m = re.search(r"(.*)\n", result)
        if m:
            print(m.group(1))
        else:
            print("<unknown>")

    throughput = args.bs*new_tokens / (end-start)
    latency = (end - start)
    print(f'\nthroughput: {throughput:.1f} tokens/sec')
    print(f'batch latency: {latency:.2f} s')

while True:
    try:
        prompt = input(f"\nEnter prompt (or CTRL-D to exit): ")
        text = [prompt for _ in range(args.bs)]
        print('\nRunning inference ...')
        sample(model_neuron, text, args.seqlen)
    except EOFError:
        print()
        break


"""main"""
def main():
    """main"""
    time = int(input()) # จำนวนครั้งที่บันทึกก่อนลดราคา
    pay = int(input()) # ราคาที่ใช้ได้กับโปรโมชัน
    givestamp = int(input()) # สแตมป์ที่ได้จากโปรฯ
    addstamp = int(input()) # จำนวนสแตมป์ที่สามารถใช้ลดราคา
    discount = int(input()) # ปริมาณราคาที่ลดให้
    stamp = 0
    world = [int(input()) for _ in range(time)] # บันทึกราคา
    for i in range(len(world)):
        if world[i] >= pay:
            count = world[i]
            while count >= pay:
                count -= pay
                stamp += givestamp
        while stamp >= addstamp:
            if i == len(world) - 1 or  world[i+1] == 0:
                break
            price = world[i+1] - discount
            world[i+1] = max(price, 0)
            stamp -= addstamp
    print(sum(world), stamp, sep="\n")

main()


class Vertex:
    """
    This represents an item.

    - Constructor Parameters

        :param item: :type any:
            This is the data which the vertex will represent.
    """

    def __init__(self, item, *args, **kwargs):
        self.neigbors = []
        self.edges = []
        self.item = item

    def __eq__(self, other):
        try:
            other.item
        except AttributeError:
            return False
        return self.item == other.item

    def __lt__(self, other):
        try:
            other.item
        except AttributeError:
            return False
        return self.item < other.item

    def __repr__(self):
        return '<Vertex ({})>'.format(self.item)

    @property
    def heaviest_edge(self):
        """
        Returns the edge connected to the vertex
        with the largest weight.
        """
        try:
            edge = max(self.edges)
        except ValueError:
            edge = None
        return edge

    def add_neighbor(self, other_vertex, edge):
        """
        This sets another vertex as a neighbor of this vertex.

        - Parameters

            :param other_vertex: :type Vertex:
                The other vertex to connect.
            :param edge: :type edge:
                The reference to the edge that connects the two vertices.
        """
        self.neigbors.append(other_vertex)
        self.edges.append(edge)

class Edge:
    """
    Represents a connection between edges.

    - Constructor Parameters

        :param vertex_1: :type Vertex:
            The first vertex of the edge.
        :param vertex_2: :type Vertex:
            The second vertex of the edge.
        :param weight: :type int:
            The initial weight of the edge. Defaults as 1.
    """

    def __init__(self, vertex_1, vertex_2, weight=1, *args, **kwargs):
        self.vertex_1 = vertex_1
        self.vertex_2 = vertex_2
        self.weight = 1
        vertex_1.add_neighbor(vertex_2, self)
        vertex_2.add_neighbor(vertex_1, self)

    def __eq__(self, other):
        if not isinstance(other, Edge):
            return False
        parallel, reverse = _get_parallels(other)
        return self.weight == other.weight and (parallel or reverse)

    def __lt__(self, other):
        if not isinstance(other, Edge):
            return False
        parallel, reverse = _get_parallels(other)
        return self.weight < other.weight and (parallel or reverse)

    def __repr__(self):
        return '<Edge ({}) | ({})>'.format(
            self.vertex_1.item, self.vertex_2.item)

    def get_vertices(self, reverse=False):
        """
        Returns the vertices in the edge as a tuple.

        - Parameters

            :param reverse: :type boolean:
                Defaults as False. If True, returns the 2nd vertex
                before the first.
        """
        return [(vertex_1, vertex_2), (vertex_2, vertex_1)][reverse]

    def _get_parallels(self, other):
        """
        A private helper function for getting reversed
        and non reversed comparisons of vertices.
        """
        parallel = (
            self.vertex_1 == other.vertex_1
            and self.vertex_2 == other.vertex_2
        )
        reverse = (
            self.vertex_1 == other.vertex_2
            and self.vertex_2 == other.vertex_1
        )
        return parallel, reverse

    def add_weight(self, weight=1):
        """
        Add weight to the edge.

        - Parameters

            :param weight: :type int:
                The value to add to the weight.
        """
        self.weight += weight

class MatchingGraph:
    """
    The graph proper. This holds the core methods for the matching.

    - Constructor Parameters

        :param x_set: :type list:
            The values received by this parameter are used as the items
            for the first set.
        :param y_set: :type list:
            The values received by this parameter are used as the items
            for the second set.
        :param x_vertex_class: :type type:
            The type of vertex that will be used to initialize the items
            from the first set as vertices. Defaults as Vertex.
        :param y_vertex_class: :type type:
            The type of vertex that will be used to initialize the items
            from the second set as vertices. Defaults as Vertex.
        :param edge_class: :type type:
            The type of edge that will be used to initialize the edge
            instances for the matching. Defaults as Edge.
        :param x_extra_vertex_initalization_values: :type dict:
            Defaults as an empty dictionary. Should the vertex
            class that will be used for the initialization of the
            first set need to accept additional constructor
            arguments, then they may be placed here. Preferably,
            the item of the vertex must be able to identify
            the key of the value.
        :param y_extra_vertex_initalization_values: :type dict:
            Defaults as an empty dictionary. Should the vertex
            class that will be used for the initialization of the
            second set need to accept additional constructor
            arguments, then they may be placed here. Preferably,
            the item of the vertex must be able to identify
            the key of the value.
        :param x_kwarg_extractor: :type method:
            Defaults as None. This is responsible for extracting
            kwargs from the x_extra_vertex_initalization_values.
            The method accepted here must be able to accept
            at least 2 values, which are a vertex's item, and the
            values from the intialization values for the X set.
        :param y_kwarg_extractor: :type method:
            Defaults as None. This is responsible for extracting
            kwargs from the y_extra_vertex_initalization_values.
            The method accepted here must be able to accept
            at least 2 values, which are a vertex's item, and the
            values from the intialization values for the Y set.
        according_to_x_set:
            Defaults as True. This only determines from which set
            should the matching comparison base from. Regardless
            of this setting, the same value will be returned because
            this only provides a minor change in the algorithm flow
            when it comes to optimally matching the data sets.
    """

    def __init__(
            self, x_set, y_set,
            x_set_vertex_class=Vertex,
            y_set_vertex_class=Vertex,
            edge_class=Edge,
            x_extra_vertex_initalization_values={},
            y_extra_vertex_initalization_values={},
            x_kwarg_extractor=None,
            y_kwarg_extractor=None,
            according_to_x_set=True,
            *args, **kwargs):
        self.x_set = x_set
        self.y_set = y_set
        self.x_set_vertex_class = x_set_vertex_class
        self.y_set_vertex_class = y_set_vertex_class
        self.edge_class = edge_class
        self.edges = []
        self.matches = []
        self.according_to_x_set = according_to_x_set
        self.vertex_attr_a = ['vertex_1', 'vertex_2'][according_to_x_set]
        self.vertex_attr_b = ['vertex_2', 'vertex_1'][according_to_x_set]
        intialization_args = (
            x_extra_vertex_initalization_values,
            y_extra_vertex_initalization_values,
            x_kwarg_extractor,
            y_kwarg_extractor
        )

        # The initialization lifecycle.
        self._initialize_vertices(*intialization_args)
        self._build_edges(*args, **kwargs)
        self.match(*args, **kwargs)

    @property
    def unique_weights(self):
        """
        Returns all the unique weights of all edges as a set.
        """
        return set([edge.weight for edge in self.edges])

    @property
    def matched_x_vertices(self):
        """
        Returns all the vertices from the x set that have been matched.
        """
        return [edge.vertex_1 for edge in self.matches]

    @property
    def matched_x_vertices(self):
        """
        Returns all the vertices from the y set that have been matched.
        """
        return [edge.vertex_2 for edge in self.matches]

    @property
    def unmatched_x_vertices(self):
        """
        Returns all the vertices from the x set that were not matched.
        """
        return [
            vertex for vertex in self.x_vertices
            if vertex not in self.matched_x_vertices
        ]

    @property
    def unmatched_y_vertices(self):
        """
        Returns all the vertices from the y set that were not matched.
        """
        return [
            vertex for vertex in self.y_vertices
            if vertex not in self.matched_y_vertices
        ]

    def _initialize_vertices(
            self,
            x_extra_vertex_initalization_values={},
            y_extra_vertex_initalization_values={},
            x_kwarg_extractor=None,
            y_kwarg_extractor=None):
        """
        Initialize vertices based on values received from constructor.
        """
        vertex_sets = ([],[])
        vertex_data = [
            (
                self.x_set,
                self.x_set_vertex_class,
                x_extra_vertex_initalization_values,
                x_kwarg_extractor
            ),
            (
                self.y_set,
                self.y_set_vertex_class,
                y_extra_vertex_initalization_values,
                y_kwarg_extractor
            )
        ]
        for index, data in enumerate(vertex_data):
            item_set, vertex_class, extra_values, extract = data
            for item in item_set:
                if extract:
                    extras = extract(item, extra_values)
                else:
                    extras = {}
                vertex_sets[index].append(vertex_class(item, **extras))
        self.x_vertices, self.y_vertices = vertex_sets

    def get_x_set_condition_values(self, x_vertex, *args, **kwargs):
        """
        An abstract method for setting up the values from the x_vertex
        that is necessary to evaluate a match.

        - Parameters

            :param x_vertex: :type Vertex:
                A vertex from the x_set.

        - Returns

            By default, this returns a dictionary in this structure:
                {'value': <the vertex>}

            This is always expected to return a dictionary.
        """
        return {'value': x_vertex}

    def get_y_set_condition_values(self, y_vertex, *args, **kwargs):
        """
        An abstract method for setting up the values from the y_vertex
        that is necessary to evaluate a match.

        - Parameters

            :param y_vertex: :type Vertex:
                A vertex from the y_set.

        - Returns

            By default, this returns a dictionary in this structure:
                {'value': <the vertex>}

            This is always expected to return a dictionary.
        """
        return {'value': y_vertex}

    def get_matching_arguments(self, x_vertex, y_vertex, *args, **kwargs):
        """
        An abstract method that collects all the values necessary
        to evaluate two vertices as a match.

        - Parameters

            :param x_vertex: :type Vertex:
                A vertex from the x_set.
            :param y_vertex: :type Vertex:
                A vertex from the y_set.

        - Returns

            This returns the results from get_x_set_condition_values and
            get_y_set_condition_values as a tupled pair.
        """
        x_conditions = (
            self.get_x_set_condition_values(x_vertex, *args, **kwargs))
        y_conditions = (
            self.get_y_set_condition_values(y_vertex, *args, **kwargs))
        return x_conditions, y_conditions

    def _check_match(self, x_vertex, y_vertex, *args, **kwargs):
        """
        A private method for checking if two vertices are a match.

        - Parameters:

            :param x_vertex: :type Vertex:
                A vertex from the x_set.
            :param y_vertex: :type Vertex:
                A vertex from the y_set.

        - Returns

            This returns
        """
        x_conditions, y_conditions = (
            self.get_matching_arguments(x_vertex, y_vertex, *args, **kwargs))
        conditions = self.get_conditions(x_conditions, y_conditions)
        is_match = self.assess_match(conditions, *args, **kwargs)
        compatibility = self.assess_compatibility(conditions, *args, **kwargs)
        return is_match, compatibility

    def get_conditions(self, x_conditions, y_conditions, *args, **kwargs):
        """
        An abstract method for setting up all the conditions
        needed to prove if a pair of vertices are a match.

        - Parameters

            :param x_conditions: :type dict:
                A dictionary of values from a vertex from the x_set
                that is necessary to compare it with a vertex from the
                y_set.
            :param y_conditions: :type dict:
                A dictionary of values from a vertex from the y_set
                that is necessary to compare it with a vertex from the
                x_set.

        - Returns

            This returns the evaluation of all conditions as
            a tuple of boolean values.
        """
        return (x_conditions['value'] == y_conditions['value'],)

    def assess_match(self, conditions, *args, **kwargs):
        """
        An abstract method for assessing a pair of vertices as
        a valid match.

        - Parameters

            :param condition: :type tuple:
                A tuple of boolean values.
        """
        return any(conditions)

    def assess_compatibility(self, conditions, *args, **kwargs):
        """
        An abstract method for counting the
        compatibility of a possible match.

        - Parameters

            :param condition: :type tuple:
                A tuple of boolean values.
        """
        return len([condition for condition in conditions if condition])

    def _build_edges(self, *args, **kwargs):
        """
        This edges all possible matches between the x_set and the y_set.
        """
        adherence = self.according_to_x_set
        x_vertices, y_vertices = self.x_vertices, self.y_vertices
        a_vertices, b_vertices = [
            (y_vertices, x_vertices), (x_vertices, y_vertices)][adherence]
        for vertex_a in a_vertices:
            for vertex_b in b_vertices:
                vertices = [
                    (vertex_b, vertex_a), (vertex_a, vertex_b)][adherence]
                is_match, compatibility = (
                    self._check_match(*vertices, *args, **kwargs))
                if is_match:
                    edge_args = vertices + (compatibility,)
                    self.edges.append(self.edge_class(*edge_args))

    def evaluate_match(self, vertex, *args, **kwargs):
        """
        An abstract method for assesing an edge as an optimal match.
        """
        optimal_match = vertex.heaviest_edge
        if optimal_match:
            self.matches.append(optimal_match)

    def match(self, *args, **kwargs):
        """
        An abstract method to assess the optimal matchings.
        """
        adherence = self.according_to_x_set
        vertices = [self.x_vertices, self.y_vertices][adherence]
        for vertex in vertices:
            self.evaluate_match(vertex, *args, **kwargs)
        return self.matches


import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0,10,0.1)
cos_x = np.cos(x)

plt.plot(x, cos_x)
plt.title('Cos')
plt.xlabel('x')
plt.ylabel('cos(x)')
plt.show()


class Solution:
    def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int:
        z=[nums[0]]
        x=1
        while(x!=n):
            for i in range(x,n):
                z.append(z[-1]+nums[i])
            z.append(nums[x])
            x+=1
        z.sort()
        return sum(z[left-1:right])

Leetcode Python/Range Sum of Sorted Subarray Sums.py


import cv2

# Capture the video from the default camera
webcam_video_stream = cv2.VideoCapture("../Videos/Compressed/Bella_Ciao.mp4")

face_detection_classifier = cv2.CascadeClassifier("../Models/haarcascades/haarcascade_frontalface_default.xml")

# Initialize the array varaible to hold all the face locations in the frame
all_face_locations = []

# loop through every frame in the video
while True:
    # get the current frame from the video stream as an image
    ret, current_frame = webcam_video_stream.read()

    # resize the current frame to 1/4 size to process faster
    current_frame_small = cv2.resize(current_frame, (0, 0), fx=0.25, fy=0.25)

    # detect all faces in the image
    all_face_locations = face_detection_classifier.detectMultiScale(current_frame_small)

    for index, current_face_location in enumerate (all_face_locations):

        x, y, width, height = current_face_location

        left_pos = x
        top_pos = y
        right_pos = x + width
        bottom_pos = y + height

        print("Found face {} at top: {}, right: {}, bottom: {}, left: {}".format(index + 1, top_pos, right_pos, bottom_pos, left_pos))

        cv2.rectangle(current_frame, (left_pos, top_pos), (right_pos, bottom_pos), (0, 0, 255), 2)

    cv2.imshow("Web-Cam Video", current_frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release the resources
webcam_video_stream.release()
cv2.destroyAllWindows()


# um professor quer sortear um dos quatro alunos para apagar o quadro
# programa que leia o nome dos alunos e escreva o nome do escolhido.
import random
a1 = input('Digite o nome do aluno 1: ')
a2 = input('Digite o nome do aluno 2: ')
a3 = input('Digite o nome do aluno 3: ')
a4 = input('Digite o nome do aluno 4: ')

print('ParabÃ©ns! O aluno sorteado Ã© {}'.format((random.choice([a1, a2, a3, a4]))))

# deu certo ðŸ¥³ (feito antes da aula com ajuda da documentaÃ§Ã£o da biblioteca)

# correÃ§Ã£o do guanabara

# from random import choice
# n1 = input('Primeiro aluno ')
# n2 = input('Segundo aluno ')
# n3 = input('Terceiro aluno ')
# n4 = input('Quarto aluno')
# lista = [n1, n2, n3, n4]
# escolhido = choice(lista)
# print('O aluno escolhido foi {}.'.format(escolhido))


"""
Module for representing simplex in n-dimensional space
"""
import math
import point as pt

# ======================================================================================================================
class Simplex:
    """
    Class represents simplex in n-dimensional space
    """
    def __init__(self, StartPoint, N, edge, F):
        """
        Constructor

        :param StartPoint: vector with initial point coordinates
        :param N: dimension - 1
        :param edge: initial simplex edge length
        :param F: function to be minimized
        """

        self.N = N
        self.F = F
        self.pnt = start_simplex(edge, StartPoint, N)
        self.ff = []  # function values at the vertices of the polyhedron
        for i in range(N + 1):
            self.ff.append(self.F(self.pnt[i].vector))

    def get_vertex(self, index):
        """
        Gets the vertex of the simplex at the given index.

        :param index: the index of the vertex of the simplex to get
        :return: the simplex vertex object at the specified index
        """

        return self.pnt[index]

    def get_dimension(self):
        """
        Gets dimension
        :return: dimension
        """

        return self.N
# ======================================================================================================================

def start_simplex(edge, StartPoint, N):
    """
    Creates a simplex in n-dimensional space

    :param edge: initial simplex edge length
    :param StartPoint: initial point
    :param N: dimension - 1
    :return: vector with simplex vertices coordinates
    """

    tnsq = edge / N / math.sqrt(2.0)  # these are formulas from Himmelblau
    n1 = math.sqrt(N + 1)
    d1 = tnsq * (n1 + N - 1)
    d2 = tnsq * (n1 - 1)
    r = [pt.Point(StartPoint, N)]  # each r[i] - Point of the polygon
    for i in range(1, N + 1):
        s = []
        for j in range(N):
            s.append(d2 + StartPoint[j])
        s[i - 1] = d1 + StartPoint[i - 1]
        r.append(pt.Point(s + StartPoint, N))
    return r
# ----------------------------------------------------------------------------------------------------------------------


import csv
import numpy as np
import matplotlib.pyplot as plt
import scipy.fft
import scipy.signal as signal

def file_to_signal_array(file_path):
    with open(file_path, mode='r') as file:
        csv_reader = csv.reader(file)
        next(csv_reader)
        signal = []
        for row in csv_reader:
            signal.append(float(row[1]))
    return np.array(signal)

csv_file = r'data/project1-1e-data.csv'
signal = file_to_signal_array(csv_file)

# Number of samples
N_samples = len(signal)

# Define the Dirichlet kernel in the frequency domain
n = 92 # the n in the Dirichlet kernel

# Define the h kernel
h_kernel = np.zeros(N_samples)
h_kernel[0] = -1
h_kernel[1] = 2
h_kernel[2] = -1

# Compute the Fourier transforms of the signal, Dirichlet kernel, and h kernel
signal_fft = scipy.fft.fft(signal)
dirichlet_kernel_fft = np.zeros(N_samples)
dirichlet_kernel_fft[int(N_samples/2-n-1):int(N_samples/2+n)] = 1
h_kernel_fft = scipy.fft.fft(h_kernel, N_samples)
dirichlet_kernel_fft = scipy.fft.fftshift(dirichlet_kernel_fft)

# Perform convolution in the frequency domain
convolution_dirichlet_fft = signal_fft * dirichlet_kernel_fft
convolution_h_fft = signal_fft * h_kernel_fft

# Compute the inverse Fourier transforms to get the convolution results
convolution_dirichlet = np.real(scipy.fft.ifft(convolution_dirichlet_fft))
convolution_h = np.real(scipy.fft.ifft(convolution_h_fft))

# Plotting
x_vals = np.linspace(0, 1, N_samples)

plt.figure(figsize=(12, 6))
plt.subplot(2, 2, 1)
plt.plot(x_vals, signal, color="blue", label="signal")
plt.title("Original signal")
plt.legend()

plt.subplot(2, 2, 2)
plt.plot(x_vals, signal, color="blue", label="signal")
plt.title("Original signal")
plt.legend()

plt.subplot(2, 2, 3)
plt.plot(x_vals, convolution_dirichlet, color="red", label="convolution")
plt.title("Convolution with Dirichlet kernel")
plt.legend()

plt.subplot(2, 2, 4)
plt.plot(x_vals, convolution_h, color="red", label="convolution")
plt.title("Convolution with h kernel")
plt.legend()

plt.tight_layout()
plt.show()


from distributed import Client

def main():
    scheduler_host = 'pinac31'

    # client = Client(cluster)
    # scheduler_address="tcp://134.58.41.100:8786"
    scheduler_address = f'{scheduler_host}:8786'
    client = Client(address=scheduler_address)
    client.shutdown()
    print("Shutting down client, its connected scheduler and workers...")

if __name__ == '__main__':
    main()


import cv2
import emilib
import time

camera = cv2.VideoCapture(0)

while True:
    ret, im = camera.read()

    ret, jpg = cv2.imencode(".jpg", im)

    msg = emilib.emi_msg(
        msgnum=1,
        data=jpg.tobytes(),
        ipaddr="127.0.0.1", # Change to the IP where server.py is in
        flag=emilib.emi_flag.EMI_MSG_MODE_BLOCK
    )

    ret = emilib.emi_msg_send(msg)

del(camera)


import streamlit as st
import pandas as pd
import punto_corte as pc

st.set_page_config(page_title=u"Resumen de datos",
                   page_icon=":ledger:",
                   layout="centered",
                   initial_sidebar_state="auto",
                   menu_items=None)

st.markdown(u"# Resumen de datos")

try:
    shared = st.session_state["shared"]
except:
    st.error(u"No hay archivos cargados.")
    st.stop()

try:
    puntaje = st.session_state["puntaje"]
except:
    st.error(u"No hay archivo de puntaje cargado.")
else:
    st.markdown(u"### Resumen de los puntajes")
    st.table(puntaje.describe())
    st.markdown(u"### Distribución acumulada de los puntajes")
    st.plotly_chart(pc.crear_cumdist(puntaje, "puntaje"))

try:
    items = st.session_state["items"]
except:
    st.error(u"No hay archivo de items cargado.")
else:
    st.markdown(u"### Resumen de los items")
    st.table(items.describe())
    st.markdown(u"### Distribución de dificultad")
    st.plotly_chart(pc.crear_cumdist(items, "items"))


from mypackage import FindBest
import numpy

eplus_run_path = './EnergyPlus/energyplus'
idf_path = '/root/cjw/1ZoneUncontrolled_win_test.idf'
output_dir = './result'
epjson_path = "/root/cjw/1ZoneUncontrolled_win_test.epJSON"

######################for SHGC or u_factor change################################
# parameter_key = ['WindowMaterial:SimpleGlazingSystem', 'SimpleWindow:DOUBLE PANE WINDOW', 'solar_heat_gain_coefficient']
# parameter_val_range = [0.25,0.75]

parameter_key = ['WindowMaterial:SimpleGlazingSystem', 'SimpleWindow:DOUBLE PANE WINDOW', 'u_factor']
parameter_val_range = [1.0,2.5]
slice_num = (parameter_val_range[1]-parameter_val_range[0])/20
best_val = parameter_val_range[0]
max_tmp = -100000
for parameter_val in numpy.arange(parameter_val_range[0],parameter_val_range[1]+slice_num,slice_num):
    fd = FindBest(idf_path=idf_path,output_dir=output_dir, epjson_path=epjson_path, eplus_run_path=eplus_run_path,parameter_key = parameter_key)
    if parameter_key[-1]=="'u_factor'":
        fd.u = parameter_val
    else:
        fd.SHGC=parameter_val
    fd.calculate_mean_temperature()
    if fd.MeanTemp>max_tmp:
        max_tmp = fd.MeanTemp
        best_val = parameter_val
print("**************************************\nBest ",parameter_key[-1]," is:",best_val)


# -*- coding: utf-8 -*-
"""Utility functions used for the Flask Processing Controller Interface"""
from http import HTTPStatus
from functools import wraps

import jsonschema
from flask import request

from config_db.sbi_client import SchedulingBlockDbClient

DB = SchedulingBlockDbClient()

def get_root_url():
    """Return the root URL for this resource."""
    # path = request.path
    # path = path[1:].split('/')
    # path = '/'.join(path[:2])
    # return request.url_root + path
    return request.url_root

def add_scheduling_block(config):
    """Adds a scheduling block to the database, returning a response object"""
    try:
        DB.add_sbi(config)
    except jsonschema.ValidationError as error:
        error_dict = error.__dict__
        for key in error_dict:
            error_dict[key] = error_dict[key].__str__()
        error_response = dict(message="Failed to add scheduling block",
                              reason="JSON validation error",
                              details=error_dict)
        return error_response, HTTPStatus.BAD_REQUEST
    response = dict(config=config,
                    message='Successfully registered scheduling block '
                            'instance with ID: {}'.format(config['id']))
    response['links'] = {
        'self': '{}scheduling-block/{}'.format(request.url_root,
                                               config['id']),
        'list': '{}'.format(request.url),
        'home': '{}'.format(request.url_root)
    }
    return response, HTTPStatus.ACCEPTED

def missing_db_response(func):
    """Decorator to check connection exceptions"""
    @wraps(func)
    def with_exception_handling(*args, **kwargs):
        """Wrapper to check for connection failures"""
        try:
            return func(*args, **kwargs)
        except ConnectionError as error:
            return (dict(error='Unable to connect to Configuration Db.',
                         error_message=str(error),
                         links=dict(root='{}'.format(get_root_url()))),
                    HTTPStatus.NOT_FOUND)
    return with_exception_handling


arr = [1,2,3]

def findpairs(arr):
    cache = {}
    answer = []
    for i in range(len(arr)):
        if arr[i] not in cache:
            cache[arr[i]] = i

    print(cache)
    for x in cache:
        for j in cache:
            if cache[x] == cache[j]:
                 answer.append((cache[x],cache[j]))
    return answer

print(findpairs(arr))


def replaceUnderScore(arr, word):
  chars = list(word)
  counter = 0
  underscore = 0
  for i in range(len(arr)):
    if (arr[i] == '_'):
      underscore += 1
      if (underscore > len(chars)):
        arr[:] = [''.join(arr[:])]
        return(arr[0])
      arr[i] = chars[counter]
      counter += 1
  if (underscore < len(chars)):
    return(False)
  else:
    arr[:] = [''.join(arr[:])]
    return(arr[0])

print (replaceUnderScore(['s'], 'u'))


import numpy as np
from sklearn.neighbors import KDTree, KNeighborsClassifier

class TrustScore:
    """
    Trust Score: a measure of classifier uncertainty based on nearest neighbors.
  """

    def __init__(self, k=10, alpha=0.0, filtering="none", min_dist=1e-12):
        """
        k and alpha are the tuning parameters for the filtering,
        filtering: method of filtering. option are "none", "density",
        "uncertainty"
        min_dist: some small number to mitigate possible division by 0.
    """
        self.k = k
        self.filtering = filtering
        self.alpha = alpha
        self.min_dist = min_dist

    def filter_by_density(self, X: np.array):
        """Filter out points with low kNN density.

    Args:
    X: an array of sample points.

    Returns:
    A subset of the array without points in the bottom alpha-fraction of
    original points of kNN density.
    """
        kdtree = KDTree(X)
        knn_radii = kdtree.query(X, k=self.k)[0][:, -1]
        eps = np.percentile(knn_radii, (1 - self.alpha) * 100)
        return X[np.where(knn_radii <= eps)[0], :]

    def filter_by_uncertainty(self, X: np.array, y: np.array):
        """Filter out points with high label disagreement amongst its kNN neighbors.

    Args:
    X: an array of sample points.

    Returns:
    A subset of the array without points in the bottom alpha-fraction of
    samples with highest disagreement amongst its k nearest neighbors.
    """
        neigh = KNeighborsClassifier(n_neighbors=self.k)
        neigh.fit(X, y)
        confidence = neigh.predict_proba(X)
        cutoff = np.percentile(confidence, self.alpha * 100)
        unfiltered_idxs = np.where(confidence >= cutoff)[0]
        return X[unfiltered_idxs, :], y[unfiltered_idxs]

    def fit(self, X: np.array, y: np.array):
        """Initialize trust score precomputations with training data.

    WARNING: assumes that the labels are 0-indexed (i.e.
    0, 1,..., n_labels-1).

    Args:
    X: an array of sample points.
    y: corresponding labels.
    """

        self.n_labels = np.max(y) + 1
        self.kdtrees = [None] * self.n_labels
        if self.filtering == "uncertainty":
            X_filtered, y_filtered = self.filter_by_uncertainty(X, y)
        for label in range(self.n_labels):
            if self.filtering == "none":
                X_to_use = X[np.where(y == label)[0]]
                self.kdtrees[label] = KDTree(X_to_use)
            elif self.filtering == "density":
                X_to_use = self.filter_by_density(X[np.where(y == label)[0]])
                self.kdtrees[label] = KDTree(X_to_use)
            elif self.filtering == "uncertainty":
                X_to_use = X_filtered[np.where(y_filtered == label)[0]]
                self.kdtrees[label] = KDTree(X_to_use)

            if len(X_to_use) == 0:
                print(
                    "Filtered too much or missing examples from a label! Please lower "
                    "alpha or check data."
                )

    def get_score(self, X: np.array, y_pred: np.array):
        """Compute the trust scores.

    Given a set of points, determines the distance to each class.

    Args:
    X: an array of sample points.
    y_pred: The predicted labels for these points.

    Returns:
    The trust score, which is ratio of distance to closest class that was not
    the predicted class to the distance to the predicted class.
    """
        d = np.tile(None, (X.shape[0], self.n_labels))
        for label_idx in range(self.n_labels):
            d[:, label_idx] = self.kdtrees[label_idx].query(X, k=2)[0][:, -1]

        sorted_d = np.sort(d, axis=1)
        d_to_pred = d[range(d.shape[0]), y_pred]
        d_to_closest_not_pred = np.where(
            sorted_d[:, 0] != d_to_pred, sorted_d[:, 0], sorted_d[:, 1]
        )
        return d_to_closest_not_pred / (d_to_pred + self.min_dist)

class KNNConfidence:
    """Baseline which uses disagreement to kNN classifier.
  """

    def __init__(self, k=10):
        self.k = k

    def fit(self, X, y):
        self.kdtree = KDTree(X)
        self.y = y

    def get_score(self, X, y_pred):
        knn_idxs = self.kdtree.query(X, k=self.k)[1]
        knn_outputs = self.y[knn_idxs]
        return np.mean(
            knn_outputs == np.transpose(np.tile(y_pred, (self.k, 1))), axis=1
        )


#!/usr/bin/env python3

largest = None
smallest = None
while True:
    num = input("Enter a number: ")
    try:
        if num == "done" : break
        else:
            number = int(num)
            if largest is None:
                largest = number
            if smallest is None:
                smallest = number;
            if number > largest:
                largest = number
            if number < smallest:
                smallest = number
    except  ValueError:
       print("Invalid input")

print("Maximum is", largest)
print("Minimum is", smallest)


import hashlib
import random
import time
from concurrent.futures import ThreadPoolExecutor
from typing import Dict, List, Optional, Union

from Pyro5.api import Proxy, expose
from Pyro5.errors import CommunicationError

from .node import Node, NodeType, Linker
from .finger_table import FingerTable
from .hash_table import HashTable
from .monitoring import echo_error, monitor

USE_MONITOR = False

@expose
class ChordNode(Node):

    _node_type = NodeType.chord

    def __init__(
        self,
        id: int,
        linker: Linker,
        cache_size: int,
        use_stabilization: bool = True,
        stabilization_interval: int = 1000,
        fix_finger_interval: int = 1000,
    ) -> None:
        self._id = id
        self.linker = linker
        self._ft = FingerTable(id, linker.BITS_COUNT)
        self.MAX = linker.MAX
        self.BIT_COUNT = linker.BITS_COUNT

        self.use_stabilization = use_stabilization
        self.stabilization_interval = stabilization_interval
        self.fixing_fingers_interval = fix_finger_interval

        self.hash_table = HashTable(cache_size)
        self.executor = ThreadPoolExecutor()

    @property
    def id(self) -> int:
        return self._id

    @property
    def finger_table(self) -> FingerTable:
        return self._ft

    @property
    def node_type(self) -> NodeType:
        return self._node_type

    @property
    def serialized_finger_table(self) -> List[str]:
        return [str(x) for x in self.finger_table]

    @property
    def serialized_hash_table_keys(self):
        return [s for s in self.hash_table]

    ###################################
    # Successor - Predecessor Section #
    ###################################
    @property
    def successor(self) -> Proxy:
        """Return the Proxy objecto to the successor node"""
        return self.linker.get_node(self.node_type, self._ft[1].node)

    @property
    def predecessor(self) -> Proxy:
        """Return the Proxy objecto to the predecessor node"""
        return self.linker.get_node(self.node_type, self._ft[0].node)

    @property
    def successor_id(self) -> Optional[int]:
        return self._ft[1].node

    @property
    def predecessor_id(self) -> Optional[int]:
        return self._ft[0].node

    def set_successor(self, value: Optional[int]):
        self._ft[1].node = value

    def set_predecessor(self, value: Optional[int]):
        self._ft[0].node = value

    #######
    # End #
    #######

    #########
    # Utils #
    #########
    def hash(self, key: str) -> int:
        return int(hashlib.md5(key.encode()).hexdigest(), base=16) % self.MAX

    def in_between(self, k: int, a: int, b: int, equals: bool = True) -> bool:
        a %= self.MAX
        b %= self.MAX

        if a == b:
            return equals
        if a < b:
            return a <= k < b
        return a <= k < b + self.MAX or (a <= k + self.MAX and k < b)

    #######
    # End #
    #######

    ##################
    # Hash Table API #
    ##################
    @monitor(active=USE_MONITOR)
    def insert(self, key: str, value: str):
        hashed_key = self.hash(key)
        print(hashed_key)
        node = self.find_successor(hashed_key)
        if node.id == self.id:
            self.hash_table[key] = value
        else:
            node.insert(key, value)

    @monitor(active=USE_MONITOR)
    def constains(self, key: str) -> bool:
        hashed_key = self.hash(key)
        node = self.find_successor(hashed_key)
        return (node.id == self.id and key in self.hash_table) or (
            node.id != self.id and node.contains(key)
        )

    @monitor(active=USE_MONITOR)
    def get(self, key: str) -> Optional[str]:
        hashed_key = self.hash(key)
        node = self.find_successor(hashed_key)
        if node.id == self.id:
            return self.hash_table[key] if key in self.hash_table else None
        else:
            return node.get(key)

    @monitor(active=USE_MONITOR)
    def pop_in_interval(self, start: int, end: int) -> Dict[str, str]:
        """
        Pop keys of the cache hashed in interval [start, end]
        """

        data = {
            x: self.hash_table[x]
            for x in self.hash_table
            if self.in_between(self.hash(x), start, end + 1)
        }
        self.hash_table.pop_many(data.keys())
        return data

    @monitor(active=USE_MONITOR)
    def update_hash_table(self):
        """
        Update the node cache transfering the keys from it successor
        The keys of a node are hashed in interval [predecessor + 1, self.id]
        """
        if self.successor_id == self.id or self.predecessor_id is None:
            return

        data = self.successor.pop_in_interval(self.predecessor_id + 1, self.id)
        self.hash_table.update(data)

    @monitor(active=USE_MONITOR)
    def update_hash_table_with_keys(self, keys):
        self.hash_table.update(keys)

    #######
    # End #
    #######

    ##########################
    # Find Successor Section #
    ##########################
    @monitor(active=USE_MONITOR)
    def find_successor(self, k: int) -> Union["ChordNode", Proxy]:
        node = self.find_predecessor(k)
        return node.successor

    @monitor(active=USE_MONITOR)
    def find_predecessor(self, key: int) -> Union["ChordNode", Proxy]:
        node = self

        while not self.in_between(key, node.id + 1, node.successor_id + 1):
            node = node.closest_preceding_finger(key)

        return node

    @monitor(active=USE_MONITOR)
    def closest_preceding_finger(self, key: int) -> Union["ChordNode", Proxy]:
        ft = self.finger_table

        for i in range(self.linker.BITS_COUNT, 0, -1):
            if ft[i].node is not None and self.in_between(ft[i].node, self.id + 1, key):
                node = self.linker.get_node(self.node_type, self._ft[i].node)
                return node
        return self

    #######
    # End #
    #######

    @monitor(active=USE_MONITOR)
    def join(self, anchor_node):
        if not self.use_stabilization and anchor_node is not None:
            self.init_finger_table(anchor_node)
            self.update_others()
            self.update_hash_table()
        elif self.use_stabilization:
            if anchor_node is not None:
                for entry in self.finger_table:
                    entry.node = None

                self.set_successor(anchor_node.find_successor(self.id).id)

            self.executor.submit(self.stabilize_subprocess)
            self.executor.submit(self.fix_fingers_subprocess)

    ##############################
    # Join without stabilization #
    ##############################
    @monitor(active=USE_MONITOR)
    def init_finger_table(self, anchor_node: Union["ChordNode", Proxy]):
        ft = self.finger_table  # I do this so as not to write a lot

        successor = anchor_node.find_successor(ft[1].start)
        ft[1].node = successor.id
        ft[0].node = successor.predecessor_id
        successor.set_predecessor(self.id)

        for i in range(1, self.linker.BITS_COUNT):
            if self.in_between(ft[i + 1].start, self.id, ft[i].node):
                ft[i + 1].node = ft[i].node
            else:
                succ = anchor_node.find_successor(ft[i + 1].start).id
                if self.in_between(self.id, ft[i + 1].start, succ, False):
                    ft[i + 1] = self.id
                else:
                    ft[i + 1] = succ

    @monitor(active=USE_MONITOR)
    def update_others(self):
        for i in range(1, self.linker.BITS_COUNT + 1):
            node = self.find_predecessor((self.id - 2 ** (i - 1)) % self.MAX)
            node.update_finger_table(self.id, i)

    @monitor(active=USE_MONITOR)
    def update_finger_table(self, new_id: int, index: int):
        ft = self.finger_table

        if self.in_between(new_id, self.id, ft[index].node):
            ft[index].node = new_id

            # node with the "new_id" id is calling remote this node
            # and it finger table is computed correctly
            if self.predecessor_id == new_id:
                return
            predecessor = self.predecessor
            predecessor.update_finger_table(new_id, index)

    #######
    # End #
    #######

    ###########################
    # Join with stabilization #
    ###########################
    @monitor(active=USE_MONITOR)
    def stabilize_subprocess(self):
        interval = self.stabilization_interval
        interval_over_4 = interval // 4
        while True:
            waiting_time = random.randint(
                interval - interval_over_4, interval + interval_over_4
            )  # milliseconds

            try:
                self.stabilize()
            except Exception as e:
                echo_error(e)

            time.sleep(waiting_time / 1000)

    @monitor(active=USE_MONITOR)
    def stabilize(self):
        node_id = self.successor.predecessor_id

        # check if exists a better succesor
        if node_id is not None and self.in_between(
            node_id, self.id + 1, self.successor_id, equals=False
        ):
            self.set_successor(node_id)

        self.successor.notify(self)
        self.update_hash_table()

    @monitor(active=USE_MONITOR)
    def notify(self, node):
        # check if node has not been eliminated from the network
        if self.predecessor_id is not None and self.predecessor_id != node.id:
            try:
                self.predecessor.id
            except CommunicationError:
                self.set_predecessor(None)

        # check if exist a better predecessor
        if self.predecessor_id is None or self.in_between(
            node.id, self.predecessor_id + 1, self.id
        ):
            self.set_predecessor(node.id)
            self.predecessor.update_hash_table()

    @monitor(active=USE_MONITOR)
    def fix_fingers_subprocess(self):
        interval = self.stabilization_interval
        interval_over_4 = interval // 4
        while True:
            waiting_time = random.randint(
                interval - interval_over_4, interval + interval_over_4
            )  # milliseconds
            try:
                self.fix_fingers()
            except Exception as e:
                echo_error(e)

            time.sleep(waiting_time / 1000)

    @monitor(active=USE_MONITOR)
    def fix_fingers(self):
        if self.BIT_COUNT < 2:
            return
        i = random.randint(2, self.BIT_COUNT)
        self.finger_table[i].node = self.find_successor(self.finger_table[i].start).id

    #######
    # End #
    #######

    #############
    # disconect #
    #############
    @monitor(active=USE_MONITOR)
    def disconnect(self):
        succ = self.successor
        pred = self.predecessor
        succ.set_predecessor(pred.id)
        pred.set_successor(succ.id)
        succ.update_hash_table_with_keys(
            {key: self.hash_table[key] for key in self.hash_table}
        )

        succ._pyroRelease()
        pred._pyroRelease()
        self.linker.remove_node(self.node_type, self.id)

    #######
    # End #
    #######

    def start_loop(self):
        self.linker.start_loop()

    def __str__(self) -> str:
        return f"Node.{self.id}"

    def __repr__(self) -> str:
        return str(self)


# Authored by Cem Kaya & ...
import threading
import json
from time import strptime
import requests as req
from flask_cors import CORS
from flask import Flask, render_template, request, send_from_directory, send_file
import torch
import torchvision
import cv2
import numpy as np
import base64
from matplotlib import pyplot as plt2

# Program for converting bytes to string using decode()

# import required module
import codecs
import matplotlib.image as mpimg

# py -3.10 .\back_end.py # to run the server
# py -3.10 -m pip freeze > requirements.txt # to create requirements.txt
# py -3.10 -m pip install -r requirements.txt # to install requirements.txt

def results_parser(results):
  s = ""
  if results.pred[0].shape[0]:
    for c in results.pred[0][:, -1].unique():
      n = (results.pred[0][:, -1] == c).sum()  # detections per class
      s += f"{n} {results.names[int(c)]}{'s' * (n > 1)}, "  # add to string
  return s
app = Flask(__name__)
CORS(app)

@app.route('/')
def index():
  return render_template('index.html')

@app.route('/post_test', methods=['POST'], strict_slashes=False  )
def test():
    global picture_index

    file = request.files['image']

    this_img_name= 'pics/tmp'+str(picture_index)+'.jpg'
    file.save(this_img_name)
    picture_index=picture_index+1

    # Reading an image in default mode
    #src = cv2.imread('tmp.jpg')

	# Window name in which image is displayed
    #window_name = 'Image'
    #plt2.switch_backend('agg')

    plt2.ion()
    img = mpimg.imread(this_img_name)

    imgplot = plt2.imshow(img)

    results = yolo_model(img)
    result=results_parser(results)
    result=result.split(" ")
    #results.print()

    is_exists_human=next((i for i, x in enumerate(result) if( x=="person," or x=="persons,")), None)
    number_of_person=0

    #find("person")
    print("resuls ",result)

    if(is_exists_human!=None):
       number_of_person=int(result[is_exists_human-1])

    print(number_of_person)

    results.show()
	# Using cv2.flip() method
	# Use Flip code 0 to flip vertically
   # image = cv2.flip(src, 0)
    #cv2.imshow(window_name, image)
    #cv2.waitKey()
    img.save(this_img_name)
    #resmi byte cevirip at
    #byte_image=bytearray(img)
    x=codecs.img.encode()
    print("x is",type(x))
    return "x" #render_template("success.html", data= req.post(data = json.dumps(myobj)).text )

#################################################
if __name__ == '__main__':  #python interpreter assigns "__main__" to the file you run
    imgs = ['https://ultralytics.com/images/zidane.jpg']  # batch of images
    picture_index=0
    print("sssssssssssssssssssjkddms")
    #img = mpimg.imread('tmp.jpg')
    #plt2.axis([-50,50,0,10000])

    yolo_model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True)
    results = yolo_model(imgs)
    plt2.pause(0.5)
    # Results
    plt2.draw()

    #results.print()
    #results.show()  # or .show()
    app.run(debug=True , host="0.0.0.0")


# Elaborador por: Camilo Sánchez Rodríguez, Gabriel Gomez Vega
# Fecha de creación: 12/10/2021, 11:16 AM
# Última edición: 16/10/2021, 11:03 PM
# Versión: 3.9.6

##############################################################
#####              Importación de Librerías              #####
##############################################################

import re
from archivo import *
from funciones import *

##############################################################
#####                 Variables Globales                 #####
##############################################################

paquetes = cargarBD()

##############################################################
#####              Definición de Funciones               #####
##############################################################

def validarNombreSucursal(pnombre):
    """
    Funcionamiento: Determina si el valor ingresado coincide con el formato de nombre de sucursal, no permite números
    Entradas:
    pnombre(str): Es el nombre a verificar si cumple con el formato
    Salidas: Una tupla (True, pnombre) o un str indicando error
    """
    if re.match("^[a-zA-ZáéíóúÁÉÍÓÚ '-]{6,}$", pnombre):
        return (True, pnombre)
    print("El nombre de la sucursal no debe tener signos de puntuación o números, y debe tener más de 5 caracteres; por ejemplo: \"CCR Cartago Centro\".")
    return " "

def pedirNombreSucursal():
    """
    Funcionamiento: Pide la entrada de la funcion validarNombreSucursal
    Entradas: Na
    Salidas: retorna la función validarNombreSucursal
    """
    vnombre = input("Ingrese el nombre de la sucursal: ")
    return validarNombreSucursal(vnombre)

def insistirNombreSucursal():
    """
    Funcionamiento: De manera repetitiva, pide un formato de nombre de sucursal hasta que esté correcto
    Entradas: Na
    Salidas:
    opcion[1](str): Equivale al nombre del con el formato correcto
    """
    opcion = " "
    while opcion[0] != True:
        opcion = pedirNombreSucursal()
    return opcion[1]

def validarEstadoPaquete(pnum):
    """
    Funcionamiento: Valida que el estado del paquete tenga un formato correcto
    Entradas:
    -pnum(str): es el numero que indica el estado
    Salidas: Una tupla; (True, pnum), o un str vacío
    """
    if re.match("^[1-3]$",pnum):
        return (True, pnum)
    print("Por favor ingrese un número entre (1) y (3)")
    return " "

def pedirEstadoPaquete():
    """
    Funcionamiento: Toma la entrada para la funcion validarEstadoPaquete
    Entrada:
    -pnum(str): Na
    Salidas: Retorna la funcion validarEstadoPaquete
    """
    vestado = input("Ingrese el estado del paquete: ")
    return validarEstadoPaquete(vestado)

def opcionInsistirEstadoPaquete():
    """
    Funcionamienot: Insiste al usuario hasta que ingrese un formato de estado correcto
    Entradas: na
    Salidas:
    -opcion[1](str): Es el estado del paquete
    """
    opcion = " "
    while opcion[0] != True:
        opcion = pedirEstadoPaquete()
    return opcion[1]

def validarPaquete():
    """
    Función:    Valida entrada de número de paquete
    Entradas:   entrada (int) - Número entero
    Salidas:    Retorna entrada si es válida. De lo contrario, imprime error
    """
    while True:
        try:
            entrada = int(input("Número de paquete: "))
            if entrada > 0:
                return entrada
            imprimirError("Valor ingresado debe ser mayor a 0") # Restricción de Valor
        except ValueError:
            imprimirError("Debe ingresar un número entero") # Restricción de Tipo

def revisarPaquete(pnum, pdict):
    """
    Función:    Indica si número de paquete existe en diccionario
    Entradas:
        pnum (int) - Número de paquete
        pdict (dict) - Diccionario de paquetes
    Salidas:    Retorna True si está, False si no está
    """
    return pnum in pdict

def validarTelefono():
    """
    Función:    Valida entrada de número telefónico
    Entradas:   entrada (str) - Número de teléfono
    Salidas:    Retorna entrada si es válida. De lo contrario, imprime error
    """
    while True:
        entrada = input("Número de teléfono: ")
        if re.match("^\d{8}$", entrada):
            return entrada
        imprimirError("Formato inválido, ingrese 8 dígitos") # Restricción de Valor

def ingresarPaquete():
    """
    Función:    Submenú de entradas requeridas para registrar datos
    Entradas:   paquetes (dict) - Diccionario de paquetes
    Salidas:    Retorna registro de datos
    """
    while True:
        print("\n" + " Registro de Datos ".center(50,"=") + "\n")
        numero = validarPaquete()
        if revisarPaquete(numero, paquetes):   # Restriccion: Paquete repetido
            imprimirError("No se puede repetir número de paquete")
            continue
        telefono, sucursal = validarTelefono(), insistirNombreSucursal()
        estado = opcionInsistirEstadoPaquete()
        dias = 10
        if estado != '1':   # Si estado es 2 o 3, cambia dias hábiles a 0
            dias = 0
        paquetes[numero] = [telefono, sucursal, dias, estado] # Crea paquete nuevo
        if not confirmarOpcion("", "¿Desea ingresar más paquetes?"):
            break   # Cierra submenu
    return paquetes

def actualizarPaquete():
    """
    Función:    Submenú de entradas requeridas para actualizar datos
    Entradas:   paquetes (dict) - Diccionario de paquetes
    Salidas:    Retorna registro de datos
    """
    while True:
        print("\n" + " Modificación de Datos ".center(50,"=") + "\n")
        numero = validarPaquete()
        if not revisarPaquete(numero, paquetes): # Restriccion: Paquete no registrado
            imprimirError("No se encuentra registrado el paquete")
            continue
        estado = opcionInsistirEstadoPaquete()
        if estado == paquetes[numero][-1]:     # Restricción: Estado ya registrado
            imprimirError("El paquete ya tiene ese estado registrado")
            continue
        if confirmarOpcion(" ADVERTENCIA ", "¿Seguro que desea realizar este cambio?"):
            dias = 0
            if estado == '1':   # Si estado es 1, cambia dias habiles a 5
                dias = 5
            paquetes[numero][-2] = dias    # Actualizan dias habiles y estado
            paquetes[numero][-1] = estado
        if not confirmarOpcion("", "¿Desea modificar más paquetes?"):
            break
    return paquetes

def eliminarPaquete():
    """
    Función:    Submenú de entradas requeridas para eliminar datos
    Entradas:   paquetes (dict) - Diccionario de paquetes
    Salidas:    Retorna registro de datos
    """
    while True:
        print("\n" + " Eliminación de Datos ".center(50,"=") + "\n")
        numero = validarPaquete()
        if not revisarPaquete(numero, paquetes):   # Restricción: Paquete no registrado
            imprimirError("No se encuentra registrado el paquete")
            continue
        if confirmarOpcion(" ADVERTENCIA ", "¿Seguro que desea eliminar este paquete?"):
            del paquetes[numero]
        if not validarMatriz():
            break
        if not confirmarOpcion("", "¿Desea eliminar más paquetes?"):
            break
    return paquetes

def cantidadPaquetes(ppaquetes):
    """
    Funcionamiento: Imprime la cantidad de paquetes que hay en el diccionario
    Entradas:
    -ppaquetes(int): es el número de paquetes
    Salidas: Na
    """
    print(f"\nEl total de paquetes registrados es: {ppaquetes}")
    return ""

def imprimirBasePaquetes(pbasePaquete):
    """
    Funcionamiento: Imprime todos los paquetes que estén almacenados en la base
    Entradas:
    -pbasePaquete(dict): es el diccionario con todos los paquetes
    Salidas: Na
    """
    lineas = "-"*140 #Esto es para no hacer la multiplicación varias veces
    print("\n" + lineas + "\n" + agregarEspacios("Número de paquete", 35) + agregarEspacios("Número de teléfono", 35) + agregarEspacios("Sucursal", 30) + agregarEspacios("Días hábiles", 25) + agregarEspacios("Estado", 15) + "\n" + lineas)
    for llave in sacarLlavesDicc(pbasePaquete):
        print(agregarEspacios(str(llave), 35) + agregarEspacios(str(pbasePaquete[llave][0]), 35) + agregarEspacios(pbasePaquete[llave][1], 30) + agregarEspacios(str(pbasePaquete[llave][2]), 25) + agregarEspacios(str(pbasePaquete[llave][-1]), 15) + "\n" + lineas)
    return ""

def menuReportes(plargoDiccionario, pbaseDiccionario):
    """
    Funcionamiento: Es el menú de reportes
    Entradas:
        -plargoDiccionario(int): Es la cantidad de elementos que tiene el diccionario
        -pabseDiccionario(dict): Es el diccionario que tiene los paquetes
    Salidas: N/A
    """
    while True:
        lista = ("\n1. Total de paquetes registrados.",
                 "2. Imprimir todos los paquetes.", "3. Salir")
        print("\n" + " Menú de Reportes ".center(50, "="))
        for elemento in lista:
            print(elemento)
        opcion = input("\nIngrese una opción: ")
        if opcion == "1":
            cantidadPaquetes(plargoDiccionario)
        elif opcion == "2":
            imprimirBasePaquetes(pbaseDiccionario)
        elif opcion == "3":
            break
        else:
            imprimirError("Se debe ingresar un número del (1) al (3).")
    print("Regresando al menú principal...")
    return ""

def validarMatriz():
    """
    Funcionamiento: Valida la entrada al menu de reportes o de eliminacion de datos
    Entradas: N/A
    Salidas: Retorna True si hay paquetes en matriz, False si no
    """
    if len(paquetes) > 0:
        return True
    imprimirError("No hay paquetes registrados")
    return False

##############################################################
#####                Programa Principal                  #####
##############################################################

opciones = ("\n1. Insertar Paquete", "2. Actualizar Paquete",
            "3. Eliminar Paquete", "4. Reportes", "0. Salir")

while True:
    print(" Menú Principal ".center(50, "="))
    for string in opciones: # Imprime cada opcion
        print(string)
    guardarBD(paquetes)     # Guarda cambios de paquetes en archivo
    opcion = input("\nIngrese una opción: ")
    if opcion == "1":           # Inserta paquetes en diccionario
        ingresarPaquete()
    elif opcion == "2":         # Modifica paquetes
        actualizarPaquete()
    elif opcion == "3":
        if validarMatriz():     # Permite eliminar paquetes si los hay
            eliminarPaquete()
    elif opcion == "4":
        if validarMatriz():     # Muestra reportes sólo si hay paquetes
            menuReportes(len(paquetes), paquetes)
    elif opcion == "0":
        print("\nGracias por usar el sistema.")
        break
    else:                   # Restricción: Opción Inválida
        imprimirError("Opción Inválida")


import re
import difflib
from event import Event

try:
    import imgurpython
except (ImportError, SystemError):
    print("Warning: QDB module requires imgurpython.")
    imgurpython = object

try:
    import requests
except (ImportError, SystemError):
    print("Warning: QDB module requires requests.")
    requests = object

class QDB:
    def __init__(self, events=None, printer_handle=None, bot=None, say=None):
        self.events = events
        self.printer = printer_handle
        self.bot = bot
        self.say = say
        try:
            from imgur_credentials import ImgurCredentials as ic
        except (ImportError, SystemError):
            print(
                "Warning: imgur module requires credentials in modules/imgur_credentials.py")

            class PhonyIc:
                imgur_client_id = "None"
                imgur_client_secret = "None"
            ic = PhonyIc()
        self.imgur_client_id = ic.imgur_client_id
        self.imgur_client_secret = ic.imgur_client_secret

        # prevent unecessarily clearing our mem_store['qdb'] dict
        if not "qdb" in self.bot.mem_store:
            self.bot.mem_store['qdb'] = {}
        # define a key for _recent since that will not be a potential channel
        # name
        self.bot.mem_store['qdb']['_recent'] = []

        # subscribing to all lines ALSO catches lines matching ".qdb something something"
        # so we don't need a second ".qdb" event
        all_lines = Event('1__all_lines__')
        all_lines.define('.*')
        all_lines.subscribe(self)

        self.bot.register_event(all_lines, self)

        self.help = ".qdb <search string of first line> | <search string of last line>"
        self.MAX_BUFFER_SIZE = 500
        self.MAX_HISTORY_SIZE = 10

    def _imgurify(self, url):
        client = imgurpython.ImgurClient(
            self.imgur_client_id, self.imgur_client_secret)

        replacement_values = list()

        if isinstance(url, list):
            for u in url:
                resp = client.upload_from_url(u)
                replacement_values.append(resp)
        else:
            try:
                resp = client.upload_from_url(url)
                replacement_values.append(resp)
            except imgurpython.helpers.error.ImgurClientError as e:
                self.bot.debug_print("ImgurClientError: ")
                self.bot.debug_print(str(e))
            except UnboundLocalError as e:
                self.bot.debug_print("UnboundLocalError: ")
                self.bot.debug_print(str(e))
            except requests.exceptions.ConnectionError as e:
                self.bot.debug_print("ConnectionError: ")
                self.bot.debug_print(str(e))
        return replacement_values

    def _detect_url(self, quote):
        """
        for tsd printouts and imgflip (.meme)
        follows this format:
        http://irc.teamschoolyd.org/printouts/8xnK5DmfMz
        http://i.imgflip.com/zs1e6.jpg
        """
        tsd_regex = "(?P<url>http://irc\\.teamschoolyd\\.org/printouts/\\w+)"
        if_regex = "(?P<url>http://i\\.imgflip\\.com/\\w+.jpg)"

        # to allow us to check both variables at the end
        tsd_url, if_url = None, None

        try:
            tsd_url = re.search(tsd_regex, quote).group("url")
        except AttributeError:
            pass
        try:
            if_url = re.search(if_regex, quote).group("url")
        except AttributeError:
            pass

        if not tsd_url and not if_url:
            return quote

        if tsd_url:
            url = tsd_url
        if if_url:
            url = if_url

        repl = self._imgurify(url)

        if tsd_url:
            new_quote = re.sub(tsd_regex, repl[0]['link'], quote)
        if if_url:
            new_quote = re.sub(if_regex, repl[0]['link'], quote)
        return new_quote

    def strip_formatting(self, msg):
        """Uses regex to replace any special formatting in IRC (bold, colors) with nothing"""
        return re.sub('([\x02\x1D\x1F\x16\x0F]|\x03([0-9]{2})?)', '', msg)

    def add_buffer(self, event=None, debug=False):
        """Takes a channel name and line passed to it and stores them in the bot's mem_store dict
        for future access. The dict will have channel as key. The value to that key will be a list
        of formatted lines of activity.
        If the buffer size is not yet exceeded, lines are just added. If the buffer
        is maxed out, the oldest line is removed and newest one inserted at the beginning.
        """
        if debug:
            print("Line: " + event.line)
            print("Verb: " + event.verb)
            print("Channel: " + event.channel)
            print("")
        if not event:
            return
        # there are certain things we want to record in history, like nick changes and quits
        # these often add to the humor of a quote. however, these are not specific to a channel
        # in IRC and our bot does not maintain a userlist per channel. Therefore, when nick
        # changes and quits occur, we will add them to every buffer. This is not technically
        # correct behavior and could very well lead to quits/nick changes that are not visible
        # showing up in a quote, but it's the best we can do at the moment
        if not event.channel:
            # discard events with unwanted verbs
            if event.verb not in ["QUIT", "NICK"]:
                return
            try:
                for chan in list(self.bot.mem_store['qdb'].keys()):
                    if chan != '_recent':
                        if len(self.bot.mem_store['qdb']
                               [chan]) >= self.MAX_BUFFER_SIZE:
                            self.bot.mem_store['qdb'][chan].pop()
                        line = self.format_line(event)
                        if line:
                            self.bot.mem_store['qdb'][chan].insert(0, line)
            except (KeyError, IndexError):
                print("QDB add_buffer() error when no event channel")
        # now we continue with normal, per channel line addition
        # create a dictionary associating the channel with an empty list if it
        # doesn't exist yet
        else:
            if event.channel not in self.bot.mem_store['qdb']:
                self.bot.mem_store['qdb'][event.channel] = []
            try:
                # check for the length of the buffer. if it's too long, pop the
                # last item
                if len(self.bot.mem_store['qdb']
                       [event.channel]) >= self.MAX_BUFFER_SIZE:
                    self.bot.mem_store['qdb'][event.channel].pop()
                # get a line by passing event to format_line
                # insert the line into the first position in the list
                line = self.format_line(event)
                if line:
                    self.bot.mem_store['qdb'][event.channel].insert(0, line)
            except IndexError:
                print("QDB add_buffer() error. Couldn't access the list index.")

    def format_line(self, event):
        """Takes an event and formats a string appropriate for quotation from it"""

        # first strip out printout urls and replace them with imgur mirrors
        # commenting out for now to avoid uploading to imgur so often
        #event.msg = self._detect_url(event.msg)

        # format all strings based on the verb
        if event.verb == "":
            return ''
        elif event.verb == "PRIVMSG":
            # special formatting for ACTION strings
            if event.msg.startswith('\001ACTION'):
                # strip out the word ACTION from the msg
                return ' * %s %s\n' % (event.user, event.msg[7:])
            else:
                return '<%s> %s\n' % (
                    event.user, self.strip_formatting(event.msg))
        elif event.verb == "JOIN":
            return ' --> %s has joined channel %s\n' % (
                event.user, event.channel)
        elif event.verb == "PART":
            return ' <-- %s has left channel %s\n' % (
                event.user, event.channel)
        elif event.verb == "NICK":
            return ' -- %s has changed their nick to %s\n' % (
                event.user, event.msg)
        elif event.verb == "TOPIC":
            return ' -- %s has changed the topic for %s to "%s"\n' % (
                event.user, event.channel, event.msg)
        elif event.verb == "QUIT":
            return ' <-- %s has quit (%s)\n' % (event.user, event.msg)
        elif event.verb == "KICK":
            # this little bit of code finds the kick target by getting the last
            # thing before the event message begins
            target = event.line.split(":", 2)[1].split()[-1]
            return ' <--- %s has kicked %s from %s (%s)\n' % (
                event.user, target, event.channel, event.msg)
        elif event.verb == "NOTICE":
            return ' --NOTICE from %s: %s\n' % (event.user, event.msg)
        else:
            # no matching verbs found. just ignore the line
            return ''

    def get_qdb_submission(
            self, channel=None, start_msg='', end_msg='', strict=False):
        """Given two strings, start_msg and end_msg, this function will assemble a submission for the QDB.
        start_msg is a substring to search for and identify a starting line. end_msg similarly is used
        to search for the last desired line in the submission. This function returns a string ready
        for submission to the QDB if it finds the desired selection. If not, it returns None.
        """
        if not channel:
            return None
        # must have at least one msg to search for and channel to look it up in
        if len(start_msg) == 0 or not channel:
            return None
        # first, check to see if we are doing a single string submission.
        if end_msg == '':
            for line in self.bot.mem_store['qdb'][channel]:
                if start_msg.lower() in line.lower():
                    # removing temporary printout urls and replacing with imgur
                    return self._detect_url(line)
            # making sure we get out of the function if no matching strings were found
            # don't want to search for a nonexistent second string later
            return None
        # search for a matching start and end string and get the buffer index
        # for the start and end message
        start_index = -1
        end_index = -1
        """Finds matching string for beginning line. Buffer is traversed in reverse-chronological order
        .qdb -> strict = False -> earliest occurence
        .qdbs -> strict = True -> latest occurence
        """
        for index, line in enumerate(self.bot.mem_store['qdb'][channel]):
            # print "evaluating line for beginning: {}".format(line)
            if start_msg.encode(
                    'utf-8', 'ignore').lower() in line.encode('utf-8', 'ignore').lower():
                # print "found match, start_index={}".format(index)
                start_index = index
                if strict:
                    break
        # finds newest matching string for ending line
        for index, line in enumerate(self.bot.mem_store['qdb'][channel]):
            # print "evaluating line for end: {}".format(line)
            if end_msg.lower() in line.lower():
                # print "found match, end_index={}".format(index)
                end_index = index
                break
        # check to see if index values are positive. if not, string was not
        # found and we're done
        if start_index == -1 or end_index == -1 or start_index < end_index:
            return None
        # now we generate the string to be returned for submission
        submission = ''
        try:
            for i in reversed(list(range(end_index, start_index + 1))):
                # print 'Index number is ' + str(i) + ' and current submission
                # is ' + submission
                # detect temporary printout urls and replace with imgur
                submission += self._detect_url(
                    self.bot.mem_store['qdb'][channel][i])
        except IndexError:
            print("QDB get_qdb_submission() error when accessing list index")

        return submission

    def submit(self, qdb_submission, debug=False):
        """Given a string, qdb_submission, this function will upload the string to hlmtre's qdb
        server. Returns a string with status of submission. If it worked, includes a link to new quote.
        """
        if debug:
            print("Submission is:")
            print(qdb_submission)
            print("Current buffer is:")
            print(self.bot.mem_store['qdb'])
            print("")
            return ''
        # accessing hlmtre's qdb api
        url = 'https://qdb.zero9f9.com/api.php'
        payload = {'q': 'new', 'quote': qdb_submission.rstrip('\n')}
        try:
            qdb = requests.post(url, payload)
        except requests.exceptions.ConnectionError as e:
            self.bot.debug_print("ConnectionError: ")
            self.bot.debug_print(str(e))
        # check for any HTTP errors and return False if there were any
        try:
            qdb.raise_for_status()
        except requests.exceptions.HTTPError as e:
            self.bot.debug_print('HTTPError: ')
            self.bot.debug_print(str(e))
            self.bot.debug_print("Perhaps informative:")
            self.bot.debug_print(url)
            self.bot.debug_print(str(payload))
            return "HTTPError encountered when submitting to QDB"
        try:
            q_url = qdb.json()
            self.add_recently_submitted(q_url['id'], qdb_submission)
            if q_url['status'] == "success":
                return "QDB submission successful! https://qdb.zero9f9.com/quote.php?id=" + \
                    str(q_url['id'])
            else:
                self.bot.debug_print("QDB error:")
                print(q_url)
                return "QDB submission unsuccessful :(. Check console output."
        except (KeyError, UnicodeDecodeError):
            return "Error getting status of quote submission."
        return "That was probably successful since no errors came up, but no status available."

    def delete(self, user, post_id='', passcode=''):
        """A special function that allows certain users to delete posts"""
        # accessing hlmtre's qdb api
        url = 'http://qdb.zero9f9.com/api.php'
        payload = {
            'q': 'delete',
            'user': user,
            'id': post_id,
            'code': passcode}
        deletion = requests.get(url, params=payload)
        # check for any HTTP errors and return False if there were any
        try:
            deletion.raise_for_status()
        except requests.exceptions.HTTPError as e:
            self.bot.debug_print('HTTPError: ')
            self.bot.debug_print(str(e))
            return "HTTPError encountered when accessing QDB"
        try:
            del_status = deletion.json()
            if del_status['success'] == "true":
                # they're a list of dicts
                for quote in self.bot.mem_store['qdb']['_recent']:
                    if int(post_id) in quote:
                        self.bot.mem_store['qdb']['_recent'].remove(quote)
                return "QDB deletion succeeded."
            return "QDB deletion failed."
        except (KeyError, UnicodeDecodeError):
            return "Error getting status of quote deletion."

    def recently_submitted(self, submission):
        """Checks to see if the given submission is string is at least 75% similar to the strings
        in the list of recently submitted quotes.
        Returns the id of the quote if it was recently submitted. If not, returns -1.
        """
        # set up a difflib SequenceMatcher with the first string to test
        comparer = difflib.SequenceMatcher()
        comparer.set_seq1(submission)
        # if we find that it has 75% similarity or greater to a recent
        # submission, return True
        try:
            for recent_quote in self.bot.mem_store['qdb']['_recent']:
                comparer.set_seq2(list(recent_quote.values())[0])
                if comparer.ratio() >= .75:
                    return list(recent_quote.keys())[0]
        except TypeError:
            return -1
        except KeyError:
            return -1
        except IndexError:
            return -1
        return -1

    def add_recently_submitted(self, q_id, submission):
        """Takes a string, submission, and adds it to the list of recent submissions.
        Also we do length checking, only keep record of the previous MAX_HISTORY_SIZE quotes.
        """
        # first, see if we have reached the maximum history size. if so, remove
        # last item
        if len(self.bot.mem_store['qdb']['_recent']) >= self.MAX_HISTORY_SIZE:
            self.bot.mem_store['qdb']['_recent'].pop()
        # inserting a dict with the qdb id of the submission and the submission
        # content
        self.bot.mem_store['qdb']['_recent'].insert(0, {q_id: submission})

    def handle(self, event):
        # first check to see if there is a special deletion going on
        if event.msg.startswith(".qdbdelete") and event.is_pm:
            deletion = event.msg.split(' ', 2)
            try:
                # requires the format ".qdbdelete <post_id> <password>"
                self.say(
                    event.user,
                    self.delete(
                        event.user,
                        deletion[1],
                        deletion[2]))
            except IndexError:
                self.say(
                    event.user,
                    "Not enough parameters provided for deletion.")
            return
        """
        See if we're going to generate a qdb submission, or just add the line to the buffer.
        .qdb is the standard, generous implementation selected after hours of testing and ideal for a significant number of situations where lines are repeated. Use specific search strings. the start_index of the submission will be the EARLIEST occurrence of the substring in the buffer.
        .qdbs is the strict implementation. The start_index will be the LATEST occurrence of the substring.
        """

        if event.msg.startswith(".qdb ") or event.msg.startswith(".qdbs "):
            # split the msg with '.qdb[s] ' stripped off beginning and divide into 1 or 2 search strings
            # e.g. ".qdb string1|string2" -> [".qdb", "string1|string2"]
            cmd_parts = event.msg.split(None, 1)
            if len(cmd_parts) < 2:
                # do something here to handle '.qdb[s]'
                return
            # determine if using strict mode
            strict_mode = cmd_parts[0] == ".qdbs"
            # split the search parameter(s)
            # e.g. "string1|string2" -> ["string1", "string2"]
            string_token = cmd_parts[1].split('|', 1)
            start_msg = string_token[0].rstrip()
            # see if we only have a one line submission
            if len(string_token) == 1:
                # s is the string to submit
                s = self.get_qdb_submission(event.channel, start_msg)
                recent = self.recently_submitted(s)
                if recent > 0:
                    q_url = "http://qdb.zero9f9.com/quote.php?id=" + \
                        str(recent)
                    self.printer(
                        "PRIVMSG " +
                        event.channel +
                        " :QDB Error: A quote of >75% similarity has already been posted here: " +
                        q_url +
                        "\n")
                    return
                if not s:
                    self.printer(
                        "PRIVMSG " +
                        event.channel +
                        ' :QDB Error: Could not find requested string.\n')
                    return
                # Print the link to the newly submitted quote
                self.printer(
                    "PRIVMSG " +
                    event.channel +
                    ' :' +
                    self.submit(s) +
                    '\n')
                return
            # We should only get here if there are two items in string_token
            end_msg = string_token[1].lstrip()
            s = self.get_qdb_submission(
                event.channel, start_msg, end_msg, strict_mode)
            recent = self.recently_submitted(s)
            if recent > 0:
                q_url = "http://qdb.zero9f9.com/quote.php?id=" + str(recent)
                self.printer(
                    "PRIVMSG " +
                    event.channel +
                    " :QDB Error: A quote of >75% similarity has already been posted here: " +
                    q_url +
                    "\n")
                return
            # if there's nothing found for the submission, then we alert the
            # channel and gtfo
            if not s:
                self.printer(
                    "PRIVMSG " +
                    event.channel +
                    ' :QDB Error: Could not find requested quotes or parameters were not specific enough.\n')
                return
            # print the link to the new submission
            self.printer(
                "PRIVMSG " +
                event.channel +
                ' :' +
                self.submit(s) +
                '\n')
            return
        self.add_buffer(event)


'''
LeetCode Medium: 1992. Find All Groups of Farmland
https://leetcode.com/problems/find-all-groups-of-farmland/

Check FindAllGroupsOfFarmland.cpp for brief solution explanation.
'''
class Solution:
    def findFarmland(self, land: List[List[int]]) -> List[List[int]]:
        def check_bounds(r, c, M, N) -> bool:
            return 0<=r<M and 0<=c<N
        M, N = len(land), len(land[0])
        vis = [[False for i in range(N)]for i in range(M)]
        ans = []
        for i in range(M):
            for j in range(N):
                if vis[i][j]==True or land[i][j]==0:
                    continue
                mnr, mnc, mxr, mxc = i, j, i, j
                ti = i
                while check_bounds(ti, j, M, N)==True and land[ti][j]==1:
                    mxr = ti
                    ti+=1
                tj = j
                while check_bounds(i, tj, M, N)==True and land[i][tj]==1:
                    mxc = tj
                    tj+=1
                for r in range(mnr, mxr+1):
                    for c in range(mnc, mxc+1):
                        vis[r][c] = True
                ans.append([mnr, mnc, mxr, mxc])
        return ans

Medium/1992. Find All Groups of Farmland/FindAllGroupsOfFarmland.py