"""
QUESTION 2: Monthly Visitors Entering Canada by Region

USAGE:

python questions/2/canada_visitors_by_region.py data/Canada_visitors.csv

OUTPUT:

A PNG file named "canada_visitors_by_region.png" will be written to the
current directory.

"""

import os
import sys

import pandas as pd
import matplotlib.pyplot as plt

def substitute(canada_visitors):
    """
    Substitute troublesome entries in the "Canada_visitors.csv" data.

    canada_visitors: A pandas DataFrame object that contains the loaded contents of
                     the "Canada_visitors.csv" input file.

    Returns: A pandas DataFrame object with a corrected index and substitutions
             correcting some entries in the data.
    """

    # Rename country column:
    canada_visitors = canada_visitors.rename(columns={"Country of residence": "Country"})

    # Set index:
    canada_visitors = canada_visitors.set_index("Country")

    # North America is a special case.
    # Let's add a row that reflects visitors from North America:
    north_america = canada_visitors.loc[[
        "North America, countries other than the United States of America",
        "United States of America residents entering Canada"]].sum()
    north_america.name = "North America"
    north_america = north_america.to_frame().transpose()
    canada_visitors = pd.concat([canada_visitors, north_america])

    return canada_visitors

# ----
# MAIN
# ----

# Load the command line argument:
canada_visitors_filepath = sys.argv[1]

#  Check that the passed filepath exists:
if not os.path.exists(canada_visitors_filepath):
    print("The passed filepath: " + str(canada_visitors_filepath) + " does not exist!")
    exit(1)

# Load the CSV file:
canada_visitors = pd.read_csv(canada_visitors_filepath)

# Make necessary substitutions in the data:
canada_visitors = substitute(canada_visitors)

# Select a specific month (May 2022):
monthly_visitors = canada_visitors[["2022-05"]]
monthly_visitors = monthly_visitors.rename(columns={"2022-05": "Visitors"})

# Build the region labels:
regions = ["North America", "South America", "Europe", "Africa", "Asia", "Oceania", "Antarctica"]

# Build the region counts:
counts = []

for region in regions:
    count = monthly_visitors.loc[region]["Visitors"]
    counts.append(count)

# Build the plot:
plt.close("all")
fig, ax = plt.subplots()

ax.bar(regions, counts)
ax.set_ylabel("visitors")
ax.set_title("Visitors to Canada by Region (May 2022)")
ax.set_yscale("log")  # Log scale because the counts are orders of magnitude different.

plt.minorticks_off()
plt.xticks(rotation=45, ha='right')  # Rotates x-axis labels.
plt.subplots_adjust(bottom=0.30)  # Makes room for x-axis labels.

plt.savefig("canada_visitors_by_region.png")
#plt.show()  # Useful for running on some systems.


import gym
import numpy as np

from reinforcement_learning_example.agent import Agent
from reinforcement_learning_example.utils import plot_learning_curve

def main():
    trainer = Trainer()
    trainer.train()

class Trainer:
    def __init__(
        self,
        gamma: float = 0.99,
        epsilon: float = 1.0,
        batch_size: int = 64,
        num_actions: int = 4,
        epsilon_min: float = 0.01,
        epsilon_dec: float = 5e-5,
        input_dims: list = [8],
        learning_rate: float = 0.001,
    ):

        self.env = gym.make("LunarLander-v2")

        self.agent = Agent(
            gamma=gamma,
            epsilon=epsilon,
            batch_size=batch_size,
            num_actions=num_actions,
            epsilon_min=epsilon_min,
            epsilon_dec=epsilon_dec,
            input_dims=input_dims,
            learning_rate=learning_rate,
        )
        self.scores, self.epsilon_history = [], []
        self.filename = "lunar_lander.png"
        self.episode_num = 0

    def train(self, num_episodes: int = 500, average_score_window: int = 100):
        try:
            for i in range(num_episodes):
                score = 0
                done = False
                observation = self.env.reset()
                while not done:
                    action = self.agent.choose_action(observation)
                    observation_, reward, done, info = self.env.step(action)
                    score += reward
                    self.agent.store_transition(observation, action, reward, observation_, done)
                    self.agent.learn()
                    observation = observation_
                self.scores.append(score)
                self.epsilon_history.append(self.agent.epsilon)

                average_score = np.mean(self.scores[-average_score_window:])
                self.episode_num += 1

                print(
                    f"episode_num {self.episode_num:>5} / episode {i:>5} / score {score:>8.2f} / "
                    f"average score {average_score:>8.2f} / epsilon {self.agent.epsilon:>3.2f}"
                )

        except KeyboardInterrupt:
            pass

        x = [i_ + 1 for i_ in range(len(self.scores))]

        plot_learning_curve(x, self.scores, self.epsilon_history, self.filename)

if __name__ == "__main__":
    main()


file = input("Enter the file location of your text:")
f = open(file,'r')
f = f.read()
listf=[]
for element in range(0, len(f)):
    listf.append(f[element])
dict={"a":0}
for i in range(len(listf)-1):
    flag = False
    for k in dict:
        if listf[i]==k:
            flag = True
            break
    if not(flag):
        dict[listf[i]]=0
for i in listf:
    dict[i]=dict.get(i)+1
for i in dict:
    dict[i]=(dict.get(i)*100/len(listf))
for i in dict:
    dict[i]=int(dict.get(i)//1)+1
    dict[i]=dict.get(i)*"*"
for i in sorted(dict.items()):
    print(i[0],":",i[1])


import bpy
from math import pi
import bmesh

# TODO: test if removing useless UV maps works.

def cleanup_mesh(obj,
		remove_doubles=False,
		quadrangulate=False,
		weight_normals=True,
		seams_from_islands=True,
		clear_unused_UVs=True,
		rename_single_UV=True):

	# Mode management
	org_active = bpy.context.object
	org_mode = org_active.mode
	org_selected = bpy.context.selected_objects[:]
	bpy.ops.object.mode_set(mode='OBJECT')
	bpy.ops.object.select_all(action='DESELECT')
	bpy.context.view_layer.objects.active = obj
	obj.select_set(True)
	bpy.ops.object.mode_set(mode='EDIT')

	# Unhide and deselect verts
	bpy.ops.mesh.reveal()
	bpy.ops.mesh.select_all(action='DESELECT')

	# Renaming shape key blocks
	if(obj.data.shape_keys is not None):
		obj.data.shape_keys.name = "Keys_" + obj.name

	# Setting auto-smooth to 180 is necessary so that splitnormals_clear() doesn't mark sharp edges
	obj.data.use_auto_smooth = True
	org_angle = obj.data.auto_smooth_angle
	obj.data.auto_smooth_angle = pi
	bpy.ops.mesh.customdata_custom_splitnormals_clear()
	obj.data.auto_smooth_angle = org_angle

	# Tris to Quads
	if(quadrangulate):
		bpy.ops.mesh.tris_convert_to_quads(shape_threshold=1.0472, uvs=True, materials=True)

	# Remove Doubles / Merge By Distance
	if(remove_doubles):
		bpy.ops.mesh.remove_doubles(threshold=0.0001)

	bpy.ops.object.mode_set(mode='OBJECT')
	if(weight_normals):
		bpy.ops.object.calculate_weighted_normals()
	bpy.ops.object.mode_set(mode='EDIT')

	### Removing useless UVMaps
	if(clear_unused_UVs):
		mesh = obj.data
		bm = bmesh.from_edit_mesh(mesh)

		# Invalid UV maps usually have all the verts on the top left or top right corner, so that's what we'll be checking for.
		# If all verts of a UV map have an X coordinate of 0, we're deleting it.

		for uv_idx in reversed(range(0, len(mesh.uv_layers))):			# For each UV layer (in reverse, since we're deleting)
			delet_this=True
			mesh.uv_layers.active_index = uv_idx
			bm.faces.ensure_lookup_table()
			for f in bm.faces:						# For each face
				for l in f.loops:					# For each loop(whatever that means)
					if(l[bm.loops.layers.uv.active].uv[0] != 0.0):	# If the loop's UVs first vert's x coord is NOT 0
						delet_this=False
						break
				if(delet_this==False):
					break
			if(delet_this):
				obj.data.uv_layers.remove(obj.data.uv_layers[uv_idx])

		bmesh.update_edit_mesh(mesh, True)

	# Renaming single UV maps
	if(len(mesh.uv_layers)==1 and rename_single_UV):
		mesh.uv_layers[0].name = 'UVMap'

	# Seams from islands
	if(seams_from_islands):
		bpy.ops.uv.seams_from_islands(mark_seams=True, mark_sharp=False)

	# Mode management
	bpy.ops.object.mode_set(mode='OBJECT')
	for o in org_selected:
		o.select_set(True)
	bpy.context.view_layer.objects.active = org_active
	bpy.ops.object.mode_set(mode=org_mode)

class CleanUpMesh(bpy.types.Operator):
	""" Clean up meshes of selected objects. """
	bl_idname = "object.mesh_cleanup"
	bl_label = "Clean Up Mesh"
	bl_options = {'REGISTER', 'UNDO'}

	# TODO: unhide all verts in edit mode.

	remove_doubles: bpy.props.BoolProperty(
		name="Remove Doubles",
		description="Enable remove doubles",
		default=False
	)

	quadrangulate: bpy.props.BoolProperty(
		name="Tris to Quads",
		description="Enable Tris to Quads (UV Seams enabledd)",
		default=False
	)

	weight_normals: bpy.props.BoolProperty(
		name="Weight Normals",
		description="Enable weighted normals",
		default=False
	)

	seams_from_islands: bpy.props.BoolProperty(
		name="Seams from Islands",
		description="Create UV seams based on UV islands",
		default=False
	)

	clear_unused_UVs: bpy.props.BoolProperty(
		name="Delete Unused UV Maps",
		description="If all UV verts' X coordinate is 0, the UV map will be deleted.",
		default=True
	)

	rename_single_UV: bpy.props.BoolProperty(
		name="Rename Singular UV Maps",
		description="If an object is only left with one UV map, rename it to the default name, 'UVMap'.",
		default=True
	)

	def execute(self, context):
		for o in bpy.context.selected_objects:
			cleanup_mesh(o,
				self.remove_doubles,
				self.quadrangulate,
				self.weight_normals,
				self.seams_from_islands,
				self.clear_unused_UVs,
				self.rename_single_UV)
		return {'FINISHED'}

def register():
	from bpy.utils import register_class
	register_class(CleanUpMesh)

def unregister():
	from bpy.utils import unregister_class
	unregister_class(CleanUpMesh)


from pynput.keyboard import Key
from printy import printy
import os
import sys

special_keys = {
    "alt": Key.alt,
    "alt gr": Key.alt_gr,
    "left alt": Key.alt_l,
    "right alt": Key.alt_r,
    "caps lock": Key.caps_lock,
    "ctrl": Key.ctrl,
    "left ctrl": Key.ctrl_l,
    "right ctrl": Key.ctrl_r,
    "delete": Key.delete,
    "down arrow": Key.down,
    "end": Key.end,
    "f1": Key.f1,
    "f2": Key.f2,
    "f3": Key.f3,
    "f4": Key.f4,
    "f5": Key.f5,
    "f6": Key.f6,
    "f7": Key.f7,
    "f8": Key.f8,
    "f9": Key.f9,
    "f10": Key.f10,
    "f11": Key.f11,
    "f12": Key.f12,
    "left arrow": Key.left,
    "right arrow": Key.right,
    "shift": Key.shift,
    "left shift": Key.shift_l,
    "right shift": Key.shift_r,
    "space": Key.space,
    "tab": Key.tab,
    "up arrow": Key.up,
}

def exit_app():
    try:
        sys.exit(1)
    except SystemExit:
        os._exit(1)

# Function which sets up the keybinds
def keybinds_setup(keys):
    # No one likes nested for loops but this has to be done :(
    for i in range(len(keys)):
        if keys[i] == "":
            current_button = "A" if i == 0 else "B"
            button_string = f"[yB]Warning:\nThe {current_button} button is not mapped to any key(s)!@"
            printy(button_string)
        for k, v in special_keys.items():
            if isinstance(keys[i], str) and keys[i] == k:
                keys[i] = v


from sklearn import linear_model
from sklearn import metrics
from sklearn.model_selection import train_test_split
import numpy as np
import torch

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

class TCAV(object):
    """
    TCAV model, for producing TCAV scores between a given model layer and concept. Also contains CAV vectors for a set of concepts.

    Attributes
    ----------
    model : PyTorch model
        The model used to calculate CAV vectors
    cavs : dict
        Dictionary with CAV vectors for each concept and model layer. Indexed as cavs[CONCEPT][LAYER NUMBER]

    Methods
    -------
    get_sensitivites:
        Calculates the dot product between a CAV vector and the gradients of a given model layer. These sensitivites are used in calculating the TCAV score
    get_score:
        Calculates the TCAV score by calculating the ratio of sensitivites which are positive for a given layer and concept
    get_sensitive_indexes:
        Generates indexes of dataset which have a positive sensitivity to a given CAV vector
    get_CAV:
        Generates the CAV vector for an input concept dataset
    """

    def __init__(self, model, concept_datasets):

        # Save Model
        self.model = model
        self.model.model.eval()

        # Generate CAV for each concept
        self.cavs = {}
        for concept_dataset in concept_datasets:
            cav, acc = self.get_CAV(concept_dataset)
            self.cavs[concept_dataset.datasets[0].root] = cav

    def get_sensitivities(self, gradients, concept, data_class, layer):
        return np.dot(gradients[data_class][layer].reshape(gradients[data_class][layer].shape[0], -1), self.cavs[concept][layer])

    def get_score(self, gradients, concept, data_class, layer):
        dots = self.get_sensitivities(gradients, concept, data_class, layer)
        return len(dots[dots > 0])/len(dots)

    def get_sensitive_indexes(self, gradients, concept, data_class, layer):
        dots = self.get_sensitivities(gradients, concept, data_class, layer)
        return np.where(np.array(dots) > 0)[0]

    def get_CAV(self, concept_dataset):

        # Generate model activations for concept dataset
        linear_loader = torch.utils.data.DataLoader(
            concept_dataset, batch_size=len(concept_dataset))
        data, activations_targets = next(iter(linear_loader))
        self.model(data.to(device))

        accs = {}
        cavs = {}

        # Generate CAV vector for each model layer
        for layer in self.model.intermediate_activations:

            # Extract model layer activations
            activations_features = self.model.intermediate_activations[layer].cpu(
            ).detach().numpy()

            activations_features = (activations_features-activations_features.mean())/activations_features.std()

            # Train linear model
            x_train, x_test, y_train, y_test = train_test_split(
                activations_features.reshape((activations_features.shape[0], -1)), activations_targets, test_size=0.15,random_state=42)

            lm = linear_model.SGDClassifier(alpha=0.01, max_iter=2000, tol=1e-3,random_state=42)
            lm.fit(x_train, y_train)

            # Calculate linear model prediction accuracy
            y_pred = lm.predict(x_test)
            num_classes = len(activations_targets.unique())
            acc = {}
            num_correct = 0
            for class_id in range(num_classes):
                idx = (y_test.numpy() == np.array(class_id))
                acc[str(class_id)] = metrics.accuracy_score(
                    y_pred[idx], np.array(y_test)[idx])
                num_correct += (sum(idx) * acc[str(class_id)])
            acc['overall'] = float(num_correct) / float(len(y_test))

            # Store CAV and linear model accutacy
            accs[layer] = acc
            cavs[layer] = lm.coef_[0]

        return cavs, accs


import pytest
import tempfile

from runner import main as runner
from differ import main as differ
from test_utils import get_expected_path

TOOL = 'ttxn'

OTF_FONT = 'SourceSansPro-Black_subset.otf'
TTF_FONT = 'SourceSansPro-Black_subset.ttf'
OTF2_FONT = 'SourceSansPro-ExtraLightIt.otf'
OTF3_FONT = 'SourceSansPro-Light.otf'
TTF2_FONT = 'NotoNaskhArabic-Regular.ttf'
TTF3_FONT = 'NotoNastaliqUrdu-Regular.ttf'

# -----
# Tests
# -----

@pytest.mark.parametrize('args, font_filename, exp_filename', [
    ([], OTF_FONT, 'OTF.ttx'),
    ([], TTF_FONT, 'TTF.ttx'),
    (['nh'], OTF_FONT, 'OTF_no_hints.ttx'),
    (['tGPOS'], OTF_FONT, 'OTF_GPOS_only.ttx'),
    (['tGSUB'], OTF_FONT, 'OTF_GSUB_only.ttx'),
    (['tGPOS'], OTF2_FONT, 'OTF2_GPOS_only.ttx'),
    (['tGSUB'], OTF2_FONT, 'OTF2_GSUB_only.ttx'),
    (['tGPOS'], OTF3_FONT, 'OTF3_GPOS_only.ttx'),
    (['tGSUB'], OTF3_FONT, 'OTF3_GSUB_only.ttx'),
    (['tGPOS'], TTF2_FONT, 'TTF2_GPOS_only.ttx'),
    (['tGSUB'], TTF2_FONT, 'TTF2_GSUB_only.ttx'),
    (['tGPOS', 'se'], TTF3_FONT, 'TTF3_GPOS_only.ttx'),
    (['tGSUB', 'se'], TTF3_FONT, 'TTF3_GSUB_only.ttx'),
])
def test_dump(args, font_filename, exp_filename):
    save_path = tempfile.mkstemp()[1]
    runner(['-t', TOOL, '-f', font_filename, '-o',
            f'o{save_path}'] + args)
    expected_path = get_expected_path(exp_filename)
    assert differ([expected_path, save_path, '-s', '<ttFont sfntVersion'])


#!/bin/python3
from collections import namedtuple
from typing import List
from ctypes import *
import pathlib
import sys

Point = namedtuple('Point', ['x', 'y'])
libPath = pathlib.Path().absolute() / "lib/libLongestSequence.so"

def readFile(path: str):
    """
    Reads a file from a given path, and returns its contents as a list of strings
    :param path: the path to file, containing the input for the program
    :return: List of strings, with the contents of the file
    """
    print("\n" + path + "\n")
    res = []
    with open(path, 'r') as reader:
        for line in reader.readlines():
            res.append(line)
    return res

def parseFileInput(data: List[str]):
    """
    From a List of strings, converts the user input to 2d matrix of integers, and a point (the size of the matrix)
    :param userInput:
    :return 2d matrix of ints and Point structure:
    """
    rowsAndCols = data[0].strip().split(' ')
    rows = int(rowsAndCols[0])
    cols = int(rowsAndCols[1])

    res = ''
    for line in data[1:]:
        for item in line.strip().split(' '):
            res += item

    return res, [rows, cols]

def libSetup(path):
    """
    Takes the path to the shared library, performs functions setup and returns the ready to use library.
    :param path:
    :return CDLL Library:
    """
    lib = CDLL(path)
    lib.visitPoints.argtypes = [c_int, c_int, c_char_p]
    lib.visitPoints.restype = c_int
    return lib

def execute(pathToFile):
    """
    Takes the path to the provided command line argument/file and executes the rest of the program functions.
    :param path to file:
    :return C lang shared library return:
    """
    lib = libSetup(libPath)
    data = readFile(pathToFile)
    parsedData = parseFileInput(data)
    matrix = c_char_p(parsedData[0].encode('utf-8'))

    return lib.visitPoints(parsedData[1][0], parsedData[1][1], matrix)

if __name__ == '__main__':
    """
    The starting point of the program. Takes the supplied command line arguments
    and passes them to run()
    """
    for arg in sys.argv[1:]:
        print(execute(arg))


# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 3 of the License, or (at your option) any
# later version.  See http://www.gnu.org/copyleft/lgpl.html for the full text
# of the license.

__author__ = 'Marco Trevisan'
__copyright__ = '(c) 2021 Canonical Ltd.'

import dbus
import fcntl
import os
import subprocess

from collections import OrderedDict
from dbusmock import DBusTestCase

BUS_NAME = 'org.gnome.Mutter.TestDBusMocksManager'
MAIN_OBJ = '/org/gnome/Mutter/TestDBusMocksManager'
MAIN_IFACE = 'org.gnome.Mutter.TestDBusMocksManager'
SYSTEM_BUS = True

def load(mock, parameters):
    mock.mocks = OrderedDict()
    DBusTestCase.setUpClass()
    mock.dbus_mock = DBusTestCase()
    mock.dbus_mock.setUp()
    mock.templates_dir = parameters['templates-dir']

def set_nonblock(fd):
    '''Set a file object to non-blocking'''

    flags = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)

@dbus.service.method(MAIN_IFACE, in_signature='s')
def StartFromTemplate(self, template):
    if template in self.mocks.keys():
        raise KeyError('Template {} already started'.format(template))

    mock_server, mock_obj = self.dbus_mock.spawn_server_template(template, {},
        stdout=subprocess.PIPE)
    set_nonblock(mock_server.stdout)

    self.mocks[template] = (mock_server, mock_obj)

@dbus.service.method(MAIN_IFACE, in_signature='s')
def StartFromLocalTemplate(self, template):
    path = os.path.join(self.templates_dir, template + '.py')
    return self.StartFromTemplate(path)

@dbus.service.method(MAIN_IFACE, in_signature='s')
def StopTemplate(self, template):
    (mock_server, mock_obj) = self.mocks.pop(template)
    mock_server.terminate()
    mock_server.wait()

@dbus.service.method(MAIN_IFACE, in_signature='s')
def StopLocalTemplate(self, template):
    path = os.path.join(self.templates_dir, template + '.py')
    return self.StopTemplate(path)

@dbus.service.method(MAIN_IFACE)
def Cleanup(self):
    for (mock_server, mock_obj) in reversed(self.mocks.values()):
        mock_server.terminate()
        mock_server.wait()

    self.dbus_mock.tearDown()
    DBusTestCase.tearDownClass()

@dbus.service.method(MAIN_IFACE, out_signature='as')
def ListRunningTemplates(self):
    return list(self.mocks.keys())


"""Linked List implementation."""

class Node(object):

    def __init__(self, data):
        self.data = data
        self.next = None

    def get_data(self):
        return self.data

class LinkedList(object):

    def __init__(self):
        self.head = None
        self.tail = None

    def get_head(self):
        return self.head

    def append(self, data):
        new_node = Node(data)
        # empty LL so set head, here - head and tail are same b/c only 1 Node
        if self.head is None:
            self.tail = new_node
            self.head = self.tail
        else:
            self.tail.next = new_node # add to node to chain
            self.tail = new_node      # set new value for tail

    def iterate(self):
        _head = self.head
        while _head is not None:
            print('Curr node val: {data}'.format(data=_head.data))
            _head = _head.next

    def remove_node(self, data):
        # if it's the head node, just set head to head.next and return
        if self.head.data == data:
            self.head = self.head.next
            return self.head
        # otherwise, iterate
        n = self.head
        # while the next node is not Null...
        while n.next is not None:
            # test to see if it is our target
            if n.next.data == data:
                # if so, set it to its next Node and return
                n.next = n.next.next
                return self.head
            # otherwise, keep iterating
            n = n.next

    def get_node(self, data):
        print('entry')

        if self.head.data == data:
            return self.head

        n = self.head
        while n.next is not None:
            if n.next.data == data:
                print('llooking for node')
                return n.next
            n = n.next

        return None


import sys
si = sys.stdin.readline
a, b = map(int, si().split())

s1 = a
s2 = b

while True:
  x = s1 % s2
  if x == 0:
    break
  else:
    s1 = s2
    s2 = x

print(s2)
print(s2 * (a // s2) * (b // s2))

# https://www.acmicpc.net/problem/2609
# 학교시험에 나왔었던 알고리즘 방법이였다.
# PASS

WEEK3/min/알고리즘기초1/300_수학1/2609_최대공약수와 최소공배수.PY

2609_최대공약수와 최소공배수.PY


class Receipt(object):
    def __init(self):
        self.__title = "Sandwich"
        self.css = "css/styles.css"
        self.__head = """
<!DOCTYPE HTML>
<html>
    <head>
        <title>Enter your information:</title>
        <link href="css/styles.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
        """
        self.body = ""
        self.__error = ' '
        self.__close = """
    </body>
</html>
        """
    def compile_order(self):
        return all


"""Preconfigured converters for msgpack."""
from datetime import datetime, timezone

from .._compat import Set
from ..converters import GenConverter

def configure_converter(converter: GenConverter):
    """
    Configure the converter for use with the msgpack library.

    * datetimes are serialized as timestamp floats
    * sets are serialized as lists
    """
    converter.register_unstructure_hook(datetime, lambda v: v.timestamp())
    converter.register_structure_hook(
        datetime, lambda v, _: datetime.fromtimestamp(v, timezone.utc)
    )

def make_converter(*args, **kwargs) -> GenConverter:
    kwargs["unstruct_collection_overrides"] = {
        **kwargs.get("unstruct_collection_overrides", {}),
        Set: list,
    }
    res = GenConverter(*args, **kwargs)
    configure_converter(res)

    return res


import robot_util
import mod_utils
import extended_command
import logging
log = logging.getLogger('LR.hardware.telly')

module = None
ser = None

def setup(robot_config):
    global module
    global ser

    module = mod_utils.import_module('hardware', 'serial_board')
    ser = module.setup(robot_config)

    if robot_config.getboolean('tts', 'ext_chat'): #ext_chat enabled, add motor commands
        extended_command.add_command('.set', set_eeprom)

def move(args):
    module.move(args)

def set_eeprom(command, args):
    if is_authed(args['name']) == 1: # Owner
        if len(command) >= 2:
            try:
                if command[1] == 'left':
                    setting = int(command[3]) # This is here to catch NAN errors
                    if command[2] == 'forward':
                        robot_util.sendSerialCommand(ser, "lwfs " + str(setting))
                        log.info("left_wheel_forward_speed set to %d", setting)
                    elif command[2] =='backward':
                        robot_util.sendSerialCommand(ser, "lwbs " + str(setting))
                        log.info("left_wheel_backward_speed set to %d", setting)
                elif command[1] == 'right':
                    setting = int(command[3]) # This is here to catch NAN errors
                    if command[2] == 'forward':
                        robot_util.sendSerialCommand(ser, "rwfs " + str(setting))
                        log.info("right_wheel_forward_speed set to %d", setting)
                    elif command[2] =='backward':
                        robot_util.sendSerialCommand(ser, "rwbs " + str(setting))
                        log.info("right_wheel_backward_speed set to %d", setting)
                elif command[1] == 'straight':
                    setting = int(command[2])
                    robot_util.sendSerialCommand(ser, "straight-distance " + str(int(setting * 255)))
                    log.info("straigh_delay set to %d", setting)
                elif command[1] == 'turn':
                    setting = int(command[2])
                    robot_util.sendSerialCommand(ser, "turn-distance " + str(int(setting * 255)))
                    log.info("turn_delay set to %d", setting)
                elif command[1] == 'brightness':
                    setting = int(command[2]) # This is here to catch NAN errors
                    robot_util.sendSerialCommand(ser, "led-max-brightness " + str(setting))
                    log.info("led_man_brightness to %d", setting)
            except ValueError:
                pass


import numpy as np
import random

def findneighbours(pos,k):
	n = k*k
	neighbours = []
	if pos+k<n :
		neighbours.append(pos+k)
	if pos-k>=0 :
		neighbours.append(pos-k)
	if((pos+1)%k!=0):
		neighbours.append(pos+1)
	if((pos)%k!=0):
		neighbours.append(pos-1)
	return neighbours

def swapsit(arr,iterations,k):

	# length = len(arr)

	for i in range(iterations):
		pos0 = int(np.where(arr==0)[0])
		neigh = findneighbours(pos0,k)
		index2 = int(neigh[random.randint(0,len(neigh)-1)])
		# print(index2)
		temp = arr[pos0]
		arr[pos0] = arr[index2]
		arr[index2] = temp
	return arr

sizen = int(input('Enter the the value of n  = '))

fd=open('input_npuz.txt','w')

for i in range(2,sizen):
	for j in range(5):
		k = i
		n= k*k-1
		temparr = np.arange(n+1)
		arr = np.append(temparr[1:],temparr[0])
		print(arr)
		# print(arr)
		modified_list = swapsit(arr,random.randint(0,10),k)
		line = str(k) + ' ' + str(modified_list)
		fd.write(line)
		fd.write('\n')

fd.close()


from kafka import KafkaProducer
from time import sleep
from json import dumps
import random
import string
from datetime import datetime
import requests
import time

topic_name = "StockTopic"

def generate_ticker(length):
    return "".join(random.choices(string.ascii_uppercase, k=length))

price_range = (10, 100)

def get_random_float(n_range):
    return random.uniform(n_range[0], n_range[1])

def get_random_int(n_range):
    return random.randint(n_range[0], n_range[1])

def initialize_tickers():
    tickers = []
    for i in range(10):
        ticker = generate_ticker(5)
        tickers.append(ticker)
    ticker_dict = {}
    price_range = (10, 100)
    qty_range = (10000, 20000)
    for ticker in tickers:
        row = {
            "open_price": get_random_float(price_range),
            "close_price": 0,
            "high": 0,
            "low": 99999,
            "volume": 0,
            "available_quantity": get_random_int(qty_range),
            "current_price": 0,
            "timestamp": datetime.now(),
        }
        ticker_dict[ticker] = row
    return ticker_dict

def test_producer():
    producer = KafkaProducer(
        bootstrap_servers="localhost:29092",
        value_serializer=lambda x: dumps(x).encode("utf-8"),
    )
    for e in range(100):
        data = {"number": e}
        print(e)
        producer.send(topic_name, value=data)
        sleep(5)

def generate_radom_stock_data(ticker_dict):
    ticker, row = random.choice(list(ticker_dict.items()))
    current_price = get_random_float(price_range)
    ticker_dict[ticker]["high"] = max(current_price, ticker_dict[ticker]["high"])
    ticker_dict[ticker]["low"] = min(current_price, ticker_dict[ticker]["low"])
    ticker_dict[ticker]["current_price"] = current_price
    ticker_dict[ticker]["timestamp"] = datetime.now()

    data_row = {}
    data_row["ticker"] = ticker
    data_row = data_row | ticker_dict[ticker]
    data_row["timestamp"] = data_row["timestamp"].strftime("%Y-%m-%d %H:%M:%S")
    return ticker_dict, data_row

def main():
    ticker_dict = initialize_tickers()
    i = 0
    # url = 'http://127.0.0.1:8001/stocks/'
    producer = KafkaProducer(
        bootstrap_servers="localhost:29092",
        value_serializer=lambda x: dumps(x).encode("utf-8"),
    )
    NUMBER_OF_DATA = 1000
    while i < 1000:
        ticker_dict, data_row = generate_radom_stock_data(ticker_dict)
        producer.send(topic_name, value=data_row)
        print(data_row)
        i += 1
        time.sleep(0.5)

if __name__ == main():
    main()


from .base import BaseRepository
from orm.purchase_map import PurchaseEntity
from models.purchase import ParsePay, PurchaseIn, PurchaseData, Purchase, PurchaseItem, DeletePurchase
from requests import post
from os import getenv
class PurchaseRepository(BaseRepository):

    def __init__(self, orm_obj):
        self.db_orm: PurchaseEntity = orm_obj

    async def request_fns(self, getting_data: PurchaseData) -> Purchase:
        token = getenv("TOKEN_FNS")
        data = {
            'fn': getting_data.fn,
            'fd' : getting_data.fd,
            'fp': getting_data.fp,
            't' : getting_data.t,
            'n' : getting_data.n,
            's' : getting_data.amount,
            'qr' : '0',
            'token': token
        }
        url = "https://proverkacheka.com/api/v1/check/get"
        req = post(url=url, data=data)
        if req.status_code == 200:
            # print(req.json())
            return ParsePay.parse_obj((req.json()['data']['json']))
        else:
            return False

    async def add_purchase(self, purchase_data: PurchaseIn) -> bool:
        """Добавление покупки"""
        if not await self.db_orm.check(purchase_data.token_sk, purchase_data.customer_sk, purchase_data.group_id):
            return False
        data = PurchaseData(
            fn=purchase_data.fn,
            fd=purchase_data.fd,
            fp=purchase_data.fp,
            t=purchase_data.t,
            n=purchase_data.n,
            amount=purchase_data.amount
        )

        receipt_info = await self.request_fns(data)
        print(receipt_info)
        result_items = list()

        for item in receipt_info.items:
            result_items.append(PurchaseItem(
                name_product=item.name,
                price=item.price,
                quantity=item.quantity,
            ))

        receipt = Purchase(
            group_id=purchase_data.group_id,
            name_store=receipt_info.user,
            total_amount=receipt_info.totalSum,
            category_id=purchase_data.category_id,
            items=result_items
        )

        responce_db = await self.db_orm.additing_purchase(receipt)
        return responce_db

    async def delete_purchase(self, purchase_data: DeletePurchase):
        if not await self.db_orm.check(purchase_data.token_sk, purchase_data.customer_sk, purchase_data.group_id):
            return False

        return await self.db_orm.delete_purchase(purchase_sk=purchase_data.purchase_id)

    async def get_purchase_today(self):
        """Получение покупок за сегодня"""

    async def get_purchase_week(self):
        """Получение покупок за неделю"""

    async def get_purchase_month(self):
        """Получение покупок за месяц"""

    async def get_purchase_year(self):
        """Получение покупок за год"""

    async def get_purchase_date_range(self):
        """Получение покупок за выбранный период"""


#!/usr/bin/env python

"""
    title:      Python Connections Manager - sqlite3 DB Updater

    date:       10.14.2009

    author:     Lupine  - http://www.thelupine.com

    description:    Quik script to update hostsfile.db with new table structure

"""

#python imports
import sys
import os
import subprocess
import re
import sqlite3

#Global variables
APPCONFDIR      = "/.pyconnmgr"
HOSTSFILE       = os.environ["HOME"] + APPCONFDIR + "/hostsfile.db"

#functions
def update_sqlhostsfile():
    """
    This function will check for the existence of a HOSTSFILE and if found,
    update it's table structure
    """
    if (os.path.isfile(HOSTSFILE)):
        sqlconn = sqlite3.connect(HOSTSFILE)
        sqlcursor = sqlconn.cursor()

        #update table
        sqlcursor.execute('''alter table hosts
                            add tab int''')

        #commit the changes, and close the DB
        sqlconn.commit()
        sqlconn.close

if __name__ == "__main__":
    update_sqlhostsfile()


from flask import render_template, request, redirect, url_for
from application import service2
import random, requests

female = ["Brewmistress", "Denirim ('priest')", "Earth-Guide", "Farmtender", "Foodmaker",
          "Healer", "Hunter", "Mage", "Teacher", "Weavewender"]

male = ["Denerim ('priest')", "Earth-Guide", "Healer", "Leader", "Mage",
        "Miner", "Sender", "Smith", "Woodsmith", "Hunter"]

clan = ["Longbeards", "Firebeards", "Ironfists", "Stonefoots"]

job = {"clan":"none", "job":"none"}

@service2.route('/job', methods=['GET', 'POST'])
def random_job():
    if request.method == 'POST':
        data = request.args.get("gender")
        if data == "Female":
            job["gender"] = data
            job["job"] = female[random.randint(0, 9)]
            job["clan"] = clan[random.randint(0 , 3)]
            return job
        elif data == "Male":
            job["gender"] = data
            job["job"] = male[random.randint(0, 9)]
            job["clan"] = clan[random.randint(0 , 3)]
            return job

    return {"job":"failure"}


"""Ejercicios de reforzamiento: Primera parte"""

"""Alumma: Karina Belén Pinao Gonzales"""

"""Pregunta 1: Creando una lista de 6 objetos"""

cursos = ["matemáticas", "biología", "estadística", " sociales", "inglés", "química"]

print("Los cursos que lleve en la universidad son: {}".format(cursos))

"""Pregunta 2: Agregando 4 elementos nuevos a la lista creada con list.append(x)"""

cursos.append("biofísica")
cursos.append("farmaco")
cursos.append("histo")
cursos.append("epidemio")

print("Mi lista actualizada es: {}".format(cursos))

"""Pregunta 3: Quitando 2 elementos por valor a la lista anterior con list.remove(x)"""

cursos.remove("biofísica")
cursos.remove("química")

print("Mi lista sin 2 elementos es: {}".format(cursos))

"""Pregunta 4: Invirtiendo el orden de los elementos con list.reverse(x)"""

cursos.reverse()

print("Mi lista invertida es: {}".format(cursos))

"""Pregunta 5: Obteniendo la cantidad total de elementos con len(list(x))"""

print("Mi lista tiene {} elementos".format((len(cursos))))

"""Pregunta 6: Obteniendo el número de veces que se repite un elemento con list.count(x)"""

cursos.append("estadística")

print("La lista con repetición es: {}".format(cursos))

print("El número de veces que se repite 'estadística' es: {}".format(cursos.count("estadística")))

"""Pregunta 7: Borrando un elemento usando su índice con list.pop(x)"""

cursos.pop(0)

print("La lista actualizada sin el primer elemento es: {}".format(cursos))

"""Pregunta 8: Creando una nueva lista vacía y agregando elementos de diferente clase"""

lista2 = []

print(lista2)

# Agregando 3 elementos float:

lista2.append(3.5)
lista2.append(8.2)
lista2.append(9.6)

# Agregando 3 elementos int:

lista2.append(74)
lista2.append(140)
lista2.append(205)

# Agregando 3 elementos string:

lista2.append("Python")
lista2.append("Java")
lista2.append("SQLServer")

print("La nueva lista tiene los siguientes elementos: {}".format(lista2))

"""Pregunta 9: Sumando dos listas creadas anteriormente"""

lista3 = cursos + lista2

print("La nueva lista fusionada es: {}".format(lista3))

"""Pregunta 10: Ordenando los elementos de una lista"""

# Primero creamos las listas en desorden:

lista4 = ["variables", "estructuras", "datos", "elementos"]

print("Mi primera lista sin ordenar es: {}".format(lista4))

lista5 = [105.9, 47, 3.5, 800]

print("Mi segunda lista sin ordenar es: {}".format(lista5))

# Ahora ordenamos las listas

lista4.sort()

print("Mi primera lista ordenada es: {}".format(lista4))

lista5.sort()

print("Mi segunda lista ordenada es: {}".format(lista5))

"""Pregunta 11: Imprimiendo elementos de una lista por índice usando list[i]"""

# Creando lista con 4 elementos float y 2 elementos bools

lista6 = [209.71, 91.03, False, 78.25, True, 4.39]

print("La lista tiene los siguientes elementos: {}".format(lista6))

# Imprimiendo el penúltimo elemento

print("El elemento en la penúltima posición de la lista es: {}".format(lista6[4]))

# Imprimiendo el último elemento

print("El elemento en la última posición de la lista es: {}".format(lista6[5]))

"""Pregunta 12: Reconociendo los tipos de dato usando type(x)"""

print("El tipo de variable de '209.71' es: {}".format(type(209.71)))

print("El tipo de variable de 91.03 es: {}".format(type(91.03)))

print("El tipo de variable de False es: {}".format(type(False)))

print("El tipo de variable de 78.25 es: {}".format(type(78.25)))

print("El tipo de variable de True es: {}".format(type(True)))

print("El tipo de variable de 4.34 es: {}".format(type(4.39)))

"""Pregunta 13: Eliminando elementos de una lista por valor con list.clear(x)"""

lista6.clear()

print("El nuevo estado de la lista6 es: {}".format(lista6))

"""Pregunta 14: Eliminando elementos de una lista por índice"""

# Creando previamente la lista

lista7 = ["Brasil", "Colombia", "Argentina", "Bolivia", "Uruguay"]

print("La lista original es: {}".format(lista7))

# Primera forma: Eliminando elementos por índice usando list.pop(i)

lista7.pop(3)

print("La lista actualizada es: {}".format(lista7))

# Segunda forma: Eliminando elementos por índice usando del list[i]

del lista7[1]

print("la lista nuevamente actualizada es: {}".format(lista7))

"""Pregunta 15: Creando una lista con los 100 primeros enteros"""

# Definimos una función y usamos range

def listado_de_numeros(n):
    numeros = []

    for i in range(1, n + 1):
        numeros.append(i)

    return numeros

listado = listado_de_numeros(100)

print("Los primeros cien números son: {}".format(listado))

# Una segunda forma es usando list(range(m, n)) que empieza en m y acaba en n-1

lista_numeros = list(range(1, 101))

print("Los primeros cien números son: {}".format(lista_numeros))

"""Pregunta 16: Mostrar solo los datos comprendidos entre la posición 10 y 35"""

# Usando la variable 'listado' que creamos en la pregunta 15, definimos las posiciones de inicio y final (n-1)

intervalo = listado[10: 36]

print("Los números del intervalo son: {}".format(intervalo))

# Otra forma es usando la variable 'lista_numeros' que creamos mediante 'list(range())'

intervalo2 = lista_numeros[10:36]

print("Los números del intervalo son: {}".format(intervalo2))

"""Pregunta 17: Creando una lista con los primeros 10 números al cuadrado"""

# Definimos la función y usamos range

def numeros_cuadrados(n):
    cuadrados = []

    for i in range(1, n + 1):
        cuadrados.append(i**2)

    return cuadrados

resultado = numeros_cuadrados(10)

print("Los 10 primeros números al cuadrado son: {}".format(resultado))

# También podemos crear una sintaxis similar para obtener los cubos

def numeros_cubos(n):
    cubos = []

    for i in range(1, n + 1):
        cubos.append(i**3)

    return cubos

resultado2 = numeros_cubos(10)

print("Los 10 primeros números al cubo serían: {}".format(resultado2))

"""Pregunta 18: Creando una lista con números impares, insertar y borrar elementos por índice"""

# Creando una lista con los 15 primeros números impares

def numeros_impares(n):
    impares = []

    for i in range(1, n + 1, 2):
        impares.append(i)

    return impares

resultado3 = numeros_impares(30)

print("Los 15 primeros números impares son: {}".format(resultado3))

# Agregando 3 números flotantes repetidos dentro del rango

resultado3.append(7.0)
resultado3.append(13.0)
resultado3.append(5.0)

print("La lista de números impares actualizada es: {}".format(resultado3))

# Agregando un valor cadena en la posición 3 usando list.insert(i, x)

resultado3.insert(3, "enteros")

print("La lista de números impares con un valor cadena es: {}".format(resultado3))

# Eliminando el valor cadena usando del list[i]

del resultado3[3]

print("La lista actualizada sin el valor cadena es: {}".format(resultado3))

# También se puede obtener los números pares cambiando el índice de inicio

def numeros_pares(n):
    pares = []

    for i in range(2, n + 1, 2):
        pares.append(i)

    return pares

resultado4 = numeros_pares(30)

print("Los 15 primeros números pares serían: {}".format(resultado4))

"""Pregunta 19"""

Nuevalista = [None] * 10

print(Nuevalista)

print("Mi lista tiene {} posiciones".format(len(Nuevalista)))

# Reemplazando valores en las posiciones existentes

Nuevalista[0: 10] = 13, 16, 19, 22, 25, 28, 31, 34, 37, 40

print("Mi lista actualizada es: {}".format(Nuevalista))

print("El lista actualizada tiene {} elementos".format(len(Nuevalista)))

# Obteniendo las posiciones

for posiciones in range(len(Nuevalista)):
    print(posiciones)

# Obteniendo los valores

for i in range(len(Nuevalista)):
    print(Nuevalista[i])

# Sumando los elementos de una lista

suma_de_elementos = 0

for suma in Nuevalista:
    suma_de_elementos += suma

print("La suma de los elementos es: {}".format(suma_de_elementos))

# Otra forma de obtener la suma

suma_de_elementos2 = sum(Nuevalista)
print(suma_de_elementos2)

# Obteniendo el promedio de los elementos

cantidad_de_elementos = len(Nuevalista)

print("Mi lista tiene {} elementos".format(cantidad_de_elementos))

promedio = suma_de_elementos/cantidad_de_elementos

print("La media de los números de la lista es {}".format(promedio))

# Enviar a cursoscerseu6.fisi@unmsm.edu.pe


import turtle
import random

wn = turtle.Screen()
wn.bgcolor("black")
wn.title("Bouncing Ball Simulator")
wn.tracer(0)

balls = []

color = ["red", "blue", "yellow", "orange", "white", "purple"]
shape = ["circle", "triangle", "square"]

for _ in range(25):
    balls.append(turtle.Turtle())

for ball in balls:
    ball.shape(random.choice(shape))
    ball.color(random.choice(color))
    ball.penup()
    ball.speed(0)
    x = random.randint(-290, 290)
    y = random.randint(200, 325)
    ball.goto(x, y)
    ball.dy = 0
    ball.dx = random.randint(-3, 3)
    ball.da = random.randint(-5, 5)

gravity = 0.09

while True:

    wn.update()

    for ball in balls:
        ball.rt(ball.da)
        ball.dy -= gravity
        ball.sety(ball.ycor() + ball.dy)

        ball.setx(ball.xcor() + ball.dx)

        # check for wall
        if ball.xcor() > 300:
            ball.dx *= -1
            ball.da *= -1

        if  ball.xcor() < -300:
            ball.setx(-300)
            ball.dx *= -1
            ball.da *= -1

        # check for bounce
        if ball.ycor() < -300:
            ball.sety(-300)
            ball.dy *= -1
            ball.da *= -1

    # check for each other
    for i in range(0, len(balls)):
        for j in range(i+1, len(balls)):
            #check for colition
            if balls[i].distance(balls[j]) < 27:
                temp_dx = balls[i].dx
                temp_dy = balls[i].dy

                balls[i].dx = balls[j].dx
                balls[i].dy = balls[j].dy

                balls[j].dx = temp_dx
                balls[j].dy = temp_dy


from os import getuid

from pyrsistent import pmap
from twisted.python.components import proxyForInterface
from zope.interface import implementer

from ....common.process import run_process
from ....testtools import random_name

from ..blockdevice import IBlockDeviceAPI, IProfiledBlockDeviceAPI
from ..blockdevice_manager import BlockDeviceManager, _unmount
from ..loopback import (
    LOOPBACK_MINIMUM_ALLOCATABLE_SIZE,
    LoopbackBlockDeviceAPI,
    Losetup,
)

from . import detach_destroy_volumes

def loopbackblockdeviceapi_for_test(test_case, allocation_unit=None):
    """
    :returns: A ``LoopbackBlockDeviceAPI`` with a temporary root directory
        created for the supplied ``test_case``.
    """
    user_id = getuid()
    if user_id != 0:
        test_case.skipTest(
            "``LoopbackBlockDeviceAPI`` uses ``losetup``, "
            "which requires root privileges. "
            "Required UID: 0, Found UID: {!r}".format(user_id)
        )

    root_path = test_case.mktemp()
    loopback_blockdevice_api = LoopbackBlockDeviceAPI.from_path(
        root_path=root_path,
        compute_instance_id=random_name(test_case),
        allocation_unit=allocation_unit,
    )
    test_case.addCleanup(detach_destroy_volumes, loopback_blockdevice_api)
    return loopback_blockdevice_api

@implementer(IProfiledBlockDeviceAPI)
class FakeProfiledLoopbackBlockDeviceAPI(
        proxyForInterface(IBlockDeviceAPI, "_loopback_blockdevice_api")):
    """
    Fake implementation of ``IProfiledBlockDeviceAPI`` and ``IBlockDeviceAPI``
    on top of ``LoopbackBlockDeviceAPI``. Profiles are not actually
    implemented for loopback devices, but this fake is useful for testing the
    intermediate layers.

    :ivar _loopback_blockdevice_api: The underlying ``LoopbackBlockDeviceAPI``.
    :ivar pmap dataset_profiles: A pmap from blockdevice_id to desired profile
        at creation time.
    """
    def __init__(self, loopback_blockdevice_api):
        self._loopback_blockdevice_api = loopback_blockdevice_api
        self.dataset_profiles = pmap({})

    def create_volume_with_profile(self, dataset_id, size, profile_name):
        """
        Calls the underlying ``create_volume`` on
        ``_loopback_blockdevice_api``, but records the desired profile_name for
        the purpose of test validation.
        """
        volume = self._loopback_blockdevice_api.create_volume(
            dataset_id=dataset_id, size=size)
        self.dataset_profiles = self.dataset_profiles.set(
            volume.blockdevice_id, profile_name)
        return volume

def fakeprofiledloopbackblockdeviceapi_for_test(test_case,
                                                allocation_unit=None):
    """
    Constructs a ``FakeProfiledLoopbackBlockDeviceAPI`` for use in tests that
    want to verify functionality with an ``IProfiledBlockDeviceAPI`` provider.
    """
    return FakeProfiledLoopbackBlockDeviceAPI(
        loopback_blockdevice_api=loopbackblockdeviceapi_for_test(
            test_case, allocation_unit=allocation_unit))

def formatted_loopback_device_for_test(test_case, label=None):
    """
    Create a loopback device, with a backing file located in the temporary
    directory for this test case.
    Format it with ext4 and optionally add a filesystem label.
    Registers test cleanup callbacks to unmount and detach the loopback device
    when the test is complete.

    :returns: A ``LoopDevice``.
    """
    losetup = Losetup()
    backing_file = test_case.make_temporary_file()
    with backing_file.open('wb') as f:
        f.truncate(LOOPBACK_MINIMUM_ALLOCATABLE_SIZE)
    device = losetup.add(backing_file=backing_file)
    bdm = BlockDeviceManager()
    bdm.make_filesystem(
        blockdevice=device.device,
        filesystem=u"ext4"
    )
    if label:
        # Assign a 16 byte label to the FS.
        run_process(['tune2fs', '-L', label, device.device.path])

    def cleanup():
        """
        Try to unmount the device 10 times or until it detaches.
        """
        device.remove()
        for _ in xrange(10):
            if device in losetup.list():
                _unmount(
                    path=device.device,
                    # Don't fail if the device is not mounted.
                    idempotent=True,
                )
            else:
                break

    # Always attempt to unmount the device when the test completes.
    test_case.addCleanup(cleanup)
    return device


N = int(input())
bases = ['A', 'G', 'C', 'T']
decode = [[0, 2, 0, 1],
          [2, 1, 3, 0],
          [0, 3, 2, 1],
          [1, 0, 1, 3]]

sequence = input()
current = bases.index(sequence[-1])
for i in range(N-2, -1, -1):
    current = decode[bases.index(sequence[i])][current]

print(bases[current])


import json

import aiohttp

from ninchat import APIException
from ninchat.call.aiohttp import call

class Error(APIException):

    def __init__(self, desc, event):
        msg = "{} ({})".format(desc, json.dumps(event, sort_keys=True))
        APIException.__init__(self, msg, event)

async def accept_invite(access_key, **kwargs):
    async with aiohttp.ClientSession() as s:
        e = await call(s, {
            "action":     "describe_access",
            "access_key": access_key,
        }, check=True, **kwargs)

        channel_id = e.get("channel_id")
        if not channel_id:
            raise Error("Not a channel invitation", e)

        call(s, {
            "action":     "join_channel",
            "channel_id": channel_id,
            "access_key": access_key,
        }, check=True, **kwargs)


"""
冒泡排序
    (1) 从前往后遍历到n-1，判断相邻两个数，如果前者比后者大，这交换两个数的位置。
    (2) 第一条执行n-1次即可
"""

def popOrder(li: list):
    for j in range(len(li) - 1):
        for i in range(len(li) - 1):
            if li[i + 1] < li[i]:
                li[i + 1], li[i] = li[i], li[i + 1]

if __name__ == '__main__':
    s = [1, 78, 79, 56, 32, 41, 112, 45, 1, 4, 32]
    print(s)
    popOrder(s)
    print(s)


from dataclasses import field, dataclass

from gs_quant.base import handle_camel_case_args, Base

@handle_camel_case_args
@dataclass
class BaseSubclass(Base):
    instance_attr: str = field(default=None)

def test_handle_camel_case_args():
    # Handling camelcase args on init
    obj = BaseSubclass(instanceAttr="test")
    assert obj.instance_attr == "test"

def test_base_getter():
    obj = BaseSubclass(instance_attr="test")

    # Handling camelcase getter
    assert obj.instanceAttr == "test"

def test_base_setter():
    obj = BaseSubclass()

    # Handling camelcase setter
    obj.instanceAttr = "test"
    assert obj.instance_attr == "test"


import tkinter as tk
from tkinter import ttk
from ho_gyaaaa import main
import time
import webbrowser

win = tk.Tk()

win.title('Traffic congestion minimization')

label = ttk.Label(win, text="Total number of cars (1-300)   ")
label.grid(column=0, row=0)

n = tk.IntVar(value=30)
nameEntered = ttk.Entry(win, width=20, textvariable=n)
nameEntered.grid(column=1, row=0)
nameEntered.focus()

label = ttk.Label(win, text="Number of proposed routes per car (1-5)   ")
label.grid(column=0, row=1)

r = tk.IntVar(value=3)
nameEntered = ttk.Entry(win, width=20, textvariable=r)
nameEntered.grid(column=1, row=1)
nameEntered.focus()

label = ttk.Label(win, text="Map location   ")
label.grid(column=0, row=2)

loc = tk.StringVar()
numberComboBox = ttk.Combobox(win, width=20, textvariable=loc, state="readonly")
numberComboBox['values'] = ("Saddar, Rawalpindi", "G-13-3, Islamabad", "Kamppi, Finland", "Blue Area, Islamabad",
                            "NUST, Islamabad")

numberComboBox.grid(column=1, row=2)
numberComboBox.current(0)

same_source = tk.IntVar()
check1 = tk.Checkbutton(win, text="Same starting point for each car", variable=same_source)
check1.select()
check1.grid(row=3, column=0, sticky=tk.W)

same_dest = tk.IntVar()
check1 = tk.Checkbutton(win, text="Same destination point for each car", variable=same_dest)
check1.select()
check1.grid(row=4, column=0, sticky=tk.W)

qc = tk.IntVar()

label = ttk.Label(win, text="Method of computation: ")
label.grid(column=0, row=5, sticky="W")

# Radio Button 1
tabu = tk.Radiobutton(win, text="Tabu search (classical)", variable=qc, value=False)
tabu.grid(column=0, row=6, sticky="W")

# Radio Button 2
dwave = tk.Radiobutton(win, text="D-Wave (quantum annealing)", variable=qc, value=True)
dwave.grid(column=0, row=7, sticky="W")

label = ttk.Label(win, text="Time taken to solve QUBO instance (in seconds): ")
label.grid(column=0, row=8)

QUBO_time = tk.StringVar()
T_0 = tk.Label(win, height=2, width=30, text="")
T_0.grid(column=1, row=8)

T_0.configure(text=QUBO_time)

label = ttk.Label(win, text="Total runtime of program (in seconds): ")
label.grid(column=0, row=9)

total_time = tk.StringVar()
T_1 = tk.Label(win, height=2, width=30, text="")
T_1.grid(column=1, row=9)

T_1.configure(text=total_time)

# Creating a button

def clickMe():
    # aButton.configure(text = "CLICKED!")
    # aLabel.configure(foreground = "red")
    print("n: ", n.get())
    print("r: ", r.get())
    print("same_source: ", same_source.get())
    print("same_dest: ", same_dest.get())
    print("qc: ", qc.get())
    print("loc: ", loc.get())

    # QUBO_time_ = main(int(n.get()),int(r.get()), loc.get(), int(same_source.get()), int(same_dest.get()), int(qc.get()))

    start = time.clock()
    QUBO_time_ = main(n.get(), r.get(), loc.get(), int(same_source.get()), int(same_dest.get()), int(qc.get()))
    end = time.clock()
    elapsed = end - start

    QUBO_time.set(QUBO_time_)
    T_0.config(text=QUBO_time.get())
    T_1.config(text=elapsed)

    webbrowser.open("heatmap_short.html")
    webbrowser.open("heatmap_opt.html")

aButton = ttk.Button(win, text="Compute", command=clickMe)
aButton.grid(column=0, row=10, sticky="E")

win.mainloop()


from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from .helpers import *

@login_required(login_url='/login/')
def statisticsDays(request):
    daysToEndOfSemester = get_days_to_end_of_semester(request.user.id)
    daysInSemester = get_number_of_days_in_semester(request.user.id)
    print('statisticsDays')

    context = {
        'daysToEndOfSemester': daysToEndOfSemester,
        'daysInSemester': daysInSemester,
    }

    return render(request, 'statistics.html', context)

@login_required(login_url='/login/')
def statisticsTimeSpentOnCourses(request):
    courseNames, timeSpendOnCourses = get_times_by_courses(request.user.id)

    context = {
        'courseNames': courseNames,
        'timeSpendOnCourses': timeSpendOnCourses
    }

    return render(request, 'statistics.html', context)

@login_required(login_url='/login/')
def statisticsRatios(request):
    courseNames, ratios = get_ratios_by_courses(request.user.id)

    context = {
        'courseNames': courseNames,
        'ratios': ratios
    }

    return render(request, 'statistics.html', context)


import glob
import os

import numpy as np
from skimage import io
from skimage.color import rgb2hed
from skimage.exposure import rescale_intensity
from skimage.filters import rank
from skimage.morphology import disk
from skimage.transform import resize

# 数据集地址
image_path = r'C:\Users\bunny\Desktop\_Training_Data\sub_mean_images\all/'

# 将所有的图片resize成100*100
w = 2000
h = 2000
c = 3

# 读取图片
def resize_img(path, new_width=0, new_height=0):
    default_height = 500
    file_path_list = [os.path.join(path, file_name) for file_name in os.listdir(path)
                      if os.path.isfile(os.path.join(path, file_name))]
    count = 0
    for file_path in file_path_list:
        img = io.imread(file_path)
        _h = img.shape[0]
        _w = img.shape[1]
        new_w = new_width
        new_h = new_height
        if new_w == 0 and new_h == 0:
            new_h = default_height
            new_w = int(_w / _h * new_h)
        if new_w != 0 and new_h == 0:
            new_h = int(_h / _w * new_w)
        if new_w == 0 and new_h != 0:
            new_w = int(_w / _h * new_h)
        img = resize(img, (new_h, new_w), anti_aliasing=True)
        io.imsave(file_path, img)
        del img
        count += 1
        if count % 10 == 0:
            print("\rreading {0}/{1}".format(count, len(file_path_list)), end='')

def stain_separate_image(root_path):
    cate = [root_path + folder for folder in os.listdir(root_path) if os.path.isdir(root_path + folder)]
    count = 0
    for idx, folder in enumerate(cate):
        print('reading the images:%s' % folder)
        for im in glob.glob(folder + '/*.jpg'):
            img = io.imread(im)
            ihc_hed = rgb2hed(img)
            # Rescale hematoxylin and DAB signals and give them a fluorescence look
            _h = rescale_intensity(ihc_hed[:, :, 0], out_range=(0, 1.0))
            _e = rescale_intensity(ihc_hed[:, :, 1], out_range=(0, 1.0))
            _d = rescale_intensity(ihc_hed[:, :, 2], out_range=(0, 1.0))
            zdh = np.dstack((_h, _e, _d))
            io.imsave(im, zdh)
            del img
            count += 1
            if count % 5000 == 0:
                print(count)

def mean_filter(img, disk_size=50):
    image_r = img[:, :, 0]
    image_g = img[:, :, 1]
    image_b = img[:, :, 2]
    selem = disk(disk_size)
    # percentile_result = rank.mean_percentile(image, selem=selem, p0=.1, p1=.9)
    # bilateral_result = rank.mean_bilateral(image, selem=selem, s0=500, s1=500)
    normal_result_r = rank.mean(image_r, selem=selem)
    normal_result_g = rank.mean(image_g, selem=selem)
    normal_result_b = rank.mean(image_b, selem=selem)
    normal_result = np.dstack((normal_result_r, normal_result_g, normal_result_b))
    return normal_result

def subtract_mean_img(path, disk_size=50):
    file_path_list = [os.path.join(path, file_name) for file_name in os.listdir(path)
                      if os.path.isfile(os.path.join(path, file_name))]
    count = 0
    for file_path in file_path_list:
        img = io.imread(file_path) / 255.0
        mean_img = mean_filter(img, disk_size) / 255.0
        sub_mean_img = img - mean_img
        io.imsave(file_path, sub_mean_img)
        del img, mean_img, sub_mean_img
        count += 1
        if count % 10 == 0:
            print("\rreading {0}/{1}".format(count, len(file_path_list)), end='')

for i in range(4):
    image_path = r'D:\Projects\pompeii\20190405\svd_500_submean/' + str(i + 1) + '/'
    # resize_img(image_path, 0, 0)
    # stain_separate_image(image_path)
    subtract_mean_img(image_path, 10)


import asyncio
import json
import pathlib
import time
import warnings
import concurrent.futures
import logging

import urllib3.exceptions

from src.abc.driver_monitor import DriverManager
from src.page_monitors.random_signal_spm import RandomSignalSPM
from src.abc.single_page_monitoring import SinglePageMonitoring
from src.util import make_do_in_interval_fn, \
    append_element_dict_to_list_dict, get_env_non_empty

from selenium.webdriver import FirefoxOptions
import websockets
import threading

logger = logging.getLogger("scraper_logger")

SPM_Classes = [
    RandomSignalSPM
]

class MonitorManager:
    """
    A class to monitor the https://rbnbr.github.io/random-signal website.

    NOTE: This class could hold multiple Driver Managers and each could hold multiple page managers, depending on
        the use case. It could be used to monitor dozens of possibly different pages.
    """

    MAX_BROWSER_INSTANCES = int(get_env_non_empty("MAX_BROWSER_INSTANCES", default=5))

    _LOCAL_DRIVER_ADDR_FMT = "http://{}:{}"

    # after detecting unhealthy page, triggers refresh; if this amount of unhealthy/refresh
    # in last MAX_PAGE_UNHEALTHY_COUNT_AGE_S, then raises exception
    MAX_PAGE_UNHEALTHY_REFRESH_IN_TIME_LIMIT = int(
        get_env_non_empty("MAX_PAGE_UNHEALTHY_REFRESH_IN_TIME_LIMIT", 5))

    # the max time in which unhealthy states are being tracked
    # should be enough time to trigger the unhealthy option
    MAX_PAGE_UNHEALTHY_COUNT_AGE_S = int(get_env_non_empty("MAX_PAGE_UNHEALTHY_COUNT_AGE_S", default=3600))

    def __init__(self, push_interval_s: float = 60, update_tabs_interval_s: float = 60 * 15,
                 browser_instances_n: int = 1, health_check_interval_s: float = 30,
                 *, ws_port=8001, ws_ssl_context=None, simulate_activity_interval_s=60,
                 headless: bool = True, headless_first_override: bool = None,
                 postgres_connection=None, schema: str = "public"):
        """
        :param push_interval_s: Interval of retrieving data from individual page managers and pushing it to the database
        :param update_tabs_interval_s: Interval to check whether tabs are still all being monitored. The update_tabs(..)
            method can integrate logic to also open or close tabs etc.
        :param browser_instances_n: Amount of browser instances (remote selenium drivers) we can leverage.
            Depends on the traffic and compute capabilities. Regular use-cases do not need more than one.
        :param health_check_interval_s: interval to check the health of individual page managers
        :param ws_port: port of the websocket server
        :param ws_ssl_context: secure websocket context (includes certificates etc.)
        :param simulate_activity_interval_s: interval of calling 'simulate activity' for each individual page manager
        :param headless: if remote driver should run headless
        :param headless_first_override: if using multiple browser/driver instances, this can be used start all in
            headless except the first one. Used for debugging purposes.
        :param postgres_connection: Postgres' connection used to push data into the database. (Assuming we use postgres)
        :param schema: Postgres schema to be used.
        """
        if browser_instances_n > self.MAX_BROWSER_INSTANCES:
            warnings.warn(f"maximum amount of browsers is limited to {self.MAX_BROWSER_INSTANCES}, "
                          f"got {browser_instances_n}; override it with {self.MAX_BROWSER_INSTANCES}")
            browser_instances_n = self.MAX_BROWSER_INSTANCES

        self.push_interval_s = push_interval_s
        self.update_tabs_interval_s = update_tabs_interval_s
        self.browser_instances_n = browser_instances_n
        self.headless = headless
        self.headless_first_override = headless_first_override
        self.health_check_interval_s = health_check_interval_s
        self.postgres_connection = postgres_connection
        self.schema = schema

        self.ws_port = ws_port
        self._ws_ssl_context = ws_ssl_context

        self.simulate_activity_interval_s = simulate_activity_interval_s

        self.driver_managers: dict[int, DriverManager] \
            = self.make_remote_driver_managers(self.browser_instances_n, self.headless, self.headless_first_override,
                                               max_time_for_retries_s=60)

        self.health_stati = dict()

        self._websocket_thread = None
        self._should_stop = False

        self._should_destroy = False

    def get_addresses(self):
        """
        Get addresses of remote selenium nodes from env.
        :return:
        """
        return [
            get_env_non_empty(f"SEL_DRIVER_ADDR_{i}",
                              default=self._LOCAL_DRIVER_ADDR_FMT.format("localhost", 5900 + i)) for i in
            range(1, self.MAX_BROWSER_INSTANCES + 1)
        ]

    async def ws_page_distributor_handler(self, websocket):
        async for message in websocket:
            data_json = json.loads(message)

            # get page_url to distribute to single page manager
            page_url = data_json["page_url"]

            driver_manager = None

            # find drm for page url
            for drm in self.driver_managers:
                if self.driver_managers[drm].is_monitoring_url(page_url):
                    driver_manager = self.driver_managers[drm]
                    break

            if driver_manager is None:
                logger.warning(f"got connection from page url which is not being monitored {page_url}... "
                               f"close connection")
                return

            # find page manager
            page_manager = driver_manager.page_managers[page_url]

            # add data to page manager
            page_manager.add_page_data(data_json)

    async def _async_while_not_stopped(self):
        while not self._should_stop:
            await asyncio.sleep(0.01)

    async def _async_init_websocket(self):
        async with websockets.serve(self.ws_page_distributor_handler, "", self.ws_port, ssl=self._ws_ssl_context):
            await self._async_while_not_stopped()

    def _init_websocket(self):
        asyncio.run(self._async_init_websocket())

    def run(self):
        """
        Run loop of the manager monitor.
        Endless loop, only returns with exception.
        :return:
        """
        self._websocket_thread = threading.Thread(target=self._init_websocket)
        self._websocket_thread.start()

        try:
            self._run()
        except Exception as e:
            self._should_stop = True
            logger.critical("got some exception... telling websocket thread to stop")
            self._websocket_thread.join(10)
            logger.critical("websocket thread stopped. destroy manager monitor")
            self.destroy()
            logger.exception(e)
            raise e

    def _run(self):
        """
        Run loop of the manager monitor.
        Endless loop, only returns on exception.
        :return:
        """
        # create time dependent functions
        push_fn = make_do_in_interval_fn(self.push_results, self.push_interval_s, time.time())
        update_available_tabs_fn = make_do_in_interval_fn(self.update_tabs, self.update_tabs_interval_s)
        simulate_activity = make_do_in_interval_fn(self.simulate_activity, self.simulate_activity_interval_s)
        check_and_handle_health_status = make_do_in_interval_fn(self.check_and_handle_drm_health_status,
                                                                self.health_check_interval_s)

        # while function will execute all the functions the first time in the provided order,
        #   but each only if the remaining wait interval has been reached.
        #   Thus, the order could become arbitrary, depending on the intervals.
        # However, the loop will never execute two functions simultaneously and the wait condition will always only
        # wait as long until the next function is to be executed.
        while True:
            wait_until_s = update_available_tabs_fn()[1]

            wait_until_s = min(check_and_handle_health_status()[1], wait_until_s)

            wait_until_s = min(simulate_activity()[1], wait_until_s)

            # may report the difference if necessary
            # if diff < 0:
            #     logger.debug(f"waiting took {-diff} longer than expected")

            # push data to database every push_interval_s
            wait_until_s = min(push_fn()[1], wait_until_s)

            # non-busy wait
            to_wait_s = wait_until_s - time.time()
            if to_wait_s > 0:
                logger.debug(f"wait remaining wait time... {to_wait_s}s")
                time.sleep(to_wait_s)

    def simulate_activity(self):
        """
        Simulate the activity of all the pages, e.g., by briefly setting them into focus.
        :return:
        """
        logger.info("simulate activity...")
        with concurrent.futures.ThreadPoolExecutor(max_workers=len(self.driver_managers)) as executor:
            futures = dict()
            # start threads
            for i in self.driver_managers:
                futures.update({executor.submit(self.driver_managers[i].simulate_activity): i})

            # wait for results
            for future in concurrent.futures.as_completed(futures):
                index = futures[future]
                try:
                    _ = future.result(60)
                except Exception as exc:
                    logger.error(f"driver manager with index {index} generated an exception:\n", exc)
                    raise exc

    def update_tabs(self):
        """
        Update the browser instances with its available tabs.
        Takes first available driver manager with an open page, refreshes it and retrieve tabs.
        If no page is open, opens the first page with first driver manager.
        :return:
        """
        logger.info("update available tabs")

        # compute which urls we already have being monitored
        got_monitored_urls = []
        for i in self.driver_managers:
            drm = self.driver_managers[i]
            got_monitored_urls += list(drm.page_managers.keys())

        got_monitored_urls = set(got_monitored_urls)

        # urls which we require
        required_monitored_urls = {"https://rbnbr.github.io/random-signal"}

        # self.compute_required_urls()
        # required_monitored_urls.update(self.required_urls)  # not implemented

        # close got monitored urls that are not required (anymore?)
        to_close_urls = list(got_monitored_urls.difference(required_monitored_urls))
        for i in self.driver_managers:
            drm = self.driver_managers[i]
            with drm:
                drm.remove_monitor_urls(to_close_urls)

        # find missing urls and distribute to drms
        required_monitored_urls.difference_update(got_monitored_urls)
        missing_monitored_urls = list(required_monitored_urls)

        # distribute to drms
        for url in missing_monitored_urls:
            # get drm with least urls
            drm_i = sorted(range(len(self.driver_managers)),
                           key=lambda k: len(self.driver_managers[k].page_managers))[0]

            drm = self.driver_managers[drm_i]

            # find suitable spm
            spm_class = None
            for spm in SPM_Classes:
                if url.startswith(spm.BASE_URL):
                    spm_class = spm

            if spm_class is None:
                raise NotImplementedError(f"no spm found for url: {url}")

            drm.add_single_page_monitor(spm_class(drm=drm, page_url=url), True)

    def push_results(self):
        """
        Push drm results.
        :return:
        """
        logger.debug("collect latest drm results")
        latest_page_results = self.collect_latest_drm_results()

        # filter signal results
        signal_results = {page_url: latest_page_results[page_url] for page_url in latest_page_results
                             if latest_page_results[page_url]["page_monitor_class"] is RandomSignalSPM}

        # debug print
        for page_url in signal_results:
            psr = signal_results[page_url]
            pd = psr['page_data']
            logger.debug(f"pulled {len(pd)} signal results from page {page_url}")

        # handle signal results
        # try:
        #     with self.postgres_connection.cursor() as cur:
        #         # count_pushed_signals = self._push_signal_results(cur, signal_results)  # Not implemented
        #         count_pushed_signals = 0
        #         self.postgres_connection.commit()
        #         logger.info(f"pushed {count_pushed_signals} many signals")
        # except Exception as e:
        #     logger.error("got error during push of spm_results: " + str(e))
        #     self.postgres_connection.rollback()

    def report_drm_health_status(self):
        """
        Reports the last drm health status
        :return:
        """
        health_status = dict()
        for i in self.driver_managers:
            drm = self.driver_managers[i]
            health_status.update(drm.report_health_status())

        return health_status

    def collect_latest_drm_results(self) -> dict:
        """
        Pull the drm results from their individual pages and return them.
        :return: A mapping {"page_url": {"page_data": page_data, "page_monitor_class": page.__class__}}
        """
        page_results = dict()

        with concurrent.futures.ThreadPoolExecutor(max_workers=len(self.driver_managers)) as executor:
            futures = dict()
            # start threads
            for i in self.driver_managers:
                futures.update({executor.submit(self.driver_managers[i].pull_latest_measurements): i})
            # wait for results
            for future in concurrent.futures.as_completed(futures):
                index = futures[future]
                try:
                    page_result = future.result(60)
                    page_results.update(page_result)

                except Exception as exc:
                    logger.error(f"driver manager with index {index} generated an exception:\n", exc)
                    raise exc

        return page_results

    def make_remote_driver_managers(self, n_instances: int, headless: bool = False,
                                    headless_first_override: bool = None, max_time_for_retries_s: int = 60):
        """
        Creates the amount of remote driver manager instances and returns them as a dict with their index as key.
        :param max_time_for_retries_s: Tries to make the remote drivers. Retries until max_time_for_retries_s
            has been reached, then raises exception.
        :param headless_first_override:
        :param headless:
        :param n_instances:
        :return:
        """
        start_s = time.time()

        driver_managers = dict()

        addresses = self.get_addresses()

        ff_profile_path = get_env_non_empty("PYAPP_FIREFOX_PROFILE_DIR",
                                            default="firefox_profiles/ff-profile.WithCACertificate")
        ff_profile_path = pathlib.Path(ff_profile_path)

        use_profile = ff_profile_path.exists() and ff_profile_path.is_dir()

        if not use_profile:
            logger.info(f"not using firefox profile as it doesn't exist or is not a dir... "
                        f"got profile path: {ff_profile_path}")
        else:
            logger.info(f"using firefox profile at path: {ff_profile_path}")

        for i in range(n_instances):
            logger.info(f"trying to connect to instance num {i}: {addresses[i]}")
            command_executor = addresses[i]

            firefox_options = FirefoxOptions()

            if use_profile:
                # firefox_options.set_preference("profile", str(ff_profile_path))
                firefox_options.profile = str(ff_profile_path)
            else:
                if not get_env_non_empty("WS_USE_SSL", default="False").lower() == "true":
                    # allow firefox insecure websocket connection from https site
                    firefox_options.set_preference('network.websocket.allowInsecureFromHTTPS', True)

            if headless_first_override is not None and i == 0:
                firefox_options.headless = headless_first_override
            else:
                firefox_options.headless = headless

            ok = False
            while max_time_for_retries_s > time.time() - start_s:
                ok = False
                try:
                    driver_managers[i] = DriverManager(command_executor=command_executor, options=firefox_options)
                    ok = True
                    break
                except (urllib3.exceptions.MaxRetryError, urllib3.exceptions.ProtocolError):
                    logger.info(f"failed to connect to instance {i}, try again in 5s")
                    time.sleep(5)
            if not ok:
                raise RuntimeError(f"failed to connect to all instances in over {max_time_for_retries_s}s")

        return driver_managers

    def destroy(self):
        """
        Destroys all driver managers.
        :return:
        """
        self._should_destroy = True
        self._should_stop = True

        for i in self.driver_managers:
            drm = self.driver_managers[i]

            drm.destroy()

        self.driver_managers.clear()

    def check_and_handle_drm_health_status(self):
        logger.debug("check and handle health status")
        health_status = self.report_drm_health_status()

        timestamp = time.time()
        only_health_status = {url: (health_status[url]["health_status"], timestamp) for url in health_status}

        # add health status to list
        append_element_dict_to_list_dict(self.health_stati, only_health_status)

        fail = False

        # check if any page has more than allowed negative health stati in the specified last interval
        max_found_not_ok = 0
        max_found_not_ok_url = "none"
        for url in self.health_stati:
            # remove health stati older than allowed
            self.health_stati[url] = sorted(list(filter(
                lambda hs_ts: timestamp - hs_ts[1] <= self.MAX_PAGE_UNHEALTHY_COUNT_AGE_S,
                self.health_stati[url])),
                key=lambda hs_ts: hs_ts[1])
            not_ok_health_status = list(filter(lambda hs_ts: not hs_ts[0], self.health_stati[url]))

            # set not ok health status to page
            health_status[url]["page_manager"].set_unhealthy_count(len(not_ok_health_status))

            if len(not_ok_health_status) >= max_found_not_ok:
                max_found_not_ok = len(not_ok_health_status)
                max_found_not_ok_url = url
            if len(not_ok_health_status) > self.MAX_PAGE_UNHEALTHY_REFRESH_IN_TIME_LIMIT:
                logger.critical(f"page with url {url} has {len(not_ok_health_status)} unhealthy reports. application "
                                f"will fail")
                fail = True

        logger.info(f"the maximum of unhealthy refreshs in the last {self.MAX_PAGE_UNHEALTHY_COUNT_AGE_S}s was "
                    f"{max_found_not_ok} from page {max_found_not_ok_url}, "
                    f"allowed are {self.MAX_PAGE_UNHEALTHY_REFRESH_IN_TIME_LIMIT}")

        if not fail:
            # warn about unhealthy pages
            total = len(only_health_status)
            ok_pages = list(filter(lambda url: only_health_status[url][0], only_health_status))
            ok = len(ok_pages)
            not_ok_pages = list(filter(lambda url: not only_health_status[url][0], only_health_status))
            not_ok = len(not_ok_pages)

            if not_ok > 0:
                logger.warning(f"detected not healthy page managers: last health status: total: {total}, "
                               f"ok: {ok}, "
                               f"not_ok: {not_ok}; refresh not ok page managers: {not_ok_pages}")

            # refresh pages that were unhealthy
            with concurrent.futures.ThreadPoolExecutor(max_workers=len(self.driver_managers)) as executor:
                futures = dict()
                # start threads
                for i in self.driver_managers:
                    futures.update({executor.submit(self.driver_managers[i].refresh_urls,
                                                    not_ok_pages): i})

                # wait for results
                for future in concurrent.futures.as_completed(futures):
                    index = futures[future]
                    try:
                        _ = future.result(2 * len(list(health_status.keys())))
                    except Exception as exc:
                        logger.error(f"driver manager with index {index} generated an exception:\n", exc)
                        raise exc

            page_with_biggest_refresh_count = max(map(lambda drm_i: max(
                self.driver_managers[drm_i].page_managers.values(), key=lambda p: p.get_total_refresh_count()),
                                                      self.driver_managers), key=lambda p: p.get_total_refresh_count())

            logger.info(
                f"the current total refresh count among all pages is {SinglePageMonitoring.TOTAL_REFRESH_COUNT}"
                f", the page with the highest refresh count is {page_with_biggest_refresh_count.page_url} with"
                f" a refresh count of {page_with_biggest_refresh_count.get_total_refresh_count()}")

        else:
            logger.critical("detected repeated unhealthy page manager: "
                            "closing program with -101 to investigate the error")
            self.destroy()
            exit(-101)


class Solution:
    def subarraySum(self, nums: List[int], k: int) -> int:
        memo = collections.defaultdict(int)
        preSum = 0
        memo[preSum] += 1
        res = 0
        for num in nums:
            preSum += num
            res += memo[preSum - k]
            memo[preSum] += 1
        return res

Data Structure/Hash/Medium/LET_no560_Subarray Sum Equals K.py


import socket
import random
import json
from functools import partial
from datetime import datetime

class SocketClientUdp ():

  def __init__ (self):
    self.host = ""
    self.port = 5678
    self.sock = False

    # default ID
    self.currentDateTime = datetime.now().strftime("%d%m%Y%H%M%S")
    self.serverUniqueId = f"{self.currentDateTime}{random.random()}"

    self.connectedCallback = False
    self.connectedCallbackArgs = False
    self.receivedCallback = False
    self.message = False

  def setServerId (self, id):
    self.serverUniqueId = f"{id}"
    return self

  def setHost (self, ip):
    self.host = ip
    return self

  def _startClient (self):

    self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    print('UDP CLIENT STARTED')

    self.sock.sendto(f"Hi!".encode(), (self.host, self.port))

    # callback
    if (self.connectedCallback): self.connectedCallback ()

    while True:
      try:
        mess, addr = self.sock.recvfrom(1024)

        if mess:
          print(f"CLIENT -> Received from {addr}: {mess.decode()}\n")
          # callback
          if (self.receivedCallback): self.receivedCallback (message = mess, address = addr)
      except Exception as e:
        print(f"error: {e}")

  def onConnect(self, **args):
    if "callback" in args:
      self.connectedCallback = args["callback"]
      self.connectedCallbackArgs = args
    return self

  def onReceive(self, **args):
    if "callback" in args:
      self.receivedCallback = args["callback"]
      self.receivedCallbackArgs = args
    return self

  def sendMessage (self, **args):
    if "message" in args:
      print(f"CLIENT:UDP->sending: {args['message']}")

      name = ""
      senderId = ""
      ipAddress = ""

      if "name" in args: name = args['name']
      if "senderId" in args: senderId = args['senderId']
      if "ipAddress" in args: ipAddress = args['ipAddress']

      __mess = {
        "id": self.serverUniqueId,
        "senderId": senderId,
        "name": f"{name}",
        "message": f"{args['message']}",
        "timestamp": f"{datetime.now().strftime('%B %d, %Y %I:%M%p')}",
        "ipAddress": f"{ipAddress}"
      }

      self.sock.sendto(f"{json.dumps(__mess)}".encode(), (self.host, self.port))
    return self

  def start (self):
    self._startClient ()
    return self

  def disconnect (self):
    try:
      self.sock.shutdown ()
    except Exception as e:
      pass


#!/usr/bin/env python

# for Python 3 compatibility
from __future__ import print_function

import os, sys, glob, argparse
import subprocess as sub

sys.path.append('/home/rpernak/python/GIT_python_modules')
import utils

# GLOBAL VARIABLES
DEFBUILDDIR = '/nas/ASR/LINEFILE_BUILD_TES_V_2.0'
DEFLNFL = \
  '/nas/project/rc/rc1/lnfl_local_version/lnfl_v3.1_linux_pgi_sgl'

class genTAPE3():
  """
  Assuming that line files exist for each HITRAN molecule, generate
  an associated binary TAPE3
  """

  def __init__(self, lineFileDir=DEFBUILDDIR, \
    lnflPath=DEFLNFL, wnBounds=[0.0, 200000.0], \
    tape5Dir='%s/LNFL_input_files' % DEFBUILDDIR, \
    tape3Dir='%s/lnfl/TAPE3_files' % DEFBUILDDIR, \
    wvIso=False):
    """
    Constructor for genTAPE3 class -- where are ASCII line files,
    what are the executable paths, where should output files go, etc.

    Inputs

    Outputs

    Keywords
      lineFileDir -- string, full path to line file build directory
        (where construction of a new line file is done
         before releasing it); it is assumed that line_file/,
         line_files_By_Molecule/, and lnfl/ subdirectories exist
         underneath it
      lnflPath -- string, full path to LNFL executable to use
      wnBounds -- float array, 2-element array of starting and ending
        wavenumbers for the TAPE3 files (25 cm-1 will be added to
        each bound to include "relevant" line contributions)
      tape5Dir -- string, path to which TAPE5 files that will be
        generated are written
      tape3Dir -- string, path to which TAPE3 files that will be
        generated are written
      wvIso -- boolean, only process the water vapor isotopologues
        (each of which has a separate line file)
    """

    lfMolDir = '%s/line_files_By_Molecule' % lineFileDir
    pathCheck = [lineFileDir, lfMolDir, lnflPath]
    for path in pathCheck: utils.file_check(path)

    # set some attributes necessary for the rest of the processing
    self.lineFileDir = str(lineFileDir)
    self.pathLNFL = str(lnflPath)
    self.mols = sorted(glob.glob('%s/*' % lfMolDir))
    self.nMols = len(self.mols)
    self.dirT5 = str(tape5Dir)
    self.dirT3 = str(tape3Dir)
    self.wnLims = list(wnBounds)
    self.isoH2O = bool(wvIso)

    # do the output dirs exist?
    for path in [tape5Dir, tape3Dir]: self.makeDirs(path)

  # end constructor

  def makeDirs(self, inPath):
    """
    Make a directory if it doesn't already exist
    """

    if not os.path.exists(inPath): os.mkdir(inPath)
  # end makeDirs()

  def cleanUp(self):
    """
    Remove any TAPE files that were generated
    """

    tapeList = sorted(glob.glob('TAPE?'))
    tapeList = ['TAPE%d' % num for num in [1, 2, 5, 6, 7, 10]]
    for tape in tapeList:
      if os.path.isfile(tape): os.remove(tape)
    # end TAPE loop

  # end cleanUp

  def makeLinks(self, source, target):
    """
    Make symbolic links

    Inputs
      source -- string, path to file to be linked
      target -- string, name associated with link
    """

    if os.path.exists(target): os.unlink(target)
    os.symlink(source, target)
  # end makeLinks()

  def makeTAPE5(self):
    """
    Make the TAPE5 LNFL specifications file for each molecule
    """

    wn1, wn2 = self.wnLims

    # loop through each HITRAN molecule and create an associated TAPE5
    allT5 = []
    for iMol, mol in enumerate(self.mols):
      base = os.path.basename(mol)
      print(base)
      tape5 = 'TAPE5_%s' % base

      # LNFL TAPE5 records
      # (see lnfl_instructions document in LNFL release)
      rec1 = '$ %s' % base
      rec2 = '%10.3f%10.3f' % (wn1-25, wn2+25)

      # start off with all molecules off, then turn iMol on, then
      # generate a single string instead of a list of characters
      # and append
      rec3 = ['0'] * self.nMols
      rec3[iMol] = '1'
      rec3 = ''.join(rec3) + '     NBLK1 NOCPL LNOUT '
      end = '%%%%%'

      outDat = [rec1, rec2]

      # line coupling molecules
      if base in ['02_CO2', '06_CH4', '07_O2']:
        rec3 = rec3.replace('NOCPL', 'MRG2')
        rec4 = [' '] * self.nMols
        rec4[iMol] = '1'
        rec4 = ''.join(rec4)
        outDat += [rec3, rec4]
      else:
        outDat.append(rec3)
      # endif coupling

      outDat.append(end)

      # now write TAPE5
      outFP = open(tape5, 'w')
      for line in outDat: outFP.write('%s\n' % line)
      outFP.close()

      # copy TAPE5 to subdirectory for molecule in buildDir
      target = '%s/%s' % (self.dirT5, tape5)
      if os.path.exists(target):
        print('WARNING: overwriting %s' % target)
      # endif target check
      os.rename(tape5, target)

      allT5.append(target)
    # end molecule loop

    self.allT5 = list(allT5)
    return self

  # end makeTAPE5()

  def runLNFL(self):
    """
    Run LNFL for each molecule, thus generating a binary TAPE3
    """

    if 'allT5' not in dir(self):
      self.allT5 = sorted(glob.glob('%s/TAPE5_*' % self.dirT5))

    # set up the input directory
    self.makeLinks(self.pathLNFL, 'lnfl')
    tapeStrList = ['TAPE1', 'TAPE5']
    self.cleanUp()

    # loop through each HITRAN molecule and create an associated TAPE5
    for iMol, mol in enumerate(self.mols):
      base = os.path.basename(mol)
      print(base)
      tape5 = self.allT5[iMol]

      if self.isoH2O:
        # there are multiple line files to consider for H2O
        isoStr = ['01_h2o_161_only', '01_h2o_162_excl', \
          '01_h2o_162_only', '01_h2o_171_only', '01_h2o_172_only', \
          '01_h2o_181_only', '01_h2o_182_only']
        tape1List = ['%s/%s' % (mol, iso) for iso in isoStr]
      else:
        tape1List = ['%s/%s' % (mol, base)]
      # endif WV

      # loop really only exists for H2O
      for tape1 in tape1List:
        tapeList = [tape1, tape5]

        # grab the line coupling file if necessary
        if base in ['02_CO2', '06_CH4', '07_O2']:
          tape2 = '%s/lncpl_lines' % mol
          tapeList.append(tape2)
          tapeStrList.append('TAPE2')
        # endif line coupling

        # stage the files necessary for an LNFL run
        for source, target in zip(tapeList, tapeStrList):
          self.makeLinks(source, target)

        # call LNFL and save TAPE3 to unique name
        sub.call(['lnfl'])
        if self.isoH2O:
          tape3 = '%s/TAPE3_%s' % (mol, os.path.basename(tape1))
        else:
          tape3 = '%s/TAPE3_%s' % (mol, base)
        # endif wv
        if os.path.exists(tape3):
          print('WARNING: overwriting %s' % tape3)
        os.rename('TAPE3', tape3)

        # clean up
        self.cleanUp()
      # end TAPE1 loop

      #self.cleanUp()
      # if we're doing WV isotopologues, *only* do them
      if self.isoH2O: return
    # end molecule loop

    return
  # end runLNFL()
# end genTAPE3

if __name__ == '__main__':
  parser = argparse.ArgumentParser(\
    description='Generate a TAPE5 for each HITRAN molecule.')
  parser.add_argument('-dir', '--build_dir', type=str, \
    default=DEFBUILDDIR, \
    help='Line file build directory (which we assume contains a ' + \
    '"line_files_by_Molecule/" and "LNFL_input_files" subdirs.)')
  parser.add_argument('-lnfl', '--lnfl_path', type=str, \
    default=DEFLNFL, \
    help='Full path to LNFL executable to be used.')
  parser.add_argument('-t5', '--tape5_dir', type=str, \
    default='TAPE5_files', help='Directory for TAPE5 files.')
  parser.add_argument('-t3', '--tape3_dir', type=str, \
    default='TAPE3_files', \
    help='Relative path to directory for resulting TAPE3 files.')
  parser.add_argument('-wv', '--water_vapor', action='store_true', \
    help='Process the separate water vapor files (i.e., one for ' + \
    'each isotopologue that the JPL team wants).')
  parser.add_argument('-wn', '--wavenum_lims', nargs=2, \
    type=float, default=[500, 3500], \
    help='Wavenumber limits (cm-1) for TAPE3 (after LNFL run)')
  parser.add_argument('-5', '--only_tape5', action='store_true', \
    help='Only write the TAPE5s (no LNFL run).')
  parser.add_argument('-3', '--only_tape3', action='store_true', \
    help='Run LNFL without first making the TAPE5s.')
  args = parser.parse_args()

  tape3 = genTAPE3(lineFileDir=args.build_dir, \
    lnflPath=args.lnfl_path, wnBounds=args.wavenum_lims, \
    tape5Dir=args.tape5_dir, tape3Dir=args.tape3_dir, \
    wvIso=args.water_vapor)

  if args.only_tape5:
    tape3.makeTAPE5()
  elif args.only_tape3:
    tape3.runLNFL()
  else:
    tape3.makeTAPE5()
    tape3.runLNFL()
  # endif
# endif main()


import numpy as np
import matplotlib.pyplot as plt

def getdata(filename):
    file = open(filename, "r")
    lines = file.read().splitlines()    # list of strings of lines
    file.close()

    title = lines[0].split()  # names of parameters (headers of columns in data file)
    lines = lines[2:len(lines)]  # remove headers and unit rows

    datalst = []
    for i in range(len(lines)):
        datalst.append(lines[i].split())  # making 2D list of strings of data in rows

    datastr = np.array(datalst)  # converting data string list to numpy array
    data = datastr.astype(float)  # turning the strings into floats
    return data

cdata = getdata("3D_corr_test.txt")
ucdata = getdata("3D_unc_test.txt")

print("Avaliable polars:\n 1. All\n 2.CL-alpha\n 3.CD-alpha\n 4.CMpitch-alpha\n 5.CMroll-alpha\n 6.CMyaw-alpha\n"
      " 7.CL-CD")
choice = int(input("Choose the desired polar (1-7): "))
all = False

if choice == 1:
    all = True
    choice = 2

if choice == 2:
    # fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)  # only for visualising all 4 at once
    # fig.set_size_inches(8, 5)
    fig1, ax1 = plt.subplots(figsize=(8, 5))
    ax1.plot(cdata[:, 1], cdata[:, 3], linewidth=1, marker='o', markersize=4, label=r'Corrected $C_L-\alpha$')
    ax1.plot(ucdata[:, 1], ucdata[:, 3], linewidth=1, marker='o', markersize=3, color='grey',
             label=r'Uncorrected $C_L-\alpha$')
    # ax1.set_title('$C_L-\alpha$')
    ax1.set_xlabel(r'$\alpha$ [deg]', fontsize=16)
    ax1.set_ylabel(r'$C_L$ [-]', fontsize=16)
    plt.grid()
    plt.legend(fontsize=11)
    plt.savefig('CL_alpha_3d_exp_unc_vs_corr.pdf', dpi=200)
    if all:
        choice = 3

if choice == 3:
    fig2, ax2 = plt.subplots(figsize=(8, 5))
    ax2.plot(cdata[:, 1], cdata[:, 4], linewidth=1, marker='^', markersize=4, color='purple',
             label=r'Corrected $C_D-\alpha$')
    ax2.plot(ucdata[:, 1], ucdata[:, 4], linewidth=1, marker='^', markersize=3, color='grey',
             label=r'Uncorrected $C_D-\alpha$')
    # ax2.set_title('Cd-alpha')
    ax2.set_xlabel(r'$\alpha$ [deg]', fontsize=16)
    ax2.set_ylabel(r'$C_D$ [-]', fontsize=16)
    plt.grid()
    plt.legend(fontsize=11)
    plt.savefig('CD_alpha_3d_exp_unc_vs_corr.pdf', dpi=200)
    if all:
        choice = 4

if choice == 4:
    fig3, ax3 = plt.subplots(figsize=(8, 5))
    ax3.plot(cdata[:, 1], cdata[:, 11], linewidth=1, marker='s', markersize=4, color='orange',
             label=r'Corrected $(C_M)_{pitch}-\alpha$')
    ax3.plot(ucdata[:, 1], ucdata[:, 11], linewidth=1, marker='s', markersize=3, color='grey',
             label=r'Uncorrected $(C_M)_{pitch}-\alpha$')
    # ax3.set_title('Cm_pitch-alpha')
    ax3.set_xlabel(r'$\alpha$ [deg]', fontsize=16)
    ax3.set_ylabel(r'$(C_M)_{pitch}$ [-]', fontsize=16)
    plt.grid()
    plt.legend(fontsize=11)
    plt.savefig('CMpitch_alpha_3d_exp_unc_vs_corr.pdf', dpi=200)
    if all:
        choice = 5

if choice == 5:
    fig4, ax4 = plt.subplots(figsize=(8, 5))
    ax4.plot(cdata[:, 1], cdata[:, 10], linewidth=1, marker='s', markersize=4, color='orange',
             label=r'Corrected $(C_M)_{roll}-\alpha')
    ax4.plot(ucdata[:, 1], ucdata[:, 10], linewidth=1, marker='s', markersize=3, color='grey',
             label=r'Uncorrected $(C_M)_{roll}-\alpha')
    ax4.set_xlabel(r'$\alpha$ [deg]', fontsize=16)
    ax4.set_ylabel(r'$(C_M)_{roll}$ [-]', fontsize=16)
    plt.grid()
    plt.legend(fontsize=11)
    plt.savefig('CMroll_alpha_3d_exp_unc_vs_corr.pdf', dpi=200)
    if all:
        choice = 6

if choice == 6:
    fig5, ax5 = plt.subplots(figsize=(8, 5))
    ax5.plot(cdata[:, 1], cdata[:, 12], linewidth=1, marker='s', markersize=4, color='orange',
             label=r'Corrected $(C_M)_{yaw}-\alpha')
    ax5.plot(ucdata[:, 1], ucdata[:, 12], linewidth=1, marker='s', markersize=3, color='grey',
             label=r'Uncorrected $(C_M)_{yaw}-\alpha')
    ax5.set_xlabel(r'$\alpha$ [deg]', fontsize=16)
    ax5.set_ylabel(r'$(C_M)_{yaw}$ [-]', fontsize=16)
    plt.grid()
    plt.legend(fontsize=11)
    plt.savefig('CMyaw_alpha_3d_exp_unc_vs_corr.pdf', dpi=200)
    if all:
        choice = 7

if choice == 7:
    fig6, ax6 = plt.subplots(figsize=(8, 5))
    ax6.plot(cdata[:, 4], cdata[:, 3], linewidth=1, marker='D', markersize=4, color='red', label=r'Corrected $C_L-C_D$')
    ax6.plot(ucdata[:, 4], ucdata[:, 3], linewidth=1, marker='D', markersize=3, color='grey',
             label=r'Uncorrected $C_L-C_D$')
    # ax4.set_title('Cl-Cd')
    ax6.set_xlabel(r'$C_D$ [-]', fontsize=16)
    ax6.set_ylabel(r'$C_L$ [-]', fontsize=16)
    plt.grid()
    plt.legend(fontsize=11)
    plt.savefig('CL_CD_3d_exp_unc_vs_corr.pdf', dpi=200)

if choice > 7 or choice < 1 or isinstance(choice, int) is False:
    print("Invalid choice!")

plt.tight_layout()