from ht16k33 import HT16K33, HT16K33Error

class HT16K337Segment(HT16K33):
    """Library for 4x7-segment display powered by HT16K33 multiplexer."""

    DOT = 0x80

    @staticmethod
    def _num2hex(number):
        num = str(number)
        if num == '0':
            return 0x3f
        elif num == '1':
            return 0x06
        elif num == '2':
            return 0x5b
        elif num == '3':
            return 0x4f
        elif num == '4':
            return 0x66
        elif num == '5':
            return 0x6d
        elif num == '6':
            return 0x7d
        elif num == '7':
            return 0x07
        elif num == '8':
            return 0x7f
        elif num == '9':
            return 0x6f
        elif num == '10' or num == 'a' or num == 'A':
            return 0x77
        elif num == '11' or num == 'b' or num == 'B':
            return 0x7c
        elif num == '12' or num == 'c' or num == 'C':
            return 0x39
        elif num == '13' or num == 'd' or num == 'D':
            return 0x5e
        elif num == '14' or num == 'e' or num == 'E':
            return 0x79
        elif num == '15' or num == 'f' or num == 'F':
            return 0x71
        return 0x00

    def __init__(self, address=0x70, bus=None):
        """Create object representing 7 segment display."""
        super().__init__(address, bus)

    def write_buffer(self, data, update=True):
        """Write whole buffer (List with 5 16-bit numbers)."""
        data = data + [0x0000] * 3
        super().write_buffer(data, update)

    def write_digit(self, position, digit, dot=False, update=True):
        register = [0,1,3,4][position]
        if dot:
            data = self._num2hex(digit) | self.DOT
        else:
            data = self._num2hex(digit)
        self.write_word(register, data, update)

    def colon(self, on=True, update=True):
        if on:
            self.write_word(2, 0x02, update)
        else:
            self.write_word(2, 0x00, update)


from MeltModelJupyter import Model
import numpy as np

# Calculating initial du for different mass/entropy combinations
Init_du = np.zeros(shape=(11,11))
massT = np.zeros(shape=(11))
Init_Mass = 3.1023287

for mass in np.arange(11):
    print('Mass:', Init_Mass*(1+mass/5), '\nEntropy:',end=' ')
    for ent in np.arange(11):
        print(ent*206+1100,end=' ',flush=True)
        initM = Model(Mtotal=Init_Mass*(1+mass/5), gamma=1e-9, vel=1.0, entropy0=(1100+206*ent), impact_angle=90); initRun=initM.run_model()
        mantM = np.sum(initM.radiusPlanet**3*initM.dv.T*initM.rho) # mass of mantle from density * volume *
        Init_du[ent][mass] = np.sum(initM.radiusPlanet**3*initM.dv*(initM.du.T*initM.rho).T)*1e5/mantM
    print('\n')

with open ('Init_du.dat','w') as f:
    print('Init_Mass\n',str(Init_Mass),'\nInit_du # [Ent][Mass]',file=f)
    [[print(round(y,2), end=' ',file=f) for y in x] and print('',file=f) for x in Init_du]


def solution(n, arr1, arr2):
    answer = []
    arr1_bin = []
    arr2_bin = []
    final_list = ["" for _ in range(n)]

    for i in range(n):
        b = ""
        while(arr1[i] != 0):
            b += str(arr1[i] % 2)
            arr1[i] //= 2
        for j in range(n-len(b)):
            b += "0"
        arr1_bin.append(''.join(reversed(b)))

    for i in range(n):
        b = ""
        while(arr2[i] != 0):
            b += str(arr2[i] % 2)
            arr2[i] //= 2
        for j in range(n-len(b)):
            b += "0"
        arr2_bin.append(''.join(reversed(b)))

    for i in range(n):
        for j in range(n):
            if arr1_bin[i][j] == '1' or arr2_bin[i][j] == "1":
                final_list[i]+= "#"
            else:
                final_list[i] += " "

    return final_list

solution(6, [46, 33, 33 ,22, 31, 50], [27 ,56, 19, 14, 14, 10])


from pathlib import Path

from database import THUMBNAIL_DIR, Category, Item, Tag, get_db
from fastapi import Depends, FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from sqlalchemy.orm import Session

app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/")
def get_root():
    return "Hello! This is FastAPI!"

@app.get("/items")
def read_items(db: Session = Depends(get_db)):
    items = db.query(Item).all()
    return items[:60]

@app.get("/categories")
def read_categories(db: Session = Depends(get_db)):
    categories = db.query(Category).all()
    return categories[:60]

@app.get("/tags")
def read_tags(db: Session = Depends(get_db)):
    tags = db.query(Tag).all()
    return tags[:60]

@app.get("/item/thumbnail/{uid}")
def get_thumbnail(uid: str, db: Session = Depends(get_db)):
    row = db.query(Item.thumbnail_path).filter(Item.uid == uid).first()
    if row is None:
        return
    thumbnail_path = Path(THUMBNAIL_DIR) / Path(row.thumbnail_path)
    if thumbnail_path.exists():
        return FileResponse(thumbnail_path)


import requests
import os
def getPages():#只能得到30张图片，想得到更多图片，需要变化params['pn']的值。
    headers={'User-Agent':"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.134 Safari/537.36 Edg/103.0.1264.77"}
    url='https://image.baidu.com/search/acjson'
    #追加请求内容（负载）
    params={
        'tn':'resultjson_com',
        'logid':'5336511566462226640',
        'ipn':'rj',
        'ct':'201326592',
        'is':' ',
        'fp':'result',
        'fr':' ',
        'word':'戴帽子的人',
        'cg':'girl',
        'queryWord':'戴帽子的人',
        'cl':'2',
        'lm':'-1',
        'ie':'utf-8',
        'oe':'utf-8',
        'adpicid':' ',
        'st':' ',
        'z':' ',
        'ic':' ',
        'hd':' ',
        'latest':' ',
        'copyright':' ',
        's':' ',
        'se':' ',
        'tab':' ',
        'width':' ',
        'height':' ',
        'face':' ',
        'istype':' ',
        'qc':' ',
        'nc':'1',
        'expermode':' ',
        'nojc':' ',
        'isAsync':' ',
        'pn':'0',
        'rn':'15',
        'gsm':'1e',
        '1660570401395':' '
        }
    res=requests.get(url=url,headers=headers,params=params)
    # print(res.json())
    data=res.json()['data']
    # print(data)
    #得到所有图片地址
    urlPages=[]
    for i in data:
        if i.get('thumbURL') !=None:
            urlPages.append(i['thumbURL'])
    # print(urlPages)
    #检测文件夹是否存在
    dir='./baidu'
    if not os.path.exists(dir):
        os.mkdir(dir)#创建目录方法
    #向每个图片url发起请求
    x=0
    for o in urlPages:
        print('下载成功')
        res=requests.get(url=o,headers=headers)
        #下载到dir文件夹
        open(f'{dir}/{x}.jpg','wb').write(res.content)
        x+=1
getPages()


#######################
# Fix import issues   #
import sys            #
sys.path.append(".")  #
sys.path.append("..") #
#######################

import numpy as np
import matplotlib.pyplot as plt

import src.produce_occupancy_grid as produce_occupancy_grid
import src.utils as utils
import src.visualization as visualization
import src.dataloader as dataloader

odometry, lidar_points = dataloader.parse_lcm_log("./data/lab_maze", load_images=False)

start = 10
cell_width = 0.05
og, (min_x, min_y) = produce_occupancy_grid.produce_occupancy_grid(odometry[:start], lidar_points[:start], cell_width, min_width=10, min_height=10)

fig, ax = plt.subplots()
visualization.draw_occupancy_grid(ax, og, cell_size=cell_width, origin_location=np.array([min_x, min_y]))
plt.draw()
plt.pause(0.001)

skip = 10
for i in range(start, len(odometry), skip):
	og = produce_occupancy_grid.update_occupancy_grid(og, odometry[i:i+skip], lidar_points[i:i+skip], cell_width, min_x, min_y)
	visualization.draw_occupancy_grid(ax, og, cell_size=cell_width, origin_location=np.array([min_x, min_y]))
	visualization.draw_path(ax, odometry[:i+skip])
	plt.draw()
	plt.pause(0.001)


from Person import Person,Student,Lecturer
def main():
    LQT=Student('Lê Quang Trung',1,'0898167571',13,1)
    DTNM=Student('Đặng Thái Nhật Minh',1,'09901238',23,1)
    PTLN=Lecturer('Phạm Thị Lê Na',2,"071231223",10,3)
    print(LQT.outputStudent())
    print(DTNM.outputStudent())
    print(PTLN.outputLecturer())
if __name__=='__main__':
    main()


import mediapipe as mp
import numpy as np
import pandas as pd
import cv2
import csv
import os
from helpers import get_coordinates, get_handedness, draw_normalized_coordinates, pre_process_hand_landmarks, get_args

# Object that let us draw landmarks in our image
mp_drawing = mp.solutions.drawing_utils

# Object with all hand tracking methods of mediapipe
mp_hands = mp.solutions.hands

# The cv2.VideoCapture needs an number representing which device will be used
# if the program does not work for you, try specifying a device other than 0
args = get_args()
device = args.device
# Object that reads from the webcam
cap = cv2.VideoCapture(device)

# Get the width and height so we can draw on the image using opencv
video_width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
video_height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)

# Hand gesture label map
gesture_label = pd.read_csv('data/gesture-label.csv', encoding = 'latin1')

with mp_hands.Hands(
    static_image_mode=False,
    max_num_hands=2,
    model_complexity=1,
    min_detection_confidence=0.8,
    min_tracking_confidence=0.5
) as hands:
    while cap.isOpened():
        # cap.read() return two variables, the 'results' which is a boolean
        # identifying if the image was read and the frame that is a cv2 image
        # object of the frame captured
        ret, frame = cap.read()

        # Before processing our image with mediapipe is necessary to convert it
        # from BGR to RGB, because mediapipe works with RGB and opencv with BGR
        image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

        # Flip on horizontal so the lib detects correct handness
        image = cv2.flip(image, 1)

        # Setting the writable flag to false before process with mediapipe leads
        # to improvement in the performance
        image.flags.writeable = False

        # Do the actual processing with the mediapipe lib
        results = hands.process(image)

        # Setting back the flag of writable so we can draw in the image
        image.flags.writeable = True

        # Writing that is waiting for the key to save the coordinates
        image = cv2.putText(
            img = image,
            text = 'Press a number from 0 to 9 to save gesture data',
            org = (50,50), #coordinates
            fontFace = cv2.FONT_HERSHEY_SIMPLEX,
            fontScale = 0.5,
            color = (0, 0, 0), #RGB
            thickness = 2,
            lineType = cv2.LINE_AA
        )

        # Drawing landmarks to the image
        ## If any hand was detected
        if results.multi_hand_landmarks:
            # The enumerate is used to multi hand detection, the hand variable
            # is basically all the landmarks from one hand
            for hand_index, hand_landmarks in enumerate(results.multi_hand_landmarks):

                # Get handedness label
                handedness_label = get_handedness(
                    hand_index = hand_index,
                    results = results
                )

                # Drawing handedness on the wrist
                image = cv2.putText(
                            img = image,
                            text = handedness_label,
                            org = get_coordinates('WRIST', hand_index, results, video_width, video_height), #coordinates
                            fontFace = cv2.FONT_HERSHEY_SIMPLEX,
                            fontScale = 0.8,
                            color = (255, 255, 255), #RGB
                            thickness = 2,
                            lineType = cv2.LINE_AA
                        )

                # Pre process the hand landmarks coordinates
                processed_hand_landmarks = pre_process_hand_landmarks(hand_index, results, video_width, video_height)

                # Draw the pre-processed coordinates according to the joint list
                joint_list = ['INDEX_FINGER_TIP','THUMB_TIP', 'MIDDLE_FINGER_TIP', 'RING_FINGER_TIP', 'PINKY_TIP']
                coordinates = []
                normalized_coordinates = []
                for joint in joint_list:
                    coordinates.append(
                        get_coordinates(
                            joint,
                            hand_index,
                            results,
                            video_width,
                            video_height
                        )
                    )
                    joint_index = mp_hands.HandLandmark[joint].numerator
                    normalized_coordinates.append(
                        tuple(processed_hand_landmarks[(joint_index*2):((joint_index*2)+2)])
                    )

                normalized_coordinates = np.around(normalized_coordinates,2)

                image = draw_normalized_coordinates(
                    image = image,
                    coordinates = coordinates,
                    normalized_coordinates = normalized_coordinates
                )

                # Utility used to draw the image based on the landmark values
                mp_drawing.draw_landmarks(
                    image = image,
                    landmark_list = hand_landmarks,
                    connections = mp_hands.HAND_CONNECTIONS,
                    landmark_drawing_spec = mp_drawing.DrawingSpec(
                                                color = (1, 190, 255),
                                                thickness = 2,
                                                circle_radius = 4
                                            ),
                    connection_drawing_spec = mp_drawing.DrawingSpec(
                                                color = (86, 213, 0),
                                                thickness = 2,
                                                circle_radius = 2
                                            )
                )

        # Converting it back to BGR so we can display using opencv
        image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)

        # Display the output frame of the webcam
        cv2.imshow('Hand Tracking', image)

        # - If 'q' is pressed the window is closed;
        # - If 'e' is pressed all training data will be erased;
        # - If a number from 0 to 9 is pressed then the coordinates
        #   will be saved  in the training sv file with those coordinates
        #   associated to the number label pressed.
        key = cv2.waitKey(10)
        if key==ord('q'):
            break
        if key==ord('e'):
            os.remove('training-data.csv')
        if key>=ord('0') and key<=ord('9'):
            # Create the headers of the csv with the joint landmark names
            headers = ['gesture_id']
            for joint in mp_hands.HandLandmark:
                headers.append(joint.name.lower()+'_x')
                headers.append(joint.name.lower()+'_y')

            if not os.path.exists('data'):
                os.makedirs('data')
            with open('data/training-data.csv','a',newline='') as file:
                writer = csv.writer(file)
                row = np.append(int(chr(key)),processed_hand_landmarks)
                # If file was created from scratch, append header. If not,
                # only append row
                if file.tell()==0:
                    writer.writerow(headers)
                    writer.writerow(row)
                else:
                    writer.writerow(row)

            # Erase the coordinates after saving it, to avoid write duplicate data
            # when no hand be captured by the video
            processed_hand_landmarks = None

            try:
                label = gesture_label.loc[gesture_label[gesture_label.Label==int(chr(key))].index[0],'Gesture']
                print(f'Gesture saved to label {label}')
            except:
                print(f'No label detected. Update the "gesture-label.csv" file with the label of "{chr(key)}".')

cap.release()
# Destroy all the windows
cv2.destroyAllWindows()


# coding: utf-8

from __future__ import absolute_import
from datetime import date, datetime  # noqa: F401

from typing import List, Dict  # noqa: F401

from tagbase_server.models.base_model_ import Model
from tagbase_server import util

class Tag200Tag(Model):
    """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).

    Do not edit the class manually.
    """

    def __init__(
        self,
        date_time=None,
        filename=None,
        submission_id=None,
        tag_id=None,
        version=None,
    ):  # noqa: E501
        """Tag200Tag - a model defined in OpenAPI

        :param date_time: The date_time of this Tag200Tag.  # noqa: E501
        :type date_time: str
        :param filename: The filename of this Tag200Tag.  # noqa: E501
        :type filename: str
        :param submission_id: The submission_id of this Tag200Tag.  # noqa: E501
        :type submission_id: int
        :param tag_id: The tag_id of this Tag200Tag.  # noqa: E501
        :type tag_id: int
        :param version: The version of this Tag200Tag.  # noqa: E501
        :type version: str
        """
        self.openapi_types = {
            "date_time": str,
            "filename": str,
            "submission_id": int,
            "tag_id": int,
            "version": str,
        }

        self.attribute_map = {
            "date_time": "date_time",
            "filename": "filename",
            "submission_id": "submission_id",
            "tag_id": "tag_id",
            "version": "version",
        }

        self._date_time = date_time
        self._filename = filename
        self._submission_id = submission_id
        self._tag_id = tag_id
        self._version = version

    @classmethod
    def from_dict(cls, dikt) -> "Tag200Tag":
        """Returns the dict as a model

        :param dikt: A dict.
        :type: dict
        :return: The Tag200_tag of this Tag200Tag.  # noqa: E501
        :rtype: Tag200Tag
        """
        return util.deserialize_model(dikt, cls)

    @property
    def date_time(self):
        """Gets the date_time of this Tag200Tag.

        Local datetime stamp at the time of eTUFF tag data file ingestion  # noqa: E501

        :return: The date_time of this Tag200Tag.
        :rtype: str
        """
        return self._date_time

    @date_time.setter
    def date_time(self, date_time):
        """Sets the date_time of this Tag200Tag.

        Local datetime stamp at the time of eTUFF tag data file ingestion  # noqa: E501

        :param date_time: The date_time of this Tag200Tag.
        :type date_time: str
        """

        self._date_time = date_time

    @property
    def filename(self):
        """Gets the filename of this Tag200Tag.

        Full name and extension of the ingested eTUFF tag data file  # noqa: E501

        :return: The filename of this Tag200Tag.
        :rtype: str
        """
        return self._filename

    @filename.setter
    def filename(self, filename):
        """Sets the filename of this Tag200Tag.

        Full name and extension of the ingested eTUFF tag data file  # noqa: E501

        :param filename: The filename of this Tag200Tag.
        :type filename: str
        """

        self._filename = filename

    @property
    def submission_id(self):
        """Gets the submission_id of this Tag200Tag.

        Unique numeric ID assigned upon submission of a tag eTUFF data file for ingest/importation into Tagbase  # noqa: E501

        :return: The submission_id of this Tag200Tag.
        :rtype: int
        """
        return self._submission_id

    @submission_id.setter
    def submission_id(self, submission_id):
        """Sets the submission_id of this Tag200Tag.

        Unique numeric ID assigned upon submission of a tag eTUFF data file for ingest/importation into Tagbase  # noqa: E501

        :param submission_id: The submission_id of this Tag200Tag.
        :type submission_id: int
        """

        self._submission_id = submission_id

    @property
    def tag_id(self):
        """Gets the tag_id of this Tag200Tag.

        Unique numeric Tag ID associated with the ingested tag eTUFF data file  # noqa: E501

        :return: The tag_id of this Tag200Tag.
        :rtype: int
        """
        return self._tag_id

    @tag_id.setter
    def tag_id(self, tag_id):
        """Sets the tag_id of this Tag200Tag.

        Unique numeric Tag ID associated with the ingested tag eTUFF data file  # noqa: E501

        :param tag_id: The tag_id of this Tag200Tag.
        :type tag_id: int
        """

        self._tag_id = tag_id

    @property
    def version(self):
        """Gets the version of this Tag200Tag.

        Version identifier for the eTUFF tag data file ingested  # noqa: E501

        :return: The version of this Tag200Tag.
        :rtype: str
        """
        return self._version

    @version.setter
    def version(self, version):
        """Sets the version of this Tag200Tag.

        Version identifier for the eTUFF tag data file ingested  # noqa: E501

        :param version: The version of this Tag200Tag.
        :type version: str
        """

        self._version = version


import json
from typing import Optional, List
from pydantic import parse_raw_as
from pydantic.json import pydantic_encoder
from aioredis import Redis
from elasticsearch import AsyncElasticsearch, NotFoundError
from fastapi import Query

from core.config import ProjectSettings
from models.base_model import BaseModel

class BaseService:
    def __init__(self, redis: Redis, elastic: AsyncElasticsearch):
        self.redis = redis
        self.elastic = elastic
        self.model = BaseModel

    async def get_by_id(self, es_index: str, data_id: str) -> Optional[BaseModel]:
        data = await self._data_from_cache(f'{es_index}::data_id::{data_id}')
        if not data:
            data = await self._get_from_elastic(es_index, data_id)
            if not data:
                return None
            await self._put_data_to_cache(f'{es_index}::data_id::{data_id}', data)
        return data

    async def _get_from_elastic(self, es_index: str, data_id: str) -> Optional[BaseModel]:
        try:
            doc = await self.elastic.get(es_index, data_id)
        except NotFoundError:
            return None
        return self.model(**doc['_source'])

    async def _data_from_cache(self, redis_key: str) -> Optional[BaseModel]:
        data = await self.redis.get(redis_key)
        if not data:
            return None
        data = self.model.parse_raw(data)
        return data

    async def _put_data_to_cache(self, redis_key: str, data: BaseModel) -> None:
        await self.redis.set(redis_key, data.json(), expire=ProjectSettings().CACHE_EXPIRE_IN_SECONDS)

    async def get_page_number(
        self, es_index: str, sort: bool, page_number: int, page_size: int
    ) -> Optional[BaseModel]:
        data = await self._many_data_from_cache(
            f'{es_index}::sort::{sort}::page_number::{page_number}::page_size::{page_size}'
        )
        if not data:
            data = await self._get_data_from_elastic(es_index, sort, page_number, page_size)
            if not data:
                return None
            await self._put_many_data_to_cache(
                f'{es_index}::sort::{sort}::page_number::{page_number}::page_size::{page_size}',
                data,
            )
        return data

    async def _get_data_from_elastic(
        self, es_index: str, sort: bool, page_number: int, data_on_page: int
    ) -> Optional[List[BaseModel]]:
        try:
            data = await self.elastic.search(
                index=es_index,
                from_=page_number,
                size=data_on_page,
                sort=f"{'genre' if es_index == 'genres' else 'name'}.keyword:{'asc' if sort else 'desc'}",
            )
        except NotFoundError:
            return None
        return [self.model(**_['_source']) for _ in data['hits']['hits']]

    async def _many_data_from_cache(self, redis_key: str) -> Optional[List[BaseModel]]:
        data = await self.redis.get(redis_key)
        if not data:
            return None
        data = parse_raw_as(List[self.model], data)
        return data

    async def _put_many_data_to_cache(self, redis_key: str, data: List[BaseModel]) -> None:
        await self.redis.set(
            redis_key, json.dumps(data, default=pydantic_encoder), expire=ProjectSettings().CACHE_EXPIRE_IN_SECONDS
        )


from types import coroutine

@coroutine
def display(root, label):
    from main import get_func2
    e_string = ''
    e_list = []

    func = get_func2(root, label)
    while True:
        e = yield
        if e != 'res' and e != 'c':
            e_string += str(e)
            e_list.append(e)
            label.config(text=f'{e_string}')
            root.update()
        else:
            if e == 'res':
                func.send(e_list)
                e_string = ''
                e_list = []

            else:
                e_list = []
                e_string = ''
                label.config(text='')
                root.update()

async def display_async(g):
    await g


import pandas as pd
import datetime
from dateutil.parser import parse
import numpy as np
import csv

if __name__ == '__main__':
    print("test")

    df = pd.read_csv('/Users/apple4u/Desktop/goksel tez/r4.2/device.csv')
    # df.info()
    print(df.head())
    users = df.user.unique()
    print(users)
    pcs = df.pc.values
    dates = df.date.values
    activities = df.activity.values

    dict = {}
    for usr in users:
        try:
            #print("finding device use time for user: " + usr)
            df_usr = df[df['user'] == usr]
            activities_usr = df_usr.activity.values

            #print(usr + " initially has " + str(len(df_usr)) + " records")

            aincr = 1
            delete_counter = 0
            while aincr < len(activities_usr):
                if str(activities_usr[aincr]) == str(activities_usr[aincr - 1]):
                    # print("issue with user " + usr + " " + activities_usr[aincr])
                    # print("duplicate at location " + str(aincr))
                    df_usr = df_usr.drop(df_usr.index[aincr - 1])
                    # print("dropped row " + str(aincr-1))
                    delete_counter += 1
                aincr += 1

            #print("deleted  " + str(delete_counter) + " rows from user " + usr)
            #print(usr + " now has " + str(len(df_usr)) + " records")

            # aincrd = 1
            # while aincrd < len(activities_usr) - 1:
            #      if activities_usr[aincrd] == activities_usr[aincrd - 1]:
            #          print("issue with user " + usr + " " + activities_usr[aincrd])
            #          print("duplicate at location " + str(aincrd))
            #      aincr += 1
            #      print("scanned user " + usr)

            dates_usr = df_usr.date.values

            count = 1
            timediff_usr_seconds = 0
            sum_timediff_usr_seconds = 0
            i = 0
            #print(len(dates_usr))
            while i < ((len(dates_usr) / 2) ):
                # print(dates_moh[i])
                # print(datetime.datetime.strptime(dates_moh[i], '%m/%d/%Y, %H:%M:%S'))
                # timediff_usr.append(i)
                timediff_usr = parse(dates_usr[count]) - parse(dates_usr[count - 1])
                timediff_usr_seconds = timediff_usr.seconds
                # print(i, "/", count)
                # print(timediff_usr, "   ", timediff_usr_seconds)
                sum_timediff_usr_seconds += timediff_usr_seconds
                # timediff_usr.append((parse(dates_usr[count])-parse(dates_usr[count-1])).seconds)
                count += 2
                i += 1
            average_time_diff_usr_seconds = sum_timediff_usr_seconds / len(dates_usr)
            print("average device use time for user: " + usr + " is: " + str(average_time_diff_usr_seconds))
            dict[usr] = average_time_diff_usr_seconds
        except:
            print("exception occured for user " + usr)
    print(dict)

    with open('device_logon_times.csv', 'w') as f:
        w = csv.writer(f)
        w.writerows(dict.items())


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

'''
Created on 14/12/2015

@author: danie
'''

from numpy import *
import numpy as np
import pandas
import os

def insert_features_OUTattribute(features,OUTattributes):
    """
    Inserts all the features created and the Out attribute into the final dataset
    Returns the final dataset
    """

    finalDataset=np.array((features))
    finalDataset=np.hstack((finalDataset,OUTattributes))
    return finalDataset

def mix_dataset(NumDataset,numIDs):
    dataset=pandas.read_csv("../Data/Datasets/Dataset"+str(NumDataset)+"/TransporterDataset/Dataset"+numIDs+".csv", sep=",", header=None)
    #print(dataset.shape)
    MD=dataset.iloc[np.random.permutation(len(dataset))]
    mixedDataset=np.array(MD)
    print("mixed dataset shape")
    print(mixedDataset.shape)
    #print(mixedDataset)
    np.savetxt("../Data/Datasets/Dataset"+str(NumDataset)+"/TransporterDataset/Dataset"+numIDs+"mixed.csv",mixedDataset,delimiter=",")

def split_features_OUTattributes(NumDataset,features,numIDs):
    mixed_dataset=genfromtxt("../Data/Datasets/Dataset"+str(NumDataset)+"/TransporterDataset/Dataset"+numIDs+"mixed.csv",delimiter=",")
    mixed_features_dataset= np.delete(mixed_dataset, s_[len(features[0]):], axis=1)
    mixed_OUTattributes_dataset=np.delete(mixed_dataset,s_[0:len(features[0])],axis=1)
    np.savetxt("../Data/Datasets/Dataset"+str(NumDataset)+"/TransporterDataset/Features/Features_Dataset"+numIDs+"_mixed.csv",mixed_features_dataset, delimiter=",")
    np.savetxt("../Data/Datasets/Dataset"+str(NumDataset)+"/TransporterDataset/Out_attributes/Out_Attributes_Dataset_"+numIDs+"_mixed.csv",mixed_OUTattributes_dataset,delimiter=",")
    print("mixed feature shape")
    print(mixed_features_dataset.shape)
    print("mixed out shape")
    print(mixed_OUTattributes_dataset.shape)

if __name__ == '__main__':
    NumDataset=input("Qual o número do dataset?")
    directory="../Data/Datasets/Dataset"+str(NumDataset)+"/TransporterDataset"
    if not os.path.exists(directory):
        os.makedirs(directory)

    directory2="../Data/Datasets/Dataset"+str(NumDataset)+"/TransporterDataset/Features"
    if not os.path.exists(directory2):
        os.makedirs(directory2)

    directory3="../Data/Datasets/Dataset"+str(NumDataset)+"/TransporterDataset/Out_attributes"
    if not os.path.exists(directory3):
        os.makedirs(directory3)

    features=genfromtxt("../Data/Datasets/Dataset"+str(NumDataset)+"/Features/Features_Dataset.csv", delimiter=",")
    index=list(range(11717,27577))

    numID1="TCDBIDs1"
    Ot1=genfromtxt("../Data/Datasets/Dataset"+str(NumDataset)+"/Out_attributes/TCDB1ID.csv",delimiter=",")
    OUT1=Ot1[:,np.newaxis]
    dataset1=insert_features_OUTattribute(features, OUT1)
    cutedDataset1=np.delete(dataset1, index, axis=0)
    np.savetxt("../Data/Datasets/Dataset"+str(NumDataset)+"/TransporterDataset/Dataset"+numID1+".csv",cutedDataset1,delimiter=",")
    mix_dataset(NumDataset, numID1)
    split_features_OUTattributes(NumDataset, features, numID1)

    numID12="TCDBIDs12"
    Ot12=genfromtxt("../Data/Datasets/Dataset"+str(NumDataset)+"/Out_attributes/TCDB12ID.csv",delimiter=",")
    OUT12=Ot12[:,np.newaxis]
    dataset12=insert_features_OUTattribute(features, OUT12)
    cutedDataset12=np.delete(dataset12, index, axis=0)
    np.savetxt("../Data/Datasets/Dataset"+str(NumDataset)+"/TransporterDataset/Dataset"+numID12+".csv",cutedDataset12,delimiter=",")
    mix_dataset(NumDataset, numID12)
    split_features_OUTattributes(NumDataset, features, numID12)

    numID123="TCDBIDs123"
    Ot123=genfromtxt("../Data/Datasets/Dataset"+str(NumDataset)+"/Out_attributes/TCDB123ID.csv",delimiter=",")
    OUT123=Ot123[:,np.newaxis]
    dataset123=insert_features_OUTattribute(features, OUT123)
    cutedDataset123=np.delete(dataset123, index, axis=0)
    np.savetxt("../Data/Datasets/Dataset"+str(NumDataset)+"/TransporterDataset/Dataset"+numID123+".csv",cutedDataset123,delimiter=",")
    mix_dataset(NumDataset, numID123)
    split_features_OUTattributes(NumDataset, features, numID123)

    numID1234="TCDBIDs1234"
    Ot1234=genfromtxt("../Data/Datasets/Dataset"+str(NumDataset)+"/Out_attributes/TCDB1234ID.csv",delimiter=",")
    OUT1234=Ot1234[:,np.newaxis]
    dataset1234=insert_features_OUTattribute(features, OUT1234)
    cutedDataset1234=np.delete(dataset1234, index, axis=0)
    np.savetxt("../Data/Datasets/Dataset"+str(NumDataset)+"/TransporterDataset/Dataset"+numID1234+".csv",cutedDataset1234,delimiter=",")
    mix_dataset(NumDataset, numID1234)
    split_features_OUTattributes(NumDataset, features, numID1234)

    #===========================================================================
    # Ot=genfromtxt("../Data/Datasets/Dataset"+str(NumDataset)+"/Out_attributes/Out_Attributes_Dataset.csv",delimiter=",")
    #
    # OUTattributes=Ot[:,np.newaxis]
    #
    # #Usar esta parte se o dataset ainda não estiver criado
    # dataset=insert_features_OUTattribute(features, OUTattributes)
    # #
    # print("dataset shape")
    # print (dataset.shape)
    # np.savetxt("../Data/Datasets/Dataset"+str(NumDataset)+"/Dataset"+str(NumDataset)+".csv",dataset,delimiter=",")
    #
    # mix_dataset(NumDataset)
    # split_features_OUTattributes(NumDataset,features)
    #===========================================================================


import requests

class Github:
    def __init__(self, username, token):
        self.username = username
        self.has_token = True if token else False
        self.token = ''
        self.languages_usage = self.calc_percent_per_lang()

    def get_user_info(self):
        headers = {'Authorization': 'token ' + self.token}
        url = 'https://api.github.com/users/' + self.username
        response = requests.get(url, headers=headers) if self.has_token else requests.get(url)
        return response.json()

    def get_repos(self):
        headers = {'Authorization': 'token ' + self.token}
        url = f'https://api.github.com/search/repositories?q=user:{self.username}'
        response = requests.get(url , headers=headers) if self.has_token else requests.get(url)
        return response.json()['items']

    def get_repo_names(self):
        return [repo['name'] for repo in self.get_repos()]

    def get_repo_language(self, repo_name):
        headers = {'Authorization': 'token ' + self.token}
        url = 'https://api.github.com/repos/' + self.username + '/' + repo_name + '/languages'
        response = requests.get(url, headers=headers) if self.has_token else requests.get(url)
        return response.json()

    def calculate_repo_language(self):
        dict_of_languages = {}
        for repo_name in self.get_repo_names():
            languages = self.get_repo_language(repo_name)

            for language, characters in languages.items():
                if language in dict_of_languages:
                    dict_of_languages[language] += characters
                else:
                    dict_of_languages[language] = characters

        return dict_of_languages

    def calc_percent_per_lang(self):
        dict_of_languages = self.calculate_repo_language()
        total_characters = sum(dict_of_languages.values())
        dict_of_languages_percent = {}

        for language, characters in dict_of_languages.items():
            # calclate percentage of each language to 2 decimal places
            dict_of_languages_percent[language] = round(characters / total_characters * 100, 2)

        # order the languages by percentage as a dictionary
        ordered_dict_of_languages_percent = {k: v for k, v in sorted(dict_of_languages_percent.items(), key=lambda item: item[1], reverse=True)}
        return ordered_dict_of_languages_percent

if __name__ == '__main__':
    # ask user for github username
    username = input("Enter your Github username: ")
    token = input("Enter your Github token: ") or None

    github_user = Github(username, token)
    print(github_user.languages_usage)


import logging

from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response
from rest_framework.viewsets import ViewSet
from rest_framework.permissions import IsAuthenticated
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from course.models import Course, CourseExpire
from edu_api.settings import constants

log = logging.getLogger("django")

class CartView(ViewSet):
    """购物车视图"""

    # 权限：登录的用户才可以访问
    permission_classes = [IsAuthenticated]

    def get_cart_length(self, request):
        user_id = request.user.id
        connection = get_redis_connection("cart")
        course_len = connection.hlen("cart_%s" % user_id)
        return Response({"cart_length": course_len})

    def add_cart(self, request):
        """
        将课程添加至购物车的相关操作
        :param request: 用户id  课程id  勾选状态  有效期选项
        :return:
        """
        course_id = request.data.get("course_id")
        user_id = request.user.id
        print(course_id, user_id)
        # 勾选状态 默认勾选
        select = True
        # 有效期  为0代表永久有效  其他的代表一定时间内有效
        expire = 0

        try:
            course = Course.objects.get(is_show=True, is_delete=False, pk=course_id)
        except Course.DoesNotExist:
            return Response({"message": "参数有误，课程不存在"}, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 获取Redis连接
            redis_connection = get_redis_connection("cart")
            # 将购物车数据通过管道保存到redis
            pipeline = redis_connection.pipeline()
            # 开启管道
            pipeline.multi()
            # 商品的信息以及对应的有效期
            pipeline.hset("cart_%s" % user_id, course_id, expire)
            # 被勾选的商品
            pipeline.sadd("select_%s" % user_id, course_id)
            # 将以上两个命令发送到redis执行
            pipeline.execute()

            # 获取购物车中商品的总数量
            course_len = redis_connection.hlen("cart_%s" % user_id)

        except:
            # 将本次错误信息记录到日志中
            log.error("购物车保存数据失败")
            return Response({"message": "购物车添加失败"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        return Response({"message": "购物车添加成功", "cart_length": course_len})

    def list_cart(self, request):
        """
        返回购物车列表所需的数据
        :param request:
        :return:
        """
        user_id = request.user.id

        redis_connection = get_redis_connection("cart")
        cart_list_byte = redis_connection.hgetall("cart_%s" % user_id)
        select_list_byte = redis_connection.smembers("select_%s" % user_id)

        print(cart_list_byte, select_list_byte)
        # 循环从数据库中查询出课程的信息
        course_data = []
        for course_id_byte, expire_id_byte in cart_list_byte.items():
            course_id = int(course_id_byte)
            expire_id = int(expire_id_byte)

            try:
                course = Course.objects.get(is_show=True, is_delete=False, pk=course_id)
            except Course.DoesNotExist:
                continue

            # 购物车所需的信息
            course_data.append({
                "id": course_id,
                "name": course.name,
                # 图片 返回的是图片的显示路径
                "image": constants.SERVER_IMAGE_DOMAIN + course.course_img.url,
                "price": course.real_price,
                "selected": True if course_id_byte in select_list_byte else False,
                "expire_id": expire_id,
                "expire_list": course.expire_list,
                "expire_price": course.expire_price(expire_id),
            })

        return Response(course_data)

    def cart_item_select(self, request):
        """
        修改购物车列表选中的状态
        :param request:
        :return:
        """
        user_id = request.user.id
        course_id = request.data.get("course_id")
        selected = request.data.get("selected")
        print(user_id, course_id, selected)
        redis_connection = get_redis_connection("cart")
        if selected:
            redis_connection.sadd("select_%s" % user_id, course_id)
        else:
            redis_connection.srem("select_%s" % user_id, course_id)
        return Response('OK')

    def del_item_select(self, request):
        """
        删除单个
        :param request:
        :return:
        """
        user_id = request.user.id
        course_id = request.data.get("course_id")
        print(user_id, course_id)
        redis_connection = get_redis_connection("cart")
        redis_connection.hdel("cart_%s" % user_id, course_id)
        redis_connection.srem("select_%s" % user_id, course_id)
        return Response('OK')

    def expire_item_select(self, request):
        """
        修改有效期的状态
        :param request:
        :return:
        """
        user_id = request.user.id
        course_id = request.data.get("course_id")
        expire_id = request.data.get("expire_id")
        print(user_id, course_id, expire_id)
        redis_connection = get_redis_connection("cart")
        redis_connection.hset("cart_%s" % user_id, course_id, expire_id)
        return Response('OK')

    def get_select_course(self, request):
        """
        获取购物车中已勾选的商品在订单结算页展示
        :param request:
        :return:
        """
        user_id = request.user.id
        redis_connection = get_redis_connection("cart")

        cart_list_byte = redis_connection.hgetall("cart_%s" % user_id)
        select_list_byte = redis_connection.smembers("select_%s" % user_id)

        data = []  # 已勾选的课程列表
        total_price = 0

        for course_id_byte, expire_id_byte in cart_list_byte.items():
            course_id = int(course_id_byte)
            expire_id = int(expire_id_byte)

            if course_id_byte in select_list_byte:
                try:
                    course = Course.objects.get(is_show=True, is_delete=False, pk=course_id)
                except Course.DoesNotExist:
                    continue

                    # 判断课程的有效期  有效期id大于0，则需要重新计算商品的价格  id不大于0代表永久有效，默认雨原价
                original_price = course.price
                expire_text = "永久有效"

                try:
                    if expire_id > 0:
                        # 获取有效期的价格，再进行活动计算
                        course_expire = CourseExpire.objects.get(pk=expire_id)
                        original_price = course_expire.price
                        expire_text = course_expire.expire_text
                except CourseExpire.DoesNotExist:
                    pass

                # 根据已勾选的商品的价格来计算商品最终的价格
                course_expire_price = course.expire_price(expire_id)

                # 将订单结算页所需的信息返回
                data.append({
                    "name": course.name,
                    # 图片 返回的是图片的显示路径
                    "image": constants.SERVER_IMAGE_DOMAIN + course.course_img.url,
                    "price": original_price,
                    # 有效期价格参与活动的价格
                    "expire_price": float(course_expire_price),
                    "expire_text": expire_text,
                    # 活动名称
                    "discount_name": course.discount_name,
                })

                # 所有勾选的课程总价
                total_price += float(course_expire_price)

        return Response({"course_list": data, "total_price": total_price})


import os
import unittest

import common.util as util

class TestUmask(unittest.TestCase):
    """
    This test verifies that Sarus is able to run under different umask configurations.
    """

    _IMAGE_NAME = util.ALPINE_IMAGE
    _umask_backup = None

    @classmethod
    def setUpClass(cls):
        util.pull_image_if_necessary(is_centralized_repository=False, image=cls._IMAGE_NAME)
        cls._umask_backup = os.umask(0) # set dummy umask to read current value
        os.umask(cls._umask_backup) # reset umask

    @classmethod
    def tearDownClass(cls):
        os.umask(cls._umask_backup)

    def test_umask(self):
        umask_backup = os.umask(0o000)
        self._run_sarus()

        os.umask(0o777)
        self._run_sarus()

        os.umask(umask_backup)

    def _run_sarus(self):
        util.run_command_in_container(is_centralized_repository=False, image=self._IMAGE_NAME, command=["true"])


from django.urls import path, include
from .views import loginView, logoutView, registerView, profileView, donorSettingsView

urlpatterns = [
	path('login/', loginView, name="login"),
	path('logout/', logoutView, name="logout"),
	path('register/', registerView, name="register"),
	path('profile/', profileView, name="profile"),
	path('settings/',donorSettingsView, name="settings"),
	path('logout/', logoutView, name="logout"),
]


from builtins import object
from nose.tools import assert_true, assert_equal

from zookeeper import stats
from zookeeper.conf import CLUSTERS
from zookeeper.views import _get_global_overview

class MockZooKeeperStats(object):

  def __init__(self, host, port):
    pass

  def get_stats(self):
    return {}

class ZooKeeperMockBase(object):

  def setUp(self):
    # Beware: Monkey patch ZooKeeper with Mock API
    if not hasattr(stats, 'OriginalZooKeeperApi'):
      stats.OriginalZooKeeperApi = stats.ZooKeeperStats

    stats.ZooKeeperStats = MockZooKeeperStats

  def tearDown(self):
    stats.ZooKeeperStats = stats.OriginalZooKeeperApi

class TestMockedZooKeeper(ZooKeeperMockBase):

  def test_get_global_overview(self):
    """Beware: this test is not testing, need to better mock the config."""
    finish = CLUSTERS.set_for_testing({'default': {'localhost:2181': {}}})

    try:
      _get_global_overview()

    finally:
      finish()

    finish = CLUSTERS.set_for_testing({'default': {'localhost:2181,localhost:2182': {}}})
    try:
      _get_global_overview()
    finally:
      finish()


from wtforms import SubmitField
from wtforms.validators import DataRequired, URL
from bluecat.wtform_extensions import GatewayForm
from bluecat.wtform_fields import CustomStringField

class EdgeForm(GatewayForm):

    workflow_name = 'hello_edge'
    workflow_permission = 'hello_edge_page'

    edge = CustomStringField(
        label='Edge CI',
        default='https://api.edge.example.com',
        validators=[DataRequired(), URL()],
        is_disabled_on_start=False
    )

    client = CustomStringField(
        label='Client ID',
        default='',
        validators=[DataRequired()],
        is_disabled_on_start=False
    )

    client_secret = CustomStringField(
        label='Client Secret',
        default='',
        validators=[DataRequired()],
        is_disabled_on_start=False
    )

    submit = SubmitField(label='Submit')


import os
from typing import Optional

def _create_base_filename(
    title: Optional[str], output_path: str, model: str, date: str
) -> str:
    base = f"{date}__{model}__{replace_path_sep(title)}"
    return os.path.join(output_path, base, base)

def create_base_filename(
    title: Optional[str], output_path: str, model: str, date: str
) -> str:
    base_filename = _create_base_filename(title, output_path, model, date)

    base_directory = os.path.dirname(base_filename)
    os.makedirs(base_directory, exist_ok=True)

    return base_filename

def replace_path_sep(title: Optional[str]) -> str:
    return "None" if title is None else title.replace(os.path.sep, "_")


import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

df = pd.read_excel('D:/软件/火狐/python实验/data/student_canteen.xlsx', 'Sheet1')

plt.rcParams['font.sans-serif'] = ['simhei']
plt.rcParams['axes.unicode_minus'] = False

fig = plt.figure()
ax = fig.add_subplot(111)
ax.hist(df['price'], bins=7)
plt.title('学生食堂数据')
plt.xlabel('price')
plt.ylabel('cardID')
plt.show()

var = df.groupby('price').price.sum()
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.set_xlabel('price')
ax1.set_ylabel('cardID')
ax1.set_title('学生食堂数据')
var.plot(kind='bar')
plt.show()


from window import Window
from actionresult import ActionResult
from textpane import TextPane
from os.path import join, dirname

class License(object):
    def __init__(self, maxy, maxx, eula_file_path, display_title):
        self.maxx = maxx
        self.maxy = maxy
        self.win_width = maxx - 4
        self.win_height = maxy - 4

        self.win_starty = (self.maxy - self.win_height) // 2
        self.win_startx = (self.maxx - self.win_width) // 2

        self.text_starty = self.win_starty + 4
        self.text_height = self.win_height - 6
        self.text_width = self.win_width - 6

        self.window = Window(self.win_height, self.win_width, self.maxy, self.maxx,
                             'Welcome to the Photon installer', False)

        if eula_file_path:
            self.eula_file_path = eula_file_path
        else:
            self.eula_file_path = join(dirname(__file__), 'EULA.txt')

        if display_title:
            self.title = display_title
        else:
            self.title = 'VMWARE LICENSE AGREEMENT'

    def display(self):
        accept_decline_items = [('<Accept>', self.accept_function),
                                ('<Cancel>', self.exit_function)]

        self.window.addstr(0, (self.win_width - len(self.title)) // 2, self.title)
        self.text_pane = TextPane(self.text_starty, self.maxx, self.text_width,
                                  self.eula_file_path, self.text_height, accept_decline_items)

        self.window.set_action_panel(self.text_pane)

        return self.window.do_action()

    def accept_function(self):
        return ActionResult(True, None)

    def exit_function(self):
        exit(0)


# 2) Dado a sequência de Fibonacci, onde se inicia por 0 e 1 e o próximo valor sempre será a soma dos 2 valores anteriores
# (exemplo: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34...), escreva um programa na linguagem que desejar onde, informado um número,
# ele calcule a sequência de Fibonacci e retorne uma mensagem avisando se o número informado pertence ou não a sequência.
# IMPORTANTE:
# Esse número pode ser informado através de qualquer entrada de sua preferência ou pode ser previamente definido no código;

num = int(input("Informe um número que deseja descobrir se faz parte da Sequência de Fibonacci: "))

ultimo = 0
penultimo = 1

fibo = []

while True:
    resultado = ultimo + penultimo
    penultimo = ultimo
    ultimo = resultado

    fibo.append(resultado)

    if num == resultado:
        print(f'O número informado ({num}) FAZ parte da sequência Fibonacci')
        print(f'Fibonacci {fibo}')
        break
    elif resultado > num:
        print(f'O número informado ({num}) NÃO FAZ parte da sequência Fibonacci')
        print(f'Fibonacci {fibo}')
        break


# -- import packages: --------------------------------------------------------------------
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import vinplots
import os

# -- import local dependencies: ----------------------------------------------------------
from ._labeled_color import LabeledColor
from ._method_functions import MethodFunctions
from ._result_classes import SIMBAResults, ScanpyResults, SeuratResults
from ._fetch_properties import fetch_properties

# -- supporting functions: ---------------------------------------------------------------
def function_group_resources(df, method_class):
    grouped = {}
    for prop in fetch_properties(method_class):
        grouped[prop] = df.loc[getattr(method_class, prop)].sum()

    return grouped

def parse_results(results_obj, method_funcs, seurat=False):

    collect = Collect(results_obj())

    if not seurat:
        time_df = collect.time().mean(1)
        mem_df  = collect.memory().mean(1)
    else:
        time_df = collect.time(seurat=True).mean(1)
        mem_df  = collect.memory(seurat=True).mean(1)

    func_time = function_group_resources(time_df, method_funcs)
    func_mem  = function_group_resources(mem_df,  method_funcs)

    return {"t": func_time, "m": func_mem}

def cumulative_barplot(ax, df, labcol, log=True, legend=True, legend_loc=(2.5,0)):

    ax.set_title("Time", fontsize=10)

    for n, (i, row) in enumerate(df.iterrows()):
        if n > 0:
            bottom = df.iloc[int(n - 1)]
        else:
            bottom = 0
        ax.bar(
            x=range(3),
            height=row,
            bottom=bottom,
            label=labcol.loc[i]["labels"],
            color=labcol.loc[i]["colors"],
            edgecolor="k",
            log=log,
        )

    ax.set_xticks([0, 1, 2], ["SIMBA", "Scanpy", "Seurat"], fontsize=8)
    ax.set_ylabel("s", rotation=0, fontsize=8)

    ax.tick_params(axis="both", which="major", labelsize=6)
    if legend:
        ax.legend(edgecolor="w", loc=legend_loc)

def memory_plot(
    ax,
    df,
    labcol,
    space=1.5,
    mem_keys=["pp", "generate_graph", "embedding", "train", "gene_discovery"],
    log=True,
    legend=False,
):

    ax.set_title("Memory", fontsize=10)

    plot_mem = df.loc[mem_keys]
    count = 0
    xr_ = np.array([])
    for n, col in enumerate(plot_mem.columns):
        n_rows = plot_mem[col].shape[0]
        ax.bar(
            x=np.arange(count, count + n_rows),
            height=plot_mem[col],
            color=labcol.loc[mem_keys]["colors"],
            label=col,
            edgecolor="k",
            lw=0.5,
            log=log,
        )
        count += n_rows + space

    ax.set_xticks([2, 8.5, 15], ["SIMBA", "Scanpy", "Seurat"], fontsize=8)
    ax.tick_params(axis="both", which="major", labelsize=6)
    ax.set_ylabel("Mb", rotation=0, fontsize=8)

    if legend:
        ax.legend(edgecolor="w")

def process_results_for_plot(compare, tm_key, idx=["SIMBA", "Scanpy", "Seurat"]):

    results = [compare.Results[key][tm_key] for key in idx]
    df = pd.DataFrame(results, index=idx).T.fillna(0).fillna(0)
    if tm_key == "t":
        return df.cumsum()
    return df

class Collect:
    def __init__(self, ResultsDict):
        self.ResultsDict = ResultsDict

    def time(self, seurat=False):

        Time = {}
        for key in self.ResultsDict.keys():
            if not seurat:
                Time[key] = self.ResultsDict[key]["resource_df"]["t"]
            else:
                Time[key] = self.ResultsDict[key].time["time_dict"]

        return pd.DataFrame(Time)

    def memory(self, seurat=False):

        Memory = {}
        for key in self.ResultsDict.keys():
            if not seurat:
                Memory[key] = self.ResultsDict[key]["resource_df"]["allocated_peak"]
            else:
                Memory[key] = self.ResultsDict[key].compute_mb_used()

        return pd.DataFrame(Memory)

class CompareMethods:

    method_funcs = MethodFunctions()

    _method_paths = {
        "SIMBA": "SIMBA/*.pkl",
        "Scanpy": "Scanpy/*.pkl",
        "Seurat": "Seurat/*/",
    }

    def __init__(self, path):
        self._base_path = path
        for method, m_path in self._method_paths.items():
            method_path = os.path.join(path, m_path)
            setattr(self, "_{}_path".format(method), method_path)

        self.Results = {}
        self.Results["SIMBA"] = parse_results(
            SIMBAResults(self._SIMBA_path), self.method_funcs.SIMBA
        )
        self.Results["Scanpy"] = parse_results(
            ScanpyResults(self._Scanpy_path), self.method_funcs.Scanpy
        )
        try:
            self.Results["Seurat"] = parse_results(
                SeuratResults(self._Seurat_path), self.method_funcs.Seurat, seurat=True
            )
        except:
            self.Results["Seurat"] = {"t": {"pp":0, "embedding":0, "gene_discovery" :0},
                                      "m": {"pp":0, "embedding":0, "gene_discovery" :0},
                                     }
        self._SIMBA_RESULTS = SIMBAResults(self._SIMBA_path)

# -- Augment SIMBA memory usage from trace file: -----------------------------------------
class SIMBAMemoryAugmentation:
    def __init__(self, compare):

        self.simba_outs = compare._SIMBA_RESULTS()

    def _time_from_iso(self, t):
        s = datetime.datetime.fromisoformat(t).second / (60*60)
        m = datetime.datetime.fromisoformat(t).minute / 60
        h = datetime.datetime.fromisoformat(t).hour

        return h + m + s

    def parse(self):

        self.MemDict = {}

        for k, v in self.simba_outs.items():
            self.MemDict[k] = {}
            self.MemDict[k]['landmarks'] = v['landmark_datetimes']
            self.MemDict[k]['memory_df'] = v['memory_trace_df']

    def _filter_time_df(self, time_df, landmark_dict, t0_key, tf_key):

        t0_ = landmark_dict[t0_key]
        tf_ = landmark_dict[tf_key]

        return time_df.loc[time_df['datetime'] > t0_].loc[time_df['datetime'] < tf_]

    def resolve_time(self, landmarks, time_df):

        keys = list(landmarks.keys())
        min_active = (time_df['active'].min() / 1e6)

        ResolvedTime = {}
        for i, key in enumerate(keys):
            if not i == 0:
                _df = self._filter_time_df(time_df, landmarks, keys[i-1], key)
                if _df.shape[0] > 0:
                    # some steps are so fast, the memory is not even recorded
                    ResolvedTime[key] = _df

        MaxMemAugmentation = {}
        for key, _df in ResolvedTime.items():
            max_mem =  _df['used'].max()/1e6 - min_active
#             print("{:<15}{:.2f} Mb".format(key,max_mem))
            MaxMemAugmentation[key] = max_mem
        return MaxMemAugmentation

    def update(self, plot_m):

        ALL = {}
        self.parse()
        for i in self.MemDict.keys():
            landmarks = self.MemDict[i]['landmarks']
            time_df = self.MemDict[i]['memory_df']
            ALL[i] = self.resolve_time(landmarks, time_df)

        augment_df = pd.DataFrame(ALL).loc[['gen_graph', 'train']]
        cols = augment_df.columns
        if len(cols) > 3:
            cols = cols[1:]
        augmented = augment_df[cols].mean(1).to_dict()

        plot_m.loc['train']['SIMBA'] = augmented['train']
        plot_m.loc['generate_graph']['SIMBA'] = augmented['gen_graph']

        return plot_m

# -- Main module class: ------------------------------------------------------------------
class PlotTimeMemory:
    def __init__(self,
                 results_path,
                 memory_trace_path=None,
                 wspace=0.2,
                 save=False,
                 savename=".svg",
                 legend_loc=(1,0),
                 **kwargs,
                ):

        # -- gather results: -------------------------------------------------------------
        self._compare = CompareMethods(results_path)
        self._results_path = results_path
        SIMBA_mem_augment = SIMBAMemoryAugmentation(self._compare)

        self.plot_m = process_results_for_plot(self._compare, tm_key="m")
        self.plot_m = SIMBA_mem_augment.update(self.plot_m)

        self.plot_t = process_results_for_plot(self._compare, tm_key="t")

        # -- plot: -----------------------------------------------------------------------
        self._labeled_colors = LabeledColor().frame()
        self.fig, self._axes = vinplots.quick_plot(nplots=2, ncols=2, wspace=wspace, **kwargs)
        self.t_ax, self.m_ax = self._axes[0], self._axes[1]

        cumulative_barplot(self.t_ax, self.plot_t, labcol=self._labeled_colors, legend=True, legend_loc=legend_loc)
        memory_plot(self.m_ax, self.plot_m, labcol=self._labeled_colors, legend=False)

        if save:
            plt.savefig(savename)


import risar
from math import sqrt
from random import randint, random

vx = []
vy = []
krogeci = []
for i in range(30):
    a= risar.krog(randint(0, risar.maxX-100), randint(0, risar.maxY-100),10,risar.nakljucna_barva())
    krogeci.append(a)
    vx.append((2+random() * 3))
    vy.append((2+random() * 3))

x, y = risar.miska
misek = risar.krog(x,y,20)

def konec(c,d):
    a=0
    while a==0:
        for i in range(len(krogeci)):
            krog = krogeci[i]
            krog.setPos(krog.x() + vx[i], krog.y() + vy[i])
            if not (3 < krog.x() < risar.maxX - 10):
                vx[i] = -vx[i]
            if not (3 < krog.y() < risar.maxY - 10):
                vy[i] = -vy[i]
            if sqrt((misek.x() - krog.x())**2  + (misek.y() - krog.y())**2) < 33:
                risar.stoj()
        risar.cakaj(0.02)

a=0
while a == 0:
    for i in range(len(krogeci)):
        krog=krogeci[i]
        krog.setPos(krog.x() + vx[i], krog.y() + vy[i])
        if not (3 < krog.x() < risar.maxX - 10):
            vx[i] = -vx[i]
        if not (3 < krog.y() < risar.maxY - 10):
            vy[i] = -vy[i]
    x,y=risar.miska
    misek.setPos(x,y)
    if risar.klik == True:
        misek.setPos(x,y)
        konec(x,y)
    risar.cakaj(0.02)


import logging
import uuid
from datetime import datetime
from typing import Optional

from _pulsar import Result
from flask import Flask, make_response
from pulsar import Client, MessageId, Producer, schema

logging.basicConfig(
    level=logging.INFO, format='[%(asctime)s] [%(levelname)s] [%(name)s] %(message)s'
)
logger = logging.getLogger(__name__)
pulsar_logger = logging.getLogger('pulsar')

class PulsarExt:
    def __init__(self, url: str) -> None:
        self._url = url
        self._client: Optional[Client] = None
        self._g_producer: Optional[Producer] = None

    def init_app(self, app_: Flask) -> None:
        app_.extensions['pulsar'] = self

    @property
    def client(self) -> Client:
        assert self._client is not None, 'Call `connect()` first'
        return self._client

    @property
    def g_producer(self) -> Producer:
        assert self._g_producer is not None, 'Call `connect()` first'
        return self._g_producer

    def connect(self) -> None:
        self._client = Client(self._url, authentication=None, logger=pulsar_logger)
        self._g_producer = self._client.create_producer(
            'non-persistent://public/default/test-gunicorn',
            producer_name=f'my-producer-{uuid.uuid4()}',
            schema=schema.StringSchema(),
        )

    def close(self) -> None:
        if self._g_producer:
            self._g_producer.close()
        if self._client:
            self._client.close()

        self._g_producer = None
        self._client = None

app = Flask(__name__)
pulsar_ext = PulsarExt('pulsar://pulsar:6650')
pulsar_ext.init_app(app)

def init_app() -> None:
    pulsar_ext.connect()

def teardown_app() -> None:
    pulsar_ext.close()

@app.post('/post-message')
def post_pulsar_message():
    logger.info(
        'Calling producer.send_async now, '
        'in the next lines there should be the callback result'
    )
    dt = datetime.now()
    pulsar_ext.g_producer.send_async(content=f'dt={dt.isoformat()}', callback=callback)
    logger.info('After producer.send_async, returning the http response')
    return '', 201

def callback(res: Result, _msg_id: MessageId):
    logger.info(f'Callback result here! Event acknowledged by the broker.')

@app.get('/')
def healthcheck():
    logger.info('API Running fine')
    return make_response({'status': 'healthy'})


"""
Python Introduction and Basic Syntax
If
while
for
"""

"""
x = 0
while x<10:
    print("wow",x)
    x = x+1

"""

while True:
    line = input ()
    if not line.startwith('a'): break
    print ("i like a")


#
# @lc app=leetcode id=797 lang=python3
#
# [797] All Paths From Source to Target
#

# @lc code=start
from typing import List

class Solution:
    '''
    my approach is using dfs and traverse the neighbors with a current path.

    if we reach the last node, append the path to res
    '''

    def allPathsSourceTarget2(self, graph: List[List[int]]) -> List[List[int]]:
        res = []
        # time: o(2^n) => number of edges
        # space: o(n) => number of nodes

        def dfs(node, path):
            if node == len(graph) - 1:
                res.append(path)
                return
            for nei in graph[node]:
                dfs(nei, path + [nei])
        dfs(0, [0])
        return res

    def allPathsSourceTarget(self, graph: List[List[int]]):
        res = []
        self.dfs(graph, [0], 0, res)
        return res

    def dfs(self, graph, path, node, res):
        if node == len(graph) - 1:
            res.append(list(path))
            # return not needed because the last node is empty => has no outgoing edges.

        for nei in graph[node]:
            path.append(nei)
            self.dfs(graph, path, nei, res)
            path.pop()

# @lc code=end
graph = [[4, 3, 1], [3, 2, 4], [3], [4], []]
graph = [[1, 2], [3], [3], []]
sol = Solution()
ans = sol.allPathsSourceTarget(graph)
print(f'ans: {ans}')


import numpy as np
import pandas as pd
from sklearn.tree import DecisionTreeClassifier

class Boosting():
    def __init__(self, data, test, iterations=3):
        self.data = data
        self.test = test

        self._preprocess(self.data)
        self._preprocess(self.test)

        self.iterations = iterations
        self.models = []
        self.alphas = []
        self.accuracy = []
        self.predictions = []

    @staticmethod
    def _preprocess(df):
        """
        Transforms nominal data to ordinal and boolean
        :param df: df to transform
        :return:
        """
        df['result'] = np.where(df['survived'] == 'yes', 1, 0)
        df['is_female'] = np.where(df['gender'] == 'female', 1, 0)
        df['is_child'] = np.where(df['age'] == 'child', 1, 0)
        df['pclass'] = pd.Categorical(df['pclass'],
                                      ordered=True,
                                      categories=['1st', '2nd', '3rd', 'crew']
                                      ).codes

        df.drop(columns=['gender', 'age', 'survived'], inplace=True)

    def fit(self):
        """
        Trains the model based on dataset
        :return:
        """
        self._set_all_examples_to_have_equal_uniform_weights()

        X = self.data.drop(['result'], axis=1)
        Y = self.data['result'].where(self.data['result'] == 1, 0)

        for i in range(0, self.iterations):
            model = self._train_model(X, Y)

            # Add ht to H
            self.models.append(model)

            self._evaluation['predictions'] = model.predict(X)
            self._evaluation['is_prediction_incorrect'] = np.where(
                self._evaluation['predictions'] != self.data['result'], 1, 0)

            error_rate = self._get_error_rate()

            # If εt > 0.5 then exit loop, else continue
            if error_rate > 0.5:
                continue

            beta = self._get_beta(error_rate)
            alpha = self._get_alpha(beta)
            self.alphas.append(alpha)

            self._recalculate_weights(beta)
            self._rescale_weights()

    def _set_all_examples_to_have_equal_uniform_weights(self):
        self._evaluation = pd.DataFrame(self.data.result.copy())
        self._evaluation['weights'] = 1 / len(self.data)
        self._evaluation.drop('result', inplace=True, axis=1)

    def _train_model(self, X, Y):
        """
        Trains model based using Tree Stump based on X and Y
        :param X: Dataset without result parameter
        :param Y: Result parameter
        :return: Trained model
        """

        # Learn a hypothesis, ht, from the weighted examples
        tree_model = DecisionTreeClassifier(criterion="entropy", max_depth=1)
        model = tree_model.fit(X, Y, sample_weight=np.array(self._evaluation['weights']))
        return model

    def _get_error_rate(self):
        # Calculate the error, εt, of the hypothesis ht as the total sum weight of the examples
        # that it classifies incorrectly
        err = np.sum(
            self._evaluation['weights'] * self._evaluation['is_prediction_incorrect'])
        return err

    @staticmethod
    def _get_alpha(beta):
        # αt =0.5*ln(1/ βt)
        return 0.5 * np.log(1 / beta)

    @staticmethod
    def _get_beta(error_rate):
        # Let βt = εt / (1 – εt )
        return error_rate / (1 - error_rate)

    def _recalculate_weights(self, alpha):
        # Multiply the weights of the examples that
        # ht classifies correctly by βt
        self._evaluation['weights'] *= np.exp(alpha * self._evaluation['is_prediction_incorrect'])

    def _rescale_weights(self):
        # Rescale the weights of all of the examples so the total sum weight remains 1
        self._evaluation['weights'].div(self._evaluation['weights'].sum())

    def predict(self):
        """
        Predict based on previous generated models and alphas
        :return:
        """
        X_test = self.test.drop(['result'], axis=1).reindex(range(len(self.test)))

        predictions = []

        for alpha, model in zip(self.alphas, self.models):
            prediction = alpha * model.predict(X_test)
            predictions.append(prediction)
        self.predictions = np.sign(np.sum(np.array(predictions), axis=0))
        self._output_result(self.predictions)

    def _output_result(self, result):
        """
        Outputs the result
        :param result: prediction result
        :return:
        """
        self._output_success(result)

        self._clean_for_output()

        self.test.to_csv('titanikPrediction.csv', index=False)
        print(self.test)

    def _output_success(self, result):
        """
        Calculates the percentage of success based on prediction results
        :param result: prediction result
        :return:
        """
        self.test['pred'] = result
        self.test['corrects_rows'] = result == self.test.result
        corrects_rows = np.sum(self.test['corrects_rows'].astype(int))
        n = len(self.test.pred)
        print("Success: {}%".format(corrects_rows * 100 / n))

    def _clean_for_output(self):
        """
        Transform tests data as it was originally before pre-process
        :return:
        """
        self.test['survived'] = np.where(self.test['result'] == 1, 'yes', 'no')
        self.test['gender'] = np.where(self.test['is_female'] == 1, 'female', 'male')
        self.test['age'] = np.where(self.test['is_child'] == True, 'child', 'adult')
        self.test['pclass'] = self.test['pclass'].replace({0: '1st', 1: '2nd', 2: '3rd', 3: 'crew'})
        self.test['pred'] = np.where(self.test['pred'] == 1, 'yes', 'no')

        self.test.drop(columns=['result', 'is_female', 'is_child', 'result', 'corrects_rows'], inplace=True)

if __name__ == "__main__":
    b = Boosting(pd.read_csv('titanikData.csv'),
                 pd.read_csv('titanikTest.csv', names=["pclass", "age", "gender", "survived"]))
    b.fit()
    b.predict()


"""Methods for uploading/managing files on Amazon S3."""

already_uploaded_files = []

class S3LoggingBucket(object):
    """A class for uploading log files from tests to Amazon S3.
    Those files can then be shared easily."""
    from seleniumbase.config import settings

    def __init__(
        self,
        log_bucket=settings.S3_LOG_BUCKET,
        bucket_url=settings.S3_BUCKET_URL,
        selenium_access_key=settings.S3_SELENIUM_ACCESS_KEY,
        selenium_secret_key=settings.S3_SELENIUM_SECRET_KEY,
    ):
        import fasteners
        from seleniumbase.fixtures import constants
        from seleniumbase.fixtures import shared_utils

        pip_find_lock = fasteners.InterProcessLock(
            constants.PipInstall.FINDLOCK
        )
        with pip_find_lock:
            try:
                import boto3
            except Exception:
                shared_utils.pip_install("boto3")
                import boto3
        self.conn = boto3.Session(
            aws_access_key_id=selenium_access_key,
            aws_secret_access_key=selenium_secret_key,
        )
        self.bucket = log_bucket
        self.bucket_url = bucket_url

    def get_key(self, file_name):
        """Create a new S3 connection instance with the given name."""
        return self.conn.resource("s3").Object(self.bucket, file_name)

    def get_bucket(self):
        """Return the bucket being used."""
        return self.bucket

    def upload_file(self, file_name, file_path):
        """Upload a given file from the file_path to the bucket
        with the new name/path file_name."""
        upload_key = self.get_key(file_name)
        content_type = "text/plain"
        if file_name.endswith(".html"):
            content_type = "text/html"
        elif file_name.endswith(".jpg"):
            content_type = "image/jpeg"
        elif file_name.endswith(".png"):
            content_type = "image/png"
        upload_key.Bucket().upload_file(
            file_path,
            file_name,
            ExtraArgs={"ACL": "public-read", "ContentType": content_type},
        )

    def upload_index_file(
        self, test_address, timestamp, data_path, save_data_to_logs
    ):
        """Create an index.html file with links to all the log files
        that were just uploaded."""
        import os

        global already_uploaded_files
        already_uploaded_files = list(set(already_uploaded_files))
        already_uploaded_files.sort()
        file_name = "%s/%s/index.html" % (test_address, timestamp)
        index = self.get_key(file_name)
        index_str = []
        for completed_file in already_uploaded_files:
            index_str.append(
                "%s" % (completed_file, completed_file)
            )
        index_page = str("
".join(index_str))
        save_data_to_logs(index_page, "index.html")
        file_path = os.path.join(data_path, "index.html")
        index.Bucket().upload_file(
            file_path,
            file_name,
            ExtraArgs={"ACL": "public-read", "ContentType": "text/html"},
        )
        return "%s%s" % (self.bucket_url, file_name)

    def save_uploaded_file_names(self, files):
        """Keep a record of all file names that have been uploaded.
        Upload log files related to each test after its execution.
        Once done, use already_uploaded_files to create an index file."""
        global already_uploaded_files
        already_uploaded_files.extend(files)


import pip

import os
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
import time
import urllib3
from bs4 import BeautifulSoup
import csv
import pandas as pd
from pandas import DataFrame
import xlsxwriter

column=['Title','Body']
dfBA=DataFrame(columns=column)
dfT=DataFrame(columns=[0,1,2,3,4])
content=[]

chromedriver = "c:/Chromedriver/chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver

options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])

driver = webdriver.Chrome(chromedriver,chrome_options=options)
driver.get("https://medium.com/search?q=data%20science")

scrape()

ScrollNumber = 50
for i in range(1,ScrollNumber):
    driver.execute_script("window.scrollTo(1,50000)")
    time.sleep(5)

file = open('DS.html', 'w')
file.write(driver.page_source)

file.close()

driver.close()

http=urllib3.PoolManager()

def scrape():
    data = open('/home/DS.html','r')
    soup = BeautifulSoup(data, 'html.parser')
    print("stupid")
    #workbook = xlsxwriter.Workbook('c:/Chromedriver/hello.xlsx')
    #worksheet = workbook.add_worksheet()

    #worksheet.write('A1', 'Hello..')

    #workbook.close()
    for links in soup.find_all('div', {'class': 'postArticle-readMore'}):
        link = links.find('a').get('href')

        Blog_post(link)

def Blog_post(link):
    try:
        print(link)
        blogData = http.request('GET', link)
        soup = BeautifulSoup(blogData.data, 'html.parser')
        article = ''
        tags = []
        heading = soup.find('h1').text
        for para in soup.find_all('p'):
            p = para.text
        p = p.strip('/u')
        article = article + ' ' + p

        for mtags in soup.find_all('a', {'class ': 'link u - baseColor — link'}):
            tags.append(mtags.text)
            # CreateDataFrame(list())
            someList = [heading, article, tuple(tags)]
            # print(someList[0])

            CreateDataFrame(someList)
    except:
        pass

def CreateDataFrame(somelist):
        t={}
        d={'title':[somelist[0]],'body':[somelist[1]]}
        for n in range(5):
            if len(somelist[2])>n:
                t[n]=[somelist[2][n]]
            else:
                t[n]=['0']
        todf=dataframe(data=d)
        global dfba,dft

        dfBA=dfBA.append(toDf)
        print(dfBA)
        dfT=dfT.append(DataFrame(data=t))

        okList = []
        for cl in dfT.columns:
            for n in dfT[cl]:
                okList.append(n)
        okList = list(set(okList))
        newDFT = DataFrame(columns=okList)
        for x in range(dfT.count()[0]):
            someDict = {}
            for d in okList:
                rowdata = list(dfT.iloc[x])
                if d in rowdata:
                    someDict[d] = 1
                else:
                    someDict[d] = 0
            newDFT = newDFT.append(someDict, ignore_index=True)
        newDFT.to_csv('c:/Chromedriver/DSTags.csv')
        worksheet.write('A1', newDFT)

        for column in dfBA.columns:
            for idx in dfBA[column].index:
                dfBA.get_value(idx, column)

        dfBA.to_csv('c:/Chromedriver/RData.csv')
        worksheet.write('B1', newDFT)


import torch
import torch.nn as nn
import torch.nn.functional as F

class PBCSABlock(nn.Module):
    def __init__(self, in_chns, reduct_ratio=16, dilation=4, is_res=True, scale=1.0):
        super(PBCSABlock, self).__init__()
        self.is_res = is_res
        self.scale = scale
        # ------------------------------------------ #
        # Channel-wise Attention Model
        # ------------------------------------------ #
        self.ch_avg_pool = nn.AdaptiveAvgPool2d(1)
        self.ch_max_pool = nn.AdaptiveMaxPool2d(1)

        self.se_block = nn.Sequential(nn.Conv2d(in_chns, in_chns // reduct_ratio,
                                                kernel_size=1, stride=1, padding=0),
                                      nn.LeakyReLU(negative_slope=0.15, inplace=True),
                                      nn.Conv2d(in_chns // reduct_ratio, in_chns,
                                                kernel_size=1, stride=1, padding=0))
        # self.ch_conv = nn.Sequential(nn.Conv2d(in_chns, in_chns,
        #                                        kernel_size=1, stride=1, padding=0),
        #                              nn.BatchNorm2d(in_chns))

        self.sp_conv = nn.Sequential(nn.Conv2d(in_chns, in_chns // reduct_ratio,
                                               kernel_size=1, stride=1, padding=0, bias=False),
                                     nn.Conv2d(in_chns // reduct_ratio, in_chns // reduct_ratio,
                                               kernel_size=3, stride=1, padding=dilation,
                                               dilation=dilation, bias=False),
                                     nn.Conv2d(in_chns // reduct_ratio, in_chns // reduct_ratio,
                                               kernel_size=3, stride=1, padding=dilation,
                                               dilation=dilation, bias=False),
                                     nn.Conv2d(in_chns // reduct_ratio, 1, kernel_size=1,
                                               stride=1, padding=0, bias=False),
                                     nn.BatchNorm2d(1))
        self.sigmoid = nn.Sigmoid()

    def forward(self, x):
        # ------------------------------------------ #
        # 1. Channel-wise Attention Model
        # ------------------------------------------ #
        res = x
        avg_p = self.se_block(self.ch_avg_pool(x))
        max_p = self.se_block(self.ch_max_pool(x))
        ch_att = avg_p + max_p

        ch_att = torch.mul(x, self.sigmoid(ch_att).exp())

        # ------------------------------------------ #
        # 2. Spatial-wise Attention Model
        # ------------------------------------------ #
        sp_att = torch.mul(x, self.sigmoid(self.sp_conv(x)).exp())

        if self.is_res:
            return sp_att + res + ch_att

        return sp_att + ch_att

def soft_jaccard_loss(inputs, targets, weights=None, ignore_index=None):
    """
    inputs : NxCxHxW Variable
    targets :  NxHxW LongTensor
    weights : C FloatTensor
    ignore_index : int index to ignore from loss
    """
    smooth = 1.0
    # inputs = F.normalize(inputs, p=2, dim=1, eps=1e-5)
    inputs = F.log_softmax(inputs, dim=1).exp()
    encoded_target = inputs.detach() * 0  # The result will never require gradient.

    if ignore_index is not None:
        mask = targets == ignore_index
        targets = targets.clone()
        targets[mask] = 0

        encoded_target.scatter_(1, targets.unsqueeze(1), 1)
        mask = mask.unsqueeze(1).expand_as(encoded_target)  # the shape of mask as same as encoded_target
        encoded_target[mask] = 0
    else:
        encoded_target.scatter_(1, targets.unsqueeze(1), 1)

    if weights is None:
        weights = 1

    intersection = inputs * encoded_target
    numerator = intersection.sum(dim=0).sum(dim=1).sum(dim=1)
    denominator = inputs + encoded_target

    if ignore_index is not None:
        denominator[mask] = 0

    denominator = denominator.sum(dim=0).sum(dim=1).sum(dim=1) + smooth
    loss_per_channel = weights * (1.0 - torch.log((numerator + smooth) / (denominator - numerator + smooth)))

    return loss_per_channel.sum() / inputs.size(1)

def dice_loss(inputs, targets, weights=None, ignore_index=None):
    """
    inputs : NxCxHxW Variable
    targets :  NxHxW LongTensor
    weights : C FloatTensor
    ignore_index : int index to ignore from loss
    """
    smooth = 1.0
    # inputs = F.normalize(inputs, p=2, dim=1, eps=1e-5)
    inputs = F.log_softmax(inputs, dim=1).exp()
    encoded_target = inputs.detach() * 0  # The result will never require gradient.

    if ignore_index is not None:
        mask = targets == ignore_index
        targets = targets.clone()
        targets[mask] = 0

        encoded_target.scatter_(1, targets.unsqueeze(1), 1)
        mask = mask.unsqueeze(1).expand_as(encoded_target)
        encoded_target[mask] = 0
    else:
        encoded_target.scatter_(1, targets.unsqueeze(1), 1)

    if weights is None:
        weights = 1

    intersection = inputs * encoded_target
    numerator = 2.0 * intersection.sum(dim=0).sum(dim=1).sum(dim=1) + smooth
    denominator = inputs + encoded_target

    if ignore_index is not None:
        denominator[mask] = 0

    denominator = denominator.sum(dim=0).sum(dim=1).sum(dim=1) + smooth
    loss_per_channel = weights * (1.0 - (numerator / denominator))

    return loss_per_channel.sum() / inputs.size(1)

class HookBasedFeatureExtractor(nn.Module):
    def __init__(self, model, layer_name, upscale=False):
        super(HookBasedFeatureExtractor, self).__init__()

        self.model = model
        self.model.eval()
        self.layer_name = layer_name
        self.outputs_size = None
        self.outputs = None
        self.inputs = None
        self.inputs_size = None
        self.upscale = upscale

    def get_input_array(self, m, i, o):
        if isinstance(i, tuple):
            self.inputs = [i[index].data.clone() for index in range(len(i))]
            self.inputs_size = [input.size() for input in self.inputs]
        else:
            self.inputs = i.data.clone()
            self.inputs_size = self.input.size()
        print('Input Array Size: ', self.inputs_size)

    def get_output_array(self, m, i, o):
        if isinstance(o, tuple):
            self.outputs = [o[index].data.clone() for index in range(len(o))]
            self.outputs_size = [output.size() for output in self.outputs]
        else:
            self.outputs = o.data.clone()
            self.outputs_size = self.outputs.size()
        print('Output Array Size: ', self.outputs_size)

    def rescale_output_array(self, newsize):
        us = nn.Upsample(size=newsize[2:], mode='bilinear')
        if isinstance(self.outputs, list):
            for index in range(len(self.outputs)): self.outputs[index] = us(self.outputs[index]).data()
        else:
            self.outputs = us(self.outputs).data()

    def forward(self, x):
        layers = self.model._modules
        target_layer = layers[self.layer_name]

        # Collect the output tensor
        h_inp = target_layer.register_forward_hook(self.get_input_array)
        h_out = target_layer.register_forward_hook(self.get_output_array)

        self.model(x)
        h_inp.remove()
        h_out.remove()

        # Rescale the feature-map if it's required
        if self.upscale:
            self.rescale_output_array(x.size())

        return self.inputs, self.outputs

"""
image = data_preprocess(img_org, mean)
    _, out_feat = extractor.forward(image)

    out_feat = out_feat.numpy()
    out_feat = np.squeeze(out_feat)

for chn, feat in enumerate(out_feat):
        print("> +++++++++++++++++++++++++++++++++++++++++++++ <")
        print("> Processing Channel: {}...".format(chn))
        feat = 255.0 * ((feat - feat.min().min()) / (feat.max().max() - feat.min().min()))
        feat = feat.astype(np.uint8)
        feat = misc.imresize(feat, (net_h, net_w), interp="bilinear")

        # cv2.namedWindow("ImageOut", cv2.WINDOW_NORMAL)
        # cv2.imshow("ImageOut", feat)
        # cv2.waitKey()

        fig, axs = plt.subplots(ncols=2, sharey=True, figsize=(14, 6))
        axs[0].set_title('blue should be up')
        pos = axs[0].imshow(img_org_copy, origin='left')
        axs[0].get_xaxis().set_visible(False)
        axs[0].get_yaxis().set_visible(False)
        axs[0].set_title("Base Image")
        fig.colorbar(pos, ax=axs[0])

        axs[1].set_title('blue should be down')
        axs[1].imshow(feat, origin='right')
        pos = axs[1].imshow(img_org_copy, origin='right', alpha=0.225)
        axs[1].get_xaxis().set_visible(False)
        axs[1].get_yaxis().set_visible(False)
        axs[1].set_title("HeatMap on Image")
        fig.colorbar(pos, ax=axs[1])
        plt.tight_layout()

        # plt.imshow(feat)
        # plt.imshow(img_org_copy, alpha=0.425)
        # plt.colorbar()
        # plt.savefig(os.path.join(save_root, str(chn) + "_heatmap_2d.png"))
        plt.show()

"""


# -*- coding: utf-8 -*-
# 导入库
from urllib import request

#内容的抓取操作
from bs4 import BeautifulSoup

# 请求

url1 = "https://www.google.com/search?q=she-ra+sexy+pic"
url2 = "&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjmsOeK74PiAhUBna0KHYugCFkQ_AUIDigB&biw=1569&bih=731"

response = request.urlopen("http://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word=she-ra",timeout=10)
print(type(response))
# 解码
html_content = response.read().decode('utf-8',"ignore")

beditor=BeautifulSoup(html_content,'html.parser')

myh1 = beditor.find('a')  #find方法只能找到一个

myh2 = beditor.findAll('a') #findall方法查找所有的

# 输出1
print(myh1.string)

#输出2
for i in myh2:
    print(i.string)


from openerp import models, fields, api

class SaleOrder(models.Model):
    _inherit = "sale.order"

    allowed_templates = fields.Many2many(
        comodel_name='product.template', string='Allowed product templates')

    @api.one
    @api.onchange('only_allowed_products')
    def onchange_only_allowed_products(self):
        template_obj = self.env['product.template']
        self.allowed_templates = template_obj.search([('sale_ok', '=', True)])
        if self.only_allowed_products and self.partner_id:
            supplierinfos = self.env['product.supplierinfo'].search(
                [('type', '=', 'customer'),
                 ('name', 'in', (self.partner_id.commercial_partner_id.id,
                                 self.partner_id.id))])
            self.allowed_templates = template_obj.search(
                [('id', 'in', [x.product_tmpl_id.id for x in supplierinfos])])


import math
from math import sqrt

"""
For Space Time Complexity Question to ask:
-ARE WE ADDING MORE SPACE? /ITEM INSTANTIATION/ ARE WE CREATING ANYTHING
-
"""

# O(1) space complexity example
#
# Same additional space used no matter how big `n` is.
def foo(n):
  total = 0 # creating O(1) space here

  for i in range(n): #no space complexity
    total += i #not creating more space, just manipulating total var

  return total

# O(n) space complexity example
#
# Additional space used is proportional to `n` (DIFF SCOPE, MULT. INNER LOOP IS O(1))
def bar(n):
  sums = [] #O(1)

  for i in range(n): #not creating space complexity if the code inside it isn't adding space, but if it is, space is added for n size in this exanple
    sums.append(i + i) #O(1) space

  return sums

# O(n^2) space complexity example
#
# Additional space used increases by the square of `n`
def baz(n):
  times_table = [] #O(1)

  for i in range(n): #(n)
    row = [] #O(1)

    for j in range(n): #(n)
      row.append(j * i) #O(1)

      #for i in range (10): # this would be O(1)

    times_table.append(row)

  return times_table


from smtplib import SMTPDataError, SMTPRecipientsRefused, SMTPSenderRefused
from typing import List

from apps.api.models import ExeChangeUser
from django.conf import settings

def send_user_email(user: ExeChangeUser, subject: str, contents: List[str]) -> bool:  # type: ignore
    """
    This function sends an email to the email stored in the user object

    Args:
        user (ExeChangeUser): User to send email to
        subject (str): Subject line of email
        contents (List[str]): Contents of the email

    Returns:
        bool: Success or Failure
    """
    # send email
    try:
        settings.YAG.send(to=user.email, subject=subject, contents=contents)  # type: ignore
        return True

    except SMTPRecipientsRefused:
        print("ERROR: Recipient(s) refused the email")
        return False

    except SMTPSenderRefused:
        print("ERROR: Sender refused to send the email")
        return False

    except SMTPDataError:
        print("ERROR: SMTP server did not accept the data")
        return False

    except AttributeError:
        print("ERROR: YAG in settings was never set up")
        return False


import json
import yaml
from pathlib import Path

def get_title(meta):
    if meta['source_metadata']['title'] != None:
        title = meta['source_metadata']['title']
        return title
    else:
        return None
def create_json(title):
    meta = {
                "description": f"{title}",
                "homepage": "https://github.com/ta4tsering/P0081656",
                "keywords": [
                    "sync",
                    "repo",
                    "metadata",
                    "npm",
                    "nuget",
                    "description",
                    "homepage",
                    "website",
                    "topics",
                    "keywords"
                ]
            }
    return meta

if __name__=='__main__':
    pecha_id = 'P005633'
    meta_yml_content = Path(f"./{pecha_id}/{pecha_id}.opf/meta.yml").read_text(encoding="utf-8")
    meta_content = yaml.safe_load(meta_yml_content)
    title = get_title(meta_content)
    meta_path = Path(f"./metadata")
    meta_path.mkdir(exist_ok=True, parents=True)
    meta = create_json(title)
    with open(f'{meta_path}/meta.json', 'w') as f:
        json.dump(meta, f)


import os
from sys import argv
from PyQt5.QtCore import QUrl, QSize
from PyQt5.QtGui import QIcon, QColor
from PyQt5.QtWebEngineWidgets import QWebEngineView

# from PyQt5.QtPrintSupport import *
from PyQt5.QtWidgets import (
    QMainWindow,
    QToolBar,
    QAction,
    QLineEdit,
    QTabWidget,
    QStatusBar,
    QApplication,
)

class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        # BG Color
        THE_COLOR = [QColor(69, 71, 73), QColor(250, 250, 250)]
        self.setAutoFillBackground(True)
        pal = self.palette()
        pal.setColor(self.backgroundRole(), THE_COLOR[0])
        self.setPalette(pal)

        # Tabs
        self.tabs = QTabWidget()
        self.tabs.setDocumentMode(True)
        self.tabs.tabBarDoubleClicked.connect(self.tab_open_doubleclick)
        self.tabs.currentChanged.connect(self.current_tab_changed)
        self.tabs.setTabsClosable(True)
        self.tabs.tabCloseRequested.connect(self.close_current_tab)
        self.setCentralWidget(self.tabs)

        # Status Bar
        self.status = QStatusBar()
        self.setStatusBar(self.status)

        # Navegation Bar
        navbar = QToolBar("Navigation")
        navbar.setIconSize(QSize(35, 35))
        self.addToolBar(navbar)

        # Icon Color = White or Black
        Icon_Color = ["_w", "_b"]

        # Back Button
        back_btn = QAction(QIcon(f"assets/left{Icon_Color[0]}.png"), "← Go Back", self)
        back_btn.triggered.connect(lambda: self.tabs.currentWidget().back())
        navbar.addAction(back_btn)

        # Forward Button
        forward_btn = QAction(
            QIcon(f"assets/right{Icon_Color[0]}.png"), "Go Forward →", self
        )
        forward_btn.triggered.connect(lambda: self.tabs.currentWidget().forward())
        navbar.addAction(forward_btn)

        # Reload Button
        reload_btn = QAction(
            QIcon(f"assets/reload{Icon_Color[0]}.png"), "Reload 🔃", self
        )
        reload_btn.triggered.connect(lambda: self.tabs.currentWidget().reload())
        navbar.addAction(reload_btn)

        # Stop Button
        stop_btn = QAction(QIcon(f"assets/stop{Icon_Color[0]}.png"), "Stop ❌", self)
        stop_btn.triggered.connect(lambda: self.tabs.currentWidget().stop())
        navbar.addAction(stop_btn)

        # Separator
        navbar.addSeparator()

        # Search Bar
        self.url_bar = QLineEdit()
        self.url_bar.returnPressed.connect(self.nav_to_url)
        navbar.addWidget(self.url_bar)

        # Home Button
        home_btn = QAction(
            QIcon(f"assets/home{Icon_Color[0]}.png"), "To Homepage🏠", self
        )
        home_btn.triggered.connect(self.nav_home)
        navbar.addAction(home_btn)

        # New Tab
        self.add_new_tab(QUrl("https://duckduckgo.com/"), "Homepage🏠")
        self.showMaximized()
        self.setWindowTitle("Wea Browser 2")

    # Add New Tabs
    def add_new_tab(self, qurl=None, label="Blank"):
        if qurl is None:
            qurl = QUrl("https://duckduckgo.com/")
        browser = QWebEngineView()
        browser.setUrl(qurl)

        # Index
        i = self.tabs.addTab(browser, label)
        self.tabs.setCurrentIndex(i)

        # Update Url
        browser.urlChanged.connect(
            lambda qurl, browser=browser: self.update_url_bar(qurl, browser)
        )
        browser.loadFinished.connect(
            lambda _, i=i, browser=browser: self.tabs.setTabText(
                i, browser.page().title()
            )
        )

    # Double Click To Open New Tab
    def tab_open_doubleclick(self, i):
        if i == -1:
            self.add_new_tab()

    def current_tab_changed(self, i):
        qurl = self.tabs.currentWidget().url()
        self.update_url_bar(qurl, self.tabs.currentWidget())
        self.update_title(self.tabs.currentWidget())

    # To Close a Tab
    def close_current_tab(self, i):
        if self.tabs.count() < 2:
            return
        self.tabs.removeTab(i)

    def update_title(self, browser):
        if browser != self.tabs.currentWidget():
            return
        title = self.tabs.currentWidget().page().title()
        self.setWindowTitle("% s - Browser" % title)

    # Nav To Homepage
    def nav_home(self):
        self.tabs.currentWidget().setUrl(QUrl("https://duckduckgo.com/"))

    # Nav To The Link You Wrote
    def nav_to_url(self):
        q = QUrl(self.url_bar.text())
        if q.scheme() == "":
            q.setScheme("https")
        self.tabs.currentWidget().setUrl(q)

    def update_url_bar(self, q, browser=None):
        if browser != self.tabs.currentWidget():
            return
        self.url_bar.setText(q.toString())
        self.url_bar.setCursorPosition(0)

app = QApplication(argv)
app.setApplicationName("Wea Browser 2")
window = MainWindow()
app.exec_()


import cv2
import os
import pandas as pd
import numpy as np
import time

df = pd.read_csv('right test images & csv/test_labels.csv')
column_name = ['filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax']
list_filename = []
img_width = 640
img_height = 480
#For Right Arrow
#obj_class = 'right_arrow'
#For Left Arrow
obj_class = 'left_arrow'
new_data = []

for i in df.index:
    phot = cv2.imread(os.path.join(os.getcwd(), 'right test images & csv', df['filename'][i]))
# For Left Arrow
    name = df['filename'][i]
    hor_flip = cv2.flip(phot, 1)
    cv2.imwrite(f'/home/anirudh_/images/right test images & csv/L{name}.jpg', hor_flip)
    hor_flip = cv2.rectangle(hor_flip,(640-df['xmin'][i],df['ymin'][i]),(640-df['xmax'][i],df['ymax'][i]),(0,0,255),2)
    cv2.imshow("FLIPPED_VIEW", hor_flip)
    data = (f'L{name}', img_width, img_height, obj_class, 640-df['xmin'][i], df['ymin'][i], 640-df['xmax'][i], df['ymax'][i])
#For Right Arrow
    # cv2.imwrite(f'/home/anirudh_/More Images/R 0/{j}.jpg', phot)
    # phot = cv2.rectangle(phot,(df['xmin'][i],df['ymin'][i]),(df['xmax'][i],df['ymax'][i]),(255,0,0),2)
    # cv2.imshow("ACTUAL_VIEW", phot)
    # data = (f'{j}', img_width, img_height, obj_class, df['xmin'][i], df['ymin'][i], df['xmax'][i], df['ymax'][i])
    new_data.append(data)
    new_df = pd.DataFrame(new_data, columns=column_name)
    time.sleep(0.05)
    if cv2.waitKey(1) & 0xFF == ord('a'):
        break

#For Left Arrow
new_df.to_csv('test.csv', index=None)

#For Right Arrow
# new_df.to_csv('train_right_more.csv', index=None)


import os
import argparse
import numpy as np
import pprint

def arguments():
  parser = argparse.ArgumentParser()
  parser.add_argument('-p', dest='percentage', metavar='N', default=70)
  parser.add_argument('file')
  parser.add_argument('-t', '--train', default='train')
  parser.add_argument('-v', '--validation', default='validation')
  parser.add_argument('-r', '--randomize', action='count', default=0)

  return parser.parse_args()

def main():
  args = arguments()
  lines = []
  percentage = args.percentage/100.0
  with open(args.file, 'r') as file:
    lines = file.readlines()

  if args.randomize > 0:
    np.random.shuffle(lines)

  line_count = len(lines)
  print('Total Lines', line_count)
  train_lines = int(line_count*percentage)
  print('Train Size', train_lines)
  print('Validation Size', line_count - train_lines)

  train = lines[:train_lines]
  validation = lines[train_lines:]
  print('Train Size', len(train))
  print('Validation Size', len(validation))

  write(args.train, train)
  write(args.validation, validation)

def write(name, lines):
  with open(name, 'w') as file:
    file.writelines(lines)

if __name__ == "__main__":
  main()