# IMPORT BOUNDARIES
import pandas as pd

# LOAD DATA
df = pd.read_csv("datasets/preprocessing3.0_sorting_session/preprocessing_session_sorted.csv", error_bad_lines=False, header=0, sep=';', low_memory=False)

# NEW COLUMN WITH "WATCHED WOMENS/MENS CLOTHING" BY SEARCHING IN URL STRING
def gender_article(s):
    content_list = s.to_list()
    word_list_damen = ["Damen", "damen" "BHs", "Kleider", "Blusen", "Mieder"]
    word_list_herren = ["Herren", "herren", "Pollunder", "Boxershorts"]
    new_column_list = []
    counter = 0
    counter_herren = 0

    # COMPARE URL CONTENT WITH WORD LIST
    for line in content_list:
        for word in word_list_damen:
            if str(word) in str(line):
                counter = counter + 1
        for word in word_list_herren:
            if str(word) in str(line):
                counter_herren += 1

        # APPEND MATCHING NUMBER TO NEW LIST
        if counter_herren > 0:
            new_column_list.append(0)#masculine clothing
        elif counter > 0:
            new_column_list.append(1) #feminine clothing
        else:
            new_column_list.append(2) #no gendered clothing

        counter = 0
        counter_herren = 0

    return pd.Series(new_column_list)

# NEW COLUMN WITH "WATCHED WOMENS/MENS CLOTHING" BY SEARCHING IN URL STRING
def search_gender(s):
    content_list = s.to_list()
    search_damen = ["Damen", "damen", "BHs", "Kleider", "Blusen", "blusen", "BH", "frau", "Frau", "Nachthemd",
                    "nachthemd", "Slip", "Mieder", "mieder", "slip", "Tunika", "tunika", "Blazer", "blazer" "Leggings",
                    "leggings", "Leggins", "leggins", "Schlüpfer", "schlüpfer", "Tasche", "tasche", "bh"]
    search_herren = ["Herren", "herren", "Pollunder", "Boxershorts", "Männer", "männer", "Mann", "mann"]
    new_column_list = []
    counter = 0
    counter_herren = 0

    # COMPARE URL CONTENT WITH WORD LIST
    for line in content_list:
        for word in search_damen:
            if str(word) in str(line):
                counter = counter + 1
        for word in search_herren:
            if str(word) in str(line):
                counter_herren += 1

        # APPEND MATCHING NUMBER TO NEW LIST
        if counter_herren > 0:
            new_column_list.append(0)#masculine clothing
        elif counter > 0:
            new_column_list.append(1) #feminine clothing
        else:
            new_column_list.append(2) #no gendered clothing

        counter = 0
        counter_herren = 0

    return pd.Series(new_column_list)

# FILLING THE DATAFRAME AND CREATING A NEW CSV
df['CLOTHING_GENDER'] = gender_article(df['CONTENT_NAME'].astype(str))
df['SEARCH_GENDER'] = search_gender(df['SEARCH_QUERY'].astype(str))
print("checked for gender clothing")
df.to_csv("datasets/preprocessing3.1_genderspecific_clothing/preprocessing_genderspecific_article.csv", sep=';', index=False)


from main_funcs import get_input

def num_els(n:int=30) -> int:
    nums = []
    for _ in range(n):
        a = get_input('Введите число: ')
        if a not in nums:
            nums.append(a)
    return(len(nums))


import cPickle
import pandas

df = pandas.DataFrame

from count_atms import CompoundLines, readSections

dat_ifn = "../dat/filtered_drugid_clustered_ligs.dat"
with open(dat_ifn, 'r') as f:
    dat = cPickle.load(f)

valid_drugs = []
for drug_id, ligs in dat.iteritems():
    if len(ligs) != 0:
        valid_drugs.append(drug_id)

ifn = "../dat/approved.txt"
sects = readSections(ifn)
dset = []
for sect in sects:
    cmp_lines = CompoundLines(sect)
    my_id = cmp_lines.getDrugBankID()
    if my_id in valid_drugs:
        dset.append((my_id, len(cmp_lines.getHeavyAtomCoordLines())))

dset = df(dset)
dset.columns = ['id','#HeavyAtom']
within_dset = dset[(dset['#HeavyAtom'] >= 8)
                   & (dset['#HeavyAtom'] <= 44)]

within_dset.to_csv("../dat/representative_drugs.csv")


import sys
sys.path.append('./')
import cv2
import os
import numpy as np
from tqdm import tqdm
import json
import shutil
import pdb

if __name__ == "__main__":
    src_dir = '/home/data0/project-datasets/dehongcheng/exp_SYB/train_val_data/train/'
    pred_dir = '/home/data0/project-datasets/dehongcheng/exp_SYB/test/train_infer_ana_0001/'
    save_dir = '/home/data0/project-datasets/dehongcheng/exp_SYB/train_val_data/train_inpaint_kill/'

    if not os.path.exists(save_dir):
        os.makedirs(save_dir)

    imgs_list = list()
    for filepath, _, filenames in os.walk(src_dir):
        for filename in filenames:
            if '.jpg' in filename:
                imp = os.path.join(filepath, filename)
                imgs_list.append(imp)

    for imp in tqdm(imgs_list):
        jsp = imp.replace('.jpg', '.json')
        pred_jsp = jsp.replace(src_dir, pred_dir)

        img = cv2.imread(imp)
        with open(pred_jsp, "r", encoding="utf-8") as fj:
            info = json.load(fj)

        for shape in info['shapes']:
            if 'PRED_kill' == shape['group_id']:
                points = shape['points']
                x_list = [k[0] for k in points]
                y_list = [k[1] for k in points]

                x1 = int(min(x_list))
                y1 = int(min(y_list))
                x2 = int(max(x_list))
                y2 = int(max(y_list))

                mask = np.zeros_like(img)[:,:,0]
                # pdb.set_trace()
                mask[y1:y2, x1:x2] = 255

                # x1_crop = max(0, x1-20)
                # y1_crop = max(0, y1-20)
                # x2_crop = min(img.shape[1], x2+20)
                # y2_crop = min(img.shape[0], y2+20)
                # src_img_crop = img[y1_crop:y2_crop, x1_crop:x2_crop, :].copy()

                img = cv2.inpaint(img, mask, 5, cv2.INPAINT_TELEA)

                # dst_img_crop = img[y1_crop:y2_crop, x1_crop:x2_crop, :].copy()
                # res = np.concatenate([src_img_crop, dst_img_crop], 1)
                # cv2.imshow('res', res)
                # cv2.waitKey(0)
        save_sub_dir = '/'.join(imp.replace(src_dir, save_dir).split('/')[:-1])
        if not os.path.exists(save_sub_dir):
            os.makedirs(save_sub_dir)
        dst_imp = imp.replace(src_dir, save_dir)
        dst_jsp = dst_imp.replace('.jpg', '.json')
        cv2.imwrite(dst_imp, img)
        shutil.copy(jsp, dst_jsp)


#!/usr/bin/python
import boto3
import sys

def get_instance_ip(instance_id):
    client = boto3.client('ec2')
    response = client.describe_instances(InstanceIds = [instance_id])
    for reservation in response['Reservations']:
        for instance in reservation['Instances']:
            for interface in instance['NetworkInterfaces']:
                if 'PrivateIpAddress' in interface:
                   yield interface['PrivateIpAddress']
                if 'Association' in interface:
                   yield interface['Association']['PublicIp']

def as_get_instances(client, asgroup):

    irsp = client.describe_auto_scaling_instances()

    for i in irsp['AutoScalingInstances']:
        if i['AutoScalingGroupName'] == asgroup:
            yield i['InstanceId']

if __name__ == '__main__':
    client = boto3.client('autoscaling')
    id_list = list(as_get_instances(client, sys.argv[1]))
    print (id_list)
    for id in id_list:
        print(list(get_instance_ip(id)))


# Sebastian Thomas (coding at sebastianthomas dot de)

# https://leetcode.com/problems/regular-expression-matching/
#
# 10. Regular Expression Matching
#
# Given an input string (s) and a pattern (p), implement regular
# expression matching with support for '.' and '*' where:
#
# '.' Matches any single character.
# '*' Matches zero or more of the preceding element.
# The matching should cover the entire input string (not partial).

def isMatch(s: str, p: str) -> bool:
    # matches[i][j] indicates whether s[i:] matches p[j:]
    matches = [[False] * (len(p) + 1) for _ in range(len(s) + 1)]

    matches[-1][-1] = True
    for i in range(len(s), -1, -1):
        for j in range(len(p) - 1, -1, -1):
            if j + 1 < len(p) and p[j + 1] == '*':  # p[j:] == 'x*…'
                matches[i][j] = matches[i][j + 2] \
                                or i < len(s) and p[j] in {s[i], '.'} \
                                and matches[i + 1][j]
                # true if s[i:] and p[j + 2:] == '…' match
                # or if s[i] and p[j] match
                # and s[i + 1:] and p[j:] match
            else:
                matches[i][j] = i < len(s) and p[j] in {s[i], '.'} \
                                and matches[i + 1][j + 1]
                # true if s[i] and p[j] match
                # and s[i + 1:] and p[j + 1:] match

    return matches[0][0]

if __name__ == '__main__':
    print(isMatch('aa', 'a'))  # False
    print(isMatch('aa', 'a*'))  # True
    print(isMatch('ab', '.*'))  # True
    print(isMatch('aab', 'c*a*b'))  # True
    print(isMatch('mississippi', 'mis*is*p*.'))  # False
    print(isMatch('ab', 'ab'))  # True
    print(isMatch('ab', 'a.'))  # True
    print(isMatch('ab', '.b'))  # True
    print(isMatch('ab', '..'))  # True


def post(self):
    """ post method """
    def status_finish(ret):
      self.set_status(ret)
      self.finish()

    def kill_parent():
      status_finish(200)
      logger.info("Killing parent executor")
      os.killpg(os.getppid(), signal.SIGTERM)

    logger = logging.getLogger(__file__)
    logger.info("Received 'Killing process' request")
    data = dict(urlparse.parse_qsl(self.request.body))

    # check shared secret
    sharedSecret = data.get('secret')
    if sharedSecret != options.secret:
      status_finish(403)
      return

    instanceId = data.get('instance_id_to_restart')
    if instanceId:
      filepath = instanceId + '.pid'
      if os.path.isfile(filepath): # instance_id found
        if instanceId.startswith('heron-executor-'): # kill heron-executor
          kill_parent()
        else: # kill other normal instance
          fh = open(filepath)
          firstLine = int(fh.readline())
          fh.close()
          logger.info("Killing process " + instanceId + " " + str(firstLine))
          os.kill(firstLine, signal.SIGTERM)
          status_finish(200)
      else: # instance_id not found
        logger.info(filepath + " not found")
        status_finish(422)
    else: # instance_id not given, which means kill the container
      kill_parent()


#%%
from database import DB
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from geopandas import GeoSeries, GeoDataFrame
import matplotlib.colors as mplc
from math import log

# %%
# Read Geopandas
world = GeoDataFrame.from_file('./docs/ne_10m_admin_0_countries.shp')

countryDataWorld = DB.SelectRows("""
SELECT
    c.code countrycode,
    CASE
        WHEN c.population IS NULL OR c.population = 0
        THEN 1
        ELSE c.population
    END population_alias,
    c.gnp gnp,
    CASE
        WHEN site.count_sites IS NULL OR site.count_sites = 0
        THEN 1
        ELSE site.count_sites
    END count_sites
FROM country c
LEFT JOIN (
    SELECT countrycode, count(*) count_sites
    FROM sitio2
    GROUP BY countrycode
) site
ON c.code = site.countrycode
""")

dfCountryDataWorld = pd.DataFrame(countryDataWorld, columns = ['countrycode', 'population', 'gnp', 'count_sites'])
world = world.merge(
                     right = dfCountryDataWorld,
                     left_on = 'ADM0_A3',
                     right_on = 'countrycode',
                     how = 'left'
                     )
world = world.drop('countrycode', axis=1)
world.head()

# %%
## SHOW MAPS
world['population2'] =  np.log2(world['population'])
world['count_sites2'] =  np.log2(world['count_sites'])

# # Mapa de población mundial
world.plot(column='population2', cmap='Reds', alpha=1, linewidth = 0.5, edgecolor='black', figsize = (14,8), categorical=False, legend=False, ax=None)

# # Mapa de producto bruto
world.plot(column='gnp', cmap='Greens', alpha=1, linewidth = 0.5, edgecolor='black', figsize = (14,8), categorical=False, legend=False, ax=None)

# # # Mapa de sitios por pais
world.plot(column='count_sites2', cmap='Blues', alpha=1, linewidth = 0.5, edgecolor='black', figsize = (14,8), categorical=False, legend=False, ax=None)

plt.show()
# %%


"""
Test Spotlight external data cache and clear cache behaviour.
"""

import json
import shutil

import requests

from renumics import spotlight

def test_external_data_cache(non_existing_image_df_viewer: spotlight.Viewer) -> None:
    """
    Test loading non-existing external data, cache it and clear cache.
    """
    image_path = non_existing_image_df_viewer.df["image"][0]
    app_url = str(non_existing_image_df_viewer)

    response = requests.get(app_url + "api/table/", timeout=5)
    assert response.status_code == 200
    assert len(response.text) > 200
    generation_id = json.loads(response.text)["generation_id"]

    response = requests.get(
        f"{app_url}api/table/image/0?generation_id={generation_id}", timeout=5
    )
    assert response.status_code == 422
    assert json.loads(response.text)["type"] == "ConversionFailed"

    shutil.copyfile("data/images/nature-360p.jpg", image_path)
    response = requests.get(
        f"{app_url}api/table/image/0?generation_id={generation_id}", timeout=5
    )
    assert response.status_code == 200
    first_image_content = response.content
    assert len(first_image_content) == 19355

    shutil.copyfile("data/images/nature-720p.jpg", image_path)
    response = requests.get(
        f"{app_url}api/table/image/0?generation_id={generation_id}", timeout=5
    )
    assert response.status_code == 200
    assert response.content == first_image_content

    spotlight.clear_caches()
    response = requests.get(
        f"{app_url}api/table/image/0?generation_id={generation_id}", timeout=5
    )
    assert response.status_code == 200
    second_image_content = response.content
    assert len(second_image_content) == 70143
    assert second_image_content != first_image_content

    shutil.copyfile("data/audio/1.wav", image_path)
    response = requests.get(
        f"{app_url}api/table/image/0?generation_id={generation_id}", timeout=5
    )
    assert response.status_code == 200
    assert response.content == second_image_content

    spotlight.clear_caches()
    response = requests.get(
        f"{app_url}api/table/image/0?generation_id={generation_id}", timeout=5
    )
    assert response.status_code == 422
    assert json.loads(response.text)["type"] == "ConversionFailed"


import colorsys
from abc import ABC, abstractmethod
import numpy as np

class Output(ABC):
    def __init__(self, rows=12, columns=12):
        self.rows = rows
        self.columns = columns

        self.brightness = 0.8

        # RGB matrix set by the games
        self.pixel_matrix = np.zeros([rows, columns, 3], dtype=np.uint8)
        # RGB matrix corrected by a specified brightness value
        self.pixel_matrix_corrected = np.zeros([rows, columns, 3], dtype=np.uint8)

        self.colormap = {
                            "blue": [66, 133, 244],
                            "red": [219, 68, 55],
                            "yellow": [244, 180, 0],
                            "green": [15, 157, 88],
                            "orange": [244, 113, 0],
                            "purple": [139, 0, 221],
                            "brown": [109, 76, 65],
        }

    def set_value_rgb(self, row, col, rgb_values):
        self.pixel_matrix[row, col] = rgb_values

    def set_value_hsv(self, row, col, h, s, v):
        rgb = colorsys.hsv_to_rgb(h, s, v)
        # Scale from range 0-1 up to 255 for Neopixel library
        rgb_values = [round(255*row) for row in rgb]
        self.pixel_matrix[row, col] = rgb_values

    def set_value_color(self, row, col, color):
        if color in self.colormap:
            self.set_value_rgb(row, col, self.colormap[color])
        else:
            print("Color not predefined. Value is not changed!")

    def color_to_rgb(self, color):
        return self.colormap[color]

    @abstractmethod
    def show(self):
        # Apply brightness settings
        # Brightness formula (0.2126 * R + 0.7152 * G + 0.0722 * B)
        self.pixel_matrix_corrected = self.pixel_matrix * self.brightness

    def empty_matrix(self):
        """
        Clears pixelMatrix and writes it out to the table (callling showRGB())
        """
        self.pixel_matrix[:, :] = [0, 0, 0]
        self.show()

    def fill_matrix_rgb(self, rgb_values):
        self.pixel_matrix[:, :] = rgb_values


# coding: utf-8

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import re
import io
import base64
import codecs
import random
import hashlib

import requests

import leancloud
from leancloud import client
from leancloud._compat import PY2
from leancloud._compat import range_type
from leancloud._compat import file_type
from leancloud._compat import buffer_type
from leancloud.mime_type import mime_types
from leancloud.errors import LeanCloudError

__author__ = 'asaka <lan@leancloud.rocks>'

class File(object):
    def __init__(self, name, data=None, type_=None):
        self._name = name
        self.id = None
        self._url = None
        self._acl = None
        self.current_user = None  # TODO
        self._metadata = {
            'owner': 'unknown'
        }
        if self.current_user and self.current_user is not None:
            self._metadata['owner'] = self.current_user.id

        pattern = re.compile('\.([^.]*)$')
        extension = pattern.findall(name)
        if extension:
            self.extension = extension[0].lower()
        else:
            self.extension = ''

        if type_:
            self._type = type_
        else:
            self._type = mime_types.get(self.extension, 'text/plain')

        if data is None:
            self._source = None
        elif isinstance(data, io.BytesIO):
            self._source = data
        elif isinstance(data, file_type):
            data.seek(0, os.SEEK_SET)
            self._source = io.BytesIO(data.read())
        elif isinstance(data, buffer_type):
            self._source = io.BytesIO(data)
        elif PY2:
            import cStringIO, StringIO
            if isinstance(data, (cStringIO.OutputType, StringIO.StringIO)):
                data.seek(0, os.SEEK_SET)
                self._source = io.BytesIO(data.getvalue())
            else:
                raise TypeError('data must be a StringIO / buffer / file instance')

        else:
            raise TypeError('data must be a StringIO / buffer / file instance')

        if self._source:
            self._source.seek(0, os.SEEK_END)
            self._metadata['size'] = self._source.tell()
            self._source.seek(0, os.SEEK_SET)
            checksum = hashlib.md5()
            checksum.update(self._source.getvalue())
            self._metadata['_checksum'] = checksum.hexdigest()

    @classmethod
    def create_with_url(cls, name, url, meta_data=None, type_=None):
        f = File(name, None, type_)
        if meta_data:
            f._metadata.update(meta_data)

        if isinstance(url, str):
            f._url = url
        else:
            raise ValueError('url must be a string')

        f._metadata['__source'] = 'external'
        return f

    @classmethod
    def create_without_data(cls, object_id):
        f = File('')
        f.id = object_id
        return f

    def get_acl(self):
        return self._acl

    def set_acl(self, acl):
        if not isinstance(acl, leancloud.ACL):
            raise TypeError('acl must be a leancloud.ACL instance')
        self._acl = acl

    @property
    def name(self):
        return self._name

    @property
    def url(self):
        return self._url

    @property
    def size(self):
        return self._metadata['size']

    @property
    def owner_id(self):
        return self._metadata['owner']

    @property
    def metadata(self):
        return self._metadata

    def get_thumbnail_url(self, width, height, quality=100, scale_to_fit=True, fmt='png'):
        if not self._url:
            raise ValueError('invalid url')

        if width < 0 or height < 0:
            raise ValueError('invalid height or width params')

        if quality > 100 or quality <= 0:
            raise ValueError('quality must between 0 and 100')

        mode = 2 if scale_to_fit else 1

        return self.url + '?imageView/{0}/w/{1}/h/{2}/q/{3}/format/{4}'.format(mode, width, height, quality, fmt)

    def destroy(self):
        if not self.id:
            return False
        response = client.delete('/files/{0}'.format(self.id))
        if response.status_code != 200:
            raise LeanCloudError(1, "the file is not sucessfully destroyed")

    def _save_to_qiniu(self, uptoken, key):
        import qiniu
        self._source.seek(0)
        ret, info = qiniu.put_data(uptoken, key, self._source)
        self._source.seek(0)

        if info.status_code != 200:
            raise LeanCloudError(1, 'the file is not saved, qiniu status code: {0}'.format(info.status_code))

    def _save_to_s3(self, upload_url):
        self._source.seek(0)
        responce = requests.put(upload_url, data=self._source.getvalue(), headers={'Content-Type':self._type})
        if responce.status_code != 200:
            raise LeanCloudError(1, 'The file is not successfully saved to S3')
        self._source.seek(0)

    def _save_external(self):
        data = {
            'name': self._name,
            'ACL': self._acl,
            'metaData': self._metadata,
            'mime_type': self._type,
            'url': self._url,
        }
        response = client.post('/files/{0}'.format(self._name), data)
        content = response.json()

        self._name = content['name']
        self._url = content['url']
        self.id = content['objectId']
        if 'size' in content:
            self._metadata['size'] = content['size']
        else:
            raise ValueError

    def _save_to_qcloud(self, uptoken, upload_url):
        headers = {
            'Authorization': uptoken,
        }
        self._source.seek(0)
        data = {
            'op': 'upload',
            'filecontent': self._source.read(),
        }
        response = requests.post(upload_url, headers=headers, files=data)
        self._source.seek(0)
        info = response.json()
        if info['code'] != 0:
            raise LeanCloudError(1, 'this file is not saved, qcloud cos status code: {}'.format(info['code']))

    def save(self):
        if self._url and self.metadata.get('__source') == 'external':
            self._save_external()
        elif not self._source:
            pass
        else:
            content = self._get_file_token()
            if content['provider'] == 'qiniu':
                self._save_to_qiniu(content['token'], content['key'])
            elif content['provider']== 'qcloud':
                self._save_to_qcloud(content['token'], content['upload_url'])
            elif content['provider'] == 's3':
                self._save_to_s3(content['upload_url'])
            else:
                raise RuntimeError('The provider field in the fetched content is empty')

    def _get_file_token(self):
        hex_octet = lambda: hex(int(0x10000 * (1 + random.random())))[-4:]
        key = ''.join(hex_octet() for _ in range(4))
        key = '{0}.{1}'.format(key, self.extension)
        data = {
            'name': self._name,
            'key': key,
            'ACL': self._acl,
            'mime_type': self._type,
            'metaData': self._metadata,
        }
        response = client.post('/fileTokens', data)
        content = response.json()
        self.id = content['objectId']
        self._url = content['url']
        content['key'] = key
        return content

    def fetch(self):
        response = client.get('/files/{0}'.format(self.id))
        content = response.json()
        self._name = content.get('name')
        self.id = content.get('objectId')
        self._url = content.get('url')
        self._type = content.get('mime_type')
        self._metadata = content.get('metaData')


from django.urls import path
from django.conf.urls import url

from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('adduser', views.adduser.as_view(), name='adduser'),
    path('loginuser', views.loginuser.as_view(), name='loginuser'),

    path('markspam', views.markspam.as_view(), name='markspam'),

    path('namesearch', views.namesearch.as_view(), name='namesearch'),
    path('phonesearch', views.phonesearch.as_view(), name='phonesearch'),
    path('getcontactdetails', views.getcontactdetails.as_view(), name='getcontactdetails'),

    path('contactsearch', views.contactsearch.as_view(), name='contactsearch'),

    path('global', views.usershow.as_view(), name='users'),
]


"""added timezone to student check in record

Revision ID: a51e95225d74
Revises: 8a1efca06e2a
Create Date: 2018-02-08 05:52:59.257192

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'a51e95225d74'
down_revision = '8a1efca06e2a'
branch_labels = None
depends_on = None

def upgrade():
    op.alter_column('student_check_in_records', 'checkin',
            type_=sa.DateTime(timezone=True), nullable=False)

def downgrade():
    op.alter_column('student_check_in_records', 'checkin',
            type_=sa.DateTime(), nullable=False)


import customtkinter
from tkinter import messagebox
import tkinter as tk
import os
import template_generator as tg
from pathvalidate import is_valid_filename, sanitize_filename

class config(customtkinter.CTk):

    """
    config is a class that allows users to choose the target path for their obsidian vault template,
    or obsidian vault path.

    Attributes
    ────────────────────────────────────────────────────────────

    filePath : str
        This decides the target path for the obsidian vault.

    config : str
        This decides whether a default obsidian vault will be generated or a custom obsidian
        vault will be generated.

    config_path : str
        This represents the target path to the custom obsidian vault template file.

    ticketNumber : str
        This represents the number of the ticket.

    ticketName : str
        This represents the name of the ticket.

    Methods
    ────────────────────────────────────────────────────────────

    initializeWidget()
        Just like any other classes in this program, it is used to initialize all the widgets in that page.
        It will call grid_configurate() to set up the grid, create three CTkLabel and one CTkButton. When the
        submitButton is clicked, the submitTemplate() method will be called.

    grid_configurate()
        Just like any other classes in this program, it will configurate the grid system for this page.

    submitTemplate()
        This method will first check whether the target directory already exists, if it does exist, a message box
        will be displayed showing the error. Else, it will use the templateGenerator() method to create the obsidian
        vault in the targetted path.

    validateInput()
        This method will check whether the ticketnum is a valid input.

    """
    def initializeWidget(self):
        self.grid_configurate()
        self.geometry("1000x500")
        self.title("Template Configuration")
        self.resizable(False,False)
        title = customtkinter.CTkLabel(self, text = "Template Configuration", font = ("American Typewriter",25))
        title.grid(row = 0, column = 0, columnspan = 2, sticky = "nsew")
        submitButton = customtkinter.CTkButton(self, text = "Submit", command = self.submitTemplate, height = 50)
        submitButton.grid(row = 3, column = 0, columnspan = 2, sticky = "nsew")
        ticketNameLabel = customtkinter.CTkLabel(self, text = "Name of the ticket", font = ("American Typewriter",25))
        ticketNameLabel.grid(row = 1, column = 0, pady = (0,0))
        self.ticketName.grid(row = 1, column = 1, pady = (0,0))
        ticketNumberLabel = customtkinter.CTkLabel(self, text = "Number of the ticket", font = ("American Typewriter",25))
        ticketNumberLabel.grid(row = 2, column = 0)
        self.ticketNumber.grid(row = 2, column = 1)

    def __init__(self, filePath, config, config_path):
        super().__init__()
        self.filePath = filePath
        self.config = config
        self.config_path = config_path
        self.ticketNumber = customtkinter.CTkTextbox(master = self, height = 40, width = 450, border_width = 3, border_color = "black")
        self.ticketName = customtkinter.CTkTextbox(master = self, height = 40, width = 450, border_width = 3, border_color = "black")
        self.initializeWidget()

    def submitTemplate(self):
        ticketName = self.ticketName.get("1.0","end-1c")
        if self.validateInput():
            if not is_valid_filename(ticketName):
                ticketName = sanitize_filename(ticketName)
                messagebox.showinfo(title = "Illegal ticket name", message = "Notice: The ticket name you provided is not a legal file name. Your ticket name has been changed to: " + ticketName)
            filePath = self.filePath + "/" + ticketName
            filePath = filePath.strip()
            if not self.directory_exists(filePath):
                os.makedirs(filePath)
                tg.templateGenerator(self.config_path,filePath, self.ticketNumber.get("1.0","end-1c"), ticketName, self.config)
                messagebox.showinfo(title = "Vault Generated", message = "Success: The Obsidian Vault: " + ticketName + " has been generated.")
                self.destroy()
            else:
                messagebox.showerror(title = "Directory already exists", message = "Error: Directory already exists.")
        else:
           messagebox.showerror(title = "Inputs not found", message = "Error: One or more inputs not found.")

    def validateInput(self):
        ticketnum = int(self.ticketNumber.get("0.0","end"))
        if ticketnum != 0:
            if self.ticketName.get("0.0","end").strip():
                return True
        return False

    def grid_configurate(self):
        self.grid_rowconfigure(0, weight = 1)
        self.grid_rowconfigure(1, weight = 1)
        self.grid_rowconfigure(2, weight = 1)
        self.grid_columnconfigure(0, weight = 1)
        self.grid_columnconfigure(1, weight = 1)

    def directory_exists(self, filePath):
        return os.path.exists(filePath)


class Solution:
    def rotate(self, matrix: list[list[int]]) -> None:

        # using zip function
        # matrix[:]=list(zip(*matrix[::-1]))

        ##Using rows exchange approach

        #declared the rows and columns
        m=len(matrix)

        # iterate the matrix and exchange rows
        up=0
        down=m-1
        while up < down:
            matrix[up],matrix[down]=matrix[down],matrix[up]
            up+=1
            down-=1

        #exchange the values in each rows
        for i in range(m):
            for j in range(i):
                matrix[i][j],matrix[j][i]=matrix[j][i],matrix[i][j]


SITE_PORT = '8080'
SITE_HOST = '127.0.0.1'

STREAM_HOST = 'https://www.radiobarmaglot.com'
STREAM_PORT = '20000'

MONGO_DB_NAME = 'barmaglot'
MONGO_HOST = 'localhost'

USER_COLLECTION = 'users'
QUOTE_COLLECTION = 'quotes'
STREAM_COLLECTION = 'streams'
TOKEN_COLLECTION = 'tokens'

DEBUG = True

SECRET_KEY = b'\xf4cx\xae\x97P\xff*Kj\xe1\xf1\xa4\x1a\xad\xb7\xcb~\xe44PDq\xf4\x11q\xf0\xecp\xb9\xc3\x19'

# mail related
INFO_EMAIL = "info@radiobarmaglot.com"
FEEDBACK_SUBJECT = "Barmaglot feedback"

# 3-rd Party API settings
MAIL_GUN_API_KEY = None
MAIL_GUN_API_URL = "https://api.mailgun.net/v3/sandbox634f2c973aa64b688e61e82dba4f72f1.mailgun.org/messages"

# should come from local settings
GOOGLE_ANALYTICS = None

try:
    from .local_settings import *
except:
    pass


#!/usr/bin/python

import socket
import sys

def check_host_status(host, port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(2)
    try:
        sock.connect((host, port))
    except ConnectionRefusedError:
        return "Close"
    else:
        return "Open"
def banner_grabbing(host, port):
    try:
        socket.setdefaulttimeout(1)
        s = socket.socket()
        s.connect((host,port))
        banner = s.recv(1024)
    except:
        return None
    else:
        return banner

host = sys.argv[1]
port = sys.argv[2]

def port_proccess(port):
    result = []
    try:
        result.append(int(port))
    except:
        if "," in port:
            for item in port.split(','):
                result.append(int(item))
        elif "-" in port:
            for item in range(int(port.split("-")[0]),int(port.split("-")[1])+1):
                result.append(int(item))
    return result

for item in port_proccess(port):
    banner = banner_grabbing(host,item)
    status = check_host_status(host,item)
    print(f" host : {host}  port : {item}  status: {status}  banner : {banner}")


from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^edit_map$', views.edit_map, name='edit_map'),
    url(r'^save_map$', views.save_map, name='save_map'),
    url(r'^get_active_users$', views.get_active_users, name='get_active_users'),
    url(r'^update_users$', views.update_users, name='update_users'),
    url(r'^hostnames$', views.show_hostnames, name='show_hostnames'),
]


import sys
input = sys.stdin.readline

n = int(input())
arr = [input().strip() for _ in range(n)]

dict = {}
for word in arr:
    length = len(word)
    if length in dict:
        dict[length].add(word)
    else:
        dict[length] = set([word])

key = sorted(dict.keys())
for k in key:
    word = sorted(list(dict[k]))
    for w in word:
        print(w)


from fastapi import APIRouter
from fastapi.responses import JSONResponse

from app import business
from app.schemas import UserSchema
from exceptions import BusinessException

users_router = APIRouter(
    prefix='/users',
    tags=['users'],
)

@users_router.post('/')
async def create_user(payload: UserSchema):
    user = payload.get_model()
    response = JSONResponse(content=payload.dict(), status_code=201)
    try:
        business.Users.create_user(user)
    except BusinessException as e:
        response = JSONResponse(content=e.payload, status_code=e.status_code)
    return response


#!/usr/bin/env python3

import os
import datetime

if __name__ == '__main__':

    os.remove('logfile.txt')
    with open('logfile.txt','w+') as log:
        date = str(datetime.datetime.today())
        log.write('Beginning retraining process: '+date+'\n\n')


BICICLETARIA = {}

name = input('Digite seu nome: ')

def menu_consulta():
    print('######################################################')
    print('## 1 - Consultar Todas as Peças                     ##')
    print('## 2 - Consultar Peças por Código                   ##')
    print('## 3 - Consultar Peças por Fabricante               ##')
    print('## 4 - Retornar                                     ##')
    print('######################################################')

def consultar_pecas():
    while True:
        menu_consulta()

        opcao = input('Escolha uma opção: ')

        if opcao == '1':
            mostrar_pecas()
        elif opcao == '2':
            codigo = input('Digite o código da peça para consulta: ')
            buscar_pecas(codigo)
        elif opcao == '3':
            pass
        elif opcao == '4':
            imprimir_menu()
            break

def mostrar_pecas():
    if BICICLETARIA:
        for codigo in BICICLETARIA:
            buscar_pecas(codigo)
    else:
        print('>>>>> Bicicletaria Vazia')

def buscar_pecas(codigo):
    try:
        print('Código:', codigo)
        print('Nome:', BICICLETARIA[codigo]['nome'])
        print('Fabricante:', BICICLETARIA[codigo]['fabricante'])
        print('Valor:', BICICLETARIA[codigo]['valor'])
        print('######################################')
    except KeyError:
        print('>>>>> Peça Inexistente')
    except Exception as error:
        print('>>>>> Um erro inesperado ocorreu')
        print(error)

def ler_detalhes_contato():
    nome = input('Digite o nome da peça: ')
    fabricante = input('Digite o fabricante da peça: ')
    valor = input('Digite o valor da peça: ')
    return (nome, fabricante, valor)

def incluir_editar_peca(codigo,nome,fabricante, valor):
    BICICLETARIA[codigo] = {
        'nome': nome,
        'fabricante': fabricante,
        'valor': valor
    }
    print()
    print('>>>>>>>>Peça de código {} adicionado/editado com sucesso'.format(codigo))
    print()

def excluir_peca(codigo):
    try:
        BICICLETARIA.pop(codigo)
        print()
        print('>>>>>Peça de código {} excluido com sucesso'.format(codigo))
        print()
    except KeyError:
        print('>>>>>Peça inexistente')
    except Exception as error:
        print('>>>>> Um erro inesperado ocorreu')
        print(error)

def imprimir_menu():

    print("Bem vindo ao Controle de Estoque da Bicicletaria do {}".format(name))
    print('######################################################')
    print('## 1 - Consultar Peça                               ##')
    print('## 2 - incluir Peça                                 ##')
    print('## 3 - Editar Peça                                  ##')
    print('## 4 - Excluir Peça                                 ##')
    print('## 0 - Fechar Bicicletaria                          ##')
    print('######################################################')

while True:

    imprimir_menu()

    opcao = input('Escolha uma opção: ')

    if opcao == '1':
       consultar_pecas()
    elif opcao == '2':
        codigo = input('Digite o código da peça: ')

        try:
            BICICLETARIA[codigo]
            print('>>>>> Peça de código {} já existente'.format(codigo))

        except KeyError:
            nome, fabricante, valor = ler_detalhes_contato()
            incluir_editar_peca(codigo, nome, fabricante, valor)

    elif opcao == '3':
        codigo = input('Digite o código da peça: ')

        try:
            BICICLETARIA[codigo]
            print('>>>>> Editando peça de código ', codigo)

            nome, fabricante, valor = ler_detalhes_contato()
            incluir_editar_peca(codigo, nome, fabricante, valor)

        except KeyError:
            print('>>>>>> Peça inexistente')

    elif opcao == '4':
        codigo = input('Digite o código da peça: ')
        excluir_peca(codigo)

    elif opcao == '0':
        print('>>>>>Fechando Programa<<<<<')
        break
    else:
        print('>>>>>Opção Inválida<<<<<')


"""AOC 2020 Day 12"""

import pathlib
import time

TEST_INPUT = """F10
N3
F7
R90
F11"""

LEFT, RIGHT = 'L', 'R'
FORWARD = 'F'
NORTH, SOUTH, EAST, WEST = 'N', 'S', 'E', 'W'

def read_input(input_path: str) -> str:
    """take input file path and return a str with the file's content"""
    with open(input_path, 'r') as input_file:
        input_data = input_file.read().strip()
        return input_data

def extract(input_data: str) -> list:
    """take input data and return the appropriate data structure"""
    entries = []
    for line in input_data.split('\n'):
        instruction = (line[0], int(line[1:]))
        entries.append(instruction)
    return entries

def rotate_ship(direction: str, rotation: str) -> str:
    """rotate the ship"""
    if direction == NORTH:
        return WEST if rotation == LEFT else EAST
    if direction == SOUTH:
        return EAST if rotation == LEFT else WEST
    if direction == EAST:
        return NORTH if rotation == LEFT else SOUTH
    if direction == WEST:
        return SOUTH if rotation == LEFT else NORTH
    return None

def move(direction: str, x: int, y: int, value: int) -> tuple:
    """move the ship or the waypoint"""
    if direction == NORTH:
        return (x, y+value)
    if direction == SOUTH:
        return (x, y-value)
    if direction == EAST:
        return (x+value, y)
    if direction == WEST:
        return (x-value, y)
    return None

def rotate_waypoint(direction: str, x: int, y: int, value: int) -> tuple:
    """rotate waypoint around ship"""
    if (direction == LEFT and value == 90) or (direction == RIGHT and value == 270):
        return (-y, x)
    if ((direction == LEFT and value == 180) or (direction == RIGHT and value == 180)):
        return (-x, -y)
    if ((direction == LEFT and value == 270) or (direction == RIGHT and value == 90)):
        return (y, -x)
    return None

def part1(entries: list) -> int:
    """part1 solver"""
    direction = EAST
    x_ship, y_ship = 0, 0

    for action, value in entries:
        if action == FORWARD:
            x_ship, y_ship = move(direction, x_ship, y_ship, value)
        elif action in (LEFT, RIGHT):
            for _ in range(value//90):
                direction = rotate_ship(direction, action)
        else:
            x_ship, y_ship = move(action, x_ship, y_ship, value)
    return abs(x_ship) + abs(y_ship)

def part2(entries: list) -> int:
    """part2 solver"""
    x_ship, y_ship = 0, 0
    x_wp, y_wp = 10, 1

    for action, value in entries:
        if action == FORWARD:
            x_ship += x_wp * value
            y_ship += y_wp * value
        elif action in (LEFT, RIGHT):
            x_wp, y_wp = rotate_waypoint(action, x_wp, y_wp, value)
        else:
            x_wp, y_wp = move(action, x_wp, y_wp, value)
    return abs(x_ship) + abs(y_ship)

def test_input_day_12():
    """pytest testing function"""
    entries = extract(TEST_INPUT)
    assert part1(entries) == 25
    assert part2(entries) == 286

def test_bench_day_12(benchmark):
    """pytest-benchmark function"""
    benchmark(main)

def main():
    """main function"""
    input_path = str(pathlib.Path(__file__).resolve().parent.parent) + "/inputs/" + str(pathlib.Path(__file__).stem)
    start_time = time.time()
    input_data = read_input(input_path)
    entries = extract(input_data)
    print("Part 1: %d" % part1(entries))
    print("Part 2: %d" % part2(entries))
    end_time = time.time()
    print("Execution time: %f" % (end_time-start_time))

if __name__ == "__main__":
    main()


from typing import List

import numpy as np
import osqp
import scipy

from sco_OSQP.variable import Variable

class OSQPVar(object):
    """
    A class representing a variable within OSQP that will be used to construct the
    QP that will be passed to the solver. The lb and ub are used to enforce a
    trust region on each variable
    """

    def __init__(self, var_name, lb=-np.inf, ub=np.inf, val=None):
        self.var_name = var_name
        self._lower_bound = lb
        self._upper_bound = ub
        self.val = val

    def __repr__(self):
        return f"OSQPVar with name {self.var_name}"
        # return f"OSQPVar with name {self.var_name}, lb={self._lower_bound}, ub={self._upper_bound}, val={self.val}"

    def get_lower_bound(self):
        return self._lower_bound

    def set_lower_bound(self, lb_val):
        assert isinstance(lb_val, float)
        assert not np.isnan(lb_val)
        self._lower_bound = lb_val

    def get_upper_bound(self):
        return self._upper_bound

    def set_upper_bound(self, ub_val):
        assert isinstance(ub_val, float)
        assert not np.isnan(ub_val)
        self._upper_bound = ub_val

class OSQPLinearObj(object):
    def __init__(self, osqp_var, coeff):
        """
        A wrapper class for a linear objective. The particular constraint represented is:

        coeff * osqp_var
        """
        self.osqp_var = osqp_var
        self.coeff = coeff

    def __repr__(self):
        return f"OSQPLinearObj with osqp_var={self.osqp_var}, coeff={self.coeff}"

    def get_all_vars(self):
        return [self.osqp_var]

class OSQPQuadraticObj(object):
    def __init__(self, osqp_vars1, osqp_vars2, coeffs):
        """
        A wrapper class for a quadratic objective. The particular objective represented is:

        0.5 * np.linalg.multi_dot(self.osqp_vars1, self.osqp_vars2, self.coeffs)
        """
        assert osqp_vars1.shape == osqp_vars2.shape == coeffs.shape
        # Together with the above condition, this implicitly implies all these arrays must
        # have shape of length 1
        assert len(osqp_vars1.shape) == 1
        self.osqp_vars1 = osqp_vars1
        self.osqp_vars2 = osqp_vars2
        self.coeffs = coeffs

    def __repr__(self):
        return f"Quadratic Objective with osqp_vars1={self.osqp_vars1}, osqp_vars2={self.osqp_vars2}, coeffs={self.coeffs}"

    def get_all_vars(self):
        return self.osqp_vars1.tolist() + self.osqp_vars2.tolist()

class OSQPLinearConstraint(object):
    def __init__(self, osqp_vars, coeffs, lb, ub):
        """
        A wrapper class for a linear constraint. The particular constraint represented is:

        lb <= np.dot(self.osqp_vars, self.coeffs) <= ub
        """
        assert osqp_vars.shape == coeffs.shape
        self.osqp_vars = osqp_vars
        self.coeffs = coeffs
        self.lb = lb
        self.ub = ub

    def __repr__(self):
        return f"OSQPLinearConstraint with osqp_vars={self.osqp_vars}, coeffs={self.coeffs}, lb = {self.lb}, ub = {self.ub}"

    def get_all_vars(self):
        return self.osqp_vars.tolist()

def optimize(
    osqp_vars: List[OSQPVar],
    sco_vars: List[Variable],
    osqp_quad_objs: List[OSQPQuadraticObj],
    osqp_lin_objs: List[OSQPLinearObj],
    osqp_lin_cnt_exprs: List[OSQPLinearConstraint],
):
    """
    Calls the OSQP optimizer on the current QP approximation with a given
    penalty coefficient.
    """
    # First, we need to setup the problem as described here: https://osqp.org/docs/solver/index.html
    # Specifically, we need to start by constructing the x vector that contains all the
    # OSQPVars that are part of the QP. This will take the form of a mapping from OSQPVar to
    # index within the x vector.
    var_to_index_dict = {}
    idx = 0
    for osqp_var in osqp_vars:
        var_to_index_dict[osqp_var] = idx
        idx += 1
    num_osqp_vars = len(osqp_vars)

    # Construct the q-vector by looping through all the linear objectives
    q_vec = np.zeros(idx)
    for lin_obj in osqp_lin_objs:
        q_vec[var_to_index_dict[lin_obj.osqp_var]] += lin_obj.coeff

    # Next, construct the P-matrix by looping through all quadratic objectives

    # Since P must be upper-triangular, the shape must be (num_osqp_vars, num_osqp_vars)
    P_mat = np.zeros((num_osqp_vars, num_osqp_vars))
    for quad_obj in osqp_quad_objs:
        for i in range(quad_obj.coeffs.shape[0]):
            idx2 = var_to_index_dict[quad_obj.osqp_vars1[i]]
            idx1 = var_to_index_dict[quad_obj.osqp_vars2[i]]
            P_mat[idx1, idx2] += quad_obj.coeffs[i]
            if idx1 != idx2:
                P_mat[idx2, idx1] += quad_obj.coeffs[i]

    # Next, setup the A-matrix and l and u vectors
    A_mat = np.zeros((num_osqp_vars + len(osqp_lin_cnt_exprs), num_osqp_vars))
    l_vec = np.zeros(num_osqp_vars + len(osqp_lin_cnt_exprs))
    u_vec = np.zeros(num_osqp_vars + len(osqp_lin_cnt_exprs))
    # First add all the linear constraints
    row_num = 0
    for lin_constraint in osqp_lin_cnt_exprs:
        l_vec[row_num] = lin_constraint.lb
        u_vec[row_num] = lin_constraint.ub
        for i in range(lin_constraint.coeffs.shape[0]):
            A_mat[
                row_num, var_to_index_dict[lin_constraint.osqp_vars[i]]
            ] = lin_constraint.coeffs[i]
        row_num += 1

    # Then, add the trust regions for every variable as constraints
    for osqp_var in osqp_vars:
        A_mat[row_num, var_to_index_dict[osqp_var]] = 1.0
        l_vec[row_num] = osqp_var.get_lower_bound()
        u_vec[row_num] = osqp_var.get_upper_bound()
        row_num += 1

    # Finally, construct the matrices and call the OSQP Solver!
    P_mat_sparse = scipy.sparse.csc_matrix(P_mat)
    A_mat_sparse = scipy.sparse.csc_matrix(A_mat)

    # from IPython import embed

    # embed()

    m = osqp.OSQP()
    m.setup(
        P=P_mat_sparse,
        q=q_vec,
        A=A_mat_sparse,
        sigma=1e-08,
        l=l_vec,
        u=u_vec,
        eps_rel=1e-05,
        polish=True,
        adaptive_rho=False,
        warm_start=False,
        verbose=False,
    )
    solve_res = m.solve()

    return (solve_res, var_to_index_dict)

def update_osqp_vars(var_to_osqp_indices_dict, solver_values):
    """
    Updates the variables values based on the OSQP solution
    """
    for osqp_var in var_to_osqp_indices_dict.keys():
        osqp_var.val = solver_values[var_to_osqp_indices_dict[osqp_var]]


import logging
import unittest
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.testing.test_pipeline import TestPipeline
from apache_beam.testing.util import assert_that
from apache_beam.testing.util import equal_to
import streaming_sliding_window
import apache_beam as beam

class Streaming_Sliding_Window_Test(unittest.TestCase):

    def test_sliding_window(self):
        options = PipelineOptions(streaming=True)
        scores = [
            {
                "player": "Cristina",
                "score": 2000,
                "timestamp": 10
            },
            {
                "player": "Cristina",
                "score": 2000,
                "timestamp": 50
            },
            {
                "player": "Marina",
                "score": 3000,
                "timestamp": 110
            },
            {
                "player": "Juan",
                "score": 2000,
                "timestamp": 90
            },
            {
                "player": "Cristina",
                "score": 2000,
                "timestamp": 80
            },
            {
                "player": "Juan",
                "score": 1000,
                "timestamp": 100
            },
        ]
        OUTPUT_70_60 = [('Marina', 3000), ('Cristina', 4000),
                        ('Cristina', 2000), ('Juan', 3000)]
        with TestPipeline(options=options) as test_pipeline:
            pcoll = test_pipeline | beam.Create(scores)
            pcoll_70_60 = streaming_sliding_window.apply_transformation(
                pcoll, 70, 60, label="ws 70_60")
            assert_that(pcoll_70_60,
                        equal_to(OUTPUT_70_60),
                        label="Output ws 70_60")

if __name__ == "__main__":
    logging.getLogger().setLevel(logging.INFO)
    run()


alfabeto = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

tamanho_triangulo = int(input())

indice = 0

contador = 1

while contador <= tamanho_triangulo:
    print(f"{alfabeto[indice]*contador}")
    contador = contador + 1
    indice = indice + 1


"""Run the simulation."""

import argparse
import json
import logging
import numpy.random
import time as time_mod

from collections import deque, defaultdict
from random import random as rand

import constants
import person
import util

from bar import Bar
from event import *
from util import tod_to_sec, sec_to_tod

LOGGER = None

def getopts():
    """Parse program command line arguments.

    Options get their default settings from the values in constants.py. If an
    option is specified on the command line, it will take precedence over the
    default definition.
    """
    defaults = {
        'log_level'             : 'WARNING',
        'days'                  : 1,
        'output_json'           : False,
        'arrival_time'          : constants.AVG_ARRIVAL_TIME,
        'num_servers'           : constants.NUM_SERVERS,
        'num_bartenders'        : constants.NUM_BARTENDERS,
        'num_bar_seats'         : constants.NUM_BAR_SEATS,
        'server_wwi'            : constants.SERVER_WWI,
        'bartender_wwi'         : constants.BARTENDER_WWI,
        'seating_time'          : constants.AVG_SEATING_TIME,
        'delivery_time'         : constants.AVG_DELIVERY_TIME,
        'delivery_time_stddev'  : constants.STDDEV_DELIVERY_TIME,
        'drink_time'            : constants.AVG_DRINK_TIME,
        'drinks_wanted_mean'    : constants.AVG_DRINKS_WANTED,
        'drinks_wanted_std_dev' : constants.STDDEV_DRINKS_WANTED,
    }

    parser = argparse.ArgumentParser(
        description="Simulate happy hour at Hemingway's."
    )

    parser.set_defaults(**defaults)

    parser.add_argument(
        '--days',
        type=util.positive_int_arg,
        dest='days',
        help='Number of days to simulate. (default: %s)' % defaults['days']
    )
    parser.add_argument(
        '-l', '--log-level',
        choices='DEBUG INFO WARNING ERROR CRITICAL'.split(),
        dest='log_level',
        help='Set the global logging level. (default: %s)' % defaults['log_level']
    )
    parser.add_argument(
        '--output-json',
        dest='output_json',
        action='store_true',
        help='Output a JSON representation of the events of the simulation.'
    )
    parser.add_argument(
        '--arrival-time',
        type=util.positive_arg,
        dest='arrival_time',
        help='The average time between customer arrivals, equal to the inverse'
             ' of the average rate.'
    )
    parser.add_argument(
        '--num-servers',
        type=util.positive_int_arg,
        dest='num_servers',
        help='The number of servers.'
    )
    parser.add_argument(
        '--num-bartenders',
        type=util.positive_int_arg,
        dest='num_bartenders',
        help='The number of bartenders.'
    )
    parser.add_argument(
        '--server-wwi',
        type=util.positive_int_arg,
        dest='server_wwi',
        help="How long in seconds servers wait when there's nothing to do"
            ' before trying to do something again.'
    )
    parser.add_argument(
        '--bartender-wwi',
        type=util.positive_int_arg,
        dest='bartender_wwi',
        help="How long in seconds bartenders wait when there's nothing to do"
            ' before trying to do something again.'
    )
    parser.add_argument(
        '--num-bar-seats',
        type=util.positive_int_arg,
        dest='num_bar_seats',
        help='The number of seats at the bar.'
    )
    parser.add_argument(
        '--seating-time',
        type=util.positive_arg,
        dest='seating_time',
        help='The average time it takes to be seated by a server.'
    )
    parser.add_argument(
        '--delivery-time',
        type=util.positive_arg,
        dest='delivery_time',
        help='The average time it takes for a server to deliver a prepared'
            ' drink.'
    )
    parser.add_argument(
        '--delivery-time-stddev',
        type=util.positive_arg,
        dest='delivery_time_stddev',
        help='The standard deviation of time it takes for a server to deliver'
            ' a prepared drink.'
    )
    parser.add_argument(
        '--drink-time',
        type=util.positive_arg,
        dest='drink_time',
        help='The average time it takes to drink a drink.'
    )
    parser.add_argument(
        '--drinks-wanted-mean',
        type=util.positive_arg,
        dest='drinks_wanted_mean',
        help='The average number of drinks wanted.'
    )
    parser.add_argument(
        '--drinks-wanted-std-dev',
        type=util.positive_arg,
        dest='drinks_wanted_std_dev',
        help='The standard deviation of drinks wanted.'
    )

    opts = parser.parse_args()

    # Override constants with those changed in the command line options.
    constants.AVG_ARRIVAL_TIME     = opts.arrival_time
    constants.NUM_SERVERS          = opts.num_servers
    constants.NUM_BARTENDERS       = opts.num_bartenders
    constants.SERVER_WWI           = opts.server_wwi
    constants.BARTENDER_WWI        = opts.bartender_wwi
    constants.NUM_BAR_SEATS        = opts.num_bar_seats
    constants.AVG_SEATING_TIME     = opts.seating_time
    constants.AVG_DRINK_TIME       = opts.drink_time
    constants.AVG_DELIVERY_TIME    = opts.delivery_time
    constants.STDDEV_DELIVERY_TIME = opts.delivery_time_stddev
    constants.AVG_DRINKS_WANTED    = opts.drinks_wanted_mean
    constants.STDDEV_DRINKS_WANTED = opts.drinks_wanted_std_dev

    return opts
# End of getopts()

def init(opts):
    """Initialize the global state of the sim, such as the logger."""
    global LOGGER
    level = util.get_log_level(opts.log_level)
    if level is None:
        level = logging.WARNING
    logging.basicConfig(
        level=level,
        format='\t|\t'.join([
            # '%(asctime)s',
            '%(levelname)s',
            '%(name)s:%(lineno)d',
            '%(message)s'
        ]),
        # datefmt='%Y-%m-%d %H:%M:%S'
    )
    LOGGER = logging.getLogger('sim')
    LOGGER.info('Initialized logger (level is %s)', opts.log_level)

def main():
    """Entry point of the simulation program."""
    global LOGGER
    opts = getopts()
    init(opts)
    cons = {}
    for constant in dir(constants):
        if constant[0].isupper():
            cons[constant] = getattr(constants, constant)
    LOGGER.info(cons)
    del cons

    if opts.output_json:
        with open(
            str(time_mod.time()) + '_events.json',
            'w+t',
            encoding='utf8'
        ) as fp:
            print('[\n[', file=fp)
            is_first = True
            day = 1
            for event in run_sim(opts):
                if not is_first:
                    print(',', file=fp)
                is_first = False
                print(json.dumps(event), file=fp, end='')
                if event['type'] == 'HappyHourEnd':
                    if day < opts.days:
                        print('],\n[', file=fp)
                    else:
                        print(']', file=fp)
                    day += 1
                    is_first = True
            print(']', file=fp)
    else:
        for _ in run_sim(opts):
            pass
# End of main()

def run_sim(opts):
    start_time = time_mod.time()
    stats = []

    for day in range(0, opts.days):
        LOGGER.info(('-' * 20) + ' Day %d ' + ('-' * 20), day + 1)
        # Main event queue, holds events of different types.
        events = EventQueue()
        # Bar
        bar = Bar(num_seats=opts.num_bar_seats)
        # Various queues
        seating_queue   = deque()
        incoming_orders = deque()
        outgoing_orders = deque()
        # Stats collection
        stats.append({
            'arrivals' : 0,
            'drinks_served' : 0,
            'server_idle_time' : defaultdict(int),
            'bartender_idle_time' : defaultdict(int),
            'seating_wait_time' : util.Averager(),
            'drink_wait_time' : util.Averager(),
        })

        # Add an event signaling the end of happy hour
        events.push(HappyHourEnd(time=constants.HAPPY_HOUR_END))

        # Reset numberings
        person.Customer.reset_numbers()
        person.Bartender.reset_numbers()
        person.Server.reset_numbers()

        # Generate customer arrival events
        for arrival in generate_arrivals(opts.arrival_time):
            events.push(arrival)
            stats[day]['arrivals'] += 1
        LOGGER.info('Generated %d arrivals', stats[day]['arrivals'])

        # Set up initial server and bartender idle events
        for _ in range(0, opts.num_servers):
            events.push(
                ServerIdle(
                    time=constants.HAPPY_HOUR_START,
                    server=person.Server()
                )
            )
        for _ in range(0, opts.num_bartenders):
            events.push(
                BartenderIdle(
                    time=constants.HAPPY_HOUR_START,
                    bartender=person.Bartender()
                )
            )

        while events:
            event = events.pop()
            yield event.to_dict()

            if isinstance(event, HappyHourEnd):
                LOGGER.info(event)
                # Can collect stats, clean up, etc. here
                break
            elif isinstance(event, Arrival):
                LOGGER.info(event)
                seating_queue.appendleft(event.get_person())
            elif isinstance(event, ServerIdle):
                # If both queues are empty, wait around for a bit
                if (
                    (not seating_queue or bar.available_seats() <= 0)
                    and not outgoing_orders
                ):
                    LOGGER.debug(
                        '%s has nothing to do at %s',
                        event.get_server(),
                        sec_to_tod(event.get_time())
                    )
                    events.push(
                        ServerIdle(
                            time=event.get_time() + opts.server_wwi,
                            server=event.get_server()
                        )
                    )
                    stats[day]['server_idle_time'][
                        event.get_server().get_number()
                    ] += opts.server_wwi
                    continue

                # Take a customer from the seating queue and seat him at the
                # bar.
                if (
                    bar.available_seats() > 0
                    and handle_seating_queue(
                        len(seating_queue),
                        len(outgoing_orders)
                    )
                ):
                    time        = event.get_time()
                    server      = event.get_server()
                    time_offset = person.Server.get_seating_time(opts.seating_time)
                    customer    = seating_queue.pop()
                    assert customer.drinks_wanted() >= 1, \
                        "New arrival doesn't want any drinks"
                    # Seat is taken at the start of the seating process to
                    # prevent it from being preempted.
                    bar.seat_customer(customer)
                    LOGGER.debug('Bar: %s', bar)
                    # Server becomes idle after seating the customer.
                    events.push(ServerIdle(time=time + time_offset, server=server))
                    events.push(
                        CustomerSeated(
                            time=time + time_offset,
                            customer=customer,
                            server=server
                        )
                    )
                    # Clean namespace
                    del time, server, time_offset, customer
                # If not handling the seating queue, handle the outgoing drink
                # queue.
                else:
                    LOGGER.info(
                        '%s is serving drinks at %s',
                        event.get_server(),
                        sec_to_tod(event.get_time())
                    )
                    assert outgoing_orders, 'No outgoing orders!'
                    # Server takes the order from the outgoing queue...
                    order = outgoing_orders.pop()
                    delivery_time = numpy.random.normal(
                        loc=opts.delivery_time,
                        scale=opts.delivery_time_stddev
                    )
                    # ... and delivers it to the customer
                    events.push(
                        DeliverDrink(
                            time=event.get_time() + delivery_time,
                            customer=order.customer
                        )
                    )
                    # Track average wait time for a drink
                    stats[day]['drink_wait_time'].add(
                        # Time for a drink to be served = time of
                        # DrinkDelivered event minus the time the order was
                        # placed.
                        event.get_time() + delivery_time - order.time_placed
                    )
                    events.push(
                        ServerIdle(
                            time=event.get_time() + delivery_time,
                            server=event.get_server()
                        )
                    )
                    del order

            elif isinstance(event, CustomerSeated):
                LOGGER.info(event)
                stats[day]['seating_wait_time'].add(
                    event.get_time() - event.get_customer().get_arrival_time()
                )
                # Customer orders a drink after being seated.
                events.push(
                    OrderDrink(
                        time=event.get_time(),
                        customer=event.get_customer(),
                    )
                )

            elif isinstance(event, OrderDrink):
                LOGGER.info(event)
                incoming_orders.appendleft(
                    drinks.Order(
                        customer=event.get_customer(),
                        time_placed=event.get_time()
                    )
                )

            elif isinstance(event, BartenderIdle):
                # Wait around for a while if there are no incoming orders.
                if not incoming_orders:
                    events.push(
                        BartenderIdle(
                            time=event.get_time() + opts.bartender_wwi,
                            bartender=event.get_bartender()
                        )
                    )
                    stats[day]['bartender_idle_time'][
                        event.get_bartender().get_number()
                    ] += opts.bartender_wwi
                    continue
                # Otherwise take an order and prepare it.
                order = incoming_orders.pop()
                assert isinstance(order.customer, person.Customer)
                LOGGER.info(
                    '%s is preparing a drink for %s at %s',
                    event.get_bartender(),
                    order.customer,
                    sec_to_tod(event.get_time())
                )
                prep_time = drinks.Drink.prep_time()
                events.push(
                    PreppedDrink(
                        time=event.get_time() + prep_time,
                        order=order
                    )
                )
                events.push(
                    BartenderIdle(
                        time=event.get_time() + prep_time,
                        bartender=event.get_bartender()
                    )
                )
                del order

            elif isinstance(event, PreppedDrink):
                LOGGER.info(event)
                outgoing_orders.appendleft(event.get_order())

            elif isinstance(event, DeliverDrink):
                customer = event.get_customer()
                customer.drink() # Decrement drinks wanted
                stats[day]['drinks_served'] += 1
                drink_time = numpy.random.exponential(opts.drink_time)
                LOGGER.info(
                    '%s served drink at %s',
                    customer,
                    sec_to_tod(event.get_time())
                )
                if customer.drinks_wanted() > 0:
                    events.push(
                        OrderDrink(
                            time=event.get_time() + drink_time,
                            customer=customer,
                        )
                    )
                else:
                    # Customer leaves after drinking last drink
                    events.push(
                        Departure(
                            time=event.get_time() + drink_time,
                            customer=customer
                        )
                    )

                del customer, drink_time

            elif isinstance(event, Departure):
                LOGGER.info(event)
                LOGGER.debug('Bar: %s', bar)
                bar.remove_customer(event.get_customer())

            else:
                raise RuntimeError('Unhandled event: ' + str(event))
        # End of event loop

    LOGGER.info(
        'Simulation complete (%f seconds)',
        time_mod.time() - start_time
    )

    for day in range(0, opts.days):
        for (key, item) in stats[day].items():
            if isinstance(stats[day][key], util.Averager):
                stats[day][key] = {
                    'mean' : item.get_mean(),
                    'stddev' : item.get_stddev(),
                    'n' : item.get_n()
                }
    print(json.dumps(stats, indent=2))
# End of run_sim()

def handle_seating_queue(waiting_customers, outgoing_orders):
    """Choose whether to handle the seating queue or the outgoing order queue.

    If there are X customers waiting for seating and Y outgoing orders, the
    probability of the server choosing to seat a customer is X / (X + Y). This
    has some nice properties, namely that the limit as X goes to infinity is
    1, the limit as Y goes to infinity is 0, and when either goes to 0 the
    probability of choosing the opposite approaches 1.

    Arguments:

    - waiting_customers: The number of customers waiting to be seated (i.e. the
      length of the seating queue).
    - outgoing_orders: The number of orders ready to be delivered (i.e. the
      length of the outgoing order queue).
    """
    return rand() < waiting_customers / (waiting_customers + outgoing_orders)

def generate_arrivals(mean_time):
    """Generate customer arrivals according to an exponential distribution.

    Note that the mean parameter is the multiplicative inverse of the rate
    parameter.
    """
    time = 0
    while True:
        arrival_time = numpy.random.exponential(scale=mean_time)
        time += arrival_time
        time_of_day = time + constants.HAPPY_HOUR_START
        if time_of_day < constants.HAPPY_HOUR_END:
            yield Arrival(
                time=time_of_day,
                customer=person.Customer(arrival_time=time_of_day)
            )
        else:
            break
# End of generate_arrivals()

if __name__ == '__main__':
    main()


# 카운팅 대상 단어
words = [
  # java
  'java',
  '자바',
  'spring',
  '스프링',
  # python
  'python',
  '파이썬',
  '파이선',
  'flask',
  '플라스크',
  'django',
  '장고',
  # js
  'js',
  '자바스크립트',
  'node',
  '노드',
  'typescript',
  'ts',
  '타입스크립트',
  # php
  'php',
  '피에이치피',
  'laravel',
  '라라벨',
  'codeIgniter',
  '코드이그나이터',
  # aws
  'aws',
  '아마존',
  # docker
  'docker',
  '독커',
  '도커',
  # git
  'git',
  '깃'
]


import ir.node
from backend.runtime.nodegenerator.nodegenerator import NodeGenerator
from ...common import data_type_to_proto
from ...proto.operations import nn_pb2

class Conv(NodeGenerator):
    @classmethod
    def accept(cls, node: ir.node.Node):
        return isinstance(node, ir.node.nn.Conv)

    @property
    def operation(self):
        if len(self.inputs[0].shape) == 4:
            operation = nn_pb2.Conv2D()
            operation.padding_height = self.node.padding_height
            operation.padding_width = self.node.padding_width
            operation.stride_height = self.node.stride_height
            operation.stride_width = self.node.stride_width
            operation.dilate_height = self.node.dilate_height
            operation.dilate_width = self.node.dilate_width
            operation.group = self.node.group
            operation.nchw = self.node.nchw
        else:
            raise RuntimeError("Unsupport conv type")

        return operation


#Importando as classes e funções necessárias do Flask.
from flask import Flask, render_template, request, redirect, url_for

#Criando uma instância do objeto Flask para a aplicação web.
app = Flask(__name__)

# Dicionário que armazenará os produtos e seus preços
produtos = {
    100: {'descricao': 'Cachorro-Quente', 'valor': 9.00},
    101: {'descricao': 'Cachorro-Quente Duplo', 'valor': 11.00},
    102: {'descricao': 'X-Egg', 'valor': 12.00},
    103: {'descricao': 'X-Salada', 'valor': 13.00},
    104: {'descricao': 'X-Bacon', 'valor': 14.00},
    105: {'descricao': 'X-Tudo', 'valor': 17.00},
    200: {'descricao': 'Refrigerante Lata', 'valor': 5.00},
    201: {'descricao': 'Chá Gelado', 'valor': 4.00}
}

# Variável criada para armazenar o valor total da compra
valor_total = 0
#Lista que armazena os produtos do pedido atual.
pedido = []

@app.route('/', methods=['GET', 'POST'])
def index():
    global valor_total
    global pedido

    if request.method == 'POST':
        # Obter o código do produto a partir do formulário
        codigo = int(request.form['codigo'])

        if codigo in produtos:
            # Adicionar o valor do produto ao valor total da compra
            valor_total += produtos[codigo]['valor']
            # Adicionar a descrição do produto ao pedido
            pedido.append(produtos[codigo]['descricao'])
            mensagem = f'{produtos[codigo]["descricao"]} adicionado ao pedido.'
        else:
            mensagem = 'Opção inválida.'

        return render_template('index.html', produtos=produtos, mensagem=mensagem, pedido=pedido)

    return render_template('index.html', produtos=produtos, pedido=pedido)

@app.route('/checkout', methods=['GET', 'POST'])
def checkout():
    global valor_total
    global pedido

    if request.method == 'POST':
        if 'submit_button' in request.form:
            if request.form['submit_button'] == 'Voltar':
                # Redirecionar para a página de checkout
                return redirect(url_for('index'))
            elif request.form['submit_button'] == 'Encerrar':
                # Finalizar o pedido, reiniciando as variáveis
                valor_final = valor_total
                valor_total = 0
                pedido = []
                return render_template('encerramento.html', valor_final=valor_final)

    return render_template('checkout.html', valor_total=valor_total, pedido=pedido)

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


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

from django import template
from django_auxilium.utils.html import simple_minify
from django.conf import settings
from django.template import engines
from django.utils.safestring import mark_safe

register = template.Library()
django_engine = engines['django']

ANGULAR_TEMPLATE = django_engine.from_string(
    '{% include angular_template_name %}'
)
ANGULAR_SCRIPT_TEMPLATE = django_engine.from_string(
    '<script type="text/ng-template" id="{{ angular_name }}">{{ template }}</script>'
)

@register.simple_tag(takes_context=True)
def angular_template(context, template_name, angular_name):
    context.update({
        'angular_template_name': template_name,
    })
    content = ANGULAR_TEMPLATE.render(context)
    if not settings.DEBUG:
        content = mark_safe(simple_minify(content))
    context = template.Context({
        'template': content,
        'angular_name': angular_name,
    })
    return ANGULAR_SCRIPT_TEMPLATE.render(context)


from urllib import request,parse
from urllib.error import URLError
from http import cookiejar
filename='cookie.txt'
header={
    'user-agent':"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36"
}
url="https://www.baidu.com/"
requ=request.Request(url,headers=header)
#cookie = cookiejar.CookieJar()
cookie=cookiejar.LWPCookieJar(filename)
#cookie=cookiejar.MozillaCookieJar(filename)
print(cookie,type(cookie))
handler = request.HTTPCookieProcessor(cookie)
opener=request.build_opener(handler)
response = opener.open(requ,timeout=1)
cookie.save(ignore_discard=True,ignore_expires=True)#
for item in cookie:
    print(item,type(item))
    print(item.name+'='+item.value)
# 下载cookie
# 使用cookie
'''
cookie.load('cookie.txt',ignore_expires=True,ignore_discard=True)
handler=request.HTTPCookieProcessor(cookie)
opener=request.build_opener(handler)
response=opener.open(url)
print(response.read().decode('utf8'))
'''


import requests
from bs4 import BeautifulSoup

def scrape():
  result = requests.get("https://www.campussafety.utoronto.ca/news/categories/community-safety-alerts")
  doc = BeautifulSoup(result.text, "html.parser")

  event = str(doc.find(class_ = "bD0vt9 KNiaIk").string)
  text = str(doc.find(class_ = "BOlnTh").string)

  time_text_start = text.find("Broadcast Time") + len("Broadcast Time: ")
  date_text_start = text.find("Date") + len("Date: ")

  time = text[time_text_start:text.find("Date")]
  date = text[date_text_start:text.find("Type")]

  hyphen = event.find("-", event.find("-")+1)
  event_text = event[:hyphen] + event[hyphen + 1:]
  event_text = event_text.lower().split()
  subject = "-".join(event_text)

  link = "https://www.campussafety.utoronto.ca/post/" + subject

  return """
Latest News
Date: %s
Time: %s
Event: %s
link: %s
""" % (date, time, event, link)


from typing import Optional

from PySide6 import QtCore
from PySide6.QtCore import QThread, Signal, Slot
from PySide6.QtGui import QImage

from social_distance.core.camera import Camera
from social_distance.core.detector import OpenCVPersonDetector
from social_distance.thread.detector_thread import DetectorThread
from social_distance.util import cv_to_qimage, get_path
from social_distance.core.frame_provider import FrameProvider
from social_distance.core.processing import *

import cv2 as cv

class CameraThread(QThread):
    pixmap_changed = Signal(QImage)
    data_changed = Signal(Stats)
    m = QtCore.QMutex()

    def __init__(self, parent: Optional[QtCore.QObject] = None):
        super(CameraThread, self).__init__(parent)
        self.keep_running = False
        self.url = None
        self.fp = FrameProvider()

        self.detector_thread = DetectorThread(self)
        self.detector_thread.done.connect(self.update_current_bb)
        self.detector_thread.start()

        self.current_bb = []
        self.distance_matrix = np.ones((3, 3), dtype=np.float32)
        self.preview_matrix = np.ones((3, 3), dtype=np.float32)
        self.preview_matrix_inv = np.ones((3, 3), dtype=np.float32)
        self.roi = None
        self.safe_distance = 2
        self.pixel_per_meter = 1
        self.view_mode = 0

        self.data = []
        self.points = []
        self.ground_points = []
        self.is_safe = []

        self.background_subtractor = cv.createBackgroundSubtractorKNN(detectShadows=True)

    def run(self):
        self.keep_running = True
        while self.keep_running:
            self.process_tick()

    def process_tick(self) -> None:
        self.m.lock()
        frame = self.fp.get_frame()
        self.m.unlock()
        if frame is None:
            return

        self.detector_thread.pass_image(frame)
        fgmask = self.background_subtractor.apply(frame)
        fgmask = cv.GaussianBlur(fgmask, (15, 15), 0)
        fgmask = cv.threshold(fgmask, 175, 255, cv.THRESH_BINARY)[1]
        frame = draw_polygon(frame, self.roi)
        preview_points = project_points(self.points, self.preview_matrix)
        if self.view_mode == 0:
            draw_bb(frame, self.is_safe, self.current_bb)
        elif self.view_mode == 1:
            frame = cv.warpPerspective(frame, self.preview_matrix, (1000, 1000))
            draw_circles(frame, preview_points, self.is_safe, self.pixel_per_meter * self.safe_distance / 2)
        else:
            warped = np.zeros((1000, 1000, 3), np.uint8)
            draw_circles(warped, preview_points, self.is_safe, self.pixel_per_meter * self.safe_distance / 2, with_points=False)
            unwarped = cv.warpPerspective(warped, self.preview_matrix_inv, (frame.shape[1], frame.shape[0]))
            cv.bitwise_not(fgmask, fgmask)
            cv.add(frame, unwarped, frame, fgmask)

        qimage = cv_to_qimage(frame)
        self.pixmap_changed.emit(qimage)

    @Slot(Camera)
    def set_camera(self, cam: Camera) -> None:
        self.m.lock()
        self.fp.set_source(cam.address)
        self.distance_matrix = getPerspectiveTransform(cam.square, distance_square(cam.side_length))
        self.preview_matrix = getPerspectiveTransform(cam.square, cam.preview_square)
        self.preview_matrix_inv = np.linalg.inv(self.preview_matrix)
        self.roi = np.asarray(cam.roi, np.int32)
        self.pixel_per_meter = cam.preview_side_length / cam.side_length
        self.m.unlock()
        self.data = []

    @Slot(list)
    def update_current_bb(self, bb: list):
        bb = filter_except_in_polygon(bb, self.roi)
        self.current_bb = bb
        self.points = bb_points(bb)
        self.ground_points = project_points(self.points, self.distance_matrix)
        self.is_safe = classify_safe_unsafe(self.ground_points, self.safe_distance)

        stats = calc_statistics(self.ground_points, self.safe_distance, self.is_safe)
        self.data.append(stats)
        self.data_changed.emit(stats)

    @Slot(float)
    def set_safe_distance(self, distance: float) -> None:
        self.safe_distance = distance

    @Slot(int)
    def set_model(self, index) -> None:
        network = NETWORK_FILENAMES[index]
        detector = OpenCVPersonDetector(get_path('models', f'{network}.cfg'),
                                        get_path('models', f'{network}.weights'),
                                        conf_threshold=0.1, nms_threshold=0.1)
        self.detector_thread.set_detector(detector)

    @Slot(int)
    def set_view_mode(self, index) -> None:
        self.view_mode = index

    def quit(self) -> None:
        self.keep_running = False
        self.fp.close()
        self.detector_thread.quit()
        self.detector_thread.wait()
        super(CameraThread, self).quit()


from syned.storage_ring.light_source import LightSource
from syned.storage_ring.electron_beam import ElectronBeam
from syned.storage_ring.magnetic_structures.undulator import Undulator
from syned.util.json_tools import load_from_json_file
import numpy
import scipy.constants as codata

def sigma_mu_vartanyants(sigma, sigmaprime, wavelength):
    epsilon = sigmaprime * sigma
    kwave = 2 * numpy.pi / wavelength
    tmp = 4 * kwave**2 * epsilon**2 - 1
    return 2 * sigma / numpy.sqrt(tmp)

def gsm_coherent_fraction_exact(beta):
    q = 1 + 0.5 * beta**2 + beta * numpy.sqrt( (beta/2)**2 + 1 )
    q = 1.0 / q
    CF = 1 - q
    return CF

def beta_srio(cf):
    # https://www.wolframalpha.com/input/?i=Solve%5B+%281-%281%2F+%281+%2B+beta**2+%2F+2%2B+beta+*+Sqrt%281%2B+%28beta%2F2%29**2%29%29++%29%29+%3Dc%2C+beta%5D
    return cf / numpy.sqrt(1-cf)

def get_sigmas_radiation(photon_energy,period_length=0.020, number_of_periods=100):
    # calculate sizes of the photon undulator beam
    # see formulas 25 & 30 in Elleaume (Onuki & Elleaume)
    lambdan = 1e-10 * codata.h * codata.c / codata.e * 1e10 / photon_energy  # in m
    sigma_r = 2.740 / 4 / numpy.pi * numpy.sqrt(lambdan * number_of_periods * period_length)
    sigma_r_prime =  0.69 * numpy.sqrt(lambdan / ( period_length * number_of_periods))
    return sigma_r, sigma_r_prime

def do_calculation(photon_energy=10000.0):

    a = load_from_json_file("tmp_id18_u20.json")

    ebeam = a.get_electron_beam()

    mstruct = a.get_magnetic_structure()

    gamma = ebeam.gamma()
    print("gamma: ", gamma)

    method = 1 # 0=using K, 1=noy using K (default)
    if method == 0:
        K = mstruct.get_K_from_photon_energy(photon_energy, gamma,harmonic=1)
        print(">>>>>>>>>>>K: ", K)
        mstruct._K_vertical = K

        Sx, Sz, Sxp, Szp = mstruct.get_photon_sizes_and_divergences(ebeam)

        cf_h = mstruct.approximated_coherent_fraction_horizontal(ebeam,harmonic=1)
        cf_v = mstruct.approximated_coherent_fraction_vertical(ebeam,harmonic=1)

    else:
        sx, sxp, sz, szp = ebeam.get_sigmas_all()
        su, sup = get_sigmas_radiation(photon_energy,
                                       period_length=mstruct.period_length(),
                                       number_of_periods=mstruct.number_of_periods())
        Sx = numpy.sqrt( sx**2 + su**2)
        Sxp = numpy.sqrt(sxp ** 2 + sup ** 2)
        Sz = numpy.sqrt(sz ** 2 + su ** 2)
        Szp = numpy.sqrt(szp ** 2 + sup ** 2)

        cf_h = su * sup / (Sx * Sxp)
        cf_v = su * sup / (Sz * Szp)

    wavelength = 1e-10 * codata.h * codata.c / codata.e * 1e10 / photon_energy # mstruct.resonance_wavelength(gamma)
    print("wavelength %f A" % (1e10 * wavelength))
    print("Sx,Sz,Sxp,Szp: ", Sx,Sz,Sxp,Szp )
    print("CF h,v: ", cf_h, cf_v )

    #
    # Vartanyants mu
    #
    mu_h_vartanyants = sigma_mu_vartanyants(Sx, Sxp, wavelength)
    mu_v_vartanyants = sigma_mu_vartanyants(Sz, Szp, wavelength)

    beta_h = mu_h_vartanyants / Sx
    beta_v = mu_v_vartanyants / Sz
    print("---- Vartanyants, photon energy=%f eV" %photon_energy)
    print("H sigmaI=%6.2f, sigmaMu=%6.2f, beta=%6.2f, CF_ratio=%6.2f, CF_GSM=%6.2f: " % (1e6 * Sx, 1e6 * mu_h_vartanyants, beta_h, cf_h, gsm_coherent_fraction_exact(beta_h)))
    print("V sigmaI=%6.2f, sigmaMu=%6.2f, beta=%6.2f, CF_ratio=%6.2f, CF_GSM=%6.2f: " % (1e6 * Sz, 1e6 * mu_v_vartanyants, beta_v, cf_v, gsm_coherent_fraction_exact(beta_v)))

    #
    # srio mu
    #
    beta_h_srio = beta_srio(cf_h)
    beta_v_srio = beta_srio(cf_v)

    mu_h_srio = beta_h_srio * Sx
    mu_v_srio = beta_v_srio * Sz

    print("---- srio, photon energy=%f eV" %photon_energy)
    print("H sigmaI=%6.2f, sigmaMu=%6.2f, beta=%6.2f, CF_ratio=%6.2f, CF_GSM=%6.2f: " % (1e6 * Sx, 1e6 * mu_h_srio, beta_h_srio, cf_h, gsm_coherent_fraction_exact(beta_h_srio)))
    print("V sigmaI=%6.2f, sigmaMu=%6.2f, beta=%6.2f, CF_ratio=%6.2f, CF_GSM=%6.2f: " % (1e6 * Sz, 1e6 * mu_v_srio, beta_v_srio, cf_v, gsm_coherent_fraction_exact(beta_v_srio)))

    return mu_h_srio, mu_v_srio, mu_h_vartanyants, mu_v_vartanyants

if __name__ == "__main__":
    from srxraylib.plot.gol import plot
    photon_energies = numpy.linspace(5000.0, 150000.0, 100)
    MU_H_SRIO = numpy.zeros_like(photon_energies)
    MU_V_SRIO = numpy.zeros_like(photon_energies)
    MU_H_VARTANYANTS = numpy.zeros_like(photon_energies)
    MU_V_VARTANYANTS = numpy.zeros_like(photon_energies)

    for i, photon_energy in enumerate(photon_energies):
        mu_h_srio, mu_v_srio, mu_h_vartanyants, mu_v_vartanyants = do_calculation(photon_energy=photon_energy)
        MU_H_SRIO[i] = mu_h_srio
        MU_V_SRIO[i] = mu_v_srio
        MU_H_VARTANYANTS[i] = mu_h_vartanyants
        MU_V_VARTANYANTS[i] = mu_v_vartanyants

    plot(photon_energies, 1e6*MU_H_SRIO, photon_energies, 1e6*MU_H_VARTANYANTS, xtitle="Photon energy [eV]", ytitle="H SigmaMu",
         title="Horizontal", legend=["SRio","Vartanyants"])
    plot(photon_energies, 1e6*MU_V_SRIO, photon_energies, 1e6*MU_V_VARTANYANTS, xtitle="Photon energy [eV]", ytitle="V SigmaMu",
         title="Vertical", legend=["SRio", "Vartanyants"])

    do_calculation(photon_energy=10000.0)


import os

blank = {'my_project': ['settings','mainapp', 'adminapp', 'authapp']}

for key, value in blank.items():
    if not os.path.isdir(key):
        os.mkdir(key)
    for folder_name in value:
        dir_path = os.path.join(key, folder_name)
        if not os.path.isdir(dir_path):
            os.mkdir(dir_path)


#!/usr/bin/env python
from __future__ import print_function

import sys
import pdbparse
from optparse import OptionParser

from pdbparse.pe import Sections
from pdbparse.omap import Omap

from pprint import pprint

class DummyOmap(object):

    def remap(self, addr):
        return addr

def cstring(str):
    return str.split('\0')[0]

def main(filename, base_address):
    pdb = pdbparse.parse(filename)
    imgbase = int(base_address, 0)
    try:
        sects = pdb.STREAM_SECT_HDR_ORIG.sections
        omap = pdb.STREAM_OMAP_FROM_SRC
    except AttributeError as e:
        sects = pdb.STREAM_SECT_HDR.sections
        omap = DummyOmap()

    gsyms = pdb.STREAM_GSYM

    for sym in gsyms.globals:
        try:
            off = sym.offset
            virt_base = sects[sym.segment - 1].VirtualAddress
            nm = cstring(sects[sym.segment - 1].Name)
            print("%s,%#x,%d" % (sym.name, imgbase + omap.remap(off + virt_base), sym.symtype))
        except:
            pass

if __name__ == '__main__':

    parser = OptionParser()
    (opts, args) = parser.parse_args()

    #filename and address
    main(args[0], args[1])


numb= int(input("Enter a number: "))
#cần 1 biến để lưu tổng qua từng vòng lặp

# trước hết cần tạo ra một dãy số bằng hàm range , sau đó tính tổng dãy đó
total = sum(range(numb+1))
print(total)

# total = 0

# for i in range (numb+1):
#     total += i

# print(total)


import sqlite3

from .User import User
from .Owner import Owner
from .Manager import Manager
from .Karyawan import Karyawan
from .store import Toko as toko

databaseName='databaseBranch.it.db'
conn = sqlite3.connect(databaseName)

class Order:
    __jumlahOrder=0
    def __init__(self,username,cabang,totalBelanja):
        #usernameObjek=eval(username)
        Order.__jumlahOrder+=1
        self.id =str(Order.__jumlahOrder).zfill(4)
        self.__idOrder=str(username.idCabang)+"-"+str(username.id)+"-"+self.id
        self.totalBelanja=totalBelanja
        totalFee=0.15*totalBelanja
        username.setTotalFee(totalFee)
        self.idUserOrder=username.idUser
        conn.execute("insert or ignore into orderTabel values (?,?,?)" , (self.__idOrder,self.idUserOrder,self.totalBelanja)) #masukkan ke database
        conn.commit()

    def getIdOrder(self):
        return self.__idOrder


from ast import Or
from email import header
from urllib import response
from flask import session
import requests

from . import ORDER_API_URL

class OrderClient:
    @staticmethod
    def get_orders():
        header = {'Authorization':session['user_api_key']}
        response = requests.get(ORDER_API_URL + '/api/order',headers=header)
        return response.json()

    @staticmethod
    def add_to_cart(book_id,quantity=1):
        payload = {
            'book_id' : book_id,
            'quantity' : quantity
        }
        header = {'Authorization': session['user_api_key']}
        response = requests.post(ORDER_API_URL+'/api/order/add-item',data=payload,headers=header)
        return response.json()

    @staticmethod
    def checkout():
        header = {'Authorization':session['user_api_key']}
        response = requests.post(ORDER_API_URL+'/api/order/checkout',headers=header)
        return response.json()

    @staticmethod
    def get_order_from_session():
        default_order = {
            'items':{}
        }
        return session.get('order',default_order)


#!/usr/bin/python3
"""
This module contains a definition of a class Student
that has an init method and a to_json method
"""

class Student:
    """
    Defines a student.

    Public instance attributes:
        first_name (str): The student's first name.
        last_name (str): The student's last name.
        age (int): The student's age.
    """
    def __init__(self, first_name, last_name, age):
        """
        Initializes a Student object.

        Args:
            first_name (str): The student's first name.
            last_name (str): The student's last name.
            age (int): The student's age.
        """
        self.first_name = first_name
        self.last_name = last_name
        self.age = age

    def to_json(self, attrs=None):
        """
        Retrieves a dictionary representation of a Student instance.

        Args:
            attrs (list): A list of attribute names to retrieve.

        Returns:
            dict: A dictionary representation of the Student instance.
        """
        if attrs:
            result = {}
            for attr in attrs:
                if hasattr(self, attr):
                    result[attr] = getattr(self, attr)
            return result
        else:
            return self.__dict__

    def reload_from_json(self, json):
        """
        Replaces all attributes of the Student instance
        with the values from a dictionary.

    Args:
        json (dict): A dictionary where keys are
        attribute names and values are attribute values.
        """
        for key, val in json.items():
            setattr(self, key, val)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/7/10 23:00
# @Author  : leo cheng
# @Email   : chengyoufu@163.com
# @File    : link_list_demo.py
# @Software: PyCharm
from copy import deepcopy

from common.func_utils import type_check_deco

class Node(object):

    def __init__(self, item_value, next_node=None):
        self.__item_value = item_value
        self.__next_node = next_node

    @property
    def item_value(self):
        return self.__item_value

    @property
    def next_node(self):
        return self.__next_node

    @next_node.setter
    def next_node(self, next_node):
        if next_node is not None and not isinstance(next_node, Node):
            raise TypeError
        self.__next_node = next_node

class LinkList(object):
    def __init__(self):
        self.__head = None
        self.__tail = None
        self.__length = 0
        self.__iter_node = self.__head
        self.__iter_modify_flag = False

    @property
    def head(self):
        return self.__head

    @property
    def tail(self):
        return self.__tail

    def is_empty(self):
        return self.__head is None

    @type_check_deco(object, Node)
    def append(self, new_node):
        """
        尾部追加
        :param new_node:
        :return:
        """
        if self.__head is None:
            self.__head = new_node
            self.__tail = new_node
        else:
            self.__tail.next_node = new_node
            self.__tail = new_node
        self.__iter_modify_flag = True
        self.__length += 1

    @type_check_deco(object, Node)
    def push(self, new_node):
        """
        头部追加
        :param new_node:
        :return:
        """
        new_node.next_node = self.__head
        self.__head = new_node
        if new_node.next_node is None:
            self.__tail = new_node
        self.__iter_modify_flag = True
        self.__length += 1

    def pop(self):
        """
        弹出头部
        :return:
        """
        if self.__head is not None:
            temp = self.__head
            self.__head = self.__head.next_node
            temp.next_node = None
            self.__length -= 1
            if self.__head is None:
                self.__tail = None
            self.__iter_modify_flag = True
            return temp
        else:
            raise EOFError

    @type_check_deco(object, int, Node)
    def insert(self, item_index, new_node):
        if item_index == self.__length - 1:
            self.append(new_node)
        elif item_index == 0:
            self.push(new_node)
        else:
            temp_node = self.__getitem__(item_index)
            temp_node.next_node, new_node.next_node = new_node, temp_node.next_node.next_node
            self.__length += 1
            self.__iter_modify_flag = True

    @type_check_deco(object, int)
    def remove(self, item_index):
        if item_index == 0:
            self.pop()
        else:
            temp_node = self.__getitem__(item_index - 1)
            if temp_node.next_node.next_node is None:
                temp_node.next_node = None
                self.__tail = temp_node
            else:
                remove_node = temp_node.next_node
                temp_node.next_node = temp_node.next_node.next_node
                remove_node.next_node = None

            self.__length -= 1
            self.__iter_modify_flag = True

    def remove_after(self, item_index): # add exercise 1.3.24
        node = self.__getitem__(item_index)
        node.next_node = None
        self.__tail = node
        self.__length = item_index + 1
        self.__iter_modify_flag = True

    def extend(self, other_link_list):  # exercise 1.3.47
        if not isinstance(other_link_list, LinkList):
            raise TypeError
        self.__tail.next_node = other_link_list.__head
        self.__tail = other_link_list.__tail
        self.__iter_modify_flag = True
        self.__length = self.__length+ len(other_link_list)

    def __iter__(self):
        self.__iter_node = self.__head
        self.__iter_modify_flag = False
        return self

    def reset_iter(self):
        self.__iter_node = self.__head
        self.__iter_modify_flag = False

    def __next__(self):
        if self.__iter_modify_flag:  # exercise 1.3.50
            raise Exception('List is modified in iterator')
        if self.__iter_node:
            temp_node = self.__iter_node
            self.__iter_node = self.__iter_node.next_node
            return temp_node
        else:
            raise StopIteration

    def __str__(self):
        return "Link list {1}".format(self.__doc__)

    def __add__(self, other):
        if not isinstance(other, self.__class__):
            raise TypeError("other must be Node LinkList")
        result_list = deepcopy(self)
        result_list.extend(other)
        return result_list

    def __deepcopy__(self, memodict={}):
        new_link_list = self.__class__()
        for temp_node in self:
            new_link_list.append(deepcopy(temp_node, memodict))
        return new_link_list

    @type_check_deco(object, int)
    def __delitem__(self, item_index):  # exercise 1.3.20
        if item_index >= self.__length:
            raise IndexError("index {0} is out of range:[0:{1}]".format(item_index, self.__length - 1))
        result_node = self.__head
        for i in range(self.__length):
            if i == item_index - 1:
                break
            result_node = result_node.next_node
        result_node.next_node = result_node.next_node.next_node
        self.__length -= 1

    @type_check_deco(object, int, Node)
    def __setitem__(self, item_index, new_node):
        if item_index >= self.__length:
            item_index = self.__length
        result_node = self.__head
        for i in range(self.__length):
            if i == item_index:
                break
            result_node = result_node.next_node
        result_node.next_node, new_node.next_node = new_node.next_node, result_node.next_node

    @type_check_deco(object, int)
    def __getitem__(self, item_index):
        if item_index >= self.__length:
            raise IndexError
        result_node = self.__head
        for i in range(self.__length):
            if i == item_index:
                break
            result_node = result_node.next_node
        return result_node

    def __len__(self):
        return self.__length

if __name__ == '__main__':
    node1 = Node(1)
    node2 = Node(2)
    node3 = Node(3)
    link_list = LinkList()
    link_list2 = LinkList()
    # link_list2.append(1)
    link_list.append(node1)
    link_list.append(node2)
    link_list.append(node3)
    link_list.remove(2)
    # list_temp = link_list+link_list2
    # for node in list_temp:
    #     print(node.item_value)
    # for node in link_list:
    #     link_list.pop()
    #     link_list.pop()
    #     link_list.pop()
    #     print(node.item_value)
    # link_list.reset_iter()
    # for node in link_list:
    #     print(node.item_value)


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if not head:
            return None
        prev = None
        while head:
            curr = head
            head = head.next
            curr.next = prev
            prev = curr
        return curr