import argparse
import os
import platform
import shutil
import time
from pathlib import Path

import cv2
import torch
import torch.backends.cudnn as cudnn
from numpy import random

from models.experimental import attempt_load
from utils.datasets import LoadStreams, LoadImages
from utils.general import (
    check_img_size, non_max_suppression, apply_classifier, scale_coords, xyxy2xywh, plot_one_box, strip_optimizer)
from utils.torch_utils import select_device, load_classifier, time_synchronized

coco_class_name = [
    'person', 'cellphone', 'identification', 'notebook', 'face', 'chest'
]

coco_chinese_name = {
    'person': '人',
    'cellphone': '手机',
    'identification': '证件',
    'notebook': '笔记本',
    'face': '脸',
    'chest': '胸'
}

colors = [(187, 127, 77), (212, 82, 94), (118, 194, 101), (59, 154, 176),
          (255, 215, 0), (255, 250, 250)]

class_colors = {}
for i in range(len(coco_class_name)):
    class_name = coco_class_name[i]
    color = colors[i]
    class_colors[class_name] = color

def a_in_b(a,b):
    #a:xywh b:xyxy
    if a[0]>b[0] and a[0]<b[2] and a[1]>b[1] and a[1]<b[3]:
        return True
    else:
        return False

def filter_items(det, names, gn, keep_height=0.3):
    people = {}
    i = 0
    face_list = []
    chest_list = []
    identification_list = []

    results = []

    if det is not None and len(det):
        for *xyxy, conf, cls in det:

            class_name = names[int(cls)]
            xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) /
                    gn).view(-1).tolist()  #xy center

            center = (xyxy2xywh(torch.tensor(xyxy).view(
                1, 4))).view(-1).tolist()[:2]  #xy center
            if xywh[1] > keep_height:  # y在keep_height 下面
                if class_name == 'person':
                    people[i] = {
                        'xyxy': torch.tensor(xyxy).tolist(),
                        'face': False,
                        'chest': False,
                        'identification': False
                    }
                    i += 1
                elif class_name == 'face':
                    face_list.append(center)
                elif class_name == 'chest':
                    chest_list.append(center)
                elif class_name == 'identification':
                    identification_list.append(center)

    for person_id, person in people.items():
        person_location = person['xyxy']
        #if identification is in person
        if len(identification_list):
            for identification in identification_list:
                if a_in_b(identification,person_location):
                    person['identification']=True
        # tell if this person has the front face
        if len(face_list):
            for face in face_list:
                if a_in_b(face, person_location):
                    person['face']=True
        #tell if one can see the chest
            if len(chest_list):
                for chest in chest_list:
                    if a_in_b(chest, person_location):
                        person['chest']=True

    people_not_wear_id=[]
    for person_id, person in people.items():
        if person['face'] and person['chest'] and not person['identification']:
            person['not_wear_identification']=True
            people_not_wear_id.append(person['xyxy'])

    if det is not None and len(det):
        for *xyxy, conf, cls in det:
            _ = torch.tensor(xyxy).tolist()
            class_name = names[int(cls)]
            if class_name == 'person' and _ in people_not_wear_id:
                CN_class_name = '未佩戴证件'
            else:
                CN_class_name = coco_chinese_name[class_name]
            color = class_colors[class_name]
            _.extend([CN_class_name, conf.item(), color])
            results.append(_)

    return results

def detect(save_img=False):
    out, source, weights, view_img, save_txt, imgsz = \
        opt.output, opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size
    webcam = source == '0' or source.startswith('rtsp') or source.startswith('http') or source.endswith('.txt')

    # Initialize
    device = select_device(opt.device)
    if os.path.exists(out):
        shutil.rmtree(out)  # delete output folder
    os.makedirs(out)  # make new output folder
    half = device.type != 'cpu'  # half precision only supported on CUDA

    x = torch.cuda.FloatTensor(256, 1024, 1000)
    del x

    # Load model
    model = attempt_load(weights, map_location=device)  # load FP32 model
    imgsz = check_img_size(imgsz, s=model.stride.max())  # check img_size
    if half:
        model.half()  # to FP16

    # Second-stage classifier
    classify = False
    if classify:
        modelc = load_classifier(name='resnet101', n=2)  # initialize
        modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model'])  # load weights
        modelc.to(device).eval()

    # Set Dataloader
    vid_path, vid_writer = None, None
    if webcam:
        view_img = True
        cudnn.benchmark = True  # set True to speed up constant image size inference
        dataset = LoadStreams(source, img_size=imgsz)
    else:
        save_img = False
        view_img = True
        dataset = LoadImages(source, img_size=imgsz)

    save_vid = True
    if save_vid:
        fourcc = 'MJPG'  # output video codec
        fps = 25
        w = int(1920)
        h = int(1080)
        vid_writer = cv2.VideoWriter('test.avi', cv2.VideoWriter_fourcc(*fourcc), fps, (w, h))

    # Get names and colors
    names = model.module.names if hasattr(model, 'module') else model.names
    colors = [[random.randint(0, 255) for _ in range(3)] for _ in range(len(names))]

    # Run inference
    t0 = time.time()
    img = torch.zeros((1, 3, imgsz, imgsz), device=device)  # init img
    _ = model(img.half() if half else img) if device.type != 'cpu' else None  # run once

    for path, img, im0s, vid_cap in dataset:

        # imgs, im0s_list = img_split(img, im0s)
        # img = imgs[2]
        # im0s = im0s_list[2]
        # for index_img in range(len(imgs)):
        #     img = imgs[index_img]
        #     im0s = im0s_list[index_img]

        img = torch.from_numpy(img).to(device)
        img = img.half() if half else img.float()  # uint8 to fp16/32
        img /= 255.0  # 0 - 255 to 0.0 - 1.0
        if img.ndimension() == 3:
            img = img.unsqueeze(0)

        # Inference
        t1 = time_synchronized()
        pred = model(img, augment=opt.augment)[0]

        # Apply NMS
        pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms)
        t2 = time_synchronized()

        # Apply Classifier
        if classify:
            pred = apply_classifier(pred, modelc, img, im0s)

        # Process detections
        for i, det in enumerate(pred):  # detections per image
            if webcam:  # batch_size >= 1
                p, s, im0 = path[i], '%g: ' % i, im0s[i].copy()
            else:
                p, s, im0 = path, '', im0s

            filter_img = im0.copy()

            save_path = str(Path(out) / Path(p).name)
            txt_path = str(Path(out) / Path(p).stem) + ('_%g' % dataset.frame if dataset.mode == 'video' else '')
            s += '%gx%g ' % img.shape[2:]  # print string
            gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwh
            if det is not None and len(det):
                # Rescale boxes from img_size to im0 size
                det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()

                # Print results
                for c in det[:, -1].unique():
                    n = (det[:, -1] == c).sum()  # detections per class
                    s += '%g %ss, ' % (n, names[int(c)])  # add to string

                # Write results
                for *xyxy, conf, cls in det:
                    if save_txt:  # Write to file
                        xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()  # normalized xywh
                        with open(txt_path + '.txt', 'a') as f:
                            f.write(('%g ' * 5 + '\n') % (cls, *xywh))  # label format

                    if save_img or view_img:  # Add bbox to image
                        label = '%s %.2f' % (names[int(cls)], conf)
                        plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)

            # Print time (inference + NMS)
            print('%sDone. (%.3fs)' % (s, t2 - t1))

            filtered_results = filter_items(det, names, gn)

            for i in filtered_results:
                if i[4] == '未佩戴证件':
                    label='no ID'
                else:
                    label=''
                plot_one_box(i[:4],
                             filter_img,
                             label=label,
                             color=i[-1],
                             line_thickness=3)

            # Stream results
            if view_img:
                cv2.imshow(p, im0)
                cv2.imshow('', filter_img)

            # Save results (image with detections)
            if save_vid:
                vid_writer.write(im0)

            if save_img:
                if dataset.mode == 'images':
                    cv2.imwrite(save_path, im0)

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

            if save_vid:
                vid_writer.release()
            cv2.destroyAllWindows()
            break

    if save_txt or save_img:
        print('Results saved to %s' % Path(out))
        if platform == 'darwin' and not opt.update:  # MacOS
            os.system('open ' + save_path)

    print('Done. (%.3fs)' % (time.time() - t0))

if __name__ == '__main__':

    ip = "172.23.0.37"
    video_path = 'rtsp://admin:123456789bit@' + ip + '/main/Channels/1'
    # video_path = '/media/yy/DATA/data/vid/monitor/monitor1.mp4'

    parser = argparse.ArgumentParser()
    parser.add_argument('--weights',
                        nargs='+',
                        type=str,
                        default='chest.pt',
                        help='model.pt path(s)')
    parser.add_argument('--source',
                        type=str,
                        default=video_path,
                        help='source')  # file/folder, 0 for webcam
    parser.add_argument('--output', type=str, default='inference/output', help='output folder')  # output folder
    parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
    parser.add_argument('--conf-thres', type=float, default=0.3, help='object confidence threshold')
    parser.add_argument('--iou-thres', type=float, default=0.5, help='IOU threshold for NMS')
    parser.add_argument('--device',
                        default='1',
                        help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
    parser.add_argument('--view-img', action='store_true', help='display results')
    parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
    parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
    parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
    parser.add_argument('--augment', action='store_true', help='augmented inference')
    parser.add_argument('--update', action='store_true', help='update all models')
    opt = parser.parse_args()
    print(opt)

    with torch.no_grad():
        if opt.update:  # update all models (to fix SourceChangeWarning)
            for opt.weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']:
                detect()
                strip_optimizer(opt.weights)
        else:
            detect()


from datetime import datetime
class Spy:
    def __init__(self,name,salutation,age,rating):

        self.name = salutation + " " + name
        self.age = age
        self.rating = rating
        self.is_online = True
        self.chats = []
        self.current_status = None

spy = Spy('Ayush','Mr.',20,3.0)
class chatmessage:
    def __init__(self,message,st):
     self.msg = chatmessage
     self.time = datetime.now()
     self.send_by_me = st


from __future__ import absolute_import
import re
from collections import namedtuple

from ..exceptions import LocationParseError
from ..packages import six, rfc3986
from ..packages.rfc3986.exceptions import RFC3986Exception, ValidationError
from ..packages.rfc3986.validators import Validator
from ..packages.rfc3986 import abnf_regexp, normalizers, compat, misc

url_attrs = ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment']

# We only want to normalize urls with an HTTP(S) scheme.
# urllib3 infers URLs without a scheme (None) to be http.
NORMALIZABLE_SCHEMES = ('http', 'https', None)

# Regex for detecting URLs with schemes. RFC 3986 Section 3.1
SCHEME_REGEX = re.compile(r"^(?:[a-zA-Z][a-zA-Z0-9+\-]*:|/)")

PATH_CHARS = abnf_regexp.UNRESERVED_CHARS_SET | abnf_regexp.SUB_DELIMITERS_SET | {':', '@', '/'}
QUERY_CHARS = FRAGMENT_CHARS = PATH_CHARS | {'?'}

class Url(namedtuple('Url', url_attrs)):
    """
    Data structure for representing an HTTP URL. Used as a return value for
    :func:`parse_url`. Both the scheme and host are normalized as they are
    both case-insensitive according to RFC 3986.
    """
    __slots__ = ()

    def __new__(cls, scheme=None, auth=None, host=None, port=None, path=None,
                query=None, fragment=None):
        if path and not path.startswith('/'):
            path = '/' + path
        if scheme is not None:
            scheme = scheme.lower()
        return super(Url, cls).__new__(cls, scheme, auth, host, port, path,
                                       query, fragment)

    @property
    def hostname(self):
        """For backwards-compatibility with urlparse. We're nice like that."""
        return self.host

    @property
    def request_uri(self):
        """Absolute path including the query string."""
        uri = self.path or '/'

        if self.query is not None:
            uri += '?' + self.query

        return uri

    @property
    def netloc(self):
        """Network location including host and port"""
        if self.port:
            return '%s:%d' % (self.host, self.port)
        return self.host

    @property
    def url(self):
        """
        Convert self into a url

        This function should more or less round-trip with :func:`.parse_url`. The
        returned url may not be exactly the same as the url inputted to
        :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls
        with a blank port will have : removed).

        Example: ::

            >>> U = parse_url('http://google.com/mail/')
            >>> U.url
            'http://google.com/mail/'
            >>> Url('http', 'username:password', 'host.com', 80,
            ... '/path', 'query', 'fragment').url
            'http://username:password@host.com:80/path?query#fragment'
        """
        scheme, auth, host, port, path, query, fragment = self
        url = u''

        # We use "is not None" we want things to happen with empty strings (or 0 port)
        if scheme is not None:
            url += scheme + u'://'
        if auth is not None:
            url += auth + u'@'
        if host is not None:
            url += host
        if port is not None:
            url += u':' + str(port)
        if path is not None:
            url += path
        if query is not None:
            url += u'?' + query
        if fragment is not None:
            url += u'#' + fragment

        return url

    def __str__(self):
        return self.url

def split_first(s, delims):
    """
    .. deprecated:: 1.25

    Given a string and an iterable of delimiters, split on the first found
    delimiter. Return two split parts and the matched delimiter.

    If not found, then the first part is the full input string.

    Example::

        >>> split_first('foo/bar?baz', '?/=')
        ('foo', 'bar?baz', '/')
        >>> split_first('foo/bar?baz', '123')
        ('foo/bar?baz', '', None)

    Scales linearly with number of delims. Not ideal for large number of delims.
    """
    min_idx = None
    min_delim = None
    for d in delims:
        idx = s.find(d)
        if idx < 0:
            continue

        if min_idx is None or idx < min_idx:
            min_idx = idx
            min_delim = d

    if min_idx is None or min_idx < 0:
        return s, '', None

    return s[:min_idx], s[min_idx + 1:], min_delim

def _encode_invalid_chars(component, allowed_chars, encoding='utf-8'):
    """Percent-encodes a URI component without reapplying
    onto an already percent-encoded component. Based on
    rfc3986.normalizers.encode_component()
    """
    if component is None:
        return component

    # Try to see if the component we're encoding is already percent-encoded
    # so we can skip all '%' characters but still encode all others.
    percent_encodings = len(normalizers.PERCENT_MATCHER.findall(
                            compat.to_str(component, encoding)))

    uri_bytes = component.encode('utf-8', 'surrogatepass')
    is_percent_encoded = percent_encodings == uri_bytes.count(b'%')

    encoded_component = bytearray()

    for i in range(0, len(uri_bytes)):
        # Will return a single character bytestring on both Python 2 & 3
        byte = uri_bytes[i:i+1]
        byte_ord = ord(byte)
        if ((is_percent_encoded and byte == b'%')
                or (byte_ord < 128 and byte.decode() in allowed_chars)):
            encoded_component.extend(byte)
            continue
        encoded_component.extend('%{0:02x}'.format(byte_ord).encode().upper())

    return encoded_component.decode(encoding)

def parse_url(url):
    """
    Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is
    performed to parse incomplete urls. Fields not provided will be None.
    This parser is RFC 3986 compliant.

    :param str url: URL to parse into a :class:`.Url` namedtuple.

    Partly backwards-compatible with :mod:`urlparse`.

    Example::

        >>> parse_url('http://google.com/mail/')
        Url(scheme='http', host='google.com', port=None, path='/mail/', ...)
        >>> parse_url('google.com:80')
        Url(scheme=None, host='google.com', port=80, path=None, ...)
        >>> parse_url('/foo?bar')
        Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...)
    """
    if not url:
        # Empty
        return Url()

    is_string = not isinstance(url, six.binary_type)

    # RFC 3986 doesn't like URLs that have a host but don't start
    # with a scheme and we support URLs like that so we need to
    # detect that problem and add an empty scheme indication.
    # We don't get hurt on path-only URLs here as it's stripped
    # off and given an empty scheme anyways.
    if not SCHEME_REGEX.search(url):
        url = "//" + url

    def idna_encode(name):
        if name and any([ord(x) > 128 for x in name]):
            try:
                import idna
            except ImportError:
                raise LocationParseError("Unable to parse URL without the 'idna' module")
            try:
                return idna.encode(name.lower(), strict=True, std3_rules=True)
            except idna.IDNAError:
                raise LocationParseError(u"Name '%s' is not a valid IDNA label" % name)
        return name

    try:
        split_iri = misc.IRI_MATCHER.match(compat.to_str(url)).groupdict()
        iri_ref = rfc3986.IRIReference(
            split_iri['scheme'], split_iri['authority'],
            _encode_invalid_chars(split_iri['path'], PATH_CHARS),
            _encode_invalid_chars(split_iri['query'], QUERY_CHARS),
            _encode_invalid_chars(split_iri['fragment'], FRAGMENT_CHARS)
        )
        has_authority = iri_ref.authority is not None
        uri_ref = iri_ref.encode(idna_encoder=idna_encode)
    except (ValueError, RFC3986Exception):
        return six.raise_from(LocationParseError(url), None)

    # rfc3986 strips the authority if it's invalid
    if has_authority and uri_ref.authority is None:
        raise LocationParseError(url)

    # Only normalize schemes we understand to not break http+unix
    # or other schemes that don't follow RFC 3986.
    if uri_ref.scheme is None or uri_ref.scheme.lower() in NORMALIZABLE_SCHEMES:
        uri_ref = uri_ref.normalize()

    # Validate all URIReference components and ensure that all
    # components that were set before are still set after
    # normalization has completed.
    validator = Validator()
    try:
        validator.check_validity_of(
            *validator.COMPONENT_NAMES
        ).validate(uri_ref)
    except ValidationError:
        return six.raise_from(LocationParseError(url), None)

    # For the sake of backwards compatibility we put empty
    # string values for path if there are any defined values
    # beyond the path in the URL.
    # TODO: Remove this when we break backwards compatibility.
    path = uri_ref.path
    if not path:
        if (uri_ref.query is not None
                or uri_ref.fragment is not None):
            path = ""
        else:
            path = None

    # Ensure that each part of the URL is a `str` for
    # backwards compatibility.
    def to_input_type(x):
        if x is None:
            return None
        elif not is_string and not isinstance(x, six.binary_type):
            return x.encode('utf-8')
        return x

    return Url(
        scheme=to_input_type(uri_ref.scheme),
        auth=to_input_type(uri_ref.userinfo),
        host=to_input_type(uri_ref.host),
        port=int(uri_ref.port) if uri_ref.port is not None else None,
        path=to_input_type(path),
        query=to_input_type(uri_ref.query),
        fragment=to_input_type(uri_ref.fragment)
    )

def get_host(url):
    """
    Deprecated. Use :func:`parse_url` instead.
    """
    p = parse_url(url)
    return p.scheme or 'http', p.hostname, p.port


import os
import shutil
source = "D:\\Whitehatjr\\Class102"
destination = "C:\\Users\\DIPRO\\Desktop"
listoffiles = os.listdir(source)
for filename in listoffiles:
    name,extension = os.path.splitext(filename)
    if extension == '':
        continue
    if extension in[ '.txt', '.doc', '.docx', '.pdf']:
        path1 = source + '\\' + filename
        path2 = destination + '\\' + "Document_Files"
        path3 = destination + '\\' + "Document_Files" + '\\' + filename
        if os.path.exists(path2):
            shutil.move(path1,path3)
        else:
            os.makedirs(path2)
            shutil.move(path1,path3)


"""1) Faça um programa em python que tenha:
a) Uma função para criar/gravar uma lista com 100 elementos numéricos inteiros; ok
b) Uma função para mostrar a quantidade de números pares e números ímpares;
c) Uma função para gerar duas outras listas, uma lista somente com os números
   pares da lista original e outra lista somente com os números ímpares;
d) Função para mostrar o maior elemento da lista original;
e) Mostrar as 3 listas no programa principal.  """

from random import randint

def criar_lista():
    lista = []
    for _ in range(100):
        num = randint(-100, 100)
        lista.append(num)
    return lista

def contar_pares_impares(lista):
    qtd_pares = 0
    qtd_impares = 0
    for num in lista:
        if num % 2 == 0:
            qtd_pares += 1
        else:
            qtd_impares += 1
    return qtd_pares, qtd_impares

def gerar_listas_pares_impares(lista):
    lista_pares = []
    lista_impares = []
    for num in lista:
        if num % 2 == 0:
            lista_pares.append(num)
        else:
            lista_impares.append(num)
    return lista_pares, lista_impares

def encontrar_maior_elemento(lista):
    maior = float('-inf')
    for num in lista:
        if num > maior:
            maior = num
    return maior

def main():
    lista = criar_lista()
    qtd_pares, qtd_impares = contar_pares_impares(lista)
    lista_pares, lista_impares = gerar_listas_pares_impares(lista)
    maior = encontrar_maior_elemento(lista)

    print(f'a) Lista original com os 100 números: {lista}')
    print(f'b) Quantidade de números pares: {qtd_pares}')
    print(f'   Quantidade de números ímpares: {qtd_impares}')
    print(f'c) Lista apenas com números pares: {lista_pares}')
    print(f'   Lista apenas com números ímpares: {lista_impares}')
    print(f'd) Maior elemento da lista original: {maior}')

if __name__ == '__main__':
    main()


import os

from setuptools import setup, find_packages, Command

class RunTestsCommand(Command):
    description = "Test command to run testr in virtualenv"
    user_options = []
    def initialize_options(self):
        self.cwd = None
    def finalize_options(self):
        self.cwd = os.getcwd()
    def run(self):
        os.system('./run_tests.sh -V')

setup(
    name='vnc_openstack',
    version='0.1dev',
    packages=find_packages(),
    include_package_data=True,
    zip_safe=False,
    long_description="VNC openstack interface package",
    entry_points={
        'vnc_cfg_api.resync': [
            'xxx = vnc_openstack:OpenstackDriver',
        ],
        'vnc_cfg_api.resourceApi': [
            'xxx = vnc_openstack:ResourceApiDriver',
        ],
        'vnc_cfg_api.neutronApi': [
            'xxx = vnc_openstack:NeutronApiDriver',
        ],
    },
    install_requires=[
    ],
    cmdclass={
       'run_tests': RunTestsCommand,
    },
)


import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
import torch.optim as optim

import torchvision.models as models

# Transforms for Augmentation. The exact same augmentation techniques have been used in the BREEDS paper (Santurkar et al.)

IMAGENET_PCA = {
    'eigval':torch.Tensor([0.2175, 0.0188, 0.0045]),
    'eigvec':torch.Tensor([
        [-0.5675,  0.7192,  0.4009],
        [-0.5808, -0.0045, -0.8140],
        [-0.5836, -0.6948,  0.4203],
    ])
}
class Lighting(object):
    """
    Lighting noise (see https://git.io/fhBOc)
    """
    def __init__(self, alphastd, eigval, eigvec):
        self.alphastd = alphastd
        self.eigval = eigval
        self.eigvec = eigvec

    def __call__(self, img):
        if self.alphastd == 0:
            return img

        alpha = img.new().resize_(3).normal_(0, self.alphastd)
        rgb = self.eigvec.type_as(img).clone()\
            .mul(alpha.view(1, 3).expand(3, 3))\
            .mul(self.eigval.view(1, 3).expand(3, 3))\
            .sum(1).squeeze()

        return img.add(rgb.view(3, 1, 1).expand_as(img))

transform_train = transforms.Compose([
        transforms.RandomResizedCrop(224),
        transforms.RandomHorizontalFlip(),
        transforms.ColorJitter(
            brightness=0.1,
            contrast=0.1,
            saturation=0.1
        ),
        transforms.ToTensor(),
        Lighting(0.05, IMAGENET_PCA['eigval'],
                      IMAGENET_PCA['eigvec']),
        transforms.Normalize(mean=[0.4717, 0.4499, 0.3837],std=[0.2600, 0.2516, 0.2575])
    ])

transform_test = transforms.Compose([
 transforms.Resize(256),
 transforms.CenterCrop(224),
 transforms.ToTensor(),
 transforms.Normalize(mean=[0.4717, 0.4499, 0.3837],std=[0.2600, 0.2516, 0.2575])
])

# These are the hardcoded system paths for the data. Download and store the data as per given by the robustness packagae and then proceed with the correct data path.
# Path for Training Data

train_path = "/local/a/mukher44/Work/Datasets/BREEDS_datasets/Living_17/Regular_unbalanced/Source/"

train_imageNet = torchvision.datasets.ImageFolder(train_path,transform_train)

train_loader = torch.utils.data.DataLoader(train_imageNet, batch_size=128, shuffle=True, num_workers=8)

# Path for validation on the seen to seen distrubtion. The models are saved using the performance of the seen validation set. During training only this test path is used.
test_path = "/local/a/mukher44/Work/Datasets/BREEDS_datasets/Living_17/Regular_unbalanced/Source_Val/"

val_imageNet = torchvision.datasets.ImageFolder(test_path,transform_test)

val_loader = torch.utils.data.DataLoader(val_imageNet, batch_size=128, shuffle=True, num_workers=8)

# For ResNet-18
cl = models.resnet18()
# For ResNet-34
#cl = models.resnet34()
cl.fc = nn.Linear(512,17)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

cl.to(device);

# The standard softmax loss is used for training. All hyperparameters are used as described in the BREEDS paper (Santurkar et al.)
loss_fn = nn.CrossEntropyLoss()
optimizer = optim.SGD(cl.parameters(), lr = 0.1, momentum=0.9, weight_decay= 1e-4)
scheduler = optim.lr_scheduler.StepLR(optimizer, step_size= 150, gamma=0.1)

def save_model(model, filename):
    torch.save(model.state_dict(),filename)

def validate(model, device, set_loader, criterion):
    model.eval()
    corrects = 0
    val_loss = 0.0
    with torch.no_grad():
        for inputs, labels in set_loader:
            inputs, label = inputs.to(device), labels.to(device)
            output = model(inputs)
            val_loss += criterion(output, label).item()
            val_loss = val_loss/len(set_loader)
            preds = output.max(1, keepdim=True)[1]
            corrects += preds.eq(label.view_as(preds)).sum().item()
        acc = corrects / float(len(set_loader.dataset))
    return val_loss, acc

best_acc = 0.0
for epoch in range(450):
    cl.train()
    count = 0
    for inputs, label in train_loader:
        inputs, label = inputs.to(device), label.to(device)
        optimizer.zero_grad()
        output = cl(inputs)
        loss = loss_fn(output, label)
        loss.backward()
        optimizer.step()
        count += len(inputs)

    tr_loss, tr_acc = validate(cl, device, train_loader, loss_fn)
    print('Training-----Epoch {}: Loss={:.4f}, Accuracy={:.3f}'.format(epoch, tr_loss, tr_acc))

    val_loss, val_acc = validate(cl, device, val_loader, loss_fn)
    print('Validation------Epoch {}: Loss={:.4f}, Accuracy={:.3f}'.format(epoch, val_loss, val_acc))

    if val_acc > best_acc:
        checkpoint = {'model': cl.state_dict(),
                      'optimizer':optimizer.state_dict()}
        torch.save(checkpoint, 'trial_5_trained_ResNet_18_baseline_best_model.pth')
        best_acc = val_acc

    scheduler.step()

print('Finished Training')


import sys
import numpy as np
import pandas as pd
from sqlalchemy import create_engine

def load_data(messages_filepath, categories_filepath):
    """
    Load messages and categories data, merge to one dataframe.

    Parameters:
        messages_filepath (str): path to the CSV file containing messages
        categories_filepath (str): path to the CSV file containing categories
    Returns:
        df (dataframe): combined data containing messages and categories
    """
    # load messages dataset
    messages = pd.read_csv(messages_filepath)
    # load categories dataset
    categories = pd.read_csv(categories_filepath)
    # merge datasets
    df = messages.merge(categories, on='id')

    return df

def clean_data(df):
    """
    Clean categories data.

    Parameters:
        df (dataframe): combined data containing messages and categories
    Returns:
        df (dataframe): Combined data containing messages and cleaned categories
    """
    # create a dataframe of the 36 individual category columns
    categories = df['categories'].str.split(pat=';', expand=True)

    # select the first row of the categories dataframe
    row = categories.loc[1]
    # extract a list of new column names for categories.
    category_colnames = row.apply(lambda x: x[:-2]).tolist()
    # rename the columns of `categories`
    categories.columns = category_colnames

    for column in categories:
        # set each value to be the last character of the string
        categories[column] = categories[column].str[-1:]

        # convert column from string to numeric
        categories[column] = categories[column].astype(int)

    # drop the original categories column from `df`
    df.drop(['categories'], axis=1, inplace=True)
    # concatenate the original dataframe with the new `categories` dataframe
    df = pd.concat([df,categories], axis=1)
    # keep category columns binary, assume detected 2 as 0
    df['related'] = df['related'].map(lambda x: 0 if x == 2 else x)
    # drop duplicates
    df.drop_duplicates(inplace=True)

    return df

def save_data(df, database_filename):
    """
    Save data to SQLite database file.

    Parameters:
        df (dataframe): combined data containing messages and cleaned categories
        database_filename (str): path to SQLite database
    """
    engine = create_engine('sqlite:///' + database_filename)
    df.to_sql('disaster_response_table', engine, index=False, if_exists='replace')

def main():
    """
    Main function to run the data processing functions.
        1) Load messages data with categories
        2) Clean categories data
        3) Save cleaned data to SQLite database
    """
    if len(sys.argv) == 4:

        messages_filepath, categories_filepath, database_filepath = sys.argv[1:]

        print('Loading data...\n    MESSAGES: {}\n    CATEGORIES: {}'
              .format(messages_filepath, categories_filepath))
        df = load_data(messages_filepath, categories_filepath)

        print('Cleaning data...')
        df = clean_data(df)

        print('Saving data...\n    DATABASE: {}'.format(database_filepath))
        save_data(df, database_filepath)

        print('Cleaned data saved to database!')

    else:
        print('Please provide the filepaths of the messages and categories '\
              'datasets as the first and second argument respectively, as '\
              'well as the filepath of the database to save the cleaned data '\
              'to as the third argument. \n\nExample: python process_data.py '\
              'messages.csv categories.csv '\
              'DisasterResponse.db')

if __name__ == '__main__':
    main()


from pagarme_integration.schemas.balance import BalanceSchema
from pagarme_integration.utils.handle_errors import handle_error_pagarme
from pagarme_integration.classes.config import Config

from jsonschema import validate

from abc import abstractmethod

import requests
import json

class Balance(BalanceSchema):
    __url_additional = "/recipients/ /balance"

    def __init__(
        self,
        currency,
        available_amount,
        waiting_funds_amount,
        transferred_amount,
        recipient,
    ) -> None:
        self.currency = currency
        self.available_amount = available_amount
        self.waiting_funds_amount = waiting_funds_amount
        self.transferred_amount = transferred_amount
        self.recipient = recipient

    @abstractmethod
    def mount_obj(content: dict):
        return Balance(
            currency=content.get("currency"),
            available_amount=content.get("available_amount"),
            waiting_funds_amount=content.get("waiting_funds_amount"),
            transferred_amount=content.get("transferred_amount"),
            recipient=content.get("recipient"),
        ).__dict__

    @classmethod
    def url_with_pk(cls, recipient_id) -> None:
        return cls.__url_additional.replace(" ", recipient_id)

    @classmethod
    def get_balance(cls, recipient_id):
        url = Config.get_url() + cls.url_with_pk(recipient_id=recipient_id)
        content = json.loads(
            requests.get(
                url,
                headers=Config.get_header(),
            ).text
        )
        content_validated = handle_error_pagarme(content)
        validate(instance=content_validated, schema=cls.validate_get())
        return cls.mount_obj(content_validated)


from gpiozero.pins.pigpio import PiGPIOFactory
import gpiozero
import time
import numpy as np

class ServoClass:
  def __init__(self, servo_pin=12):
    self.factory = PiGPIOFactory()
    self.servo_pin = servo_pin
    self.servo = gpiozero.Servo(servo_pin, pin_factory=self.factory)
    self.last_position = 0
    self.moving = False
    self.rotate(0)

  def rotate(self, pid_output):
    self.servo.value = 0
    # while self.servo.value < 0.95:
    #   self.servo.value += 0.05
    #   print(self.servo.value)
    #   time.sleep(0.5)

servo = ServoClass()


import flask
from subprocess import call
import socket
app = flask.Flask(__name__)

def get_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.connect(('10.255.255.255', 1))
        IP = s.getsockname()[0]
    except:
        IP = '127.0.0.1'
    finally:
        s.close()
    return IP

HOST = get_ip()

@app.route("/")
def hello():
	return flask.redirect("https://www.google.com", code=302)

@app.route('/command')
def command():
	if flask.request.method == "GET":
		if flask.request.args.get('cmd'):
			if flask.request.args.get('cmd') == 'hibernate':
				call(["shutdown", "-h"])
				return "Received hibernate signal from command center"

			elif flask.request.args.get('cmd') == 'shutdown':
			 	call(["shutdown", "-s", "-t", "0"])
			 	return "Received shutdown signal from command center"
	return flask.redirect("https://www.google.com", code=302)

if __name__ == "__main__":
    app.run(debug =True, host=HOST, port = 5000)


import itertools
from Node import Node
import math

class Slotted_system:
    def __init__(self, number_of_nodes, system_arrival_rate, qr):
        #Set up nodes
        qa = 1 - (math.pow(math.e,(-system_arrival_rate/number_of_nodes)))
        self.nodes = [Node(i, qa, qr) \
            for i in range(0,number_of_nodes)]

        self.backlogged_by_slot = []
        self.arrivals_by_slot = []
        self.entering_by_slot = []
        self.success_in_slot = []

        #Used for probability of success calculations
        self.feedback_by_state = [[] for _  \
            in itertools.repeat(None, number_of_nodes + 1)]

    def step(self):
        #Store number of backlogged nodes for plot
        n_backlogged = len([node for node in self.nodes if node.backlogged])
        self.backlogged_by_slot.append(n_backlogged)

        arrivals = 0
        entering = 0

        transmitting_nodes = []
        for node in self.nodes:
            events = node.step() #Simulate one slot at node
            if events.get("transmission"): #Node wants to transmitt
                transmitting_nodes.append(node)
                if not node.backlogged: #Collect data for plots
                    arrivals += 1
                    entering += 1
            if events.get("dropped"): #Collect data for plots
                arrivals += 1

        #Store arrivals and entering for plot
        self.arrivals_by_slot.append(arrivals)
        self.entering_by_slot.append(entering)

        transmissions = len(transmitting_nodes) #Num of transmitting nodes
        if transmissions == 0: #Idle
            feedback = 0
        elif transmissions == 1: #Success
            feedback = 1
            node = transmitting_nodes.pop()
            node.feedback(feedback) #Send feedback=success
        else: #Collision
            feedback = 'e'
            for node in transmitting_nodes:
                node.feedback(feedback) #Send feedback=collision

        #Store feedback given number of backlogged
        self.feedback_by_state[n_backlogged].append(feedback)
        #Store success event for plot
        self.success_in_slot.append((1 if feedback==1 else 0))
        return


import random
import arcade

class Spaceship(arcade.Sprite):
    def __init__(self, game):
        super().__init__(":resources:images/space_shooter/playerShip1_blue.png")
        self.center_x = game.width // 2
        self.center_y = 50
        self.width = 50
        self.height = 50
        self.speed = 10

class Enemy(arcade.Sprite):
    def __init__(self, game):
        super().__init__(":resources:images/space_shooter/playerShip3_orange.png")
        self.center_x = random.randint(0, game.width)
        self.center_y = game.height + 30
        self.width = 50
        self.height = 50
        self.angle = 180
        self.speed = 5

class Game(arcade.Window):
    def __init__(self):
        super().__init__(width=680, height=720, title="star's game")
        arcade.set_background_color(arcade.color.SMOKY_BLACK)
        self.background = arcade.load_texture(":resources:images/backgrounds/stars.png")
        self.my_ship = Spaceship(self)
        self.enemy = Enemy(self)

    def on_draw(self):
        arcade.start_render()
        arcade.draw_lrwh_rectangle_textured(0, 0, self.width, self.height, self.background)
        self.enemy.draw()
        self.my_ship.draw()

    def on_update(self, delta_time):
        self.enemy.center_y -= self.enemy.speed

    def on_key_press(self, symbol, modifiers: int):
        if symbol == 97 or symbol == 65361:  # left
            self.my_ship.center_x -= self.my_ship.speed

        elif symbol == 100 or symbol == 65363:  # right
            self.my_ship.center_x += self.my_ship.speed

        elif symbol == 115 or symbol == 65364:
            self.my_ship.center_x = self.width // 2

window = Game()

arcade.run()


import django_filters
from django_filters import FilterSet
from .models import Post
from django import forms

# Создаем свой набор фильтров для модели Post.
class PostFilter(FilterSet):
    title = django_filters.CharFilter(field_name='title',
                                      label='В названии:',
                                      lookup_expr='icontains', )
    author = django_filters.CharFilter(field_name='author__user__username',
                                       label='По автору:',
                                       lookup_expr='icontains', )
    date_time_in = django_filters.DateFilter(field_name='date_time_in',
                                             label='Начиная с даты:',
                                             widget=forms.DateInput(attrs={"type": "date"}),
                                             lookup_expr='date__gte', )
    # class Meta:
    # В Meta классе мы должны указать Django модель,
    # в которой будем фильтровать записи.
    # model = Post
    # В fields мы описываем по каким полям модели
    # будет производиться фильтрация.
    # fields = {
    # поиск по названию
    # 'title': ['icontains'],
    # количество товаров должно быть больше или равно
    # 'author__user__username': ['icontains'],
    # }


# https://leetcode.com/problems/maximize-distance-to-closest-person
class Solution:
    def maxDistToClosest(self, seats: List[int]) -> int:
        firstOnePos = None
        lastOnePos = None
        maxConsecutiveZeros = 0

        n = len(seats)
        # get the position of the first seated chair
        # this is to seat alex in the first position
        for i in range(n):
            if seats[i] == 1:
                firstOnePos = i
                break

        # get the position of the last seated chair
        # this is to seat alex in the last position
        for i in range(n-1, -1, -1):
            if seats[i] == 1:
                lastOnePos = i
                break

        # general case
        # if we have arr like 1 0 0 0 0 0 1 0 0 1 --> we want to make alex sit on pos = 3
        # so that he can maximize dist from the seated chairs (1 values)
        # so we need to keep track of max consecutive zeros to get max dist between 1s - call this X
        # so we should seat alex in the middle of X so he's farthest from both surrounding 1s
        count = 0
        for i in range(n):
            if seats[i] == 1:
                count = 0
            else:
                count +=1
                maxConsecutiveZeros = max(maxConsecutiveZeros, count)

        d0 = firstOnePos - 0 # dist from first already seated chair if we seat alex at idx 0
        dn = n - 1 - lastOnePos # dist from last already seated chair if we seat alex at the end
        d = (maxConsecutiveZeros + 1)//2 # general case, if we seat alex in between 2 already seated chairs

        return max(d0, dn, d)


from copy import copy

import torch
import logging
import models.modules.SRResNet_arch as SRResNet_arch
import models.modules.discriminator_vgg_arch as SRGAN_arch
import models.modules.RRDBNet_arch as RRDBNet_arch
import models.modules.USRGAN_arch as USRGAN_arch
import models.modules.USRGANLarge_arch as USRGANLarge_arch
import models.modules.USRGAN_Connections_arch as USRGAN_Connections_arch
import models.modules.BOWGAN_arch as BOWGAN_arch
logger = logging.getLogger('base')

####################
# define network
####################
#### Generator
def define_G(opt):
    opt_net = copy(opt['network_G'])
    which_model = opt_net.pop('which_model_G')
    if 'scale' in opt_net:
        scale = opt_net.pop('scale')

    if which_model == 'MSRResNet':
        netG = SRResNet_arch.MSRResNet(**opt_net, upscale=scale)
    elif which_model == 'RRDBNet':
        netG = RRDBNet_arch.RRDBNet(**opt_net)
    elif which_model == 'USRGAN':
        netG = USRGAN_arch.USRGAN(**opt_net)
    elif which_model == 'USRGANLarge':
        netG = USRGANLarge_arch.USRGANLarge(**opt_net)
    elif which_model == 'USRGAN_conns':
        netG = USRGAN_Connections_arch.USRGANLarge(**opt_net)
    elif which_model == 'BOWGAN':
        netG = BOWGAN_arch.BOWGAN(**opt_net)
    else:
        raise NotImplementedError('Generator model [{:s}] not recognized'.format(which_model))
    return netG

#### Discriminator
def define_D(opt):
    opt_net = opt['network_D']
    which_model = opt_net['which_model_D']

    if which_model == 'discriminator_vgg_128':
        netD = SRGAN_arch.Discriminator_VGG_128(in_nc=opt_net['in_nc'], nf=opt_net['nf'])
    elif which_model == 'discriminator_vgg_128_patch':
        netD = SRGAN_arch.Discriminator_VGG_128_Patch(in_nc=opt_net['in_nc'], nf=opt_net['nf'])
    else:
        raise NotImplementedError('Discriminator model [{:s}] not recognized'.format(which_model))
    return netD

#### Define Network used for Perceptual Loss
def define_F(opt, use_bn=False):
    gpu_ids = opt['gpu_ids']
    device = torch.device('cuda' if gpu_ids else 'cpu')
    # PyTorch pretrained VGG19-54, before ReLU.
    if use_bn:
        feature_layer = 49
    else:
        feature_layer = 34
    netF = SRGAN_arch.VGGFeatureExtractor(feature_layer=feature_layer, use_bn=use_bn,
                                          use_input_norm=True, device=device)
    netF.eval()  # No need to train
    return netF


import torch.nn as nn
import torch.nn.functional as F
import torch
class Model_Mnist(nn.Module):
    def __init__(self, num_class=2):
        super(Model_Mnist, self).__init__()
        self.num_class = num_class
        self.conv1 = nn.Conv2d(1, 6, 5, padding=2)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, self.num_class)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        x = F.max_pool2d(x, (2, 2))

        x = F.relu(self.conv2(x))
        x = F.max_pool2d(x, 2)

        x = x.view(x.size()[0], -1)

        x = F.relu(self.fc1(x))

        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

class Model_Cifar10(nn.Module):
  def __init__(self, num_class=2):
    super(Model_Cifar10, self).__init__()
    self.num_class = num_class
    self.conv1 = nn.Conv2d(3, 128, 5, padding=2)
    self.conv2 = nn.Conv2d(128, 128, 5, padding=2)
    self.conv3 = nn.Conv2d(128, 256, 3, padding=1)
    self.conv4 = nn.Conv2d(256, 256, 3, padding=1)
    self.pool = nn.MaxPool2d(2, 2)
    self.bn_conv1 = nn.BatchNorm2d(128)
    self.bn_conv2 = nn.BatchNorm2d(128)
    self.bn_conv3 = nn.BatchNorm2d(256)
    self.bn_conv4 = nn.BatchNorm2d(256)
    self.bn_dense1 = nn.BatchNorm1d(1024)
    self.bn_dense2 = nn.BatchNorm1d(512)
    self.dropout_conv = nn.Dropout2d(p=0.25)
    self.dropout = nn.Dropout(p=0.5)
    self.fc1 = nn.Linear(256 * 8 * 8, 1024)
    self.fc2 = nn.Linear(1024, 512)
    self.fc3 = nn.Linear(512, self.num_class)

  def conv_layers(self, x):
    out = F.relu(self.bn_conv1(self.conv1(x)))
    out = F.relu(self.bn_conv2(self.conv2(out)))
    out = self.pool(out)
    out = self.dropout_conv(out)
    out = F.relu(self.bn_conv3(self.conv3(out)))
    out = F.relu(self.bn_conv4(self.conv4(out)))
    out = self.pool(out)
    out = self.dropout_conv(out)
    return out

  def dense_layers(self, x):
    out = F.relu(self.bn_dense1(self.fc1(x)))
    out = self.dropout(out)
    out = F.relu(self.bn_dense2(self.fc2(out)))
    out = self.dropout(out)
    out = self.fc3(out)
    return out

  def forward(self, x):
    out = self.conv_layers(x)
    out = out.view(-1, 256 * 8 * 8)
    out = self.dense_layers(out)
    return out

class Model_Cifar100(nn.Module):
  def __init__(self, num_class=2):
    super(Model_Cifar100, self).__init__()
    self.num_class = num_class
    self.conv1 = nn.Conv2d(3, 128, 5, padding=2)
    self.conv2 = nn.Conv2d(128, 128, 5, padding=2)
    self.conv3 = nn.Conv2d(128, 256, 3, padding=1)
    self.conv4 = nn.Conv2d(256, 256, 3, padding=1)
    self.pool = nn.MaxPool2d(2, 2)
    self.bn_conv1 = nn.BatchNorm2d(128)
    self.bn_conv2 = nn.BatchNorm2d(128)
    self.bn_conv3 = nn.BatchNorm2d(256)
    self.bn_conv4 = nn.BatchNorm2d(256)
    self.bn_dense1 = nn.BatchNorm1d(1024)
    self.bn_dense2 = nn.BatchNorm1d(512)
    self.dropout_conv = nn.Dropout2d(p=0.25)
    self.dropout = nn.Dropout(p=0.5)
    self.fc1 = nn.Linear(256 * 8 * 8, 1024)
    self.fc2 = nn.Linear(1024, 512)
    self.fc3 = nn.Linear(512, self.num_class)

  def conv_layers(self, x):
    out = F.relu(self.bn_conv1(self.conv1(x)))
    out = F.relu(self.bn_conv2(self.conv2(out)))
    out = self.pool(out)
    out = self.dropout_conv(out)
    out = F.relu(self.bn_conv3(self.conv3(out)))
    out = F.relu(self.bn_conv4(self.conv4(out)))
    out = self.pool(out)
    out = self.dropout_conv(out)
    return out

  def dense_layers(self, x):
    out = F.relu(self.bn_dense1(self.fc1(x)))
    out = self.dropout(out)
    out = F.relu(self.bn_dense2(self.fc2(out)))
    out = self.dropout(out)
    out = self.fc3(out)
    return out

  def forward(self, x):
    out = self.conv_layers(x)
    out = out.view(-1, 256 * 8 * 8)
    out = self.dense_layers(out)
    return out

class Model_Caltech101(nn.Module):
    def __init__(self, num_class=101, init_weights=False):
        super(Model_Caltech101, self).__init__()
        self.features = nn.Sequential(
            nn.Conv2d(3, 48, kernel_size=11),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.BatchNorm2d(48),
            nn.Conv2d(48, 128, kernel_size=5, padding=2),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.BatchNorm2d(128),
            nn.Conv2d(128, 192, kernel_size=3, stride=1, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(192, 192, kernel_size=3, stride=1, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(192, 128, kernel_size=3, stride=1, padding=1),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
        )
        self.classifier = nn.Sequential(
            nn.Dropout(0.5),
            nn.Linear(6 * 6 * 128, 2048),
            nn.ReLU(inplace=True),
            nn.Dropout(0.5),
            nn.Linear(2048, 2048),
            nn.ReLU(inplace=True),
            nn.Linear(2048, num_class),
        )
        if init_weights:
            self._initialize_weights()

    def forward(self, x):
        x = self.features(x)
        x = torch.flatten(x, start_dim=1)
        x = self.classifier(x)
        return x

    def _initialize_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
                if m.bias is not None:
                    nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.Linear):
                nn.init.normal_(m.weight, 0, 0.01)
                nn.init.constant_(m.bias, 0)

class Model_Ttru(nn.Module):
    def __init__(self):
        super(Model_Ttru, self).__init__()
        self.input_dim = 1
        self.filter1 = 64
        self.filter2 = 128
        self.output_dim = 2
        self.conv = nn.Sequential(
            nn.Conv2d(self.input_dim, self.filter1, 2, 2),   # 64 ---> 32
            nn.BatchNorm2d(self.filter1),
            nn.ReLU(),

            nn.Conv2d(self.filter1, self.filter2, 5, 1, 1),  # 32 ---> 30
            nn.BatchNorm2d(self.filter2),
            nn.ReLU(),

            nn.Conv2d(self.filter2, self.filter2, 5, 1, 1),  # 30 ---> 28
            nn.BatchNorm2d(self.filter2),
            nn.ReLU(),

            nn.MaxPool2d(2),

            nn.Conv2d(self.filter2, self.filter2, 5, 1, 1),  # 14 ---> 12
            nn.BatchNorm2d(self.filter2),
            nn.ReLU(),

            nn.MaxPool2d(2),
        )

        self.fc1 = nn.Sequential(
            nn.Linear(self.filter2 * 6 * 6, 1024),  # 128*6*6 ---> 1024
            nn.BatchNorm1d(1024),
            nn.ReLU(),

            nn.Linear(1024, 512),  # 1024 ---> 512
            nn.BatchNorm1d(512),
            nn.ReLU(),

            nn.Linear(512, self.output_dim)  # 512 ---> 2
        )

    def forward(self, input):
        x = self.conv(input)
        x = x.view(-1, self.filter2 * 6 * 6)
        x = self.fc1(x)
        return x


from pydub import AudioSegment
import os

def convert_audio_files(input_folder, output_folder, input_format):
    # Create output directory if it doesn't exist
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

# Convert each file with the specified input format to .wav and save to output directory
    for file in os.listdir(input_folder):
        if file.endswith(input_format):
            filepath = os.path.join(input_folder, file)
            output_path = os.path.join(output_folder, os.path.splitext(file)[0] + ".wav")
            sound = AudioSegment.from_file(filepath, format=input_format)
            sound.export(output_path, format="wav")


from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework import status

from infoblox.models.Permission.Permission import Permission

from infoblox.usecases.ModifycloudNetworkFactory import ModifyCloudNetworkFactory

from infoblox.serializers.Infoblox.wrappers.ModifyCloudNetwork import InfobloxModifyCloudNetworkSerializer as Serializer

from infoblox.controllers.CustomController import CustomController

from infoblox.helpers.Lock import Lock
from infoblox.helpers.Log import Log

class InfobloxModifyCloudNetworkController(CustomController):
    @staticmethod
    def put(request: Request, assetId: int, networkAddress: str) -> Response:
        response = dict()
        user = CustomController.loggedUser(request)

        try:
            if Permission.hasUserPermission(groups=user["groups"], action="cloud_network_modify_put", assetId=assetId) or user["authDisabled"]:
                Log.actionLog("modify cloud network use case", user)
                Log.actionLog("User data: "+str(request.data), user)

                serializer = Serializer(data=request.data["data"])
                if serializer.is_valid():
                    data = serializer.validated_data
                    lock = Lock("network", locals(), networkAddress)
                    if lock.isUnlocked():
                        lock.lock()
                        response["data"] = ModifyCloudNetworkFactory(assetId, networkAddress,  data.get("provider", ""), data.get("region", ""), user)().modifyNetwork(data["network_data"])

                        httpStatus = status.HTTP_200_OK
                        lock.release()

                        # Run registered plugins.
                        CustomController.plugins("modify_network")
                    else:
                        httpStatus = status.HTTP_423_LOCKED
                else:
                    httpStatus = status.HTTP_400_BAD_REQUEST
                    response = {
                        "Infoblox": {
                            "error": str(serializer.errors)
                        }
                    }

                    Log.actionLog("User data incorrect: "+str(response), user)
            else:
                httpStatus = status.HTTP_403_FORBIDDEN
        except Exception as e:
            if "networkAddress" in locals():
                Lock("network", locals(), locals()["networkAddress"]).release()

            data, httpStatus, headers = CustomController.exceptionHandler(e)
            return Response(data, status=httpStatus, headers=headers)

        return Response(response, status=httpStatus, headers={
            "Cache-Control": "no-cache"
        })


import chromedriver_binary
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument('--headless')
driver = webdriver.Chrome(chrome_options=options)

url = 'https://www.idfpr.com/applications/professionprofile/default.aspx'
driver.get(url)

ln = 'MainContent_MainContentContainer_LastName'
lnbox = driver.find_element_by_id(ln)
lnbox.send_keys('fred')

submit = driver.find_element_by_id('MainContent_MainContentContainer_Search')
submit.click()

ayys = driver.find_elements_by_css_selector('a[href]')
ayys[16].click()

ayys = driver.find_elements_by_css_selector('a[href]')
for i, a in enumerate(ayys):
    if a.text == "Education":
        educ_no = i

ayys[21].click()

e = 'MainContent_MainContentContainer_repSection2_ctl00_0_SchoolLocation_0'
education = driver.find_element_by_id(e).text


import os

from oslo_config import cfg
from oslo_db import options as db_options
import oslo_messaging as messaging
from paste import deploy

from vnfsvc.api.v2 import attributes
from vnfsvc.common import utils
from vnfsvc.openstack.common import log as logging
from vnfsvc import version
from vnfsvc.common import rpc as n_rpc
from vnfsvc.openstack.common.gettextutils import _

LOG = logging.getLogger(__name__)

core_opts = [
    cfg.StrOpt('bind_host', default='0.0.0.0',
               help=_("The host IP to bind to")),
    cfg.IntOpt('bind_port', default=9010,
               help=_("The port to bind to")),
    cfg.StrOpt('api_paste_config', default="api-paste.ini",
               help=_("The API paste config file to use")),
    cfg.StrOpt('api_extensions_path', default="",
               help=_("The path for API extensions")),
    cfg.StrOpt('policy_file', default="policy.json",
               help=_("The policy file to use")),
    cfg.StrOpt('auth_strategy', default='keystone',
               help=_("The type of authentication to use")),
    cfg.StrOpt('core_plugin',
               help=_("The core plugin Vnfsvc will use")),
    cfg.BoolOpt('allow_bulk', default=True,
                help=_("Allow the usage of the bulk API")),
    cfg.BoolOpt('allow_pagination', default=False,
                help=_("Allow the usage of the pagination")),
    cfg.BoolOpt('allow_sorting', default=False,
                help=_("Allow the usage of the sorting")),
    cfg.StrOpt('pagination_max_limit', default="-1",
               help=_("The maximum number of items returned in a single "
                      "response, value was 'infinite' or negative integer "
                      "means no limit")),
    cfg.StrOpt('host', default=utils.get_hostname(),
               help=_("The hostname Vnfsvc is running on")),
    cfg.StrOpt('nova_url',
               default='http://127.0.0.1:8774/v2',
               help=_('URL for connection to nova')),
    cfg.StrOpt('nova_admin_username',
               help=_('Username for connecting to nova in admin context')),
    cfg.StrOpt('nova_admin_password',
               help=_('Password for connection to nova in admin context'),
               secret=True),
    cfg.StrOpt('nova_admin_tenant_id',
               help=_('The uuid of the admin nova tenant')),
    cfg.StrOpt('nova_admin_auth_url',
               default='http://localhost:5000/v2.0',
               help=_('Authorization URL for connecting to nova in admin '
                      'context')),
    cfg.StrOpt('nova_ca_certificates_file',
               help=_('CA file for novaclient to verify server certificates')),
    cfg.BoolOpt('nova_api_insecure', default=False,
                help=_("If True, ignore any SSL validation issues")),
    cfg.StrOpt('nova_region_name',
               help=_('Name of nova region to use. Useful if keystone manages'
                      ' more than one region.')),
    cfg.IntOpt('send_events_interval', default=2,
               help=_('Number of seconds between sending events to nova if '
                      'there are any events to send.')),
]

core_cli_opts = [
    cfg.StrOpt('state_path',
               default='/var/lib/nfvsvc',
               help=_("Where to store NFV Service state files. "
                      "This directory must be writable by the agent.")),
]

# Register the configuration options
cfg.CONF.register_opts(core_opts)
cfg.CONF.register_cli_opts(core_cli_opts)

# Ensure that the control exchange is set correctly
messaging.set_transport_defaults(control_exchange='vnfsvc')
_SQL_CONNECTION_DEFAULT = 'sqlite://'
# Update the default QueuePool parameters. These can be tweaked by the
# configuration variables - max_pool_size, max_overflow and pool_timeout
db_options.set_defaults(cfg.CONF,
                        connection=_SQL_CONNECTION_DEFAULT,
                        sqlite_db='', max_pool_size=10,
                        max_overflow=20, pool_timeout=10)

def init(args, **kwargs):
    cfg.CONF(args=args, project='vnfsvc',
             version='%%prog %s' % version.version_info.release_string(),
             **kwargs)

    # FIXME(ihrachys): if import is put in global, circular import
    # failure occurs
    from vnfsvc.common import rpc as n_rpc
    n_rpc.init(cfg.CONF)

def setup_logging(conf):
    """Sets up the logging options for a log with supplied name.

    :param conf: a cfg.ConfOpts object
    """
    product_name = "vnfsvc"
    logging.setup(product_name)
    LOG.info(_("Logging enabled!"))

def load_paste_app(app_name):
    """Builds and returns a WSGI app from a paste config file.

    :param app_name: Name of the application to load
    :raises ConfigFilesNotFoundError when config file cannot be located
    :raises RuntimeError when application cannot be loaded from config file
    """

    config_path = cfg.CONF.find_file(cfg.CONF.api_paste_config)
    if not config_path:
        raise cfg.ConfigFilesNotFoundError(
            config_files=[cfg.CONF.api_paste_config])
    config_path = os.path.abspath(config_path)
    LOG.info(_("Config paste file: %s"), config_path)

    try:
        app = deploy.loadapp("config:%s" % config_path, name=app_name)
    except (LookupError, ImportError):
        msg = (_("Unable to load %(app_name)s from "
                 "configuration file %(config_path)s.") %
               {'app_name': app_name,
                'config_path': config_path})
        LOG.exception(msg)
        raise RuntimeError(msg)
    return app


INPUT = open("./input_files/input_10", "r").read().strip("\n")

class Light:
    def __init__(self, light: str):
        self.position_y = int(light[10:16])
        self.position_x = int(light[18:24])
        self.velocity_y = int(light[36:38])
        self.velocity_x = int(light[40:42])

    def move(self):
        self.position_x += self.velocity_x
        self.position_y += self.velocity_y

    def move_back(self):
        self.position_x -= self.velocity_x
        self.position_y -= self.velocity_y

def get_lights():
    return [Light(x) for x in INPUT.split("\n")]

LIGHTS = get_lights()

def run_1():
    second = 0
    width = None

    while True:
        min_x = 0
        max_x = 0
        min_y = 0
        max_y = 0
        for light in LIGHTS:
            light.move()
            min_x = min(min_x, light.position_x)
            max_x = max(max_x, light.position_x)
            min_y = min(min_y, light.position_y)
            max_y = max(max_y, light.position_y)
        second += 1
        new_width = max_x - min_x
        if width is None or new_width < width:
            width = new_width
        else:
            for light in LIGHTS:
                light.move_back()
            lights = [(light.position_x, light.position_y) for light in LIGHTS]
            for x in range(min_x, max_x + 1):
                line = list()
                for y in range(min_y, max_y + 1):
                    line.append("#" if (x, y) in lights else ".")
                print("".join(line))
            break
    return second - 1

print(run_1())


from logs import init_logs
init_logs.init()
#TODO:
#- Implement more advanced Counting Channels (Track several roles in one channel)
#- Split main.py into several files. probably utils.py, bot.py, commands.py, and maybe one file for every command
#-

from db import db
from events import events
from commands import commands as commands
import discord
from discord.ext import commands as discordCommands
from utils import config
from utils import utils

from logs.log import print
from DiscordOverrides.Bot import Bot

DEFAULT_PREFIX = config.DEFAULT_PREFIX
BOT_TOKEN = config.BOT_TOKEN
intents = discord.Intents.default()
# Intents.members is needed for the bot to be able to see what roles every member has
intents.members = True
# Intents.presences is needed for the bot to be able to see what members are online
intents.presences = True
def get_prefix(bot, message):
    return db.getPrefix(message.guild.id)

bot = Bot(command_prefix=get_prefix, intents=intents)

@bot.event
async def on_ready():
    global bot
    await events.on_ready(bot)

@bot.event
async def on_guild_join(guild):
    await events.on_guild_join(guild)

@bot.event
async def on_guild_leave(guild):
    await events.on_guild_leave(guild)

@bot.listen('on_message')
async def on_message(message):
    global bot
    await events.on_message(bot, message)

@bot.event
async def on_member_update(before, after):
    await events.on_member_update(before, after)

@bot.event
async def on_member_join(member):
    await events.on_member_join(member)

@bot.event
async def on_member_remove(member):
    await events.on_member_remove(member)

@bot.event
async def on_guild_channel_delete(channel):
    await events.on_guild_channel_delete(channel)

@bot.command(name="forceupdate", help="Forces an update to the Counting Channels in your guild")
async def forceUpdate(ctx):
    await commands.forceUpdate(ctx)

@bot.command(name="prefix", brief="Changes the bot's prefix", help=commands.prefixHelpText())
@discordCommands.has_permissions(manage_guild=True)
async def prefix(ctx, prefix):
    await commands.prefix(ctx, prefix)

@prefix.error
async def prefixError(ctx, error):
    await commands.prefixError(ctx, error)

@bot.command(name="create", brief="Creates a Counting Channel", help=commands.createHelpText())
@discordCommands.has_permissions(manage_channels=True)
async def create(ctx, name, role):
    await commands.create(ctx, name, role)

@create.error
async def createError(ctx, error):
    await commands.createError(ctx, error)

@bot.command(name="edit", brief="Changes what role a Counting Channel tracks", help=commands.editHelpText())
async def edit(ctx, name, role, newName):
    await commands.edit(ctx, name, role, newName)

@edit.error
async def editError(ctx, error):
    await commands.editError(ctx, error)

@bot.command(name="notify", brief="Signs your guild up for announcements about the bot's development and upcomming features", help=commands.notifyHelpText())
async def notify(ctx, channel):
    await commands.notify(ctx, channel)

@notify.error
async def notifyError(ctx, error):
    await commands.notifyError(ctx, error)
@bot.command(name="listchannels", help="Lists all the Counting Channels in your guild")
async def listChannels(ctx):
    await commands.listChannels(ctx)

@bot.command(name="listguilds", help="Debugging command - Lists all the guilds the bot is in")
@discordCommands.is_owner()
async def listGuilds(ctx):
    global bot
    await commands.listGuilds(ctx, bot)

@listGuilds.error
async def listGuildsError(ctx, error):
    await commands.listGuildsError(ctx, error)

@bot.command(name="listchannelsinallguilds", help="Debugging command - Lists all the channels in the guilds the bot is apart of")
@discordCommands.is_owner()
async def listChannelsInAllGuilds(ctx):
    global bot
    await commands.listChannelsInAllGuilds(ctx, bot)

@listChannelsInAllGuilds.error
async def listChannelsInAllGuildsError(ctx, error):
    await commands.listChannelsInAllGuildsError(ctx, error)

@bot.command(name="listroles", help="Lists all the roles in your guild, exists mostly for debugging")
async def listRoles(ctx):
    await commands.listRoles(ctx)

@listRoles.error
async def listRolesError(ctx, error):
    await commands.listRolesError(ctx, error)

@bot.command(name="repeat", help="Replies with what you typed")
async def repeat(ctx):
    await utils.printAndSend(ctx, "stat/help")

@repeat.error
async def repeatError(ctx, error):
    await utils.printAndSend(ctx ,error)

bot.run(BOT_TOKEN)


import matplotlib.pyplot as plt
import csv
import numpy as np

n=[]
temp=[]
humi=[]
ave_temp=[]
ave_humi=[]

with open('sensordata.txt','r') as csvfile:
    data=csv.reader(csvfile,delimiter=',')
    for row in data:
        n.append(int(row[0]))
        temp.append(int(row[1]))
        humi.append(int(row[2]))

mean_temp=int(np.mean(temp))
mean_humi=int(np.mean(humi))
ave_temp=[mean_temp]*10
ave_humi=[mean_humi]*10

plt.plot(n,temp,label='temperature')
plt.plot(n,humi,label='humidity')
plt.plot(n,ave_temp,label='mean temperature')
plt.plot(n,ave_humi,label='mean humidity')
plt.xlabel('last 10 samples, 2 sec intervals')
plt.ylabel('temperature in deg C & humidity in %')
plt.legend()
plt.show()


class Solution:
    def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
        string1 = ""
        string2 = ""
        for word in word1:
            string1 += "".join(word)
        for word in word2:
            string2 += "".join(word)
        if string1 == string2:
            return True
        return False


#!/usr/bin/env python3
import itertools

import utils

class Challenge(utils.BaseChallenge):
    def solve(self, _input, debug=False):
        """
        >>> Challenge().default_solve()
        375
        """
        return PathSet.from_paths_text(_input).get_black_count()

class PathSet:
    @classmethod
    def from_paths_text(cls, paths_text):
        """
        >>> PathSet.from_paths_text(
        ...     "sesenw\\n"
        ...     "neeene\\n"
        ...     "seswne\\n"
        ... )
        PathSet([Path(('se', 'se', 'nw')), Path(('ne', 'e', 'e', 'ne')),
            Path(('se', 'sw', 'ne'))])
        """
        non_emtpy_lines = filter(None, paths_text.splitlines())
        return cls(list(map(Path.from_path_text, non_emtpy_lines)))

    def __init__(self, paths):
        self.paths = paths

    def __repr__(self):
        return f"{type(self).__name__}({self.paths})"

    def get_black_count(self, start=(0, 0)):
        """
        >>> PathSet.from_paths_text(
        ...     "sesenwnenenewseeswwswswwnenewsewsw\\n"
        ...     "neeenesenwnwwswnenewnwwsewnenwseswesw\\n"
        ...     "seswneswswsenwwnwse\\n"
        ...     "nwnwneseeswswnenewneswwnewseswneseene\\n"
        ...     "swweswneswnenwsewnwneneseenw\\n"
        ...     "eesenwseswswnenwswnwnwsewwnwsene\\n"
        ...     "sewnenenenesenwsewnenwwwse\\n"
        ...     "wenwwweseeeweswwwnwwe\\n"
        ...     "wsweesenenewnwwnwsenewsenwwsesesenwne\\n"
        ...     "neeswseenwwswnwswswnw\\n"
        ...     "nenwswwsewswnenenewsenwsenwnesesenew\\n"
        ...     "enewnwewneswsewnwswenweswnenwsenwsw\\n"
        ...     "sweneswneswneneenwnewenewwneswswnese\\n"
        ...     "swwesenesewenwneswnwwneseswwne\\n"
        ...     "enesenwswwswneneswsenwnewswseenwsese\\n"
        ...     "wnwnesenesenenwwnenwsewesewsesesew\\n"
        ...     "nenewswnwewswnenesenwnesewesw\\n"
        ...     "eneswnwswnwsenenwnwnwwseeswneewsenese\\n"
        ...     "neswnwewnwnwseenwseesewsenwsweewe\\n"
        ...     "wseweeenwnesenwwwswnew\\n"
        ... ).get_black_count()
        10
        """
        flipped_destinations = self.get_flipped_destinations(start)
        return len(flipped_destinations)

    def get_flipped_destinations(self, start=(0, 0)):
        destinations = self.get_destinations(start)
        flip_counts = {
            destination: len(list(items))
            for destination, items in itertools.groupby(sorted(destinations))
        }
        return [
            destination
            for destination in destinations
            if flip_counts[destination] % 2 == 1
        ]

    def get_destinations(self, start=(0, 0)):
        """
        >>> PathSet.from_paths_text(
        ...     "sesenwnenenewseeswwswswwnenewsewsw\\n"
        ...     "neeenesenwnwwswnenewnwwsewnenwseswesw\\n"
        ...     "seswneswswsenwwnwse\\n"
        ...     "nwnwneseeswswnenewneswwnewseswneseene\\n"
        ...     "swweswneswnenwsewnwneneseenw\\n"
        ...     "eesenwseswswnenwswnwnwsewwnwsene\\n"
        ...     "sewnenenenesenwsewnenwwwse\\n"
        ...     "wenwwweseeeweswwwnwwe\\n"
        ...     "wsweesenenewnwwnwsenewsenwwsesesenwne\\n"
        ...     "neeswseenwwswnwswswnw\\n"
        ...     "nenwswwsewswnenenewsenwsenwnesesenew\\n"
        ...     "enewnwewneswsewnwswenweswnenwsenwsw\\n"
        ...     "sweneswneswneneenwnewenewwneswswnese\\n"
        ...     "swwesenesewenwneswnwwneseswwne\\n"
        ...     "enesenwswwswneneswsenwnewswseenwsese\\n"
        ...     "wnwnesenesenenwwnenwsewesewsesesew\\n"
        ...     "nenewswnwewswnenesenwnesewesw\\n"
        ...     "eneswnwswnwsenenwnwnwwseeswneewsenese\\n"
        ...     "neswnwewnwnwseenwseesewsenwsweewe\\n"
        ...     "wseweeenwnesenwwwswnew\\n"
        ... ).get_destinations()
        [(-2, 2), (-1, -3), (-2, 3), ...]
        """
        return [
            path.get_destination(start)
            for path in self.paths
        ]

class Path:
    DIRECTION_OFFSETS = {
        0: {
            'e': (1, 0),
            'se': (0, 1),
            'ne': (0, -1),
            'w': (-1, 0),
            'nw': (-1, -1),
            'sw': (-1, 1),
        },
        1: {
            'e': (1, 0),
            'se': (1, 1),
            'ne': (1, -1),
            'w': (-1, 0),
            'nw': (0, -1),
            'sw': (0, 1),
        },
    }
    INSTRUCTIONS = sorted(DIRECTION_OFFSETS[0])

    @classmethod
    def from_path_text(cls, path_text):
        """
        >>> Path.from_path_text("esenee")
        Path(('e', 'se', 'ne', 'e'))
        """
        instruction_path = ()
        while path_text:
            instruction = path_text[:2]
            if instruction not in cls.DIRECTION_OFFSETS[0]:
                instruction = path_text[:1]
                if instruction not in cls.DIRECTION_OFFSETS[0]:
                    raise Exception(
                        f"Unknown instruction '{instruction}', expected one "
                        f"of {', '.join(cls.INSTRUCTIONS)}")
            instruction_path += (instruction,)
            path_text = path_text[len(instruction):]

        return cls(instruction_path)

    @classmethod
    def add(cls, lhs, rhs):
        """
        >>> Path.add((0, 0), (0, 0))
        (0, 0)
        >>> Path.add((1, -2), (-3, 4))
        (-2, 2)
        """
        l_x, l_y = lhs
        r_x, r_y = rhs

        return l_x + r_x, l_y + r_y

    def __init__(self, direction_path):
        self.direction_path = direction_path

    def __repr__(self):
        return f"{type(self).__name__}({self.direction_path})"

    def get_destination(self, start=(0, 0)):
        """
        >>> Path.from_path_text("").get_destination()
        (0, 0)
        >>> Path.from_path_text("esenee").get_destination()
        (3, 0)
        >>> Path.from_path_text("esew").get_destination()
        (0, 1)
        >>> Path.from_path_text("nwwswee").get_destination()
        (0, 0)
        """
        position = start
        for instruction in self.direction_path:
            position = self.get_neighbour(position, instruction)

        return position

    @classmethod
    def get_neighbours(cls, position):
        return [
            cls.get_neighbour(position, instruction)
            for instruction in cls.INSTRUCTIONS
        ]

    @classmethod
    def get_neighbour(cls, position, instruction):
        _, y = position
        offset = cls.DIRECTION_OFFSETS[y % 2][instruction]
        position = cls.add(position, offset)

        return position

Challenge.main()
challenge = Challenge()


import random

print("Welcome to Guess the Number!")
print("The rules are simple. I will think of a number, and you will try to guess it.")
# asking user to enter a number from 1 to 10
# generating a random number from 1 to 10
number = random.randint(1,10)

isGuessRight = False
while isGuessRight != True:
    guess = input("Guess a number between 1 and 10: ")
    if int(guess) == number:
        print("You guessed {}. That is correct! You win!".format(guess))
        # If the user has guessed the correct answer, exit the loop.
        isGuessRight = True
    else:
        # If the user has not guessed the correct answer, enter the loop.
        print("You guessed {}. Sorry, that isn’t it. Try again.".format(guess))


#!/usr/bin/python3
"""Defines class Square with private attribute size"""

class Square:
    """
    Arguments:
        size: size of Square
    """
    def __init__(self, size=0):
        if type(size) is not int:
            raise TypeError("size must be an integer")
        elif size < 0:
            raise ValueError("size must be >= 0")
        self.__size = size


#!/usr/bin/python3
# The python command server is actually located in bukkit/src/main/resources/cmdsvr
# Here we just start it with appropiate environment

import os
import sys
from os.path import abspath, dirname, join
from argparse import ArgumentParser
from subprocess import Popen

parent_dir = dirname(dirname(dirname(abspath(__file__))))
server_dir = join("bukkit", "src", "main", "resources", "cmdsvr")
server_path = join(parent_dir, server_dir, "pycmdsvr.py")
parser = ArgumentParser()
parser.add_argument("--apihost", default="localhost", help="api host")
parser.add_argument("--apiport", default="4711", help="api port")
parser.add_argument("--svrhost", default="localhost", help="server host")
parser.add_argument("--svrport", default="4731", help="server port")
args = parser.parse_args()
env = {"PYTHONHASHSEED": "6666",
       "JRP_API_HOST": args.apihost,
       "JRP_API_PORT": args.apiport,
       "JRP_CMDSVR_HOST": args.svrhost,
       "JRP_CMDSVR_PORT": args.svrport}
if "SYSTEMROOT" in os.environ:
    env['SYSTEMROOT'] = os.environ['SYSTEMROOT']

print("Python:", sys.executable)
print("cmdsvr:", server_path)
Popen([sys.executable, server_path], env=env)


import cv2
import numpy as np
from config import *

def ReadImg(path):
    return np.array(cv2.cvtColor(cv2.imread(path.strip()), code=cv2.COLOR_RGB2BGR))

# http://docs.opencv.org/3.1.0/d5/daf/tutorial_py_histogram_equalization.html
def AdaptiveThresholding(img):
    clahe = cv2.createCLAHE()
    return clahe.apply(img)

def abs_sobel_thresh(img, orient='x', thresh=(0, 255)):
    # Apply the following steps to img
    # 1) Convert to grayscale
    # 2) Take the derivative in x or y given orient = 'x' or 'y'
    # 3) Take the absolute value of the derivative or gradient
    # 4) Scale to 8-bit (0 - 255) then convert to type = np.uint8
    # 5) Create a mask of 1's where the scaled gradient magnitude
            # is > thresh_min and < thresh_max
    # 6) Return this mask as your binary_output image
    gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

    if orient == 'x':
        abs_sobel = np.absolute(cv2.Sobel(gray, cv2.CV_64F, 1, 0))
    else:
        abs_sobel = np.absolute(cv2.Sobel(gray, cv2.CV_64F, 0, 1))

    scaled_sobel = np.uint8(255*abs_sobel/np.max(abs_sobel))
    binary_output = np.zeros_like(scaled_sobel)
    binary_output[(scaled_sobel >= thresh[0]) & (scaled_sobel <= thresh[1])] = 1
    return binary_output

def mag_thresh(img, sobel_kernel=3, mag_thresh=(0, 255)):

    # Apply the following steps to img
    # 1) Convert to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

    # 2) Take the gradient in x and y separately
    sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)
    sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)

    # 3) Calculate the magnitude
    gradmag = np.sqrt(sobelx**2 + sobely**2)

    # Rescale to 8 bit
    gradmag = (255*gradmag/np.max(gradmag)).astype(np.uint8)

    # Create a binary image of ones where threshold is met, zeros otherwise
    binary_output = np.zeros_like(gradmag)
    binary_output[(gradmag >= mag_thresh[0]) & (gradmag <= mag_thresh[1])] = 1
    return binary_output

def dir_threshold(img, sobel_kernel=3, thresh=(0, np.pi/2)):

    # Apply the following steps to img
    # 1) Convert to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

    # 2) Take the gradient in x and y separately
    sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)
    sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)

    # 3) Take the absolute value of the x and y gradients
    abs_sobelx = np.absolute(sobelx)
    abs_sobely = np.absolute(sobely)
    # 4) Use np.arctan2(abs_sobely, abs_sobelx) to calculate the direction of the gradient
    gradir = np.arctan2(abs_sobely, abs_sobelx)
    # 5) Create a binary mask where direction thresholds are met
    binary_output = np.zeros_like(gradir)
    binary_output[(gradir >= thresh[0]) & (gradir <= thresh[1])] = 1
    # 6) Return this mask as your binary_output image
    return binary_output

def color_threshold(img, sthreshold=(100, 255), vthreshold=(50, 255)):
    img = np.copy(img)
    hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)
    s_channel = hls[:,:,2]

    sbinary = np.zeros_like(s_channel)
    sbinary[(s_channel > sthreshold[0]) & (s_channel <= sthreshold[1])] = 1

    hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
    v_channel = hsv[:, :, 2]
    vbinary = np.zeros_like(v_channel)
    vbinary[(v_channel > vthreshold[0]) & (v_channel <= vthreshold[1])] = 1

    output = np.zeros_like(s_channel)
    output[(sbinary == 1) & (vbinary == 1)] = 1
    return output

class Polyfit():

    def __init__(self):
        self.fit_intercept = []

    def fit(self, X, y):
        self.fit_intercept = np.polyfit(X, y, 2)

    def predict(self, y):
        return np.array(self.fit_intercept[0]*y*y + self.fit_intercept[1]*y + self.fit_intercept[2], np.int32)

def window_mask(width, height, img_ref, center, level):
    output = np.zeros_like(img_ref)
    output[int(img_ref.shape[0]-(level+1)*height):int(img_ref.shape[0]-level*height),max(0,int(center-width/2)):min(int(center+width/2),img_ref.shape[1])] = 1
    return output

"""
Tested src/dst
src = np.float32([[590, 450], [750, 450], [1225, 700], [200, 700]])
src = np.float32([[560, 470], [790, 470], [1150, 700], [260, 700]])
src = np.float32([[590, 470], [790, 470], [1190, 700], [260, 700]])
src = np.float32([[(img_size[0] / 2) - 55, img_size[1] / 2 + 100],[((img_size[0] / 6) - 10), img_size[1]],[(img_size[0] * 5 / 6) + 60, img_size[1]],[(img_size[0] / 2 + 55), img_size[1] / 2 + 100]])
dst = np.float32([[(img_size[0] / 4), 0],[(img_size[0] / 4), img_size[1]],[(img_size[0] * 3 / 4), img_size[1]],[(img_size[0] * 3 / 4), 0]])
"""
def Warp(img, src, dst):
    img_size = (img.shape[1], img.shape[0])
    offset = 260
    src = np.float32([[590, 470], [750, 470], [1190, 700], [260, 700]])
    dst = np.float32([[offset, 0], [img_size[0]-offset, 0], [img_size[0]-offset, img_size[1]], [offset, img_size[1]]])
    M = cv2.getPerspectiveTransform(src, dst)
    Minv = cv2.getPerspectiveTransform(dst, src)
    warpedImage = cv2.warpPerspective(img, M, img_size, flags=cv2.INTER_LINEAR)

    return (warpedImage, M, Minv)

def region_of_interest(img, vertices):
    """
    Applies an image mask.

    Only keeps the region of the image defined by the polygon
    formed from `vertices`. The rest of the image is set to black.
    """
    #defining a blank mask to start with
    mask = np.zeros_like(img)

    #defining a 3 channel or 1 channel color to fill the mask with depending on the input image
    if len(img.shape) > 2:
        channel_count = img.shape[2]  # i.e. 3 or 4 depending on your image
        ignore_mask_color = (255,) * channel_count
    else:
        ignore_mask_color = 255

    #filling pixels inside the polygon defined by "vertices" with the fill color
    cv2.fillPoly(mask, vertices, ignore_mask_color)

    #returning the image only where mask pixels are nonzero
    masked_image = cv2.bitwise_and(img, mask)
    return masked_image


from selenium import webdriver
from selenium.webdriver.common.keys import Keys#导入的键盘
import time
#可能需要手动添加路径
chromedriverAddress = r"C:\Users\lenovo1\AppData\Local\Programs\Python\Python37\Lib\site-packages\selenium\webdriver\chrome\chromedriver.exe"
driver = webdriver.Chrome(executable_path=chromedriverAddress)
#写这一行的时候报错了，可见这里配置：https://blog.csdn.net/weixin_43746433/article/details/95237254

url = "http://www.baidu.com"
driver.get(url)
text1 = driver.find_element_by_id("wrapper").text#得到这个元素的值
print(text1)
print(driver.title)
#得到页面的快照
driver.save_screenshot("index,png")

driver.find_element_by_id("kw").send_keys(u"大熊猫")#向这个id输入“大熊猫”（实际上这里的kw的id就是查找的字段）
driver.find_element_by_id("su").click()#点击操作（实际上就是上一步键入信息，下一步我们进行检索）
time.sleep(5)
driver.save_screenshot("daxiongmao.png")
#获取当前界面的cookie
print(driver.get_cookies())
#模拟输入两个按键ctrl+a
driver.find_element_by_id("kw").send_keys(Keys.CONTROL,'a')
#模拟ctrl + x,剪切操作
driver.find_element_by_id("kw").send_keys(Keys.CONTROL,'x')
driver.find_element_by_id("kw").send_keys(u"航空母舰")
driver.save_screenshot("hangmu.png")
driver.find_element_by_id("su").send_keys(Keys.RETURN)
time.sleep(5)
driver.save_screenshot("hangmu2.png")
#清空输入框,clear
driver.find_element_by_id("kw").clear()

#关闭浏览器
driver.quit()


import streamlit as st
import pandas as pd
import time
import plotly.graph_objs as go

#
# ページのセッティング
#
st.set_page_config(
    page_title="Streamlit Examples",
    page_icon="🧊",
    layout="wide",
    initial_sidebar_state="expanded",
    menu_items={
        'Get Help': 'https://www.extremelycoolapp.com/help',
        'Report a bug': "https://www.extremelycoolapp.com/bug",
        'About': "# This is a header. This is an *extremely* cool app!"
    }
)

def mainview():
    st.markdown("# Streamlit Examples Demo")

    # -------------------------------------------------------
    # タイトルとテキストの表示
    # -------------------------------------------------------
    st.markdown("## 文字表示")
    st.markdown("""
    markdownでテキストやヘッダを記述することができます．markdown以外にもタイトルの表示には
    `st.title()`，テキストの表示には`st.write()`を使うことができます．
    `st.write()`はテキスト以外にもデータフレームや数値など様々な形式を汎用的に扱えます．

    markdownでのコードブロックの表示や数式の表示にも対応しています．
    ```python
    print("Hello World")
    ```
    $$
    e^{i \pi} + 1 = 0
    $$

    コードは`st.code()`，数式は`st.latex()`でも表示可能です．また，`st.echo()`を用いると
    コードを実行しつつ表示することが可能です．
    """)

    st.markdown("## メッセージの装飾")
    st.info('This is a purely informational message')
    st.warning('This is a warning')
    st.error('This is an error')
    st.success('This is a success message!')
    e = RuntimeError('This is an exception of type RuntimeError')
    st.exception(e)

    #
    # multipage
    #
    st.markdown("## multipage")

if __name__ == "__main__":
    mainview()