# stocker l'image das un variable

from PIL import Image

# Calculer le nombre de personne présente sur l'image
# sachant qu'un personne correspond aux pixels entre M - 10 et M
# 1 personne = 40 pixel dans le techlab
# convertir en entier

# print(int(count / 40))

# importer les 8 images i.png pour i allant de 1 à 8, les convertir en gris et les stocker dans une matrice

# Path: img.jpg

im1 = Image.open("images/1.jpg")

# calculer le nombre de personne présente sur chaque image

def countPerson(img):
    img_grey = img.convert("L")
    width, height = img_grey.size
    nb_pixels_per_person = 70
    pixelsGrey = [[0 for x in range(width)] for y in range(height)]
    for x in range(width):
        for y in range(height):
            g = img_grey.getpixel((x, y))
            pixelsGrey[y][x] = g
    M = max(
        [max(pixelsGrey[i]) for i in range(len(pixelsGrey))]
    )
    count = 0
    for i in range(len(pixelsGrey)):
        for j in range(len(pixelsGrey[0])):
            if pixelsGrey[i][j] >= M - 10:
                count += 1
    return int(count / nb_pixels_per_person)

# calculer le nombre de personne présente sur chaque image
# et afficher le résultat

print(countPerson(im1))


# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from paginate_sqlalchemy import SqlalchemyOrmPage as SQLAlchemyORMPage
from pyramid.httpexceptions import HTTPBadRequest, HTTPNotFound, HTTPSeeOther
from pyramid.view import view_config

from warehouse.malware.models import (
    MalwareCheck,
    MalwareVerdict,
    VerdictClassification,
    VerdictConfidence,
)
from warehouse.utils.paginate import paginate_url_factory

@view_config(
    route_name="admin.verdicts.list",
    renderer="admin/malware/verdicts/index.html",
    permission="moderator",
    request_method="GET",
    uses_session=True,
)
def get_verdicts(request):
    result = {}
    result["check_names"] = set(
        [name for (name,) in request.db.query(MalwareCheck.name)]
    )
    result["classifications"] = set([c.value for c in VerdictClassification])
    result["confidences"] = set([c.value for c in VerdictConfidence])

    validate_fields(request, result)

    result["verdicts"] = SQLAlchemyORMPage(
        generate_query(request.db, request.params),
        page=int(request.params.get("page", 1)),
        items_per_page=25,
        url_maker=paginate_url_factory(request),
    )

    return result

@view_config(
    route_name="admin.verdicts.detail",
    renderer="admin/malware/verdicts/detail.html",
    permission="moderator",
    request_method="GET",
    uses_session=True,
)
def get_verdict(request):
    verdict = request.db.query(MalwareVerdict).get(request.matchdict["verdict_id"])

    if verdict:
        return {
            "verdict": verdict,
            "classifications": list(VerdictClassification.__members__.keys()),
        }

    raise HTTPNotFound

@view_config(
    route_name="admin.verdicts.review",
    permission="moderator",
    request_method="POST",
    uses_session=True,
    require_methods=False,
    require_csrf=True,
)
def review_verdict(request):
    verdict = request.db.query(MalwareVerdict).get(request.matchdict["verdict_id"])

    try:
        classification = getattr(VerdictClassification, request.POST["classification"])
    except (KeyError, AttributeError):
        raise HTTPBadRequest("Invalid verdict classification.") from None

    verdict.manually_reviewed = True
    verdict.reviewer_verdict = classification

    request.session.flash(
        "Verdict %s marked as reviewed." % verdict.id, queue="success"
    )

    # If no query params are provided (e.g. request originating from
    # admins.verdicts.detail view), then route to the default list view
    query = request.GET or {"classification": "threat", "manually_reviewed": "0"}
    return HTTPSeeOther(request.route_path("admin.verdicts.list", _query=query))

def validate_fields(request, validators):
    try:
        int(request.params.get("page", 1))
    except ValueError:
        raise HTTPBadRequest("'page' must be an integer.") from None

    validators = {**validators, **{"manually_revieweds": set(["0", "1"])}}

    for key, possible_values in validators.items():
        # Remove the trailing 's'
        value = request.params.get(key[:-1])
        additional_values = set([None, ""])
        if value not in possible_values | additional_values:
            raise HTTPBadRequest(
                "Invalid value for '%s': %s." % (key[:-1], value)
            ) from None

def generate_query(db, params):
    """
    Returns an SQLAlchemy query wth request params applied as filters.
    """
    query = db.query(MalwareVerdict)
    if params.get("check_name"):
        query = query.join(MalwareCheck)
        query = query.filter(MalwareCheck.name == params["check_name"])
    if params.get("confidence"):
        query = query.filter(MalwareVerdict.confidence == params["confidence"])
    if params.get("classification"):
        query = query.filter(MalwareVerdict.classification == params["classification"])
    if params.get("manually_reviewed"):
        query = query.filter(
            MalwareVerdict.manually_reviewed == bool(int(params["manually_reviewed"]))
        )

    return query.order_by(MalwareVerdict.run_date.desc())


from django.conf.urls import patterns, url

from .views import (
	createLine,
	getLine,
	getAllLines,

	createLocation,
        getLocation,

        createEmotion,
        getEmotion,
        getAllEmotions,

        createPledgeBreak1,
        getPledgeBreak,
        getAllPledgeBreaks,

        createPartyQuirk,
        getPartyQuirk,
        getAllPartyQuirks,

        createPartyQuirk2,
        getPartyQuirk2,
        getAllPartyQuirks2,

        createPartyQuirk3,
        getPartyQuirk3,
        getAllPartyQuirks3,

        wstest,
        wsline,
        wsline1,
        wsscript,
        wsgeturl,
        getSlides,

        createHaloblue,
        createHalogreen,
        createHaloyellow,
        createHaloredyellow,
        createHalopurple,

        getHaloblue,
        getHalogreen,
        getHaloyellow,
        getHaloredyellow,
        getHalopurple
)

urlpatterns = (

	url(r"^lines/create/$", createLine, name="createLine"),
	url(r"^lines/get/$", getLine, name="getLine"),
	url(r"^lines/getall/$", getAllLines, name="getAllLines"),

        url(r"^dinnerparty/create/$", createLocation, name="createLocation"),
        url(r"^dinnerparty/get/$", getLocation, name="getLocation"),

        url(r"^jumpgenre/create/$", createEmotion, name="createStyle"),
        url(r"^jumpgenre/get/$", getEmotion, name="getStyle"),
        url(r"^jumpgenre/getall/$", getAllEmotions, name="getAllStyles"),

        url(r"^productpitch/create/$", createPledgeBreak1, name="createNoun"),
        url(r"^productpitch/get/$", getPledgeBreak, name="getNoun"),
        url(r"^productpitch/getall/$", getAllPledgeBreaks, name="getAllNouns"),

        url(r"^partyquirks1/create/$", createPartyQuirk, name="createQuirk"),
        url(r"^partyquirks1/get/$", getPartyQuirk, name="getQuirk"),
        url(r"^partyquirks1/getall/$", getAllPartyQuirks, name="getAllQuirks"),

        url(r"^partyquirks2/create/$", createPartyQuirk2, name="createCelebrity"),
        url(r"^partyquirks2/get/$", getPartyQuirk2, name="getCelebrity"),
        url(r"^partyquirks2/getall/$", getAllPartyQuirks2, name="getAllCelebrities"),

        url(r"^partyquirks3/create/$", createPartyQuirk3, name="createQuirk3"),
        url(r"^partyquirks3/get/$", getPartyQuirk3, name="getQuirk3"),
        url(r"^partyquirks3/getall/$", getAllPartyQuirks3, name="getAllQuirks3"),

        url(r"^slides/get/$", getSlides, name="getSlides"),

        url(r"^ws/$", wstest, name="wstest"),
        url(r"^ws/get/$", wsgeturl, name="wsgeturl"),
        url(r"^ws/line/$", wsline, name="wsline"),
        url(r"^ws/line1/$", wsline1, name="wsline1"),
        url(r"^ws/loadscript/$", wsscript, name="wsscript"),

        url(r"^api/haloblue/create/$", createHaloblue, name="createHaloblue"),
        url(r"^api/haloblue/get/$", getHaloblue, name="getHaloblue"),

        url(r"^api/halogreen/create/$", createHalogreen, name="createHalogreen"),
        url(r"^api/halogreen/get/$", getHalogreen, name="getHalogreen"),

        url(r"^api/haloyellow/create/$", createHaloyellow, name="createHaloyellow"),
        url(r"^api/haloyellow/get/$", getHaloyellow, name="getHaloyellow"),

        url(r"^api/haloredyellow/create/$", createHaloredyellow, name="createHaloredyellow"),
        url(r"^api/haloredyellow/get/$", getHaloredyellow, name="getHaloredyellow"),

        url(r"^api/halopurple/create/$", createHalopurple, name="createHalopurple"),
        url(r"^api/halopurple/get/$", getHalopurple, name="getHalopurple")

)


import sys
from PySide6 import QtWidgets
# import wx
from demo.MainTreeWidget import MainTreeWidget

def main():
    # app = wx.App()
    app.MainLoop()

if __name__ == "__main__":
    app = QtWidgets.QApplication([])

    widget = MainTreeWidget()
    widget.resize(300, 1200)
    widget.show()

    sys.exit(app.exec())


from apiDev.models import Store, Product, Category, Customer, Order
from apiDev.serializers import StoreSerializer, ProductSerializer, CategorySerializer, CustomerSerializer, OrderSerializer, RegisterSerializer
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.authtoken.serializers import AuthTokenSerializer
from rest_framework import viewsets, status
from knox.auth import AuthToken

# user auth views
@api_view(['POST'])
def login_view(request):
    serializer = AuthTokenSerializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    user = serializer.validated_data['user']

    _, token = AuthToken.objects.create(user)

    return Response({
        'user_info':
        {
            'id':user.id,
            'username':user.username,
        },
        'token':token
    })

@api_view(["GET"])
def get_user_data(request):
    user = request.user

    if user.is_authenticated:
        return Response({
            'user_info':{
                "id":"user.id",
                "username":user.username,
            },

        })

    return Response({'error':'You are not authorize to access this end point'}, status=status.HTTP_400_BAD_REQUEST)

@api_view(['POST'])
def register_user(request):
    serializer = RegisterSerializer(data = request.data)
    serializer.is_valid(raise_exception=True)

    user = serializer.save()

    _, token = AuthToken.objects.create(user)

    return Response({
                        'user_info':
                        {
                            'id':user.id,
                            'username':user.username,
                        },
                        'token':token
                    })

class StoreViewSet(viewsets.ModelViewSet):
    serializer_class = StoreSerializer
    queryset = Store.objects.all()

class ProductViewSet(viewsets.ModelViewSet):
    serializer_class = ProductSerializer
    queryset = Product.objects.all()

class CategoryViewSet(viewsets.ModelViewSet):
    serializer_class = CategorySerializer
    queryset = Category.objects.all()

class CustomerViewSet(viewsets.ModelViewSet):
    serializer_class = CustomerSerializer
    queryset = Customer.objects.all()

class OrderViewSet(viewsets.ModelViewSet):
    serializer_class = OrderSerializer
    queryset = Order.objects.all()


# https://github.com/Noixas/BERT-Toxicity

import numpy as np
import torch.utils.data
import torch
import json
import regex as re
import csv
from datetime import datetime
from pytorch_pretrained_bert import BertTokenizer, BertForSequenceClassification

BATCH_SIZE = 256
MAX_SEQUENCE_LENGTH = 128

def convert_lines(texts, max_seq_length, tokenizer):
    max_seq_length -= 2
    all_tokens = []
    longer = 0
    for text in texts:
        tokens_a = tokenizer.tokenize(text)
        if len(tokens_a) > max_seq_length:
            tokens_a = tokens_a[:max_seq_length]
            longer += 1
        one_token = tokenizer.convert_tokens_to_ids(['[CLS]']+tokens_a+['[SEP]'])+[0] * (max_seq_length - len(tokens_a))
        all_tokens.append(one_token)
    return np.array(all_tokens)

def get_predictions(comments):
    model.eval()
    with torch.no_grad():
        valid_preds_pews = np.zeros((len(comments)))
        valid_pews = torch.utils.data.TensorDataset(torch.tensor(comments, dtype=torch.long))
        valid_loader_pews = torch.utils.data.DataLoader(valid_pews, batch_size=BATCH_SIZE, shuffle=False)
        for i, (x_batch,) in enumerate(valid_loader_pews):
            pred_pews = model(x_batch.to(device), attention_mask=(x_batch > 0).to(device), labels=None)
            valid_preds_pews[i*BATCH_SIZE:(i+1)*BATCH_SIZE] = pred_pews[:,0].detach().cpu().squeeze().numpy()
        test_df_pews = torch.sigmoid(torch.tensor(valid_preds_pews)).numpy()
        return test_df_pews

device = torch.device('cuda')
model = BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=1)
model.load_state_dict(torch.load('bert_pytorch.bin'))
model.to(device)

tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')

def process_json(name):
    print('Processing', name)
    with open('json/' + name + '.json') as f:
        lines = f.readlines()

    date_to_threads = {}

    for line in lines:
        data = json.loads(line)
        text = data['title']
        if 'selftext' in data:
            text += ' ' + data['selftext']
        date = datetime.utcfromtimestamp(data['created_utc']).strftime('%Y-%m-%d')
        if date not in date_to_threads:
            date_to_threads[date] = []
        date_to_threads[date].append(text)

    with open('csv/' + name + '_texts.csv', 'a') as texts_csv_file, open('csv/' + name + '_output.csv', 'a') as output_csv_file:
        texts_writer = csv.writer(texts_csv_file, delimiter=',')
        output_writer = csv.writer(output_csv_file, delimiter=',')
        dates = [date for date, _ in date_to_threads.items()]
        dates.sort(reverse=True)
        for date in dates:
            texts = date_to_threads[date]
            converted = convert_lines(texts, MAX_SEQUENCE_LENGTH, tokenizer)
            predictions = get_predictions(converted)
            mean_prediction = np.mean(predictions)
            toxic_amount = len([tox for tox in predictions if tox > 0.5])
            total_threads = len(predictions)
            print(date, str(total_threads), str(toxic_amount), str(mean_prediction))
            for i in range(len(texts)):
                texts_writer.writerow([date, re.sub(r'[\r\n\t;]', ' ', texts[i])[0:MAX_SEQUENCE_LENGTH], str(predictions[i])])
            output_writer.writerow([date, str(total_threads), str(toxic_amount), str(mean_prediction)])

process_json('pathofexile')
process_json('diablo3')
process_json('Wolcen')
process_json('Warframe')
process_json('leagueoflegends')
process_json('GlobalOffensive')
process_json('DotA2')
process_json('Overwatch')
process_json('VALORANT')


"""Sample poses for testing the averaging algorithms.

The visualizations of this poses are stored in the folder: tests/data/viz_sample_poses

Authors: Ayush Baid
"""
import copy
from typing import Dict, List, Tuple

import numpy as np
from gtsam import Cal3_S2, Point3, Pose3, Rot3, Unit3
from gtsam.examples import SFMdata

DEFAULT_ROTATION = Rot3.RzRyRx(0, np.deg2rad(10), 0)
DEFAULT_TRANSLATION = np.array([0, 2, 0])

def generate_relative_from_global(
    wTi_list: List[Pose3], pair_indices: List[Tuple[int, int]]
) -> Dict[Tuple[int, int], Pose3]:
    """Generate relative poses from global poses.

    Args:
        wTi_list: global poses.
        pair_indices: pairs (i1, i2) to construct relative poses for.

    Returns:
        Dictionary (i1, i2) -> i2Ti1 for all requested pairs.
    """
    return {(i1, i2): wTi_list[i2].between(wTi_list[i1]) for i1, i2 in pair_indices}

"""4 poses in the circle of radius 5m, all looking at the center of the circle.

For relative poses, each pose has just 2 edges, connecting to the immediate neighbors.
"""
CIRCLE_TWO_EDGES_GLOBAL_POSES = SFMdata.createPoses(Cal3_S2(fx=1, fy=1, s=0, u0=0, v0=0))[::2]

CIRCLE_TWO_EDGES_RELATIVE_POSES = generate_relative_from_global(
    CIRCLE_TWO_EDGES_GLOBAL_POSES, [(1, 0), (2, 1), (3, 2), (0, 3)]
)

"""4 poses in the circle of radius 5m, all looking at the center of the circle.

For relative poses, each pose is connected to every other (3) pose.
"""
CIRCLE_ALL_EDGES_GLOBAL_POSES = copy.copy(CIRCLE_TWO_EDGES_GLOBAL_POSES)

CIRCLE_ALL_EDGES_RELATIVE_POSES = generate_relative_from_global(
    CIRCLE_TWO_EDGES_GLOBAL_POSES, [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
)

"""3 poses on a line, simulating forward motion, with large translations and no relative rotation.

For relative poses, we have a fully connected graph.
"""
LINE_LARGE_EDGES_GLOBAL_POSES = [
    Pose3(DEFAULT_ROTATION, DEFAULT_TRANSLATION + np.array([0, 0, 0])),
    Pose3(DEFAULT_ROTATION, DEFAULT_TRANSLATION + np.array([0, 0, 5])),
    Pose3(DEFAULT_ROTATION, DEFAULT_TRANSLATION + np.array([0, 0, 10])),
]

LINE_LARGE_EDGES_RELATIVE_POSES = generate_relative_from_global(LINE_LARGE_EDGES_GLOBAL_POSES, [(0, 1), (0, 2), (1, 2)])

"""3 poses on a line, simulating forward motion, with small translations and no relative rotation.

For relative poses, we have a fully connected graph.
"""
LINE_SMALL_EDGES_GLOBAL_POSES = [
    Pose3(DEFAULT_ROTATION, DEFAULT_TRANSLATION + np.array([0, 0, 0])),
    Pose3(DEFAULT_ROTATION, DEFAULT_TRANSLATION + np.array([0, 0, 1e-3])),
    Pose3(DEFAULT_ROTATION, DEFAULT_TRANSLATION + np.array([0, 0, 5e-3])),
]

LINE_SMALL_EDGES_RELATIVE_POSES = generate_relative_from_global(LINE_SMALL_EDGES_GLOBAL_POSES, [(0, 1), (0, 2), (1, 2)])

"""3 poses in a panorama (i.e. 3 translation values being the same but large relative rotations i.e. pitch varies)

For relative poses, we have a fully connected graph.
"""
PANORAMA_GLOBAL_POSES = [
    Pose3(Rot3.RzRyRx(0, np.deg2rad(-30), 0), DEFAULT_TRANSLATION),
    Pose3(Rot3.RzRyRx(0, 0, 0), DEFAULT_TRANSLATION),
    Pose3(Rot3.RzRyRx(0, np.deg2rad(+30), 0), DEFAULT_TRANSLATION),
]

PANORAMA_RELATIVE_POSES = generate_relative_from_global(PANORAMA_GLOBAL_POSES, [(0, 1), (0, 2), (1, 2)])

def convert_data_for_rotation_averaging(
    wTi_list: List[Pose3], i2Ti1_dict: Dict[Tuple[int, int], Pose3]
) -> Tuple[Dict[Tuple[int, int], Rot3], List[Rot3]]:
    """Converts the poses to inputs and expected outputs for a rotation averaging algorithm.

    Args:
        wTi_list: List of global poses.
        i2Ti1_dict: Dictionary of (i1, i2) -> i2Ti1 relative poses.

    Returns:
        i2Ti1_dict's values mapped to relative rotations i2Ri1.
        wTi_list mapped to global rotations.
    """

    wRi_list = [x.rotation() for x in wTi_list]
    i2Ri1_dict = {k: v.rotation() for k, v in i2Ti1_dict.items()}

    return i2Ri1_dict, wRi_list

def convert_data_for_translation_averaging(
    wTi_list: List[Pose3], i2Ti1_dict: Dict[Tuple[int, int], Pose3]
) -> Tuple[List[Rot3], Dict[Tuple[int, int], Unit3], List[Point3]]:
    """Converts the poses to inputs and expected outputs for a translation averaging algorithm.

    Args:
        wTi_list: List of global poses.
        i2Ti1_dict: Dictionary of (i1, i2) -> i2Ti1 relative poses.

    Returns:
        wTi_list mapped to global rotations.
        i2Ti1_dict's values mapped to relative unit translations i2Ui1.
        wTi_list mapped to global translations.
    """

    wRi_list = [x.rotation() for x in wTi_list]
    wti_list = [x.translation() for x in wTi_list]
    i2Ui1_dict = {k: Unit3(v.translation()) for k, v in i2Ti1_dict.items()}

    return wRi_list, i2Ui1_dict, wti_list


from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from bs4 import BeautifulSoup
import datetime
import time
import os

# Specify the path where chromedriver is installed
chrome_path = r"C:\Users\Siddhant Mahurkar\Desktop\chromedriver.exe"

driver = webdriver.Chrome(chrome_path)
driver.get("http://sat.gov.in/scripts/search.asp")

def get_data(year, month):

	date, appeal_no, ma_ra_no, title, pdf_link = [],[],[],[],[]

	select_year = Select(driver.find_element_by_xpath('//*[@id="form1"]/table/tbody/tr[2]/td/p/font/select[1]'))
	select_year.select_by_visible_text(year)

	select_month = Select(driver.find_element_by_xpath('//*[@id="form1"]/table/tbody/tr[2]/td/p/font/select[2]'))
	select_month.select_by_visible_text(month)

	driver.find_element_by_xpath('//*[@id="form1"]/table/tbody/tr[2]/td/p/font/input').click()

	a = []
	ar = driver.find_element_by_xpath('//*[@id="form1"]/table').get_attribute(('innerHTML'))
	table = BeautifulSoup(ar, "lxml")
	# for tr in table.find_all('tr'):
	# 	a.append(tr)

	for links in table.find_all('a'):

		link = links["href"]
		link = link[2:]

		pdf_link.append("http://sat.gov.in" + str(link))
		title.append(links.text)

	row_count = len(title)
	# t_data = driver.find_element_by_xpath('//*[@id="form1"]/table/tbody/tr[4]/td[1]')
	# t_data = t_data.text

	# for i in range(4,(((row_count+1)*2)+2),2):

	for i in range(4,(4 + (row_count)*2)+1,2):

		t_data_date = driver.find_element_by_xpath('//*[@id="form1"]/table/tbody/tr[' + str(i) + ']/td[1]')
		date.append(t_data_date.text)

		t_data_appeal = driver.find_element_by_xpath('//*[@id="form1"]/table/tbody/tr[' + str(i) + ']/td[2]')
		appeal_no.append(t_data_appeal.text)

		t_data_mara = driver.find_element_by_xpath('//*[@id="form1"]/table/tbody/tr[' + str(i) + ']/td[3]')
		ma_ra_no.append(t_data_mara.text)

	return date, appeal_no, ma_ra_no, title, pdf_link
# //*[@id="form1"]/table/tbody/tr[4]
# //*[@id="form1"]/table/tbody/tr[100]/td[2]
# //*[@id="form1"]/table/tbody/tr[120]/td[2]
# //*[@id="form1"]/table/tbody/tr[122]/td[2]
# //*[@id="form1"]/table/tbody/tr[78]/td[2]

date, appeal_no, ma_ra_no, title, pdf_link = get_data('2018', 'March')

print(date)
# print(len(date))
print("\n")
print(appeal_no)
# print(len(appeal_no))
print("\n")
print(ma_ra_no)
# print(len(ma_ra_no))
print("\n")
print(title)
# print(len(title))
print("\n")
print(pdf_link)
print(len(pdf_link))


import cv2 as cv
import numpy as np

blank = np.zeros((500,500,3),dtype='uint8')
cv.imshow('Blank',blank)

'''img = cv.imread("Images\img2.jpg")
cv.imshow('Image',img)'''

#Paint the image
'''blank[:]=0,255,0
cv.imshow('Green',blank)

blank[0:100,10:110]=0,0,255
cv.imshow('Red',blank)'''

#Draw a rectangle
cv.rectangle(blank,(0,0),(blank.shape[0]//3,blank.shape[1]//3),(255,0,0),thickness=-1)
cv.imshow("Rectangle",blank)

cv.rectangle(blank,(0,0),(200,200),(255,0,0),thickness=-1)
cv.imshow("Rectangle",blank)

#Draw a circle
blank1 = np.zeros((500,500,3),dtype='uint8')
cv.circle(blank1,(blank1.shape[0]//2,blank1.shape[1]//2),50,(200,200,200),thickness=-1)
cv.imshow('Circle',blank1)

#Draw a line
cv.line(blank1,(0,0),(250,250),(255,255,255),thickness=4)
cv.imshow('Line',blank1)

#Write text on an image
cv.putText(blank1,'I am C.V.Anish',(250,250),cv.FONT_HERSHEY_DUPLEX,1,(0,0,255),2)
cv.imshow("Text",blank1)

cv.waitKey(0)


#!/usr/bin/env python
# coding: utf-8

# # Project Assignment 5 - Get different types of data
# ## Author: Jonathan Heard
# ## Class: CIS256DA

# Chapter 5 Asignment
#
# Search KaggleLinks to an external site. for something that you are interested in to see if there is any datasets related to that interest. If there is, download that dataset.  If not, just download one of the trending datasets in the trending section as shown below (2 pts.):
#
# Tasks
#
# 1. Read the data from the CSV file into a DataFrame (2 pts.).
# 2. Display the first five rows of data (2 pts.).
# 3. Display information about each of the columns (2 pts.).
#
# Question
#
# Why did you choose the downloaded dataset (2 pts.)?
#
#
# After completing the assignment, please submit your .ipynb file and the dataset you downloaded from Kaggle.
#
#

# ### The url for the site the data came from is:
#
# https://www.kaggle.com/datasets/taruntiwarihp/phishing-site-urls
#
# The download was a 9 MB zip file,
#     called "Malicious_and_Phishing_attacks_ulrs_archive.zip"

# ## Import required modules

# In[1]:

# Import the modules needed for this project.

# Import pandas and assign the alias pd
import pandas as pd

# Import ZipFile from the zipfile module
from zipfile import ZipFile

# ## Tasks list

# In[2]:

# Extract the files from the zip file and diplsy the file names

file_names = list()
with ZipFile('Malicious_and_Phishing_attacks_ulrs_archive.zip', mode = 'r') as zip:
    zip.extractall()
    for file in zip.infolist():
        file_names.append(file.filename)
        print(file.filename, file.compress_size, file.file_size)

# In[3]:

# Task 01 Read the data from the CSV file into a DataFrame (2 pts.).

phishing = pd.read_csv('phishing_site_urls.csv')

# In[4]:

# Task 02 Display the first five rows of data (2 pts.).

phishing.head()

# In[5]:

# Task 03 Display information about each of the columns (2 pts.).

phishing.info()

# ## Question

# ### Why did you choose the downloaded dataset (2 pts.)?
#
# The reason for my line of inquiry, is that I am always looking into Cybersecurity topics. I was not very happy with
#     my first few attempts at this assignment.
#
# I had to download 4 different zip files, before I found one that would let step 1 proceed.
#     "Read the data from the CSV file into a DataFrame."
#
# I finally decided to quit looking once, I was able to satisfy the requirements for this assignment.
#
# The "bad" csv files I tried, all gave the same error messages as in the Jonathan_Heard_PA-5_Bad_csv.ipynb. I am
#     include
#
#
#

# In[ ]: