diff --git a/AWS Management Scripts/AWS Automation Script for AWS endorsement management/Readme.md b/AWS Management Scripts/AWS Automation Script for AWS endorsement management/Readme.md new file mode 100644 index 0000000000..698821ba7f --- /dev/null +++ b/AWS Management Scripts/AWS Automation Script for AWS endorsement management/Readme.md @@ -0,0 +1,37 @@ +## Aws Script for AWS Management + +This python script can be used to manage a AWS endorsement. + +This provides features like : + +### EC2 : + +1. Create your own Key based SnapShots +2. Delete SnapShots +3. Delete/ Terminate any EC2 instance which does not have a user/ any specific tag +4. stop any useless Running Ec2 instance + +### RDS : + +1. delete RDS Instance +2. Delete RDS Cluster +3. Stop any useless Running RDS Cluster/Instance +4. Delete useless Snapshots +5. Delete any RDS Instance or Cluster which does not have a specific tag with it +6. Delete any RDS Snapshot that is older then 2 days + +these Scripts can directly be used with AWS lambda function for Automation purposes as well + +## Installation + +First of all install [python]("https://www.python.org/downloads/") on your system. +``` +pip install boto3 +``` + +### Made with ❤️ by Shantam Sultania + +You can find me at:- +[Linkedin](https://www.linkedin.com/in/shantam-sultania-737084175/) or [Github](https://github.com/shantamsultania) . + +Happy coding ❤️ . diff --git a/AWS Management Scripts/AWS Automation Script for AWS endorsement management/awsLambda.py b/AWS Management Scripts/AWS Automation Script for AWS endorsement management/awsLambda.py new file mode 100644 index 0000000000..319354f032 --- /dev/null +++ b/AWS Management Scripts/AWS Automation Script for AWS endorsement management/awsLambda.py @@ -0,0 +1,17 @@ +def lambda_handler(event, context): + print("event " + str(event)) + print("context " + str(context)) + ec2_reg = boto3.client('ec2') + regions = ec2_reg.describe_regions() + for region in regions['Regions']: + region_name = region['RegionName'] + instances = Ec2Instances(region_name) + deleted_counts = instances.delete_snapshots(1) + instances.delete_available_volumes() + print("deleted_counts for region " + str(region_name) + " is " + str(deleted_counts)) + instances.shutdown() + print("For RDS") + rds = Rds(region_name) + rds.cleanup_snapshot() + rds.cleanup_instances() + return 'Hello from Lambda' diff --git a/AWS Management Scripts/AWS Automation Script for AWS endorsement management/ec2.py b/AWS Management Scripts/AWS Automation Script for AWS endorsement management/ec2.py new file mode 100644 index 0000000000..7e439e41e4 --- /dev/null +++ b/AWS Management Scripts/AWS Automation Script for AWS endorsement management/ec2.py @@ -0,0 +1,98 @@ +from datetime import datetime, timedelta, timezone + +import boto3 + + +def get_delete_data(older_days): + delete_time = datetime.now(tz=timezone.utc) - timedelta(days=older_days) + return delete_time; + + +def is_ignore_shutdown(tags): + for tag in tags: + print("K " + str(tag['Key']) + " is " + str(tag['Value'])) + if str(tag['Key']) == 'excludepower' and str(tag['Value']) == 'true': + print("Not stopping K " + str(tag['Key']) + " is " + str(tag['Value'])) + return True + return False + + +def is_unassigned(tags): + if 'user' not in [t['Key'] for t in tags]: + return True + return False + + +class Ec2Instances(object): + + def __init__(self, region): + print("region " + region) + + # if you are not using AWS Tool Kit tool you will be needing to pass your access key and secret key here + + # client = boto3.client('rds', region_name=region_name, aws_access_key_id=aws_access_key_id, + # aws_secret_access_key=aws_secret_access_key) + self.ec2 = boto3.client('ec2', region_name=region) + + def delete_snapshots(self, older_days=2): + delete_snapshots_num = 0 + snapshots = self.get_nimesa_created_snapshots() + for snapshot in snapshots['Snapshots']: + fmt_start_time = snapshot['StartTime'] + if fmt_start_time < get_delete_data(older_days): + try: + self.delete_snapshot(snapshot['SnapshotId']) + delete_snapshots_num + 1 + except Exception as e: + print(e) + return delete_snapshots_num + + def get_user_created_snapshots(self): + snapshots = self.ec2.describe_snapshots( + Filters=[{ + 'Name': 'owner-id', 'Values': ['your owner id'], + }]) # Filters=[{'Name': 'description', 'Values': ['Created by Nimesa']}] + return snapshots + + def delete_available_volumes(self): + volumes = self.ec2.describe_volumes()['Volumes'] + for volume in volumes: + if volume['State'] == "available": + self.ec2.delete_volume(VolumeId=volume['VolumeId']) + + def delete_snapshot(self, snapshot_id): + self.ec2.delete_snapshot(SnapshotId=snapshot_id) + + def shutdown(self): + instances = self.ec2.describe_instances() + instance_to_stop = [] + instance_to_terminate = [] + for res in instances['Reservations']: + for instance in res['Instances']: + tags = instance.get('Tags') + if tags is None: + instance_to_terminate.append(instance['InstanceId']) + continue + if is_unassigned(tags): + print("instance_to_terminate " + instance['InstanceId']) + instance_to_terminate.append(instance['InstanceId']) + if is_ignore_shutdown(tags): + continue + if instance['State']['Code'] == 16: + instance_to_stop.append(instance['InstanceId']) + + if any(instance_to_stop): + self.ec2.stop_instances( + InstanceIds=instance_to_stop + ) + if any(instance_to_terminate): + print(instance_to_terminate) + self.ec2.terminate_instances( + InstanceIds=instance_to_terminate + ) + + +if __name__ == "__main__": + ec2 = Ec2Instances('us-east-1') + ec2.delete_snapshots(3) + ec2.shutdown() diff --git a/AWS Management Scripts/AWS Automation Script for AWS endorsement management/rds.py b/AWS Management Scripts/AWS Automation Script for AWS endorsement management/rds.py new file mode 100644 index 0000000000..f967e6da7c --- /dev/null +++ b/AWS Management Scripts/AWS Automation Script for AWS endorsement management/rds.py @@ -0,0 +1,132 @@ +import boto3 +import datetime + + +class Rds(object): + + def __init__(self, region) -> None: + super().__init__() + self.rds = boto3.client('rds', region) + + def cleanup_snapshot(self): + self._cleanup_snapshot_instance() + self._cleanup_snapshots_clusters() + + def cleanup_instances(self): + clusters = self.rds.describe_db_clusters() + for cluster in clusters['DBClusters']: + self._cleanup_cluster(cluster) + instances = self.rds.describe_db_instances() + for instance in instances['DBInstances']: + self._cleanup_instance(instance) + + def _stop_cluster(self, identifier): + self.rds.stop_db_cluster(DBClusterIdentifier=identifier) + + def _stop_instance(self, identifier): + self.rds.stop_db_instance(DBInstanceIdentifier=identifier) + + def _delete_instance(self, identifier): + self.rds.describe_db_instances(DBInstanceIdentifier=identifier) + + def _delete_cluster(self, identifier): + self.rds.describe_db_clusters(DBClusterIdentifier=identifier) + + def _delete_instance_snapshot(self, identifier): + self.rds.delete_db_snapshot(DBSnapshotIdentifier=identifier) + + def _delete_cluster_snapshot(self, identifier): + self.rds.delete_db_cluster_snapshot(DBClusterSnapshotIdentifier=identifier) + + @staticmethod + def _can_delete_instance(tags): + if any('user' in tag for tag in tags): + return False + + @staticmethod + def _can_stop_instance(tags): + for tag in tags: + if tag["Key"].lower() == 'excludepower' and tag['Value'].lower() == 'true': + return False + return True + + @staticmethod + def _can_delete_snapshot(tags): + if tags is not None: + for tag in tags: + if tag['Key'].lower() == 'retain' and tag['Value'].lower() == 'true': + return False + return True + + def _cleanup_instance(self, instance): + identifier = instance['DBInstanceIdentifier'] + tags = instance['TagList'] + if self._can_delete_instance(tags): + self._delete_instance(identifier) + else: + if self._can_stop_instance(tags) and instance['DBInstanceStatus'] == 'available': + try: + self._stop_instance(identifier) + except Exception as e: + print(str(e)) + + def _cleanup_cluster(self, cluster): + tags = cluster['TagList'] + if self._can_delete_instance(tags): + self._delete_cluster(cluster['DBClusterIdentifier']) + else: + if self._can_stop_instance(tags) and cluster['Status'] == 'available': + try: + self._stop_cluster(cluster['DBClusterIdentifier']) + except Exception as e: + print(str(e)) + + def _cleanup_snapshots_clusters(self): + snapshots = self.rds.describe_db_cluster_snapshots() + for snapshot in snapshots['DBClusterSnapshots']: + tags = snapshot['TagList'] + if self._can_delete_snapshot(tags) and self._is_older_snapshot( + str(snapshot['SnapshotCreateTime']).split(" ")): + try: + self._delete_cluster_snapshot(snapshot['DBClusterSnapshotIdentifier']) + except Exception as e: + print(str(e)) + + def _cleanup_snapshot_instance(self): + snapshots = self.rds.describe_db_snapshots() + for snapshot in snapshots['DBSnapshots']: + tags = snapshot['TagList'] + if self._can_delete_snapshot(tags) and self._is_older_snapshot( + str(snapshot['SnapshotCreateTime']).split(" ")): + try: + self._delete_instance_snapshot(snapshot['DBSnapshotIdentifier']) + except Exception as e: + print(str(e)) + + @staticmethod + def _is_older_snapshot(snapshot_datetime): + snapshot_date = snapshot_datetime[0].split("-") + snapshot_date = datetime.date(int(snapshot_date[0]), int(snapshot_date[1]), int(snapshot_date[2])) + today = datetime.date.today() + if abs(today - snapshot_date).days > 2: + return True + else: + return False + + @staticmethod + def _check_snapshot_tag(tags): + flag = False + for tag in tags: + if tag['Key'].lower() == 'retain' and tag['Value'].lower() == 'true': + flag = True + if flag: + return True + else: + return False + + +if __name__ == "__main__": + rds = Rds('us-east-1') + # # rds.shutdown() + rds.cleanup_snapshot() + rds.cleanup_instances() diff --git a/AWS Management Scripts/AWS testing Script/Readme.md b/AWS Management Scripts/AWS testing Script/Readme.md new file mode 100644 index 0000000000..3cd5c52fdb --- /dev/null +++ b/AWS Management Scripts/AWS testing Script/Readme.md @@ -0,0 +1,29 @@ +## Aws Script for testing using moto (a AWS testing framework ) + +This python script automatically generates a set of EC2 machine's with any demo ami Id that could be used in case of testing. + +## Installation + +First of all install [python]("https://www.python.org/downloads/") on your system. +```bash +pip install moto +pip install boto3 +pip install Flask +``` + +## Results + +![](https://i.postimg.cc/Jzx6f02c/image1.png) + +![](https://i.postimg.cc/L6RVmRfy/image.png) + +![](https://i.postimg.cc/Zq1r2h4x/image.png) + +### Made with ❤️ by Shantam Sultania + +You can find me at:- +[Linkedin](https://www.linkedin.com/in/shantam-sultania-737084175/) or [Github](https://github.com/shantamsultania) . + +Happy coding ❤️ . + + diff --git a/AWS Management Scripts/AWS testing Script/agentMain.py b/AWS Management Scripts/AWS testing Script/agentMain.py new file mode 100644 index 0000000000..9dc2f99a8d --- /dev/null +++ b/AWS Management Scripts/AWS testing Script/agentMain.py @@ -0,0 +1,33 @@ +from flask import Flask +from flask_ngrok import run_with_ngrok +import awstesting.awsTester as aws_testing + +app = Flask(__name__) + +# run_with_ngrok(app) + + +@app.route("/", methods=['POST', 'GET']) +def welcome(): + message = "Welcome to create your own test Api for AWS for Ec2 just use your Url/ec2 and your 100 ec2 " \ + "instance will be created in test environment if you dont want to use it in api based " \ + "just go to code and use awsTesting class and done " + return message + + +# this api is to create an ec2 for testing + +@app.route("/ec2", methods=['POST', 'GET']) +def ec2(): + client = aws_testing.add_service("ec2", "us-east-1") + return aws_testing.test_create_ec2(client) + + +# you can add more apis of your choice here like +# create Volume, VPC and snapshots + +# to do so just add a call function in awsTester class and agentMain and you are done + +# run the app +if __name__ == '__main__': + app.run() diff --git a/AWS Management Scripts/AWS testing Script/awsHandler.py b/AWS Management Scripts/AWS testing Script/awsHandler.py new file mode 100644 index 0000000000..26f96a9315 --- /dev/null +++ b/AWS Management Scripts/AWS testing Script/awsHandler.py @@ -0,0 +1,15 @@ +def create_ec2(client, ami_id, count): + client.run_instances(ImageId=ami_id, MinCount=count, MaxCount=count) + + +def create_ec2_snapshots(client, volume_id): + client.create_snapshot(VolumeId=volume_id) + + +def create_ec2_volume(client, AZ): + ab = client.create_volume(AZ) + return ab + + +def create_vpc(client, cidr_block): + client.create_vpc(CidrBlock=cidr_block) diff --git a/AWS Management Scripts/AWS testing Script/awsTester.py b/AWS Management Scripts/AWS testing Script/awsTester.py new file mode 100644 index 0000000000..4fb6606919 --- /dev/null +++ b/AWS Management Scripts/AWS testing Script/awsTester.py @@ -0,0 +1,59 @@ +import boto3 +import boto.sqs +from boto.s3.key import Key +from moto import mock_ec2, mock_s3 +import awstesting.awsHandler as aws + + +def add_service(service_name, region): + aws_client = boto3.client(service_name, region_name=region) + return aws_client + + +@mock_ec2 +def test_create_ec2(aws_client): + # demo ami + ami_id = "ami-123" + count = 100 + aws.create_ec2(aws_client, ami_id, count) + instances = aws_client.describe_instances()['Reservations'][0]['Instances'] + for i in instances: + print(i) + if len(instances) == count: + return "ec2 created successfully Insatnce ID = " + instances[0]['InstanceId'] + "" + else: + return "ec2 not created " + + +@mock_s3 +def test_s3(): + print('Testing moto S3') + + # create bucket + bucket_name = 'bucket1' + conn = boto.connect_s3() + print('Creating bucket: {}'.format(bucket_name)) + bucket = conn.create_bucket(bucket_name) + + # add object + k = Key(bucket) + key_name = 'file1' + k.key = key_name + k.set_contents_from_string('hello world') + + # list objects + print('List of files:') + for key in bucket.list(): + print(' {}/{}'.format(key.bucket.name, key.name)) + + # get object + k2 = Key(bucket) + k2.key = key_name + data = k2.get_contents_as_string() + print('Fetched object {}/{} with content: {}'.format(bucket.name, + key.name, data)) + + +if __name__ == "__main__": + client = add_service("ec2", "us-east-1") + test_create_ec2(client) diff --git a/Brick Breaker game/Readme.md b/Brick Breaker game/Readme.md new file mode 100644 index 0000000000..9af6525438 --- /dev/null +++ b/Brick Breaker game/Readme.md @@ -0,0 +1,15 @@ +# Brick Breaker Game + +Brick Breaker (The game) is a Breakout clonewhich the player must smash a wall of bricks by deflecting a bouncing ball with a paddle. The paddle may move horizontally and is controlled with the side arrow keys. + +## Setup instructions + +Run `python/python3 brick_breaker.py` + +## Output + +![image](https://user-images.githubusercontent.com/43489758/114232380-68122e00-9999-11eb-93c2-6de9af43804a.png) + +## Author + +[Yuvraj kadale](https://github.com/Yuvraj-kadale) with ❤ diff --git a/Brick Breaker game/brick_breaker.py b/Brick Breaker game/brick_breaker.py new file mode 100644 index 0000000000..b6615f239a --- /dev/null +++ b/Brick Breaker game/brick_breaker.py @@ -0,0 +1,284 @@ + +import pygame +from pygame.locals import * + +pygame.init() + +''' +Defining gaming window size and font +''' +Window_width = 500 +Window_height = 500 + +window = pygame.display.set_mode((Window_width, Window_height)) +pygame.display.set_caption('Brickstroy') + + +font = pygame.font.SysFont('Arial', 30) + +''' +Defining Bricks colour +''' +O_brick = (255, 100, 10) +w_brick = (255, 255, 255) +g_brick = (0, 255, 0) +black = (0, 0, 0) + + +game_rows = 6 +game_coloumns = 6 +clock = pygame.time.Clock() +frame_rate = 60 +my_ball = False +game_over = 0 +score = 0 + + +class Ball(): + ''' + Creating ball for the game + ''' + + def __init__(self, x, y): + + self.radius = 10 + self.x = x - self.radius + self.y = y - 50 + self.rect = Rect(self.x, self.y, self.radius * 2, self.radius * 2) + self.x_speed = 4 + self.y_speed = -4 + self.max_speed = 5 + self.game_over = 0 + + def motion(self): + collision_threshold = 5 + block_object = Block.bricks + brick_destroyed = 1 + count_row = 0 + for row in block_object: + count_item = 0 + for item in row: + # check collision with gaming window + if self.rect.colliderect(item[0]): + if abs(self.rect.bottom - item[0].top) < collision_threshold and self.y_speed > 0: + self.y_speed *= -1 + + if abs(self.rect.top - item[0].bottom) < collision_threshold and self.y_speed < 0: + self.y_speed *= -1 + if abs(self.rect.right -item[0].left) < collision_threshold and self.x_speed > 0: + self.x_speed *= -1 + if abs(self.rect.left - item[0].right) < collision_threshold and self.x_speed < 0: + self.x_speed *= -1 + + if block_object[count_row][count_item][1] > 1: + block_object[count_row][count_item][1] -= 1 + else: + block_object[count_row][count_item][0] = (0, 0, 0, 0) + + if block_object[count_row][count_item][0] != (0, 0, 0, 0): + brick_destroyed = 0 + count_item += 1 + count_row += 1 + + if brick_destroyed == 1: + self.game_over = 1 + + + # check for collision with bricks + if self.rect.left < 0 or self.rect.right > Window_width: + self.x_speed *= -1 + + if self.rect.top < 0: + self.y_speed *= -1 + if self.rect.bottom > Window_height: + self.game_over = -1 + + + # check for collission with base + if self.rect.colliderect(user_basepad): + if abs(self.rect.bottom - user_basepad.rect.top) < collision_threshold and self.y_speed > 0: + self.y_speed *= -1 + self.x_speed += user_basepad.direction + if self.x_speed > self.max_speed: + self.x_speed = self.max_speed + elif self.x_speed < 0 and self.x_speed < -self.max_speed: + self.x_speed = -self.max_speed + else: + self.x_speed *= -1 + + self.rect.x += self.x_speed + self.rect.y += self.y_speed + + return self.game_over + + + def draw(self): + pygame.draw.circle(window, (0, 0, 255), (self.rect.x + self.radius, self.rect.y + self.radius), self.radius) + pygame.draw.circle(window, (255, 255, 255), (self.rect.x + self.radius, self.rect.y + self.radius), self.radius, 1) + + + + def reset(self, x, y): + + self.radius = 10 + self.x = x - self.radius + self.y = y - 50 + self.rect = Rect(self.x, self.y, self.radius * 2, self.radius * 2) + self.x_speed = 4 + self.y_speed = -4 + self.max_speed = 5 + self.game_over = 0 + + + +class Block(): + ''' + This class will help me create Blocks/bricks of the game + ''' + def __init__(self): + self.width = Window_width // game_coloumns + self.height = 40 + + def make_brick(self): + self.bricks = [] + single_brick = [] + for row in range(game_rows): + + brick_row = [] + + for coloumn in range(game_coloumns): + + x_brick = coloumn * self.width + y_brick = row * self.height + rect = pygame.Rect(x_brick, y_brick, self.width, self.height) + # assign power to the bricks based on row + if row < 2: + power = 3 + elif row < 4: + power = 2 + elif row < 6: + power = 1 + + single_brick = [rect, power] + + brick_row.append(single_brick) + + self.bricks.append(brick_row) + + + def draw_brick(self): + for row in self.bricks: + for brick in row: + + if brick[1] == 3: + brick_colour = O_brick + elif brick[1] == 2: + brick_colour = w_brick + elif brick[1] == 1: + brick_colour = g_brick + pygame.draw.rect(window, brick_colour, brick[0]) + pygame.draw.rect(window, black, (brick[0]), 1) + + + + + +class base(): + ''' + This class is to create the base pad of the game + ''' + def __init__(self): + + self.height = 20 + self.width = int(Window_width / game_coloumns) + self.x = int((Window_width / 2) - (self.width / 2)) + self.y = Window_height - (self.height * 2) + self.speed = 8 + self.rect = Rect(self.x, self.y, self.width, self.height) + self.direction = 0 + + + def slide(self): + + self.direction = 0 + key = pygame.key.get_pressed() + if key[pygame.K_LEFT] and self.rect.left > 0: + self.rect.x -= self.speed + self.direction = -1 + if key[pygame.K_RIGHT] and self.rect.right < Window_width: + self.rect.x += self.speed + self.direction = 1 + + def draw(self): + pygame.draw.rect(window,(0, 0, 255), self.rect) + pygame.draw.rect(window, (255, 255, 255), self.rect, 1) + + + def reset(self): + + self.height = 20 + self.width = int(Window_width / game_coloumns) + self.x = int((Window_width / 2) - (self.width / 2)) + self.y = Window_height - (self.height * 2) + self.speed = 8 + self.rect = Rect(self.x, self.y, self.width, self.height) + self.direction = 0 + + + +def draw_text(text, font, w_brick, x, y): + ''' + Funtion for showing text in gaming window + ''' + image = font.render(text, True, w_brick) + window.blit(image, (x, y)) + + + +Block = Block() +Block.make_brick() # Creating Brick +user_basepad = base() # Defining base pad +ball = Ball(user_basepad.x + (user_basepad.width // 2), user_basepad.y - user_basepad.height) # Defining ball + +game = True +while game: + + clock.tick(frame_rate) + window.fill(black) # Gaming window Background + Block.draw_brick() # Drawing bricks + user_basepad.draw() # Drawing user basepad + ball.draw() # Drawing gaming ball + + if my_ball: + user_basepad.slide() + game_over = ball.motion() + if game_over != 0: + my_ball = False + + + # Game Info on the gaming window + if not my_ball: + if game_over == 0: + draw_text('CLICK ANYWHERE TO START', font, w_brick, 90, Window_height // 2 + 100) + elif game_over == 1: + draw_text('YOU WON!', font, w_brick, 180, Window_height // 2 + 50) + draw_text('CLICK ANYWHERE TO RESTART', font, w_brick, 90, Window_height // 2 + 100) + elif game_over == -1: + draw_text('GAME OVER!', font, w_brick, 180, Window_height // 2 + 50) + draw_text('CLICK ANYWHERE TO RESTART', font, w_brick, 90, Window_height // 2 + 100) + + + for event in pygame.event.get(): + if event.type == pygame.QUIT: + game = False + if event.type == pygame.MOUSEBUTTONDOWN and my_ball == False: + my_ball = True + ball.reset(user_basepad.x + (user_basepad.width // 2), user_basepad.y - user_basepad.height) + user_basepad.reset() + Block.make_brick() + + + + pygame.display.update() + +pygame.quit() diff --git a/Fast Algorithm (Corner Detection)/Fast_Algorithm.py b/Fast Algorithm (Corner Detection)/Fast_Algorithm.py new file mode 100644 index 0000000000..1ea82b1c4f --- /dev/null +++ b/Fast Algorithm (Corner Detection)/Fast_Algorithm.py @@ -0,0 +1,46 @@ +''' + For using this Script you need to install OpenCV in your machine +''' +#Importing openCV library +import cv2 as cv + +#Taking path of input from the user +path=input("Enter the path of image: ") +img=cv.imread(path) +img=cv.resize(img,(640,640)) #resizing the image + +#Printing the original image +cv.imshow('Original',img) + +# Initiate FAST object with default values +fast = cv.FastFeatureDetector_create() + +# find and draw the keypoints +kp = fast.detect(img,None) +img2 = cv.drawKeypoints(img, kp, None, color=(255,0,0)) + +# Print all default parameters +print( "Threshold: {}".format(fast.getThreshold()) ) +print( "nonmaxSuppression:{}".format(fast.getNonmaxSuppression()) ) +print( "neighborhood: {}".format(fast.getType()) ) +print( "Total Keypoints with nonmaxSuppression: {}".format(len(kp)) ) + +# Disable nonmaxSuppression +fast.setNonmaxSuppression(0) +kp = fast.detect(img,None) + +print( "Total Keypoints without nonmaxSuppression: {}".format(len(kp)) ) +final = cv.drawKeypoints(img, kp, None, color=(255,0,0)) + +#Naming the output image +image_name = path.split(r'/') +image = image_name[-1].split('.') +output = r".\\"+ image[0] + "(_detected).jpg" + +#Saving the image +cv.imwrite(output,final) + +#Printing the final output image +cv.imshow('Final',final) +cv.waitKey(0) +cv.destroyAllWindows() diff --git a/Fast Algorithm (Corner Detection)/Output.png b/Fast Algorithm (Corner Detection)/Output.png new file mode 100644 index 0000000000..08f2a16d8c Binary files /dev/null and b/Fast Algorithm (Corner Detection)/Output.png differ diff --git a/Fast Algorithm (Corner Detection)/Readme.md b/Fast Algorithm (Corner Detection)/Readme.md new file mode 100644 index 0000000000..8f1c28f1fc --- /dev/null +++ b/Fast Algorithm (Corner Detection)/Readme.md @@ -0,0 +1,14 @@ +# Fast Algorithm + +- In this script, we implement the `Fast (Features from Accelerated Segment Test)` algorithm of `OpenCV` to detect the corners from any image. + +## Setup instructions + +- For using this script, you have to install `Open CV` in your machine and after that you easily run the **Fast_Algorithm.py** file + +## Output + + +## Author + +[Shubham Gupta](https://github.com/ShubhamGupta577) diff --git a/Fast Algorithm (Corner Detection)/input.jpg b/Fast Algorithm (Corner Detection)/input.jpg new file mode 100644 index 0000000000..2eb032b45d Binary files /dev/null and b/Fast Algorithm (Corner Detection)/input.jpg differ diff --git a/Guessing_Game_GUI/README.md b/Guessing_Game_GUI/README.md new file mode 100644 index 0000000000..4d70bc6227 --- /dev/null +++ b/Guessing_Game_GUI/README.md @@ -0,0 +1,17 @@ +# Guessing Game GUI + _A random number is generated between an upper and lower limit both entered by the user. The user has to enter a number and the algorithm checks if the number matches or not within three attempts._ + +## Modules used + +- tkinter +- random + +## How it works + +- User enters the upper limit and lower limit number (example 7 and 10) and locks these numbers. +- When the user locks these numbers a random number in the given range is generated by the random module. +- User guesses a number and enters it. +- The GUI displays if the number is correct or wrong within three attempts. +- After three attempts the user can either *play again* or *quit* + +Made by [K. Sai Drishya](https://github.com/saidrishya) diff --git a/Guessing_Game_GUI/guessing_game_tkinter.py b/Guessing_Game_GUI/guessing_game_tkinter.py new file mode 100644 index 0000000000..a0780e664c --- /dev/null +++ b/Guessing_Game_GUI/guessing_game_tkinter.py @@ -0,0 +1,133 @@ +# -*- coding: utf-8 -*- +"""guessing_game_tkinter.ipynb + +Automatically generated by Colaboratory. + +Original file is located at + https://colab.research.google.com/drive/1OzOm77jUVrxo1jWWlQoXkj19Pc8D_GdC +""" + +from tkinter import * +import random + +root = Tk() +root.title('Number Guessing Game') +root.geometry('450x450+50+50') + +font_used = ('Arial', 12) +#lower limit number +num1 = IntVar() +#upper limit number +num2 = IntVar() +#user guessed value +guessed_num = IntVar() +#value is the random value generated +global value +value= None +global attempts +attempts = 3 + +#generate random number +def get_rand(): + b4.configure(state=DISABLED) + global value + value = random.randint(num1.get(), num2.get()) + + +#resets the window +def reset(): + num1.set(0) + num2.set(0) + guessed_num.set(0) + global attempts + attempts = 3 + b4.configure(state=NORMAL) + b1.configure(state = NORMAL) + l4.configure(text = '') + l5.configure(text = 'You have 3 attempts left') + b2.configure(state = DISABLED) + + +def check(): + global value + #Label(root, text=str(value)).grid(row=8) + + #tells the user how many attempts are left + global attempts + attempts -= 1 + + #if all attempts are over + if attempts == 0 and guessed_num.get() != value: + b1.configure(state=DISABLED) + l5.configure(text = 'You have 0 attempts left') + l4.configure(text='Sorry! All attempts done. The correct answer is ' + str(value), fg='red') + b2.configure(text = 'Play Again', command=reset, state=NORMAL) + b2.grid(row=9, column=1) + b3.configure(text = 'Quit', command = root.quit) + b3.grid(row = 9, column=2) + else: + #if attempts are still left + + #if guessed value is correct + if guessed_num.get() == value: + l4.configure(text='Congratulations! You are right') + b2.configure(text = 'Play Again', command=reset, state =NORMAL) + b2.grid(row=9, column=1) + b3.configure(text = 'Quit', command = root.quit) + b3.grid(row = 9, column=2) + + #if guessed value is incorrect + else: + if guessed_num.get() > value: + l4.configure(text='Better Luck Next time! Try a lesser number') + else: + l4.configure(text='Better Luck Next time! Try a greater number') + l5.configure(text = 'You have ' + str(attempts) + ' attempts left') + +l6 = Label(root, text = 'Input fields cannot be 0', font=font_used, fg='red') +l6.grid(row=0, columnspan=3, pady=5) + +# from i.e lower limit +l1 = Label(root, text = 'From', font=font_used, fg='red') +l1.grid(row=1, column=0, sticky=W) +e1 = Entry(root, textvariable = num1, font=font_used, fg='blue') +e1.grid(row=1, column=1, padx=5, pady=5) + +# to i.e upper limit +l2 = Label(root, text = 'To', font=font_used, fg='red') +l2.grid(row=2, column=0, sticky=W, padx=5, pady=5) +#locking numbers is neccessary as it generates only a single random number for the limit +b4 = Button(root, text = 'Lock Numbers', fg='magenta', command=get_rand) +b4.grid(row=3, columnspan=3, pady=5) +e2 = Entry(root, textvariable = num2, font=font_used, fg='blue') +e2.grid(row=2, column=1, padx=5, pady=5) + + +#guess the number +l3 = Label(root, text = 'Guess any number', font=font_used, fg='darkviolet') +l3.grid(row=4, columnspan=3,pady=5) + +#label for showing the number of attempts +l5 = Label(root, text = 'You have 3 attempts left', font=font_used, fg='darkviolet') +l5.grid(row=5, columnspan=3,pady=5) + +#the user enters the guessed number +e3 = Entry(root, textvariable = guessed_num, font=font_used, fg='darkorchid') +e3.grid(row=6, columnspan=3,pady=5) + +#checks whether the guessed number is correct or not +b1 = Button(root, text='Check', font=font_used, fg='darkviolet', command=check) +b1.grid(row=7, columnspan=3, pady=5) + +#displays the result +l4 = Label(root, text = 'Result', font=font_used, fg='magenta') +l4.grid(row=8, columnspan=3,pady=5) + +#button for play again +b2 = Button(root) +#button for quit which closes the window +b3 = Button(root) + + +root.mainloop() + diff --git a/Health_Log_Book/README.md b/Health_Log_Book/README.md new file mode 100644 index 0000000000..4319e5828e --- /dev/null +++ b/Health_Log_Book/README.md @@ -0,0 +1,18 @@ +## Health log book + +### Details of the script:- +The script will contain the daily records of food and workouts of a person. The user will only enter the name of the foods, it will be stored in a text file with corresponding date and time. Similarly, the user will enter the types of workout at their workout time. The workouts will be stored in a text file with date and time. The user can also retrieve the data whenever they want to see. + +### Advantages of the script:- +This script will help the user to maintain his/her health, as it is keeping a daily track of their diet and workout style. At the end of the day, or at the end of the week, he/she can analyze the data and can lead a healthy and fit lifestyle. + +### Modules Used:- + +1) datetime +2) sqlite3 +3) tkinter +4) messagebox + +### Image of the GUI:- +![Screenshot from 2021-04-09 12-52-27](https://user-images.githubusercontent.com/62845847/114144009-7a0cb600-9932-11eb-8f47-8fcc541229e7.png) + diff --git a/Health_Log_Book/database.py b/Health_Log_Book/database.py new file mode 100644 index 0000000000..4a8ed07692 --- /dev/null +++ b/Health_Log_Book/database.py @@ -0,0 +1,78 @@ +# Importing the module +import sqlite3 + +# Writing the Query for creating the exercise table +Create_exercise_table = """ + CREATE TABLE IF NOT EXISTS exercise + ( + id INTEGER PRIMARY KEY, + date TEXT, + data TEXT + ); + """ + +# Writing the query for inserting values into exercise table +insert_exercise = """ + INSERT INTO exercise (date, data) VALUES (?, ?); +""" + +# Writing the query for inserting values into food table +insert_food = """ + INSERT INTO food (date, data) VALUES (?, ?); +""" + +# Writing the query for creating the food table +Create_food_table = """ + CREATE TABLE IF NOT EXISTS food + ( + id INTEGER PRIMARY KEY, + date TEXT, + data TEXT + ); + """ + +# Writing the query for deleting the exercise table +delete_exercise_table = """ + DROP TABLE exercise + """ + +# Writing the query for deleting the food table +delete_food_table = """ + DROP TABLE food + """ + +# defining functions for different queries + +def connect(): + connection = sqlite3.connect("data.db") + return connection + + +def create_table1(connection): + with connection: + connection.execute(Create_exercise_table) + + +def create_table2(connection): + with connection: + connection.execute(Create_food_table) + + +def add_exercise(connection, date, data): + with connection: + connection.execute(insert_exercise, (date, data)) + + +def add_food(connection, date, data): + with connection: + connection.execute(insert_food, (date, data)) + + +def delete_exercise(connection): + with connection: + connection.execute(delete_exercise_table) + + +def delete_food(connection): + with connection: + connection.execute(delete_food_table) diff --git a/Health_Log_Book/main.py b/Health_Log_Book/main.py new file mode 100644 index 0000000000..c6be886309 --- /dev/null +++ b/Health_Log_Book/main.py @@ -0,0 +1,175 @@ +# importing the modules +import tkinter as tk +from tkinter import messagebox +from tkinter import ttk +import datetime +import database + + +# creating a function to return date and time +def getdate(): + return datetime.datetime.now() + + +# Creating the connection +connection = database.connect() +database.create_table1(connection) +database.create_table2(connection) + + +def store_exercise(): + date = getdate() + data = exercise_entry.get("1.0", 'end-1c') + if data != "": + exercise_entry.delete("1.0", "end") + database.add_exercise(connection, date, data) + messagebox.showinfo("Success", "Log is inserted") + else: + messagebox.showerror("Error", "Enter Something") + + +def store_food(): + date = getdate() + data = food_entry.get("1.0", "end-1c") + if data != "": + food_entry.delete("1.0", "end") + database.add_food(connection, date, data) + messagebox.showinfo("Success", "Log is inserted") + else: + messagebox.showerror("Error", "Enter Something") + + +def show_exercise(): + con = database.connect() + cor = con.cursor() + try: + cor.execute('''SELECT * from exercise''') + rows = cor.fetchall() + new = tk.Tk() + new.title("Exercise Log") + new.geometry("650x500") + + frm = tk.Frame(new) + frm.pack(side=tk.LEFT, padx=20) + + tv = ttk.Treeview(frm, selectmode='browse') + tv.pack() + verscrlbar = ttk.Scrollbar(new, + orient="vertical", + command=tv.yview) + + verscrlbar.pack(side='right', fill='x') + + tv.configure(xscrollcommand=verscrlbar.set) + + tv["columns"] = ("1", "2", "3") + tv['show'] = 'headings' + + tv.column("1", width=50, anchor='c') + tv.column("2", width=250, anchor='c') + tv.column("3", width=400, anchor='w') + + tv.heading("1", text="Sl.No") + tv.heading("2", text="Time") + tv.heading("3", text="Data") + + for i in rows: + tv.insert("", "end", values=i) + + new.mainloop() + except: + messagebox.showerror("Error", "Some Error Occurred") + + +def show_food(): + con = database.connect() + cor = con.cursor() + try: + cor.execute('''SELECT * from food''') + rows = cor.fetchall() + new = tk.Tk() + new.title("Food Log") + new.geometry("650x500") + + frm = tk.Frame(new) + frm.pack(side=tk.LEFT, padx=20) + + tv = ttk.Treeview(frm, selectmode='browse') + tv.pack() + verscrlbar = ttk.Scrollbar(new, + orient="vertical", + command=tv.yview) + + verscrlbar.pack(side='right', fill='x') + + tv.configure(xscrollcommand=verscrlbar.set) + + tv["columns"] = ("1", "2", "3") + tv['show'] = 'headings' + + tv.column("1", width=50, anchor='c') + tv.column("2", width=250, anchor='c') + tv.column("3", width=400, anchor='w') + + tv.heading("1", text="Sl.No") + tv.heading("2", text="Time") + tv.heading("3", text="Data") + + for i in rows: + tv.insert("", "end", values=i) + + new.mainloop() + except: + messagebox.showerror("Error", "Some Error Occurred") + + +def delete_exercise_log(): + messagebox.showinfo("Delete", "The Exercise Log is deleted") + database.delete_exercise(connection) + + +def delete_food_log(): + messagebox.showinfo("Delete", "The Food Log is deleted") + database.delete_food(connection) + + +# Making the GUI +root = tk.Tk() + +root.title("main") +root.geometry("500x500") + +heading = tk.Label(root, text="Health Log book", font=('Helvetica', 18, 'bold')) +heading.pack() + +exercise_heading = tk.Label(root, text=" 1) Enter each exercise separated with commas", font=('Helvetica', 11, 'bold')) +exercise_heading.place(x=30, y=40) + +exercise_entry = tk.Text(root, height=5, width=42) +exercise_entry.pack(pady=30) + +exercise_submit = tk.Button(root, text="Submit", command=store_exercise) +exercise_submit.place(x=210, y=160) + +food_heading = tk.Label(root, text="2) Enter each food separated with commas", font=('Helvetica', 11, 'bold')) +food_heading.place(x=30, y=200) + +food_entry = tk.Text(root, height=5, width=42) +food_entry.pack(pady=40) + +food_submit = tk.Button(root, text="Submit", command=store_food) +food_submit.place(x=210, y=330) + +retrieve_exercise = tk.Button(root, text="Show Exercise Log", command=show_exercise) +retrieve_exercise.place(x=50, y=400) + +retrieve_food = tk.Button(root, text="Show food Log", command=show_food) +retrieve_food.place(x=300, y=400) + +delete_exercise = tk.Button(root, text="Delete Exercise Log", command=delete_exercise_log) +delete_exercise.place(x=50, y=450) + +delete_food = tk.Button(root, text="Delete food Log", command=delete_food_log) +delete_food.place(x=300, y=450) + +root.mainloop() diff --git a/Mini Google Assistant/Mini google assistant.py b/Mini Google Assistant/Mini google assistant.py new file mode 100644 index 0000000000..76ef218ffc --- /dev/null +++ b/Mini Google Assistant/Mini google assistant.py @@ -0,0 +1,97 @@ +import speech_recognition as sr +import pyttsx3 +import pywhatkit +import datetime +import pyjokes +import cv2 + + +listener = sr.Recognizer() +engine = pyttsx3.init() +voices = engine.getProperty("voices") +engine.setProperty("voice",voices[1].id) #use [1]->female voice and [0]-> male voice + +def talk(text): + engine.say(text) + engine.runAndWait() + +def take_command(): + try: + with sr.Microphone() as source: + print("Listening.....(speak now)") + voice = listener.listen(source) + command = listener.recognize_google(voice) + command=command.lower() + if "google" in command: + command = command.replace("google", '') + print(command) + except: + print("Ooops something went wrong!") + + pass + return command + +def run_mini_google_assistant(): + + command = take_command() + print(command) + + if "play" in command: + song = command.replace("play","") + talk("playing the song" + song) + print(song) + pywhatkit.playonyt(song) + elif "time" in command: + time = datetime.datetime.now().strftime("%I:%M%p") + print(time) + talk("Current time is" + time) + elif "joke" in command: + talk("Here is the joke") + talk(pyjokes.get_joke()) + talk(" heeheehehe quite funny! ") + elif 'date' in command: + date = datetime.date.today() + print(date) + talk( "Today is") + talk (date) + elif 'how are you' in command: + talk('I am good. Nice to see you here!') + elif "capture" or "camera" in command: + talk("Ok I'll do it for you!") + talk("Remenber, You can use s button to quit") + vid = cv2.VideoCapture(0) + + while (True): + + # Capture the photo/video frame by frame + ret, frame = vid.read() + + # Display the resulting frame + cv2.imshow('frame', frame) + + + if "photo" in command: + if cv2.waitKey(0) & 0xFF == ord('s'): # used 's' as quitting button + #talk("You can use s button to quit") + break + elif "video" in command: + if cv2.waitKey(1) & 0xFF == ord('s'): # used 's' as quitting button + #talk("You can use s button to quit") + + break + + # After the loop release the cap object + vid.release() + # Destroy all the windows + cv2.destroyAllWindows() + + else: + talk("Sorry i am not getting you! Can you please repeat!") + + +talk("Hello my friend, i am your personal mini google assistant.") +talk("And i can help you to play song, tell time, tell date, tell joke and i can also capture photo and video for you") +talk("Now please tell me how can i help you!") +while True: + run_mini_google_assistant() + #talk("Nice to see you here, I belive that you enjoyed!") diff --git a/Mini Google Assistant/README.md b/Mini Google Assistant/README.md new file mode 100644 index 0000000000..59b5f3e90d --- /dev/null +++ b/Mini Google Assistant/README.md @@ -0,0 +1,15 @@ +# Mini-google-assistant + +A mini google assistant using python which can help you to play song, tell time, tell joke, tell date as well as help you to capure a photo/video. + +## Libraries used: +Imported the required libraries which are - +* speech_recognition as sr +* pyttsx3 +* pywhatkit +* datetime +* pyjokes +* cv2 + +## Methods Used +Taking voice command as input and then using if/else statement to run a particular library related to that command and finally getting the required output. diff --git a/Random Password Generator/README.md b/Random Password Generator/README.md new file mode 100644 index 0000000000..22bcc59da8 --- /dev/null +++ b/Random Password Generator/README.md @@ -0,0 +1,40 @@ +# RANDOM PASSWORD GENERATOR + +## Description +This is a random password generator. + +The password is generated based on two parameters : +- Password length +- Strength of password + +Both these parameters are selected by the user. + +## Modules used + +- Tkinter +- Random +- String +- Pyperclip + +## Output +

+ +
+ Initial window +

+ +
+ Password generated +

+ +
+ Warning message +

+ +
+ Password copied to clipboard +

+

+ +## Author +[Tanvi Bugdani](https://github.com/tanvi355) diff --git a/Random Password Generator/script.py b/Random Password Generator/script.py new file mode 100644 index 0000000000..8e41c6bb57 --- /dev/null +++ b/Random Password Generator/script.py @@ -0,0 +1,116 @@ +import tkinter as tk +from tkinter import * +from tkinter import messagebox +import random +import string +import pyperclip + +#main window +root = tk.Tk() +#title of the window +root.title("Random Password Generator") +#disabling resizing of window +root.resizable(0, 0) + +#variables for Password +upper = string.ascii_uppercase +lower = string.ascii_lowercase +num = string.digits +punc = string.punctuation + +pass_str = StringVar() +pass_wrd = StringVar() + +#function to create a random password +def create_pass(): + password.delete(0, END) + Len = len.get() + strn = opt.get() + pass_wrd = "" + #password of low strength + if(strn==1): + for i in range (0,Len): + pass_wrd = pass_wrd + random.choice(lower + num) + return pass_wrd + #password of medium strength + elif(strn==2): + for i in range (0, Len): + pass_wrd = pass_wrd + random.choice(lower + upper + num) + return pass_wrd + #password of high strength + elif(strn==3): + for i in range (0, Len): + pass_wrd = pass_wrd + random.choice(lower + upper + num + punc) + return pass_wrd + else: + messagebox.showwarning("Warning", "Select all parameters") + +#function to generate the password +def gen(): + pass_str = create_pass() + password.insert(0, pass_str) + +#function to copy password to clipboard +def cpy(): + random_pass = password.get() + pyperclip.copy(random_pass) + messagebox.showinfo("Message", "Copied to clipboard !") + +#Adding frames + +#---frame for top name--- +top = Frame(root, width = 700, height = 50, bd=8, relief="raise") +top.pack(side = TOP) + +#---frame for length of password--- +Length = Frame(root, width = 700, height = 50, bd=8, relief="raise") +Length.pack(side = TOP) + +#---frame for strength of password--- +strength = Frame(root, width = 300, height = 450, bd=8, relief="raise", padx=100, pady=20) +strength.pack(side = LEFT) + +#---frame for output--- +output = Frame(root, width = 450, height = 450, bd=8, relief="raise") +output.pack(side = RIGHT) + + +#Adding widgets +greeting = Label(top, text="Random Password Generator", width=40, height=2, font = ("Lucida Console", 20, "italic")) +greeting.grid(padx = 18) + +#---length of password--- +lengthlabel = Label(Length, text="Length of Password", width=20, height=5, font = ("Arial", 10, "bold")) +lengthlabel.grid(row = 5, column = 1, padx = 3, pady = 10) + +len = IntVar() +scale = Scale(Length, orient = HORIZONTAL, from_ = 6, to = 24, tickinterval = 1, length = 500, variable=len) +scale.grid(row = 5, column = 2) + + +#---strength of password--- +strengthlabel = Label(strength, text = "Strength",justify="center", width = 6, height = 2, font = ("Arial", 12, "bold")) +strengthlabel.grid(row = 10, column = 2, pady = 10) + +opt = IntVar() +c1 = Radiobutton(strength, text="Low", width = 6, height = 2 , variable=opt, value = 1, font = ("Arial", 12)) +c1.grid(row = 12, column = 2, ipadx = 2, ipady = 2, sticky = 'E', pady = 5, padx = 5) + +c2 = Radiobutton(strength, text="Medium", width = 6, height = 2, variable=opt, value = 2, font = ("Arial", 12)) +c2.grid(row = 14, column = 2, ipadx = 2, ipady = 2, sticky = 'E', pady = 5, padx = 5) + +c3 = Radiobutton(strength, text="High", width = 6, height = 2, variable=opt, value = 3, font = ("Arial", 12)) +c3.grid(row = 16, column = 2, ipadx = 2, ipady = 2, sticky = 'E', pady = 5, padx = 5) + + +#---output--- +genbtn = Button(output, text = "Generate Password", justify = "center", width = 20, height = 3, command=gen, font = ("Arial", 12, "bold")) +genbtn.grid(row = 1, column = 4, padx = 30, pady = 17) + +password = Entry(output, justify = "center", width=50, textvariable = pass_str) +password.grid(row = 2, column = 4, padx = 30, pady = 20, ipady = 8) + +copybtn = Button(output, text = "Copy", justify = "center", width = 20, height = 3, font = ("Arial", 12, "bold"), command=cpy) +copybtn.grid(row = 3, column = 4, padx = 30, pady = 17) + +root.mainloop() diff --git a/TicTacToe-GUI/README.md b/TicTacToe-GUI/README.md new file mode 100644 index 0000000000..d4dfdd2b75 --- /dev/null +++ b/TicTacToe-GUI/README.md @@ -0,0 +1,37 @@ +## Tic Tac Toe + + +### How To Play + +1. The game is played on a grid that's 3 squares by 3 squares. +2. You are X, your friend (or the computer in this case) is O. +3. Players take turns putting their marks in empty squares. +4. The first player to get 3 of her marks in a row (up, down, across, or diagonally) is the winner. +5. When all 9 squares are full, the game is over. + +### How The Game Works + +1. Our Tic Tac Toe is programmed in other to allow two users or players to play the game in the same time. +2. It is GUI game & gives an instant alert when players wins or losses or draw the game basically tells us to restart. + +### Details +Libraries Required + +| Library | Command To Install | Documentation | +| :------------ | :------------ | :------------ | +| Pygame | `pip install pygame` | https://pypi.org/project/pygame/ | +| Sys | `pip install os-sys` | https://pypi.org/project/os-sys/ | + +### Steps Required To Make This Awesome Game Live: +- First of all, create a folder named any in your PC & drag it to your code editor. +- Secondly, open your command prompt(CMD) & install the Pygame package by typing pip install pygame command and os-sys package by typing pip install os-sys .(I used windows10 OS) +- Thirdly, make a file called TicTacToeGame.py . It will you to store all your code needed for the game. +- Set your codes which are given below to your respective files. +- Lastly just run this code and enjoy the game. + +### How It Will Look +download + +### Author : [Lakhan Kumawat](https://github.com/Lakhankumawat) + + diff --git a/TicTacToe-GUI/TicTacToe.py b/TicTacToe-GUI/TicTacToe.py new file mode 100644 index 0000000000..2c62f38fb0 --- /dev/null +++ b/TicTacToe-GUI/TicTacToe.py @@ -0,0 +1,194 @@ +# -*- coding: utf-8 -*- +""" +Tic Toe Using pygame , numpy and sys with Graphical User Interface +""" +import pygame, sys +from pygame.locals import * +import numpy as np +#------ +#constants +#------- +width=800 +height=800 +#row and columns +board_rows=3 +board_columns=3 +cross_width=25 +square_size=width//board_columns +#colors in RGB format +line_Width=15 +red=(255, 0, 0) +bg_color=(28, 170, 156) +line_color=(23, 145, 135) +circle_color=(239,231,200) +cross_color=(66,66,66) +space=square_size//4 +#circle +circle_radius=square_size//3 +circle_width=14 +pygame.init() +screen = pygame.display.set_mode((height,width)) +pygame.display.set_caption('Tic Tac Toe!') +screen.fill( bg_color ) +#color to display restart +white = (255, 255, 255) +green = (0, 255, 0) +blue = (0, 0, 128) + +font = pygame.font.Font('freesansbold.ttf', 25) + +# create a text suface object, +# on which text is drawn on it. +text = font.render('Press R to restart', True, green, blue) + +Won= font.render(" Won", True ,blue,green) +leave=font.render("Press X to Exit" ,True, white, red) +# create a rectangular object for the +# text surface object +leaveRect=text.get_rect() +textRect = text.get_rect() +winRect=Won.get_rect() +winRect.center=(100,30) +textRect.center = (width-400, 30) +leaveRect.center=(width-120,30) +board=np.zeros( (board_rows,board_columns)) +#print(board) +#pygame.draw.line( screen ,red ,(10,10),(300,300),10) + +def draw_figures(): + for row in range(board_rows): + for col in range(board_columns): + if board[row][col]==1: + pygame.draw.circle(screen,circle_color,( int(col*square_size + square_size//2 ),int(row*square_size +square_size//2)),circle_radius,circle_width) + elif board[row][col]==2: + pygame.draw.line( screen ,cross_color ,(col*square_size + space,row*square_size +square_size -space),(col*square_size+square_size -space,row*square_size +space),cross_width) + pygame.draw.line( screen ,cross_color ,(col*square_size +space,row*square_size +space),(col*square_size +square_size -space,row*square_size +square_size -space),cross_width) + +def draw_lines(): + pygame.draw.line( screen ,line_color ,(0,square_size),(width,square_size),line_Width) + #2nd horizontal line + pygame.draw.line( screen ,line_color ,(0,2*square_size),(width,2*square_size),line_Width) + #1st verticle + pygame.draw.line( screen ,line_color ,(square_size,0),(square_size,height),line_Width) + #2nd verticle + pygame.draw.line( screen ,line_color ,(2*square_size,0),(2*square_size,height),line_Width) + +#To mark which square player has chosen +def mark_square(row,col,player): + board[row][col]=player + +# TO check the availablity of a square +def available_square(row,col): + return board[row][col]==0 + +#check board full or not +def is_board_full(): + k=False + for row in range(board_rows): + for col in range(board_columns): + if board[row][col]==0: + k=False + else: + k=True + return k + +def check_win(player): + #check verticle win + for col in range(board_columns): + if board[0][col]==player and board[1][col]==player and board[2][col]==player: + draw_vertical_winning_line(col, player) + return True + #check Horizontal win + for row in range(board_rows): + if board[row][0]==player and board[row][1]==player and board[row][2]==player: + draw_horizontal_winning_line(row, player) + return True + #check for asc win + if board[2][0]==player and board[1][1]==player and board[0][2]==player: + draw_asc_diagonal(player) + return True + if board[0][0]==player and board[1][1]==player and board[2][2]==player: + draw_des_diagonal(player) + return True + +def draw_horizontal_winning_line(row,player): + posY=row*square_size +square_size//2 + + if(player==1): + color=circle_color + else: + color=cross_color + + pygame.draw.line(screen, color, (15,posY), (width-15,posY),15) + +def draw_vertical_winning_line(col,player): + posX=col*square_size +square_size//2 + if(player==1): + color=circle_color + else: + color=cross_color + pygame.draw.line(screen, color, (posX,15), (posX,width-15),15) +def draw_asc_diagonal(player): + if(player==1): + color=circle_color + else: + color=cross_color + pygame.draw.line(screen,color,(15,height-15),(width-15,15),15) +def draw_des_diagonal(player): + if(player==1): + color=circle_color + else: + color=cross_color + pygame.draw.line(screen,color,(15,15),(width-15,height-15),15) + +def restart(): + screen.fill(bg_color) + draw_lines() + player = 1 + for row in range(board_rows): + for col in range(board_columns): + board[row][col]=0 +draw_lines() +#player +player=1 +game_over=False +while True: # main game loop + for event in pygame.event.get(): #constantly looks for the event + if event.type == pygame.QUIT: #if user clicks exit pygame.QUIT and sys exits + pygame.quit() + sys.exit() + board_full=is_board_full() + if board_full and not game_over: + Won= font.render(" It's a Tie ", True ,blue,green) + screen.blit(Won, winRect) + screen.blit(text, textRect) + screen.blit(leave,leaveRect) + if event.type==pygame.MOUSEBUTTONDOWN and not game_over: + mouseX= event.pos[0] #x + mouseY= event.pos[1] #y + clicked_row=int(mouseY // square_size) + clicked_column=int(mouseX // square_size) + if available_square(clicked_row, clicked_column): + mark_square(clicked_row,clicked_column, player) + if(check_win(player)): + game_over=True + Won= font.render("Player"+str(player)+" Won ", True ,blue,green) + screen.blit(Won, winRect) + screen.blit(text, textRect) + screen.blit(leave,leaveRect) + player=player%2 +1 + if not game_over and not board_full: + Won= font.render("Player"+str(player)+" Turn ", True ,blue,green) + screen.blit(Won, winRect) + draw_figures() + #to restart the game + if event.type==pygame.KEYDOWN: + if event.key==pygame.K_r: + restart() + game_over=False + elif event.key==pygame.K_x: + pygame.quit() + sys.exit() + #print(board) + pygame.display.update() + diff --git a/Udemy Scraper/README.md b/Udemy Scraper/README.md new file mode 100644 index 0000000000..eb44600a5f --- /dev/null +++ b/Udemy Scraper/README.md @@ -0,0 +1,30 @@ +# Udemy Scraper +There are 2 scripts in this project- +1. fetcher.py - This script is used to scrape course data from udemy based on the category entered as input by the user +2. display.py - This script is used to display the scraped courses from the database to the terminal + +## Setup instructions +In order to run this script, you need to have Python and pip installed on your system. After you're done installing Python and pip, run the following command from your terminal to install the requirements from the same folder (directory) of the project. +``` +pip install -r requirements.txt +``` + +After satisfying all the requirements for the project, Open the terminal in the project folder and run +``` +python fetcher.py +python display.py +``` +or +``` +python3 fetcher.py +python3 display.py +``` +depending upon the python version. Make sure that you are running the command from the same virtual environment in which the required modules are installed. + +## Output +![Sample output of fetcher script](https://i.postimg.cc/SNCmzfhp/fetcher.png) + +![Sample output of display script](https://i.postimg.cc/7h7r0wjN/display.png) + +## Author +[Ayush Jain](https://github.com/Ayushjain2205) \ No newline at end of file diff --git a/Udemy Scraper/display.py b/Udemy Scraper/display.py new file mode 100644 index 0000000000..f6bdf94c97 --- /dev/null +++ b/Udemy Scraper/display.py @@ -0,0 +1,43 @@ +import sqlite3 +from sqlite3 import Error + +# Function to connect to the SQL Database +def sql_connection(): + try: + con = sqlite3.connect('./Udemy Scraper/udemyDatabase.db') + return con + except Error: + print(Error) + +con = sql_connection() + +# Function to Fetch courses from database +def sql_fetch(con): + cursorObj = con.cursor() + try: + cursorObj.execute('SELECT * FROM courses') # SQL search query + except Error: + print("Database empty... Fetch courses using fetcher script") + return + + rows = cursorObj.fetchall() + + # Print table header + print("{:^30}".format("Title"),"{:^30}".format("Description"),"{:^20}".format("Instructor"), + "{:<15}".format("Current Price"),"{:<18}".format("Original Price"),"{:^10}".format("Rating"), + "{:^10}".format("Hours"),"{:^10}".format("Lectures")) + + # Print all rows + for row in rows: + # Format individual data items for printing in a table like manner + title = "{:<30}".format(row[0] if len(row[0])<30 else row[0][:26]+"...") + description = "{:<30}".format(row[1] if len(row[1])<30 else row[1][:26]+"...") + instructor = "{:<20}".format(row[2] if len(row[2])<30 else row[2][:16]+"...") + current_price = "{:^15}".format(row[3]) + original_price= "{:^18}".format(row[4]) + rating = "{:^10}".format(row[5]) + hours= "{:^10}".format(row[6]) + lectures = "{:^10}".format(row[7]) + print(title,description,instructor,current_price,original_price,rating,hours,lectures) + +sql_fetch(con) \ No newline at end of file diff --git a/Udemy Scraper/fetcher.py b/Udemy Scraper/fetcher.py new file mode 100644 index 0000000000..8836ffe593 --- /dev/null +++ b/Udemy Scraper/fetcher.py @@ -0,0 +1,79 @@ +import requests +from bs4 import BeautifulSoup +from selenium import webdriver +from selenium.webdriver.common.keys import Keys +import time +import sqlite3 +from sqlite3 import Error + +# Function to connect to the SQL Database +def sql_connection(): + try: + con = sqlite3.connect('./Udemy Scraper/udemyDatabase.db') + return con + except Error: + print(Error) + +# Function to create table +def sql_table(con): + cursorObj = con.cursor() + cursorObj.execute("CREATE TABLE IF NOT EXISTS courses(title text, description text, instructor text,current_price INTEGER, original_price INTEGER, rating REAL, hours REAL, lectures INTEGER)") + con.commit() + +# Call functions to connect to database and create table +con = sql_connection() +sql_table(con) + +# Function to insert into table +def sql_insert(con, entities): + cursorObj = con.cursor() + cursorObj.execute('INSERT INTO courses(title, description, instructor, current_price, original_price, rating, hours, lectures) VALUES(?, ?, ?, ?, ?, ?, ?, ?)', entities) + con.commit() + + +# Get chrome driver path +driver_path = input("Enter chrome driver path: ") + +print("\nSome Categories Available on Udemy include:\nDevelopment - Python, Web Development, Javascript, Java \nDesign - Photoshop, Blender, Graphic design\n") + +# Get input for course category to scrape +category = input("Enter course category: ") + +url = 'https://www.udemy.com/courses/search/?src=ukw&q={}'.format(category) + +# initiating the webdriver. Parameter includes the path of the webdriver. +driver = webdriver.Chrome(driver_path) +driver.get(url) + +# this is just to ensure that the page is loaded +time.sleep(5) +html = driver.page_source + +# Now apply bs4 to html variable +soup = BeautifulSoup(html, "html.parser") +course_divs = soup.find_all("div", {"class": "course-card--container--3w8Zm course-card--large--1BVxY"}) + +# Get all course divs and extract information from individual divs +for course_div in course_divs: + title = course_div.find("div",{"class":"udlite-focus-visible-target udlite-heading-md course-card--course-title--2f7tE"}).text.strip() + description = course_div.find("p",{"class":"udlite-text-sm course-card--course-headline--yIrRk"}).text.strip() + instructor = course_div.find("div",{"class":"udlite-text-xs course-card--instructor-list--lIA4f"}).text.strip() + + current_price = course_div.find("div",{"class":"price-text--price-part--Tu6MH course-card--discount-price--3TaBk udlite-heading-md"}).text.strip() + current_price = current_price.replace("Current price₹","") + + original_price = course_div.find("div",{"class":"price-text--price-part--Tu6MH price-text--original-price--2e-F5 course-card--list-price--2AO6G udlite-text-sm"}).text.strip() + original_price = original_price.replace("Original Price₹","") + + rating = course_div.find("span",{"class":"udlite-heading-sm star-rating--rating-number--3lVe8"}).text.strip() + + hours = course_div.find_all("span",{"class":"course-card--row--1OMjg"})[0].text.strip().split()[0] + + lectures = course_div.find_all("span",{"class":"course-card--row--1OMjg"})[1].text.strip().split()[0] + + entities = (title, description, instructor, current_price, original_price, rating, hours, lectures) + sql_insert(con, entities) + +print("Saved successfully in database!") + +driver.close() # closing the webdriver \ No newline at end of file diff --git a/Udemy Scraper/requirements.txt b/Udemy Scraper/requirements.txt new file mode 100644 index 0000000000..b74b115ce7 --- /dev/null +++ b/Udemy Scraper/requirements.txt @@ -0,0 +1,3 @@ +requests +beautifulsoup4 +selenium \ No newline at end of file