diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..3406964 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,12 @@ +language: python +python: + - "3.3" + - "3.4" + - "3.5" +install: + - pip install coveralls + - pip install pep8 +script: + - pep8 --max-line-length 5000 bin +after_success: + - coveralls diff --git a/README.md b/README.md index b9c6e44..0bd32da 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ -# Python Scripts +# [Python Scripts](https://logan1x.github.io/Python-Scripts/) [![forthebadge](http://forthebadge.com/images/badges/made-with-python.svg)](http://forthebadge.com) +[![forthebadge](http://forthebadge.com/images/badges/built-by-developers.svg)](http://forthebadge.com) +[![forthebadge](http://forthebadge.com/images/badges/check-it-out.svg)](http://www.logan1x.me/Python-Scripts/) > This Repo is a collection of Various python scripts. @@ -19,21 +21,26 @@ cd Python-Scripts/bin ``` ## Scripts -* ### Approximating *pi* -This script is useful to show a way to approximate the value of pi using a Monte Carlo method. It is also optimized using the `@jit` (*just-in-time*) decorator from the [numba](https://numba.pydata.org/) library. +* ### Air Quality Script + - This script renders the air quality from the location of the user + - The location is fetched using the user's IP address -To see different approximations you just need to modify the argument passed to the main function. + - This script requires a key from WAQI. + - It is free and can be fetched from http://aqicn.org/data-platform/token/#/ + #### Usage Instructions + ```python + python air-quality.py token + ``` +* ### Approximating *pi* -```bash -python pi.py -``` +This script is useful to show a way to approximate the value of pi using a Monte Carlo method. It is also optimized using the `@jit` (*just-in-time*) decorator from the [numba](https://numba.pydata.org/) library. * ### Blog Reader Blog Reader is the terminal reader that scrapes the article from [planet dgplug](http://planet.dgplug.org/) and displays it on the terminal. -It seprates the content accrding to the screen size. +It separates the content accrding to the screen size. ```bash python Blog_reader.py @@ -51,15 +58,26 @@ pip install twitter python bulk_add_twitter_list.py ``` + * ### Caesar Cipher Encrypts or Decrypts any message you want, simply enter the message and the rotation number ```bash python caesar_cipher.py ``` +* ### Contributor list +For a given repo generate contribute.md with images in same size like the one in this README.md + +```python + python .\contributors.py https://github.com/Logan1x/Python-Scripts/ +``` +where the argument is the url of the repo + +you may need to install packages like PIL@1.1.7 and requests if not installed + * ### End To End Encryption It is a simple program to implement and understand the basic of end_to_end encryption. -Here i am using caesar cipher to encrpt nbut in reality they Use algotihms lile SHA-1, RSA etc. +Here I am using caesar cipher to encrypt but in reality they use algotihms lile SHA-1, RSA etc. ```bash python end_to_end.py ``` @@ -72,6 +90,8 @@ Simple GUI program which helps you calculate your expenses, monitor them just th python expense_manger.py ``` + + * ### Facebook Auto Post This is python script that log in into facebook and post the status. @@ -103,6 +123,28 @@ Parameters: python ftp_download_file.py ``` +* ### Fetch HTML +This script fetch html response from the provided url and parse xml tag to get only text content and print out. + +```bash +python fetch_html.py https://github.com +`````` + +* ### Get External IP +Gets the external IP-Address from the current machine and prints it to the console +```bash +python getExternalIp.py +``` + +* ### Group files by type + - Group files by their extensions + - Files are moved into folders with extension names + + #### Usage Instructions + ```python + python group_file_by_type.py 'C:\\test\\products' + ``` + * ### Handy offline dictionary A tiny offline dictionary app based on nltk wordnet and pyqt5 ```bash @@ -110,9 +152,39 @@ cd dictionary python app.py ``` +* ### Highcharts loader +It is a simple program that can load charts from [highcharts](www.highcharts.com). +After loading chart you can save it to file or embed it into your html page in base64 format. +Don't forget install `requests` library from `highcharts_loader_requirements.txt` +```python +from highcharts_loader import ChartLoader, Options + +options = Options(from_file='options.json') +chart = ChartLoader(options) +chart.save_to_file('result.png') +``` + +options.json example: +```json +{ + "chart": { + "type": "bar" + }, + "title": { + "text": "Which channels are driving engagement?" + }, + "xAxis": { + "categories": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] + }, + "series": [{ + "data": [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] + }] +} +``` * ### Image Encoder -It is a simple program to encode and decode images, which helps to reduce and handle images on server, as it is convertedto base64 address. +It is a simple program to encode and decode images, which helps to reduce and handle images on server, as it is converted to base64 address. ```bash python image_encoder.py ``` @@ -125,7 +197,6 @@ It then calculates the area using two methods, the Simpson method and the Trapez python integrate-graph.py ``` - * ### Locate Me Run this script and it will locate you. @@ -144,7 +215,6 @@ This uses [Checkip](http://checkip.dyndns.com/) and [ipinfo.io](http://ipinfo.io python locate-me.py ``` - * ### Meme Density This script tells you the amount of memes in your facebook feed @@ -155,7 +225,6 @@ pip install memedensity memedensity ``` - * ### Mi Community Bot This python script uses selenium module in python to automate the thread posting. @@ -167,16 +236,11 @@ If you want to understand this code you can visit [here.](https://l0gan1x.quora. pip install -r mi-community-bot.requirements.txt python mi-community-bot.py ``` - - * ### Missionaires And Cannibals Problem It is a simple program to mimic Missionaries And Cannibals River Crossing Problem. ```bash python missionaries_and_cannibals_problem.py ``` - - - * ### Password Strength Checker This code checks for your password strength. For the right password, password must contain mixture of an upper case letters, an digit (including 0-9), and a special characters with lower case letters. @@ -184,17 +248,10 @@ This code checks for your password strength. For the right password, password mu ```bash python password-strength-checker.py ``` - - * ### Plotting a function This script contains an example of plotting a function using [`matplotlib`](http://matplotlib.org/). Feel free to modify the value of `y` to obtain different functions that depend on `x`. -```bash -python plot_example.py -``` - - * ### Server And Client It is simple client server communication script, will add more functionality in future. ```bash @@ -203,7 +260,6 @@ python client.py python server.py ``` - * ### Tweetload Download latest tweets (default: up to 4000) from a specific twitter user. The script will create a file with one tweet per line, stripped from mentions, hashtags and links.
@@ -211,13 +267,20 @@ For that to work, create a json file with your twitter credentials (see source) ```bash python3 tweetload.py ``` - - * ### Twitter_retweet_bot It is a simple script that retweets any hashtag provided in it. ```bash python twitter_retweet_bot.py ``` +* ### Twitter Sentiment Analysis +A python script that goes through the twitter feeds and calculates the sentiment of the users on the topic of Demonetization in India. +Sentiments are calculated to be positive, negative or neutral. +Various other analyses are represented using graphs. + +```bash +pip install -r analyseTweets-requirements.txt +python analyseTweets.py +``` * ### URL Shortener @@ -231,13 +294,12 @@ python shortener.py url1 url2 python shortener.py url1 url2 > file.txt ``` - * ### Video-downloader v1.1 -#### About + #### About -This file allows the user to download videos off of the web. +This file allows the user to download videos off of the web. as of version 1 the user is able to download highquality videos as a playlist or single file as well as audio files from the supported websites given here http://rg3.github.io/youtube-dl/supportedsites.html are supported. @@ -247,38 +309,33 @@ a simple video downloader using youtube-dl Library, a starter script for making of youtube-dl. #### Requirements - * You will need to install youtube_dl * This can be installed using pip on windows, - * if you do not know how to use pip please read the installation instructions -* requests library - * can be downloaded using pip on windows and respective package managers on different operating systems. -* ffmpeg in order to convert the downloaded files to the right format + * If you do not know how to use pip please read the installation instructions + * Requests library + * Can be downloaded using pip on windows and respective package managers on different operating systems. + * ffmpeg in order to convert the downloaded files to the right format #### Installation -clone this repo and run `python vid.py` script! +Clone this repo and run `python vid.py` script! assuming you already have the other requirements. - #### FFmpeg - +* ### Bulk add users to Twitter list Follow this wiki-How tutorial http://www.wikihow.com/Install-FFmpeg-on-Windows - #### PIP Extensive information on how to set up virtual env and pip. https://www.dabapps.com/blog/introduction-to-pip-and-virtualenv-python/ - #### Commands Just run the script and follow the interface! Videos downloaded in same folder as the script. - * ### YouTube Bot This is a simple python script that increases your video count/ views. Log out from all google accounts and run this. @@ -298,15 +355,23 @@ In case your browser stoped working delete/comment the following line in the scr #### _Windows_ `os.system("TASKKILL /F /IM " + brow + ".exe")` - - - ## Release History * 0.0.1 * Work in progress +### Markdown to presentation +You can convert markdown in a directory into a **.html** file for presentation using reveal.js + +``` +python reveal-md.py -d folder_name -c config + +``` + +### Note +The config is optional. You can specify with keys as here https://github.com/hakimel/reveal.js/#configuration in a json file. Reveal.js cdn link is included in generated html you may need to download them if you want to use the presentation offline + ## Meta Khushal Sharma – [@Khushal](https://twitter.com/herkuch) – sharmakhushal78@gmail.com @@ -316,40 +381,24 @@ Distributed under the MIT LICENSE license. See [``LICENSE``](https://github.com/ [Logan1x](https://github.com/Logan1x/) - ## Contributing 1. Fork it () 2. Create your feature branch (`git checkout -b feature/fooBar`) -3. Commit your changes (`git commit -am 'Add some fooBar'`) -4. Push to the branch (`git push origin feature/fooBar`) -5. Create a new Pull Request -6. Add your name with a link to your profile in the contributors list. +3. Add your docs in `docs/data.json` file +4. Commit your changes (`git commit -am 'Add some fooBar'`) +5. Push to the branch (`git push origin feature/fooBar`) +6. Create a new Pull Request +7. Add your name with a link to your profile in the contributors list + ## Contributors The following people helped in creating the above content. -* Khushal Sharma -* Kayvan Mazaheri -* Lakshay Kalbhor -* Pradhvan Bisht -* David Antonini -* Nguyen Anh Tien -* Akshit Grover -* Sharan Pai -* Madhav Bahl -* Ishank Arora -* Vishal Sharma -* Apurva Nitanjay -* Surya K -* Peter L. -* Andreas K. -* Lukas S. -* Iyanu Ashiri -* Harshvardhan Singh -* Shivam Pachauri -* Khushboo Paddiyar -* Ahad Ali +![ayrusme](./images/ayrusme.png "ayrusme" )![lionasp](./images/lionasp.png "lionasp" )![zinuzoid](./images/zinuzoid.png "zinuzoid" )![dgupta777](./images/dgupta777.png "dgupta777" )![chiraag-jain](./images/chiraag-jain.png "chiraag-jain" )![niharikakrishnan](./images/niharikakrishnan.png "niharikakrishnan" )![ahadali](./images/ahadali.png "ahadali" )![khushboopaddiyar](./images/khushboopaddiyar.png "khushboopaddiyar" )![Harshvardhan58](./images/Harshvardhan58.png "Harshvardhan58" )![pr0me](./images/pr0me.png "pr0me" )![abhinavralhan](./images/abhinavralhan.png "abhinavralhan" )![Souldiv](./images/Souldiv.png "Souldiv" )![szepnapot](./images/szepnapot.png "szepnapot" )![SuryaThiru](./images/SuryaThiru.png "SuryaThiru" )![apuayush](./images/apuayush.png "apuayush" )![ishank011](./images/ishank011.png "ishank011" )![ValentinChCloud](./images/ValentinChCloud.png "ValentinChCloud" )![MadhavBahlMD](./images/MadhavBahlMD.png "MadhavBahlMD" )![vigov5](./images/vigov5.png "vigov5" )![RodolfoFerro](./images/RodolfoFerro.png "RodolfoFerro" )![toonarmycaptain](./images/toonarmycaptain.png "toonarmycaptain" )![harsha7890](./images/harsha7890.png "harsha7890" )![Pradhvan](./images/Pradhvan.png "Pradhvan" )![Rafi993](./images/Rafi993.png "Rafi993" )![ehnydeel](./images/ehnydeel.png "ehnydeel" )![shivamp123](./images/shivamp123.png "shivamp123" )![vis2797](./images/vis2797.png "vis2797" )![Sharanpai](./images/Sharanpai.png "Sharanpai" )![kalbhor](./images/kalbhor.png "kalbhor" )![iyanuashiri](./images/iyanuashiri.png "iyanuashiri" )![akshitgrover](./images/akshitgrover.png "akshitgrover" )![KayvanMazaheri](./images/KayvanMazaheri.png "KayvanMazaheri" )![Logan1x](./images/Logan1x.png "Logan1x" )![mohitpeshwani](./images/mohitpeshwani.png "mohitpeshwani" ) ### If you like the project give a star [Star button](https://github.com/Logan1x/Python-Scripts/stargazers) + + +[`Back to Top`](https://github.com/Logan1x/Python-Scripts#python-scripts) diff --git a/bin/A-Star-GUI/AStarGUI.py b/bin/A-Star-GUI/AStarGUI.py new file mode 100644 index 0000000..e88843f --- /dev/null +++ b/bin/A-Star-GUI/AStarGUI.py @@ -0,0 +1,277 @@ +# A * Pathfinding Algorithm 🌟 + +# Implemented with pygame, this script will find the shortest distance between two nodes using A * Algorithm 🎮 + +# Instructions / Keys Functionalities: +# -Left Click to add start and end nodes +# -Right Click to remove the nodes +# -Space Bar to start finding the shortest distance +# -'C' to clear and reset the grid + +# Requirements: +# pip install pygame + +# By Susnata Goswami(https://github.com/proghead00) + +import pygame +import math +from queue import PriorityQueue + +WIDTH = 800 +WIN = pygame.display.set_mode((WIDTH, WIDTH)) # dimension to make it a square +pygame.display.set_caption("A* Path Finding Algorithm") + +RED = (235, 77, 75) +GREEN = (186, 220, 88) +BLUE = (48, 51, 107) +YELLOW = (249, 202, 36) +WHITE = (255, 255, 255) +BLACK = (53, 59, 72) +PURPLE = (130, 88, 159) +ORANGE = (225, 95, 65) +GREY = (128, 128, 128) +TURQUOISE = (10, 189, 227) + + +class Spot: + def __init__(self, row, col, width, total_rows): + self.row = row + self.col = col + self.x = row * width + self.y = col * width + self.color = WHITE + self.neighbors = [] + self.width = width + self.total_rows = total_rows + + def get_pos(self): + return self.row, self.col + + def is_closed(self): + return self.color == RED + + def is_open(self): + return self.color == GREEN + + def is_barrier(self): + return self.color == BLACK + + def is_start(self): + return self.color == ORANGE + + def is_end(self): + return self.color == TURQUOISE + + def reset(self): + self.color = WHITE + + def make_start(self): + self.color = ORANGE + + def make_closed(self): + self.color = RED + + def make_open(self): + self.color = GREEN + + def make_barrier(self): + self.color = BLACK + + def make_end(self): + self.color = TURQUOISE + + def make_path(self): + self.color = PURPLE + + def draw(self, win): + pygame.draw.rect( + win, self.color, (self.x, self.y, self.width, self.width)) + + def update_neighbors(self, grid): + self.neighbors = [] + # DOWN + if self.row < self.total_rows - 1 and not grid[self.row + 1][self.col].is_barrier(): + self.neighbors.append(grid[self.row + 1][self.col]) + + if self.row > 0 and not grid[self.row - 1][self.col].is_barrier(): # UP + self.neighbors.append(grid[self.row - 1][self.col]) + + # RIGHT + if self.col < self.total_rows - 1 and not grid[self.row][self.col + 1].is_barrier(): + self.neighbors.append(grid[self.row][self.col + 1]) + + if self.col > 0 and not grid[self.row][self.col - 1].is_barrier(): # LEFT + self.neighbors.append(grid[self.row][self.col - 1]) + + def __lt__(self, other): + return False + + +def h(p1, p2): + x1, y1 = p1 + x2, y2 = p2 + return abs(x1 - x2) + abs(y1 - y2) # finding absolute distance + + +def reconstruct_path(came_from, current, draw): + while current in came_from: + current = came_from[current] + current.make_path() + draw() + + +def algorithm(draw, grid, start, end): + count = 0 + open_set = PriorityQueue() + open_set.put((0, count, start)) + came_from = {} + # keeps track of current shortest distance from start node to this node + g_score = {spot: float("inf") for row in grid for spot in row} + g_score[start] = 0 + # keeps track of predicted distance from this node to end node + f_score = {spot: float("inf") for row in grid for spot in row} + f_score[start] = h(start.get_pos(), end.get_pos()) + + open_set_hash = {start} + + while not open_set.empty(): + for event in pygame.event.get(): + if event.type == pygame.QUIT: + pygame.quit() + + current = open_set.get()[2] + open_set_hash.remove(current) + + if current == end: + reconstruct_path(came_from, end, draw) + end.make_end() + return True + + for neighbor in current.neighbors: + temp_g_score = g_score[current] + 1 + + if temp_g_score < g_score[neighbor]: + came_from[neighbor] = current + g_score[neighbor] = temp_g_score + f_score[neighbor] = temp_g_score + \ + h(neighbor.get_pos(), end.get_pos()) + if neighbor not in open_set_hash: + count += 1 + open_set.put((f_score[neighbor], count, neighbor)) + open_set_hash.add(neighbor) + neighbor.make_open() + + draw() + + if current != start: + current.make_closed() + + return False + + +def make_grid(rows, width): + grid = [] + gap = width // rows # integer division: gap b/w each of these rows + for i in range(rows): + grid.append([]) + for j in range(rows): + spot = Spot(i, j, gap, rows) + grid[i].append(spot) + + return grid + + +def draw_grid(win, rows, width): + gap = width // rows + for i in range(rows): + pygame.draw.line(win, GREY, (0, i * gap), + (width, i * gap)) # horizontal line + for j in range(rows): + pygame.draw.line(win, GREY, (j * gap, 0), + (j * gap, width)) # vertical lines + + +def draw(win, grid, rows, width): + win.fill(WHITE) + + for row in grid: + for spot in row: + spot.draw(win) + + draw_grid(win, rows, width) + pygame.display.update() + +# getting mouse postiion + + +def get_clicked_pos(pos, rows, width): + gap = width // rows + y, x = pos + + row = y // gap + col = x // gap + + return row, col + + +def main(win, width): + ROWS = 50 + grid = make_grid(ROWS, width) + + start = None + end = None + + run = True + while run: + draw(win, grid, ROWS, width) + for event in pygame.event.get(): + if event.type == pygame.QUIT: + run = False + + if pygame.mouse.get_pressed()[0]: # LEFT MOUSE BUTTON: 0 + pos = pygame.mouse.get_pos() + # actual spot in 2D list where mouse is clicked + row, col = get_clicked_pos(pos, ROWS, width) + spot = grid[row][col] + + # if start and end aren't done + if not start and spot != end: + start = spot + start.make_start() + + # to avoid overlapping of start and end node + elif not end and spot != start: + end = spot + end.make_end() + + elif spot != end and spot != start: + spot.make_barrier() + + elif pygame.mouse.get_pressed()[2]: # RIGHT MOUSE BUTTON: 2 + pos = pygame.mouse.get_pos() + row, col = get_clicked_pos(pos, ROWS, width) + spot = grid[row][col] + spot.reset() + if spot == start: + start = None + elif spot == end: + end = None + + if event.type == pygame.KEYDOWN: + if event.key == pygame.K_SPACE and start and end: + for row in grid: + for spot in row: + spot.update_neighbors(grid) + + algorithm(lambda: draw(win, grid, ROWS, width), + grid, start, end) + + if event.key == pygame.K_c: + start = None + end = None + grid = make_grid(ROWS, width) + + pygame.quit() + + +main(WIN, WIDTH) diff --git a/bin/A-Star-GUI/README.md b/bin/A-Star-GUI/README.md new file mode 100644 index 0000000..e6770db --- /dev/null +++ b/bin/A-Star-GUI/README.md @@ -0,0 +1,18 @@ +# A\* Pathfinding Algorithm 🌟 + +## Implemented with pygame, this script will find the shortest distance between two nodes using A\* Algorithm 🎮 + +## Instructions/ Keys Functionalities : + +- ### Left Click to add start and end nodes +- ### Right Click to remove the nodes +- ### Space Bar to start finding the shortest distance +- ### 'C' to clear and reset the grid + +## Requirements: + + pip install pygame + +![ss](https://user-images.githubusercontent.com/55017730/92324354-88be8200-f05e-11ea-8d10-e8314ec8f5c1.png) + +### By Susnata Goswami(https://github.com/proghead00) diff --git a/bin/A-Star-GUI/requirements.txt b/bin/A-Star-GUI/requirements.txt new file mode 100644 index 0000000..231dd17 --- /dev/null +++ b/bin/A-Star-GUI/requirements.txt @@ -0,0 +1 @@ +pygame \ No newline at end of file diff --git a/bin/Blog_reader.py b/bin/Blog_reader.py index c1d9a14..bf2f078 100644 --- a/bin/Blog_reader.py +++ b/bin/Blog_reader.py @@ -10,9 +10,9 @@ piu = data[i] heading = piu.find("a").get_text() for n in range(84): - print ("-", end=" ") - print ('{}{}'.format(' ' * (int(columns / 2 - len(heading) / 2)), heading)) + print("-", end=" ") + print('{}{}'.format(' ' * (int(columns / 2 - len(heading) / 2)), heading)) for n in range(84): - print ("-", end=" ") + print("-", end=" ") main_content = piu.find(class_="content").get_text() - print (main_content) + print(main_content) diff --git a/bin/File_Dispatcher/main.py b/bin/File_Dispatcher/main.py new file mode 100644 index 0000000..2e8b711 --- /dev/null +++ b/bin/File_Dispatcher/main.py @@ -0,0 +1,18 @@ +import shutil +import os + +path = "D:\\Abdul Rehman\\AI Automations\\File_Dispatcher" + +print("Before Moving Files ") +print(os.listdir(path)) + +m = "D:\\Abdul Rehman\\AI Automations\\Source\\Source\\abd.txt" +print(os.listdir(m)) + +destination = "D:\\Abdul Rehman\\Downloads_Backup\Images" + +if m.endswith(('.txt')): + + dest = shutil.move(source, destination, copy_function="Move") +else: + print("Unable to Fetch it") diff --git a/bin/Find image difference requirements.txt b/bin/Find image difference requirements.txt new file mode 100644 index 0000000..6ca6c45 --- /dev/null +++ b/bin/Find image difference requirements.txt @@ -0,0 +1 @@ +pillow==7.2.0 \ No newline at end of file diff --git a/bin/Find image difference.py b/bin/Find image difference.py new file mode 100644 index 0000000..1281e27 --- /dev/null +++ b/bin/Find image difference.py @@ -0,0 +1,9 @@ +# importing dependecies +from PIL import Image ,ImageChops +img1=Image.open("Image Difference/img1.jpg") +img2=Image.open("Image Difference/img2.jpg") + +#returns the new image with pixel-by-pixel difference between the two images +newImage=ImageChops.difference(img1,img2) +if newImage.getbbox(): + newImage.show() diff --git a/bin/Image Difference/img1.jpg b/bin/Image Difference/img1.jpg new file mode 100644 index 0000000..fe48a6b Binary files /dev/null and b/bin/Image Difference/img1.jpg differ diff --git a/bin/Image Difference/img2.jpg b/bin/Image Difference/img2.jpg new file mode 100644 index 0000000..a724926 Binary files /dev/null and b/bin/Image Difference/img2.jpg differ diff --git a/bin/ImagetoData.py b/bin/ImagetoData.py index eadcb7e..dd69feb 100644 --- a/bin/ImagetoData.py +++ b/bin/ImagetoData.py @@ -1,4 +1,5 @@ -import os, os.path +import os +import os.path import numpy as np from PIL import Image @@ -16,5 +17,6 @@ def image_classifier(path): return np.array(imgs) - # converts all images in a particular directory to a 64*64*3 (3 for the rgb value of image) dimension vector + # converts all images in a particular directory to a 64*64*3 + # (3 for the rgb value of image) dimension vector # use - in machine learning and image processing diff --git a/bin/Linux and Windows Desktop Setup Automation/README.md b/bin/Linux and Windows Desktop Setup Automation/README.md new file mode 100644 index 0000000..493202a --- /dev/null +++ b/bin/Linux and Windows Desktop Setup Automation/README.md @@ -0,0 +1,65 @@ +# 🛠️ In Development + +This repository contains a collection of **automation and optimization scripts**, aiming to improve the **development environment on Linux** and **gaming performance on Windows**. + +--- + +## 🐧 Linux Automation Scripts + +The Python script **`automation_script.py`** is designed to streamline the setup of a new development environment on Linux. +It automates the installation of essential tools, ensuring everything is ready to get you started quickly. + +### Linux Script Features +- **System Updates**: Runs `apt update` and `apt upgrade` to keep packages up to date. +- **Essential Tools**: Automatically installs `htop` (process monitor), `Git` (version control), and `Neofetch` (system information). +- **Development Environment**: Installs **Visual Studio Code** via Snap. +- **Customization**: Includes `GNOME Tweaks` and `GNOME Shell Extensions` to customize the user interface. + +--- + +## 🎮 Windows Optimization Scripts + +The PowerShell script **`windows_gaming_tweaks.ps1`** is an interactive tool for optimizing Windows and boosting gaming performance. +It provides a simple, straightforward menu to run system maintenance and repair tasks. + +### 💻 Windows Script Features +- **SFC/SCANNOW**: Scans and repairs corrupted system files. +- **CHKDSK**: Analyzes and fixes disk errors to maintain data integrity. +- **Temporary File Cleanup**: Removes unnecessary files that take up space and slow down the system. +- **DISM**: Repairs the operating system image, ensuring updates work properly. + +--- + +## How to Use + +### 🔹 On Linux +1. Clone the repository: + ```bash + git clone https://github.com/Logan1x/Python-Scripts.gitgit + ``` + +2. Enter the repository directory: + ```bash + cd Python-Scripts + ``` + +3. Execute the script: + ```bash + python3 automation_script.py + ``` + +### 🔹 On Windows + +1. Open PowerShell as Administrator. To do this, right-click the Start Menu icon and select `Windows PowerShell (Admin)` or `Terminal (Admin)`. + +2. Navigate to the directory where the script is saved: + ```bash + cd C:\path\to\repository + ``` + +3. Execute the script: + ```bash + .\windows_gaming_tweaks.ps1 + ``` + +Note: If the script doesn't run, you might need to adjust the PowerShell execution policy. Use the command `Set-ExecutionPolicy RemoteSigned` (run as Administrator) to allow local scripts to execute. \ No newline at end of file diff --git a/bin/Linux and Windows Desktop Setup Automation/scriptLinux.py b/bin/Linux and Windows Desktop Setup Automation/scriptLinux.py new file mode 100644 index 0000000..c20380d --- /dev/null +++ b/bin/Linux and Windows Desktop Setup Automation/scriptLinux.py @@ -0,0 +1,38 @@ +#In development + +import subprocess +import sys + +def autom_sudoapt(command): + try: + subprocess.run(command, check=True, text=True, shell=True) + print(f"Comando '{command}' executado com sucesso.") + except subprocess.CalledProcessError as e: + print(f"Erro ao executar o comando '{command}': {e}", file=sys.stderr) + sys.exit(1) + +def main(): + print("Iniciando a atualização e instalação do htop, vscode e git...") + + autom_sudoapt("sudo apt update -y") + + autom_sudoapt("sudo apt upgrade -y") + + autom_sudoapt("sudo apt install -y htop") + + autom_sudoapt("sudo apt install -y git") + + autom_sudoapt("sudo snap install -y --classic code") + + autom_sudoapt("sudo apt install neofetch -y") + + autom_sudoapt("sudo apt install gnome-tweaks -y") + + autom_sudoapt("sudo apt install gnome-shell-extensions -y") + + autom_sudoapt("sudo apt install gnome-terminal -y") + + print("Atualização e instalação concluídos!") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/bin/Linux and Windows Desktop Setup Automation/scriptWin.ps1 b/bin/Linux and Windows Desktop Setup Automation/scriptWin.ps1 new file mode 100644 index 0000000..60184b9 --- /dev/null +++ b/bin/Linux and Windows Desktop Setup Automation/scriptWin.ps1 @@ -0,0 +1,104 @@ +#In development + +# Check for administrator privileges +if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { + Write-Warning "This script needs to be run as an Administrator. Restarting with elevated privileges..." + Start-Process powershell "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs + exit +} + +# Function to display the menu +function Show-Menu { + Clear-Host + Write-Host "------------------------------------------------------" -ForegroundColor Cyan + Write-Host "Script for Windows optimization with a focus on games " -ForegroundColor White + write-Host " Developed by euopaulin " -ForegroundColor White + Write-Host "------------------------------------------------------" -ForegroundColor Cyan + Write-Host " Choose an option:" -ForegroundColor White + Write-Host "------------------------------------------------------" -ForegroundColor Cyan + Write-Host "1. Run SFC/SCANNOW" -ForegroundColor DarkRed + Write-Host "2. Run CHKDSK" -ForegroundColor DarkRed + Write-Host "3. Clean temporary files" -ForegroundColor DarkRed + Write-Host "4. Restore system image (DISM)" -ForegroundColor DarkRed + Write-Host "5. Exit" -ForegroundColor DarkGreen + Write-Host "------------------------------------------------------" -ForegroundColor Cyan +} + +# Main loop to show the menu and process user input +while ($true) { + Show-Menu + + $choice = Read-Host "Enter the number of your choice" + + switch ($choice) { + "1" { + Write-Host "Option 1 selected: Running SFC/SCANNOW..." -ForegroundColor Yellow + try { + & sfc /scannow + if ($LASTEXITCODE -eq 0) { + Write-Host "SFC/SCANNOW executed successfully." -ForegroundColor Green + } else { + Write-Host "Error running SFC/SCANNOW. Make sure to run the script as an Administrator." -ForegroundColor Red + } + } catch { + Write-Host "An error occurred while running the command." -ForegroundColor Red + } + break + } + "2" { + Write-Host "Option 2 selected: Running CHKDSK..." -ForegroundColor Yellow + $drive = Read-Host "Enter the drive letter (e.g., C)" + Write-Host "Checking drive $drive..." -ForegroundColor Yellow + try { + # Using the native PowerShell command + Repair-Volume -DriveLetter $drive -Scan -Verbose + Write-Host "CHKDSK executed successfully." -ForegroundColor Green + } catch { + Write-Host "An error occurred while running the command." -ForegroundColor Red + } + break + } + "3" { + Write-Host "Option 3 selected: Cleaning temporary files..." -ForegroundColor Yellow + try { + $tempPaths = "$env:TEMP\*", "$env:SystemRoot\Temp\*" + foreach ($tempPath in $tempPaths) { + if (Test-Path $tempPath) { + Remove-Item -Path $tempPath -Recurse -Force -ErrorAction SilentlyContinue + } + } + Write-Host "Temporary files cleaned successfully." -ForegroundColor Green + } catch { + Write-Host "An error occurred while cleaning temporary files." -ForegroundColor Red + } + break + } + "4" { + Write-Host "Option 4 selected: Restoring system image (DISM)..." -ForegroundColor Yellow + try { + & dism /Online /Cleanup-Image /RestoreHealth + if ($LASTEXITCODE -eq 0) { + Write-Host "DISM executed successfully." -ForegroundColor Green + } else { + Write-Host "Error running DISM. Make sure to run the script as an Administrator." -ForegroundColor Red + } + } catch { + Write-Host "An error occurred while running the command." -ForegroundColor Red + } + break + } + "5" { + Write-Host "Exiting the script. Goodbye!" -ForegroundColor Red + Start-Sleep -Seconds 2 + exit + } + default { + Write-Host "Invalid option. Please enter a number from 1 to 5." -ForegroundColor Red + break + } + } + + Write-Host "" + Write-Host "Press any key to continue..." -ForegroundColor White + $null = [System.Console]::ReadKey($true) +} \ No newline at end of file diff --git a/bin/Lost Robot/Solution.py b/bin/Lost Robot/Solution.py new file mode 100644 index 0000000..62745f4 --- /dev/null +++ b/bin/Lost Robot/Solution.py @@ -0,0 +1,17 @@ +# According to question we can only instruct robot up or down or left or right. +# So in his current coordiantes and home coordinates one of the/ +# coordinate either X or Y must be same. + + +for _ in range(int(input())): + x1, y1, x2, y2 = map(int, input().split()) # This will parse input to x1,y1,x2 and y2 + if x1 != x2 and y1 != y2: + print('sad') + elif x1 == x2 and y1 < y2: + print('up') + elif x1 == x2 and y1 > y2: + print('down') + elif y1 == y2 and x1 < x2: + print('right') + elif y1 == y2 and x1 > x2: + print('left') diff --git a/bin/Lost Robot/quiz b/bin/Lost Robot/quiz new file mode 100644 index 0000000..02f35da --- /dev/null +++ b/bin/Lost Robot/quiz @@ -0,0 +1,34 @@ + +Robot Bunny is lost. It wants to reach its home as soon as possible. Currently it is standing at coordinates (x1, y1) in 2-D plane. +Its home is at coordinates (x2, y2). Bunny is extremely worried. Please help it by giving a command by telling the direction in which it +should to go so as to reach its home. If you give it a direction, it will keep moving in that direction till it reaches its home. +There are four possible directions you can give as command - "left", "right", "up", "down". It might be possible that you can't instruct +the robot in such a way that it reaches its home. In that case, output "sad". + +Input +First line of the input contains an integer T denoting the number of test cases. T test cases follow. + +First line of each test case contains four space separated integers x1, y1, x2, y2. + +Output +For each test case, output a single line containing "left" or "right" or "up" or "down" or "sad" (without quotes). + +Constraints +1 ≤ T ≤ 5000 +0 ≤ x1, y1, x2, y2. ≤ 100 +It's guaranteed that the initial position of robot is not his home. +Example + +Input +3 +0 0 1 0 +0 0 0 1 +0 0 1 1 + +Output: +right +up +sad + +Explanation +Test case 1. If you give Bunny the command to move to the right, it will reach its home. diff --git a/bin/Pyfirebase.py b/bin/Pyfirebase.py index 333b304..3a8b559 100644 --- a/bin/Pyfirebase.py +++ b/bin/Pyfirebase.py @@ -1,18 +1,18 @@ import requests.packages.urllib3 -requests.packages.urllib3.disable_warnings() import serial import json +from firebase import firebase -arduinoData = serial.Serial('com31',9600) +requests.packages.urllib3.disable_warnings() +arduinoData = serial.Serial('com31', 9600) -from firebase import firebase -firebase = firebase.FirebaseApplication('https://___YOUR_PROJECT_NAME____.firebaseio.com/') +firebase = firebase.FirebaseApplication( + 'https://___YOUR_PROJECT_NAME____.firebaseio.com/') while 1: myData = (arduinoData.readline().strip()) myData = (myData.decode('utf-8')) myData = float(myData) - result = firebase.put('MainNode/Leaf','temp',myData) - print 'Data : ',result - + result = firebase.put('MainNode/Leaf', 'temp', myData) + print 'Data : ', result diff --git a/bin/Selenium basics with python/README.md b/bin/Selenium basics with python/README.md new file mode 100644 index 0000000..b098245 --- /dev/null +++ b/bin/Selenium basics with python/README.md @@ -0,0 +1,134 @@ +## Selenium Driver with the Python from scratch with examples + +## Need to install +Python
+Selenium ------------------> pip instll selenium
+Chromedriver--------------->https://chromedriver.chromium.org/getting-started
+
+ +
+ +## Selenium basics 1 + (i) basics of the selenium web driver small commands
+ (ii) minimize and maximise the functionality
+ +
+ +## Selenium basics 2 +Navigation commands mainly use to move previous page(<-) and forward page(->) page +(i) driver.back()
+(ii) driver.forward()
+ +
+ +## Selenium basics 3 +Demonstrating the condtional function is_selected, is_enabled, is_displayed() mainly for validation purpose
+ (i) is_enabled()
+ (ii) is_selected()
+ (iii) is_displayed()
+ +
+ +## Selenium basics 4 + +Demonstrating the Waits in selenium web driver
+ +Explicit Wait command, the WebDriver is directed to wait until a certain condition occurs before proceeding with executing the code. +Setting Explicit Wait is important in cases where there are certain elements that naturally take more time to load +
+Implicit Wait directs the Selenium WebDriver to wait for a certain measure of time before throwing an exception. +Once this time is set, WebDriver will wait for the element before the exception occurs +
+ +
+ +## Selenium basics 5 +Input Box And Text Box fucntionality using selenium driver
+ +(i) send_keys() to add the message or input into input_box/textarea
+(ii) submit button to submit.
+ + +
+ +## Selenium basics 6 +In this web page we will select the checkbox and radio types of input +using
+ element.click()
+And also check whenever there is a iframe we need to go into iframe using (optional)(Note: we are selecting radio buttons in frame that's why required to go iframe)
+ (i)switch_to.frame('frame_id') --> to select the elements in the specific sections
+ (ii)switch_to.default_content() --> switch to normal mode always is best practice
+ (This two are mostly used in the automation testing perspective. "In safty place like the tracsaction for ex, slack transcation they use nested iframes.)
+ +
+ +## Selenium basics 7 +Lets select from the drop down plane with the help of the selenium web driver command by 3 ways as follow:
+Step 1) Select the element using the element = select(driver.find_element())
+Step 2) Select the value using the following three ways we have
+ (i)element.select_by_visible_text("")
+ (ii)element.select_by_value("")
+ (iii)element.select_by_index()
+
+ +## Selenium basics 8 +''' +We are trying to interact with the links and mainly simply we can get them using the By function
+ +Let's getting the No of the links, all link text, partial link text so we get hands on find_elements function too.
+ + +another ways to find +(i) By.LINK_TEXT --> complete text for single element
+(ii) By.PARTIAL_LINK_TEXT --> partial text is enough for finding individual work
+''' + +
+ +## Selenium basics 9 + +Let us check how we can handle the alerts and popups on the website using selenium websdrive in python +
+we can driver.switch_to.alert()
+where multiple things there accept using .accept()
+where multiple things there accept using .dismiss() +
+another ways to find
+(i) By.LINK_TEXT --> complete text for single element
+(ii) By.PARTIAL_LINK_TEXT --> partial text is enough for finding individual work +'''
+
+ +## Selenium basics 10 +Handling the Windows tab using selenium webdriver with Python
+ +Basics which is necessary to understand.
+ +
+ +## Selenium basics 11 + +handle the scroll in a web page using the python with selenium
+ +
+ +## Selenium basics 12 + +handle the mouse hower or touch on mobile screen actions through the selenium web driver commands
+ + +## Selenium basics 13 + +Double Click action using mouse handling on python selenium
+ +## Selenium basics 14 + +perform some more functionality around ActionChain
+ + +

Connect with me:

+

+mohit peshwani +coding_nightmare +mohit peshwani +

diff --git a/bin/Selenium basics with python/basics_selenium1.py b/bin/Selenium basics with python/basics_selenium1.py new file mode 100644 index 0000000..7a7d4c8 --- /dev/null +++ b/bin/Selenium basics with python/basics_selenium1.py @@ -0,0 +1,12 @@ + +''' +Simple hands on the selenium with help of python library + +''' +from selenium import webdriver +driver = webdriver.Chrome(executable_path="chromedriver.exe") # to use the functionality of the web driver we need to create the object of the drive with specific browser which we want to use +driver.get("https://mohitpeshwani.github.io/crazyprogrammer/") #to load the target url we user webdriver.get("url") to load it +driver.maximize_window() #to maxiumize the windows +driver.minimize_window() #to minimize the windows +print(driver.title) #to get the exact title of the page we can use the webdriver.title +driver.quit() # to close the automation windows \ No newline at end of file diff --git a/bin/Selenium basics with python/basics_selenium10.py b/bin/Selenium basics with python/basics_selenium10.py new file mode 100644 index 0000000..bf633ab --- /dev/null +++ b/bin/Selenium basics with python/basics_selenium10.py @@ -0,0 +1,40 @@ +''' +Handling the Windows tab using selenium webdriver with Python + +Basics which is necessary to understand + +Every windows has it's own hexadecimal value assign with it ex,(CDwindow-5907D74FC9E6C6E2918AB140D08C34AE) +using + driver.current_window_handler + +To switch into within any other tab of the similar webpage we can simply use the same + + driver.switch_to.windows(handler) + +to get all the windows + + driver.window_handles + +Remeber difference between the two .quit() and .close() + --> quit() terminate the browser + --> close() terminate the current tab on the browser + +''' +from selenium import webdriver +from selenium.webdriver.common.by import By +import time +driver =webdriver.Chrome(executable_path="chromeDriver.exe") +driver.get("https://demo.automationtesting.in/Windows.html") +clicked_element = driver.find_element(By.XPATH,"//a[@href='http://www.selenium.dev']//button[@class='btn btn-info'][normalize-space()='click']").click() +time.sleep(2) +print(driver.current_window_handle) +tabs = driver.window_handles +for tab in tabs: + driver.switch_to.window(tab) + time.sleep(2) + print(driver.title) + driver.close() +driver.quit() + + + diff --git a/bin/Selenium basics with python/basics_selenium11.py b/bin/Selenium basics with python/basics_selenium11.py new file mode 100644 index 0000000..083e427 --- /dev/null +++ b/bin/Selenium basics with python/basics_selenium11.py @@ -0,0 +1,21 @@ +''' +Let's check who we can handle the scroll in a web page using the python with selenium + +Simplest wait is to execute the js using the + driver.execute_script("windows.scrollBy(0,500)) + + Note: we can execute javascript using + (1) driver.execute_script("","") + (2) driver.execute_async_scipt("","") + + +''' + +from selenium import webdriver +import time +driver =webdriver.Chrome(executable_path="chromeDriver.exe") +driver.get("https://mohitpeshwani.github.io/crazyprogrammer/") +time.sleep(3) +driver.execute_script("window.scrollBy(0,500)","") +time.sleep(3) +driver.quit() diff --git a/bin/Selenium basics with python/basics_selenium12.py b/bin/Selenium basics with python/basics_selenium12.py new file mode 100644 index 0000000..777bcd7 --- /dev/null +++ b/bin/Selenium basics with python/basics_selenium12.py @@ -0,0 +1,31 @@ +''' +Let'us handle the mouse hower or touch on mobile screen actions through the selenium web driver commands + +step 1: We need to import addition Object which is + ActionChain +step 2: + Also initilize it using using a variable is always preferable + action =ActionChain(webdriver) + +step 3: + to perform any action we need to + element.move_to().perform() + +''' + +from selenium import webdriver +from selenium.webdriver.common.by import By +from selenium.webdriver import ActionChains +import time +driver =webdriver.Chrome(executable_path="chromeDriver.exe") +driver.get("https://www.browserstack.com") +action = ActionChains(driver) +time.sleep(3) +product_menu = driver.find_element(By.CSS_SELECTOR,"#product-menu-toggle") +live_submenu = driver.find_element(By.CSS_SELECTOR,"a[aria-label='Live'] div[class='dropdown-link-text']") +action.move_to_element(product_menu).perform() +time.sleep(2) +live_submenu.click() +time.sleep(2) +print("Title include Live: ",driver.title) +driver.quit() \ No newline at end of file diff --git a/bin/Selenium basics with python/basics_selenium13.py b/bin/Selenium basics with python/basics_selenium13.py new file mode 100644 index 0000000..95e3170 --- /dev/null +++ b/bin/Selenium basics with python/basics_selenium13.py @@ -0,0 +1,32 @@ +''' +Let us check the Double Click action using mouse handling on python selenium + +step 1: We need to import addition Object which is + ActionChain +step 2: + Also initilize it using using a variable is always preferable + action =ActionChain(webdriver) + +step 3: + to perform any Doubleclick + action.doule_click(element).perform() ------------> Double click action + action.context_click(element).perform() ------------> Right click actions appear + +''' + +from selenium import webdriver +from selenium.webdriver.common.by import By +from selenium.webdriver import ActionChains +import time + +driver=webdriver.Chrome(executable_path="chromedriver.exe") +driver.get("https://testautomationpractice.blogspot.com/") +element = driver.find_element(By.CSS_SELECTOR,"button[ondblclick='myFunction1()']") +time.sleep(2) +#ActionChains(driver).double_click(element).perform() +ActionChains(driver).context_click(element).perform() + +time.sleep(2) +label2 = driver.find_element(By.ID,"field2") +print(label2.get_property) +driver.quit() diff --git a/bin/Selenium basics with python/basics_selenium14.py b/bin/Selenium basics with python/basics_selenium14.py new file mode 100644 index 0000000..681f358 --- /dev/null +++ b/bin/Selenium basics with python/basics_selenium14.py @@ -0,0 +1,26 @@ +''' +Let us perform some more functionality around ActionChain + + Drag and Drop --> we can simple drag and drop the elements using + action.drag_and_drop(element_source, element_target).perform() + + + +''' +from selenium import webdriver +from selenium.webdriver.common.by import By +from selenium.webdriver import ActionChains +import time + +driver=webdriver.Chrome(executable_path="chromedriver.exe") +driver.get("https://testautomationpractice.blogspot.com/") +element = driver.find_element(By.CSS_SELECTOR,"button[ondblclick='myFunction1()']") +time.sleep(2) +action =ActionChains(driver) +drag = driver.find_element(By.ID,"draggable") +to_drop = driver.find_element(By.ID,"droppable") +action.drag_and_drop(drag,to_drop).perform() +time.sleep(2) +driver.maximize_window() +driver.save_screenshot("dragAnddrop.png") +driver.quit() diff --git a/bin/Selenium basics with python/basics_selenium15.py b/bin/Selenium basics with python/basics_selenium15.py new file mode 100644 index 0000000..2d5ea85 --- /dev/null +++ b/bin/Selenium basics with python/basics_selenium15.py @@ -0,0 +1,31 @@ +''' +When performing API testing we manily work on the cookies and determine +So simple things around the cookies are demonstrate which are manily used by QA/Developer during building the website + +(i) driver.get_cookies() ----------------------------------------------------> Get all the cookies properities +(ii) driver.get_cookie("name") -----------------------------------------------> Get individual cookies +(iii) driver.add_cookie({"name":"string_value", "value": "string_value"})------> Injecting the cookies in current driver from coding point of view +(iv) driver.delete_all_cookies() ---------------------------------------------> Deleting all the cookies +(v) driver.delete_cookie(name)-----------------------------------------------> Deleting individual cookie + +''' + + + +from selenium import webdriver +from selenium.webdriver.common.by import By +import time +driver =webdriver.Chrome(executable_path="chromeDriver.exe") +driver.get("https://www.linkedin.com/in/mohit-peshwani/") +cookies = driver.get_cookies() +# get all the cookies +# print(cookies) --------------------> print all the cookies with list not looks good uncomment it for better understanding while performing +driver.add_cookie({"name":"python","value":"mohit"}) + +for cookie in cookies: + print(cookie) +time.sleep(2) + +cookies = driver.delete_all_cookies() +print(driver.get_cookies()) +driver.quit() diff --git a/bin/Selenium basics with python/basics_selenium2.py b/bin/Selenium basics with python/basics_selenium2.py new file mode 100644 index 0000000..0e889c3 --- /dev/null +++ b/bin/Selenium basics with python/basics_selenium2.py @@ -0,0 +1,22 @@ +''' +Navigation commands mainly use to move previous page(<-) and forward page(->) page +(i) driver.back() +(ii) driver.forward() + +''' + +from selenium import webdriver +import time +driver =webdriver.Chrome(executable_path="chromedriver.exe") +driver.get("https://www.github.com") +print(driver.title) +time.sleep(2) # to wait for 2 seconds +driver.get("https://www.google.com") +print(driver.title) +time.sleep(2) +driver.back() # it goes once action backward +time.sleep(2) +print("Navigated to the back page: ",driver.title) +driver.forward() # it goes to the next action page if gone +print("Navigrated to the next page: ",driver.title) +driver.quit() diff --git a/bin/Selenium basics with python/basics_selenium3.py b/bin/Selenium basics with python/basics_selenium3.py new file mode 100644 index 0000000..95e476b --- /dev/null +++ b/bin/Selenium basics with python/basics_selenium3.py @@ -0,0 +1,26 @@ +''' +conditional commands are used to check wheater the fuction is working fine or not properly (Validation purpose) +(i) is_enable() +(ii) is_displayed() +(iii) is_selected() + +prior this we need to select the selector to check for the element to use +using css selector and xpath selector +''' +from selenium import webdriver +from selenium.webdriver.common.by import By # need to use this selector +driver = webdriver.Chrome(executable_path="chromedriver.exe") + + +''' +Using the CSS_selector we are selecting input and checking wheather it's dispalyed properly or not +Executed : 1)is_displayed() 2)is_enabled() + +''' +driver.get("https://www.google.com/") + +element = driver.find_element(By.CSS_SELECTOR,"input[title='Search']") + +print(element.is_displayed()) +print(element.is_enabled()) + diff --git a/bin/Selenium basics with python/basics_selenium3_is_selected.py b/bin/Selenium basics with python/basics_selenium3_is_selected.py new file mode 100644 index 0000000..7d4a1b2 --- /dev/null +++ b/bin/Selenium basics with python/basics_selenium3_is_selected.py @@ -0,0 +1,15 @@ +''' +Demonstrating the condtional function is_selected in this file +''' + +from selenium import webdriver +from selenium.webdriver.common.by import By +driver = webdriver.Chrome(executable_path="chromedriver.exe") +driver.get("https://demoqa.com/radio-button") + +# storing elements and detect wheather they are selected or not + +selected_button = driver.find_element(By.CSS_SELECTOR,"label[for='yesRadio']") +selected_button2 = driver.find_element(By.CSS_SELECTOR,"label[for='impressiveRadio']") +print(selected_button.is_selected()) +driver.quit() diff --git a/bin/Selenium basics with python/basics_selenium4_explict_wait.py b/bin/Selenium basics with python/basics_selenium4_explict_wait.py new file mode 100644 index 0000000..564f369 --- /dev/null +++ b/bin/Selenium basics with python/basics_selenium4_explict_wait.py @@ -0,0 +1,23 @@ +''' +Explicit Wait command, the WebDriver is directed to wait until a certain condition occurs before proceeding with executing the code. +Setting Explicit Wait is important in cases where there are certain elements that naturally take more time to load + +Implicit Wait directs the Selenium WebDriver to wait for a certain measure of time before throwing an exception. +Once this time is set, WebDriver will wait for the element before the exception occurs +''' +from selenium import webdriver +from selenium.webdriver.common.by import By +from selenium.webdriver.support.ui import WebDriverWait +from selenium.webdriver.support import expected_conditions as EC + +driver = webdriver.Chrome(executable_path="chromedriver.exe") +driver.get("https://mohitpeshwani.github.io/crazyprogrammer/") +try: + # wait 10 extra seconds before looking for element until it found my website image + element = WebDriverWait(driver, 10).until( + EC.presence_of_element_located((By.CSS_SELECTOR, "img[src='./images/man12.png']")) + ) + print(element.is_displayed()) # should return true + print("Demontrating the explicit wait ") +finally: + driver.quit() \ No newline at end of file diff --git a/bin/Selenium basics with python/basics_selenium4_implict_wait.py b/bin/Selenium basics with python/basics_selenium4_implict_wait.py new file mode 100644 index 0000000..45a0294 --- /dev/null +++ b/bin/Selenium basics with python/basics_selenium4_implict_wait.py @@ -0,0 +1,20 @@ +''' +Explicit Wait command, the WebDriver is directed to wait until a certain condition occurs before proceeding with executing the code. +Setting Explicit Wait is important in cases where there are certain elements that naturally take more time to load + +Implicit Wait directs the Selenium WebDriver to wait for a certain measure of time before throwing an exception. +Once this time is set, WebDriver will wait for the element before the exception occurs +''' +from selenium import webdriver +from selenium.webdriver.common.by import By +from selenium.webdriver.support.ui import WebDriverWait +from selenium.webdriver.support import expected_conditions as EC + +driver = webdriver.Chrome(executable_path="chromedriver.exe") +driver.get("https://mohitpeshwani.github.io/crazyprogrammer/") +#implicity waiting for the 10 seconds +driver.implicitly_wait(10) +#element will check after the 10 seconds of wait +element=driver.find_element(By.XPATH,"//div[@class=' hero flex flex-1 items-center justify-between ']//img[1]") #using xpath selector to get the element +print(element.is_displayed()) +driver.quit() diff --git a/bin/Selenium basics with python/basics_selenium5.py b/bin/Selenium basics with python/basics_selenium5.py new file mode 100644 index 0000000..5a21173 --- /dev/null +++ b/bin/Selenium basics with python/basics_selenium5.py @@ -0,0 +1,25 @@ +''' +Input Box And Text Box fucntionality using selenium driver + +(i) send_keys() to add the message or input into input_box/textarea +(ii) submit button to submit. +''' +from selenium import webdriver +from selenium.webdriver.common.by import By +from selenium.webdriver.support.ui import WebDriverWait +import time +driver = webdriver.Chrome(executable_path="chromedriver.exe") +driver.get('https://app.hackthebox.com/login') +driver.maximize_window() +time.sleep(5) +# adding the id/class of input boxs into the variables +login_email = driver.find_element(By.XPATH,"//input[@id='loginEmail']") +password = driver.find_element(By.XPATH,"//input[@id='loginPassword']") +submit_btn = driver.find_element(By.XPATH,"//input[@id='loginPassword']") + +# Now we will send the random names, email and message and submit +login_email.send_keys("automation@gmail.com") +password.send_keys("Ronaldo the GOAT") +submit_btn.submit() +time.sleep(5) +driver.quit() \ No newline at end of file diff --git a/bin/Selenium basics with python/basics_selenium6.py b/bin/Selenium basics with python/basics_selenium6.py new file mode 100644 index 0000000..5c3b303 --- /dev/null +++ b/bin/Selenium basics with python/basics_selenium6.py @@ -0,0 +1,38 @@ +''' +In this web page we will select the checkbox and radio types of input +using + element.click() +And also check whenever there is a iframe we need to go into iframe using (optional)(Note: we are selecting radio buttons in frame that's why required to go iframe) + (i)switch_to.frame('frame_id') --> to select the elements in the specific sections + (ii)switch_to.default_content() --> switch to normal mode always is best practice + (This two are mostly used in the automation testing perspective. "In safty place like the tracsaction for ex, slack transcation they use nested iframes.) + + +''' + +from selenium import webdriver +from selenium.webdriver.common.by import By +driver = webdriver.Chrome(executable_path="chromedriver.exe") +driver.get("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_type_radio") + +#Switching to iframe with id you can even use iframe_name +driver.switch_to.frame('iframeResult') + +#getting the locators of the elements +html_selector = driver.find_element(By.XPATH, "//input[@id='html']") +css_selector = driver.find_element(By.XPATH, "//input[@id='css']") +js_selector = driver.find_element(By.XPATH, "//input[@id='javascript']") + +#Selected the element +html_selector.click() + +# html selector should give the true and other will be false +print(html_selector.is_selected()) +print(css_selector.is_selected()) +print(js_selector.is_selected()) + +#Switching to normal window format +driver.switch_to.default_content() +driver.quit() + + diff --git a/bin/Selenium basics with python/basics_selenium7.py b/bin/Selenium basics with python/basics_selenium7.py new file mode 100644 index 0000000..93df509 --- /dev/null +++ b/bin/Selenium basics with python/basics_selenium7.py @@ -0,0 +1,29 @@ +''' +Lets select from the drop down plane with the help of the selenium web driver command by 3 ways as follow: +Step 1) Select the element using the element = select(driver.find_element()) +Step 2) Select the value using the following three ways we have + (i)element.select_by_visible_text("") + (ii)element.select_by_value("") + (iii)element.select_by_index() +''' + +from selenium import webdriver +from selenium.webdriver.common.by import By +from selenium.webdriver.support.ui import Select +import time +driver = webdriver.Chrome(executable_path="chromeDriver.exe") + +driver.get("https://fs2.formsite.com/meherpavan/form2/index.html?1537702596407") +link_first = Select(driver.find_element(By.ID,'RESULT_RadioButton-9')) + +#link_first.select_by_visible_text("Afternoon") + +#link_first.select_by_value("Radio-2") + +link_first.select_by_index(2) + +time.sleep(2) + +driver.quit() + + diff --git a/bin/Selenium basics with python/basics_selenium8.py b/bin/Selenium basics with python/basics_selenium8.py new file mode 100644 index 0000000..d1998f3 --- /dev/null +++ b/bin/Selenium basics with python/basics_selenium8.py @@ -0,0 +1,37 @@ +''' +We are trying to interact with the links and mainly simply we can get them using the By function + +Let's getting the No of the links, all link text, partial link text so we get hands on find_elements function too. + + +another ways to find +(i) By.LINK_TEXT --> complete text for single element +(ii) By.PARTIAL_LINK_TEXT --> partial text is enough for finding individual work +''' +from selenium import webdriver +from selenium.webdriver.common.by import By +import time + +driver =webdriver.Chrome(executable_path="chromeDriver.exe") +driver.get("https://mohitpeshwani.github.io/crazyprogrammer/") +time.sleep(5) +no_of_links = driver.find_elements(By.TAG_NAME,'a') +time.sleep(2) +print("No of the links available in the web page:", len(no_of_links)) + +#we link to go on the link no 2 +no_of_links[2].click() + +#printing the assosicate text with the link +for i in no_of_links: + print(i.text) + +#element using LINK_TEXT +print(driver.find_element(By.LINK_TEXT,'mohitpesh23@gmail.com').is_displayed()) + +#element using LINK_TEXT +print(driver.find_element(By.PARTIAL_LINK_TEXT,'mohitpesh23').is_displayed()) + +time.sleep(5) +driver.quit() + diff --git a/bin/Selenium basics with python/basics_selenium9.py b/bin/Selenium basics with python/basics_selenium9.py new file mode 100644 index 0000000..e8bcc71 --- /dev/null +++ b/bin/Selenium basics with python/basics_selenium9.py @@ -0,0 +1,28 @@ +''' +Let us check how we can handle the alerts and popups on the website using selenium websdrive in python + +we can driver.switch_to.alert() +where multiple things there accept using .accept() +where multiple things there accept using .dismiss() + +''' + +from selenium import webdriver +from selenium.webdriver.common.by import By +from selenium.webdriver.support.ui import WebDriverWait +import time + +driver = webdriver.Chrome(executable_path= "chromeDriver.exe") +driver.get("https://demo.automationtesting.in/Alerts.html") +alert_box = driver.find_element(By.CSS_SELECTOR,".btn.btn-danger") +alert_box.click() +time.sleep(2) +# Switching to the ok using accept() else we can use the dismiss() for cancle purpose if available +driver.switch_to.alert.accept() +time.sleep(2) +driver.switch_to.default_content() + +time.sleep(2) +driver.quit() + + diff --git a/bin/Selenium basics with python/chromedriver.exe b/bin/Selenium basics with python/chromedriver.exe new file mode 100644 index 0000000..bc6efd7 Binary files /dev/null and b/bin/Selenium basics with python/chromedriver.exe differ diff --git a/bin/Selenium basics with python/dragAnddrop.png b/bin/Selenium basics with python/dragAnddrop.png new file mode 100644 index 0000000..cf7e54a Binary files /dev/null and b/bin/Selenium basics with python/dragAnddrop.png differ diff --git a/bin/Text-to-audio/README.md b/bin/Text-to-audio/README.md new file mode 100644 index 0000000..e7b6cd9 --- /dev/null +++ b/bin/Text-to-audio/README.md @@ -0,0 +1,26 @@ +## Text To Audio + +### We are using gtts module for conversion + +Requirements: pip install gtts + +#### Flow + +gtts(Google Text To Speech) + +1. Initialise the variable for your text ("mytext" line 6 in main.py) +2. Initialise the variable for language ("language" line 9 in main.py) +3. Create an instance of gTTS class ("myobj" line 12 in main.py) +4. Call the method save() and pass the filename that you want as a parameter (line 15 in main.py) +5. Play the audio file (line 19 in main.py) + +#### NOTE +If you make any changes main.py, please mention it in README.md (this file). A better documentation makes the process of development faster. + +--- +Author - Saumitra Jagdale + + + + + diff --git a/bin/Text-to-audio/hello_world.mp3 b/bin/Text-to-audio/hello_world.mp3 new file mode 100644 index 0000000..74a64a7 Binary files /dev/null and b/bin/Text-to-audio/hello_world.mp3 differ diff --git a/bin/Text-to-audio/text-to-audio.py b/bin/Text-to-audio/text-to-audio.py new file mode 100644 index 0000000..052889c --- /dev/null +++ b/bin/Text-to-audio/text-to-audio.py @@ -0,0 +1,19 @@ + +from gtts import gTTS +import os + +# Enter the text in string format which you want to convert to audio +mytext = "Hello World!, this audio is created using GTTS module." + +# Specify the language in which you want your audio +language = 'en' + +# Create an instance of gTTS class +myobj = gTTS(text=mytext, lang=language, slow=False) + +# Method to create your audio file in mp3 format +myobj.save("hello_world.mp3") +print("Audio Saved") + +# This will play your audio file +os.system("mpg321 welcome.mp3") diff --git a/bin/Video-downloader/vid.py b/bin/Video-downloader/vid.py index 64ef37a..c42ef4b 100644 --- a/bin/Video-downloader/vid.py +++ b/bin/Video-downloader/vid.py @@ -5,29 +5,29 @@ # Master dictionary--will be expanding in future iterations of the project # version 1 of vid.py master = { - 'Audio': { - 'format': 'bestaudio/best', - 'noplaylist': True, - 'postprocessors': [{ - 'key': 'FFmpegExtractAudio', - 'preferredcodec': 'mp3', - 'preferredquality': '192', - }] - }, - 'Video': { - 'format': 'bestvideo+bestaudio/best', - 'noplaylist': True, - 'postprocessors': [{ - 'key': 'FFmpegVideoConvertor', - 'preferedformat': 'mp4', - # 'preferredquality': '137', - }] - }, - 'list': { - 'listsubtitles': True + 'Audio': { + 'format': 'bestaudio/best', + 'noplaylist': True, + 'postprocessors': [{ + 'key': 'FFmpegExtractAudio', + 'preferredcodec': 'mp3', + 'preferredquality': '192', + }] }, - 'listformat': { - 'lisformats': True + 'Video': { + 'format': 'bestvideo+bestaudio/best', + 'noplaylist': True, + 'postprocessors': [{ + 'key': 'FFmpegVideoConvertor', + 'preferedformat': 'mp4', + # 'preferredquality': '137', + }] + }, + 'list': { + 'listsubtitles': True + }, + 'listformat': { + 'lisformats': True } } @@ -69,7 +69,7 @@ def check(link): return False -def download(link,data): +def download(link, data): try: with youtube_dl.YoutubeDL(data) as ydl: ydl.download([link]) @@ -87,21 +87,22 @@ def main(): print("2.Download a Video playlist") print("3.Download a Single Audio") print("4.Download a single video file") - ch=int(input("Enter your choice: ")) - if ch in [1,2,3,4]: + ch = int(input("Enter your choice: ")) + if ch in [1, 2, 3, 4]: if ch == 1: master['Audio']['noplaylist'] = False - download(link,master['Audio']) + download(link, master['Audio']) elif ch == 2: master['Video']['noplaylist'] = False - download(link,master['Video']) + download(link, master['Video']) elif ch == 4: - download(link,master['Video']) + download(link, master['Video']) else: - download(link,master['Audio']) + download(link, master['Audio']) else: print("Bad choice") ch = str(input("do you want to continue?(Y/n)")) -if __name__=="__main__": + +if __name__ == "__main__": main() diff --git a/bin/Wallpaper Changer requirements.txt b/bin/Wallpaper Changer requirements.txt new file mode 100644 index 0000000..9b79631 --- /dev/null +++ b/bin/Wallpaper Changer requirements.txt @@ -0,0 +1,6 @@ +praw==7.1.0 +requests==2.20.0 +config==0.5.0.post0 +schedule==0.6.0 +mmh3==2.5.1 +bitarray==1.2.1 \ No newline at end of file diff --git a/bin/Wallpaper Changer.py b/bin/Wallpaper Changer.py new file mode 100644 index 0000000..1596a84 --- /dev/null +++ b/bin/Wallpaper Changer.py @@ -0,0 +1,127 @@ +# wallpaper changer to fetch images from reddit with bloom filter to avoid repitition +# Find the full Repo at https://github.com/ApoorvTyagi/praw +import praw, requests, re +import os, config, ctypes +import random +import schedule, time +import logging +import mmh3 +from bitarray import bitarray + + +#Setting Up Logs +logger = logging.getLogger() +logging.basicConfig(level=logging.INFO) +logger.setLevel(logging.INFO) + +#initializing bloom filter and hash +filter=bitarray(128) +filter.setall(0) +no_of_hash=3 + +def resetFilter(): + logger.info("Reseting Filter...") + filter.setall(0) + +def add(item): + for i in range(no_of_hash): + index=mmh3.hash(item,i)%64 + filter[index]=1 + +def find(item): + for i in range(no_of_hash): + index=mmh3.hash(item,i)%64 + if filter[index]==0: + return False + return True + +reddit = praw.Reddit( + client_id="", + client_secret="", + username="", + password="", + user_agent="", +) + +def set_wallpaper_from_file(filename): + logger.info("Setting wallpaper to your desktop") + use = os.getcwd() + "/" + filename + ctypes.windll.user32.SystemParametersInfoW(20, 0, use, 0) + time.sleep(2) + os.remove(use) + return "Success" + + +def get_random_subreddit(): + logger.info("Selceting random subreddit...") + #subreddits = ["Wallpaper"] + subreddits = [ + "Wallpaper", + "Wallpapers", + "BackgroundArt", + "naturepics", + "natureporn", + "EarthPorn" + ] + + random_subreddit = random.choice(subreddits) + print(random_subreddit) + return random_subreddit + + +def change_wallpaper(): + tryCount=1 + logger.info("Getting subreddit...") + subreddit = reddit.subreddit(get_random_subreddit()) + logger.info("Getting hot post...") + topPost = subreddit.hot(limit=5) + + for post in topPost: + url = post.url + print('url is :',url) + print("Post_id is " , post.id) + + if tryCount>3: + return "Failure, Try-Count Limit Exceeded" + + + print("Try Count : {}".format(tryCount)) + tryCount+=1 + if(reddit.submission(post.id).domain != 'i.redd.it'): + logger.info("Post does not have any media") + continue + if find(post.id): + logger.info("Post already added in last 7 days...") + continue + else: + logger.info("Found New Image Post") + add(post.id) + + + file_name = url.split("/") + + if len(file_name) == 0: + file_name = re.findall("/(.*?)", url) + + file_name = file_name[-1] + if "." not in file_name: + file_name += ".jpg" + + break + + print(file_name) + r = requests.get(url) + with open(file_name, "wb") as f: + f.write(r.content) + + return set_wallpaper_from_file(file_name) + + +#print(change_wallpaper()) +#schedule.every(1).minutes.do(change_wallpaper) +schedule.every().sunday.at("07:00").do(resetFilter) +schedule.every().day.at("07:00").do(change_wallpaper) +while True: + schedule.run_pending() + time.sleep(3600) + diff --git a/bin/WhatsApp-personalized-messages/README.md b/bin/WhatsApp-personalized-messages/README.md new file mode 100644 index 0000000..d340c00 --- /dev/null +++ b/bin/WhatsApp-personalized-messages/README.md @@ -0,0 +1,17 @@ +# WhatsApp Personalized Message Sender + +This uses selenium to open WhatsApp Web and send personalized messages on your behalf. + +## Installation Instructions + +- Install Selenium and pandas + +```sh +pip install selenium pandas +``` + +- Download [ChromeDriver](https://chromedriver.chromium.org/) for your appropriate browser version and operating system. Update `PATH_TO_CHROMEDRIVER` in `send_greeting.py` + +- Make sure to update the message you want to send. + +- Export your contacts and place them in the root directory as `contacts.csv` diff --git a/bin/WhatsApp-personalized-messages/filter_contacts.py b/bin/WhatsApp-personalized-messages/filter_contacts.py new file mode 100644 index 0000000..91bc758 --- /dev/null +++ b/bin/WhatsApp-personalized-messages/filter_contacts.py @@ -0,0 +1,20 @@ +import pandas as pd + + +def filter_contacts(filename): + all_contacts = pd.read_csv(filename) + all_contacts = all_contacts[["Name", "Given Name"]] + print("Type Given name if you wish to include them in your Spam list.") + print("To break, Enter x") + print("To keep it same as the given name(the one after -), press f") + wishing_contacts = dict() + for index, row in all_contacts.iterrows(): + print(str(row['Name'])+" - "+str(row['Given Name'])) + y = input() + if y == 'x': + break + if y == 'f': + wishing_contacts[str(row['Name'])] = str(row['Given Name']) + elif y != '': + wishing_contacts[str(row['Name'])] = y + return wishing_contacts diff --git a/bin/WhatsApp-personalized-messages/send_greeting.py b/bin/WhatsApp-personalized-messages/send_greeting.py new file mode 100644 index 0000000..8249512 --- /dev/null +++ b/bin/WhatsApp-personalized-messages/send_greeting.py @@ -0,0 +1,35 @@ +from selenium import webdriver +from time import sleep +import filter_contacts + +PATH_TO_CHROMEDRIVER = '' + +wishingContacts = filter_contacts.filter_contacts("contacts.csv") +driver = webdriver.Chrome(PATH_TO_CHROMEDRIVER) +driver.get('https://web.whatsapp.com') +sleep(15) +contacts = dict() + +for key, value in wishingContacts.items(): + pre_msg = "SOME PRE SALUTATION MESSAGE" + post_msg = """ + SOME POST SALUTATION MESSAGE + """ + input_box = None + try: + input_box = driver.find_element_by_css_selector("input[type='text']") + input_box.click() + input_box.send_keys(key) + sleep(1) + userbox = driver.find_element_by_css_selector("span[title='"+key+"']") + userbox.click() + inputbox = driver.find_element_by_css_selector("div[data-tab='1']") + inputbox.click() + inputbox.send_keys(pre_msg+value+post_msg) + send_button = driver.find_element_by_css_selector( + "span[data-icon='send']") + send_button.click() + sleep(1) + except Exception: + input_box.clear() + continue diff --git a/bin/air-quality.py b/bin/air-quality.py new file mode 100644 index 0000000..f9637be --- /dev/null +++ b/bin/air-quality.py @@ -0,0 +1,21 @@ +"""Script to get the air quality based on the user's current location""" + +import sys + +import requests as req + +if __name__ == "__main__": + if len(sys.argv) > 1: + url = "https://api.waqi.info/feed/here/?token=" + sys.argv[1] + response = req.get(url, verify=False) + if response.json()['status'] == "ok": + print("The air quality is " + str(response.json()['data']['aqi'])) + print("The data was fetched from " + + response.json()['data']['city']['name']) + print("The pollutant measured was " + + str(response.json()['data']['dominentpol'])) + elif response.json()['status'] == "error": + print("The server returned an error. The message is " + + response.json()['data']) + else: + print("Cannot fetch AQI without token") diff --git a/bin/bulk_add_twitter_list.py b/bin/bulk_add_twitter_list.py index 1bbb8d5..fbc0782 100644 --- a/bin/bulk_add_twitter_list.py +++ b/bin/bulk_add_twitter_list.py @@ -19,4 +19,5 @@ for i in range(len(screen_name))[::chunk_size]: # split to chunk size sn = ','.join(screen_name[i:i+chunk_size]) - tw.lists.members.create_all(owner_screen_name='your_screen_name_here', slug='your_list', screen_name=sn) + tw.lists.members.create_all( + owner_screen_name='your_screen_name_here', slug='your_list', screen_name=sn) diff --git a/bin/caesar_cipher.py b/bin/caesar_cipher.py index 0bdbc95..d18271d 100644 --- a/bin/caesar_cipher.py +++ b/bin/caesar_cipher.py @@ -1,5 +1,6 @@ key = 'abcdefghijklmnopqrstuvwxyz' + def encrypt(n, plaintext): """Encrypt the string and return the ciphertext""" result = '' @@ -27,16 +28,15 @@ def decrypt(n, ciphertext): return result -print("Encrypt or decrypt?") -ans = input() + +print("***** CAESAR CIPHER *****") +ans = input("Encrypt or Decrypt ? ") ans = ans.lower() -print("Enter message") -k = input() -print("Enter rotation number") -nn = int(input()) +k = input("Enter message : ") +nn = int(input("Enter number of rotation : ")) if ans == 'encrypt': - ret = encrypt(nn,k) - print ('Encrytped: %s' % ret) + ret = encrypt(nn, k) + print('Encrytped message: %s' % ret) else: - ret = decrypt(nn,k) - print ('Decrytped: %s' % ret) + ret = decrypt(nn, k) + print('Decrytped message: %s' % ret) diff --git a/bin/contributors.py b/bin/contributors.py new file mode 100644 index 0000000..1bd7c19 --- /dev/null +++ b/bin/contributors.py @@ -0,0 +1,57 @@ +import sys +import requests +from urllib.parse import urljoin +import PIL +import shutil + +from PIL import Image + + +def generate_markdown(data): + """ + This functions takes an array of dicts with keys login and avatar + and generates markdown. For embeding images in markdown it downloads the + image and resizes it to standard size + :param data: Array of dicts with key login and avatar + """ + basewidth = 50 + markdown = '' + for author in data: + response = requests.get(author.get('avatar'), stream=True) + with open('temp.png', 'wb') as out_file: + shutil.copyfileobj(response.raw, out_file) + del response + img = Image.open("temp.png") + wpercent = (basewidth / float(img.size[0])) + hsize = int((float(img.size[1]) * float(wpercent))) + img = img.resize((basewidth, hsize), PIL.Image.ANTIALIAS) + img.save(author.get('login') + '.png') + markdown = markdown + '![' + author.get('login', '') + '](' + author.get('login', '')+'.png "'+author.get('login', '') + '" )' + + with open("contributors.md", "w") as text_file: + text_file.write(markdown) + + +def get_data(url): + """ + Fetches data from the given url and filters author sub dictionary + :param url: String + """ + headers = { + 'User-Agent': 'My User Agent 1.0', + 'accept': 'application/json' + } + response = requests.get(urljoin(url, 'graphs/contributors-data'), headers=headers) + if response.status_code == 200: + data = [author.get('author', '') for author in response.json()] + return data + else: + print('Check if the url is right and if you have network connection') + sys.exit(0) + + +repo_url = sys.argv[1] +if repo_url is None or len(repo_url) == 0: + print('Please enter valid url') +else: + generate_markdown((get_data(repo_url))) diff --git a/bin/dice_simulator.py b/bin/dice_simulator.py index e215d67..092d6b5 100644 --- a/bin/dice_simulator.py +++ b/bin/dice_simulator.py @@ -1,10 +1,14 @@ -import random # random is a python built-in module +import random - -def roll_dice(): - dice_side = random.randrange(1, 7) - print(dice_side) +def roll_dice(range): + while True: + dice_side = random.randrange(1, range) + print("You rolled: " + str(dice_side)) + yes_or_no=input("Do you want to continue? y/n ") + if yes_or_no == 'n': + print("Over!") + break if __name__ == '__main__': - roll_dice() \ No newline at end of file + roll_dice(7) diff --git a/bin/end_to_end.py b/bin/end_to_end.py index ac360d8..325978e 100644 --- a/bin/end_to_end.py +++ b/bin/end_to_end.py @@ -1,39 +1,53 @@ import time -a = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] +a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', + 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] + + def encrypt(msg): off = 3 enc = "" for i in msg: - enc = enc + (a[(a.index(i)+off)%26]) + try: + enc = enc + a[int((a.index(i)+off)) % 26] + except ValueError: + enc += i return enc + + def decrypt(msg): off = 3 dec = "" for i in msg: - dec = dec + (a[(a.index(i)-off)%26]) + try: + dec = dec + a[int((a.index(i)-off)) % 26] + except ValueError: + dec += i return dec -#Client Side(Sender) -msg = input("Enter Message To Send: ") -f = open('server.txt','w+') -print("Encrypting..........") -time.sleep(2) -enc = encrypt(msg) -print("Message Sent Is: ",enc) -#Server Side +# Client Side(Sender) +print("***** END-TO-END ENCRYPTION *****") +msg = input("Enter message to send : ") +print() +print("Encrypting...") +enc = encrypt(msg.lower()) +print("Message sent is : %s " % enc) + +# Server Side +time.sleep(2) +f = open('server.txt', 'w+') f.write(enc) f.close() +# Client Side(Receiver) print() -#Client Side(Reciever) -print("Reciever Is Recieving.........") +print("Receiving message...") time.sleep(2) -f = open('server.txt','r+') +f = open('server.txt', 'r+') msg = f.read() -print("Message Recieved Is: ",msg) -print("Decrypting........") +print("Message received is : %s " % msg) +print() +print("Decrypting...") time.sleep(2) dec = decrypt(msg) -print("Message Displayed Is: ",dec) - +print("Decrypted message : %s " % dec) diff --git a/bin/expense_manager.py b/bin/expense_manager.py index dad8299..1d9c5c3 100644 --- a/bin/expense_manager.py +++ b/bin/expense_manager.py @@ -1,4 +1,13 @@ -#General Function: +import os +import tkinter + + +root = tkinter.Tk() +root.geometry('1250x700') + + +# General Function: + def combine_funcs(*funcs): def combined_func(*args, **kwargs): @@ -7,216 +16,242 @@ def combined_func(*args, **kwargs): return combined_func - -#Defining the create function: +# Defining the create function: def create(): def sub_create(): def sub1(): def sub2(): f1.destroy() - b=TextArea.get("1.0",'end') - if(b!='0'): + b = TextArea.get("1.0", 'end') + if(b != '0'): f.write(b) f.write("\n") f2.destroy() - f1=tkinter.Frame(bg="#CCCCFF") - f1.pack(fill="both",expand="true") - l1=tkinter.Label(f1,text="Congratulations! Your Entry Is Made.",bg="#330033",fg="#FFFFFF",relief="groove",pady=30,font=16) - l1.pack(fill="x",expand="true") - b1=tkinter.Button(f1,text="Return To MainMenu",bg="#FFFFFF",fg="blue",relief="groove",command=combine_funcs(sub2,start),height=2,width=25) - b1.pack(side="right") - a=e.get() - a=a.upper() + f1 = tkinter.Frame(bg="#CCCCFF") + f1.pack(fill="both", expand="true") + l1 = tkinter.Label(f1, text="Congratulations! Your Entry Is Made.", + bg="#330033", fg="#FFFFFF", relief="groove", pady=30, font=16) + l1.pack(fill="x", expand="true") + b1 = tkinter.Button(f1, text="Return To MainMenu", bg="#FFFFFF", fg="blue", + relief="groove", command=combine_funcs(sub2, start), height=2, width=25) + b1.pack(side="right") + a = e.get() + a = a.upper() f1.destroy() - f=open(a,"w") - f2=tkinter.Frame(bg="#CCCCFF") - f2.pack(fill="both",expand="true") - l1=tkinter.Label(f2,text="Make An Entry:\n\nExample: Item1 Rs amount\nItem2 Rs amount",bg="#FFFFFF",fg="#680000",relief="groove",anchor="n",pady=50,font=25) - l1.pack(fill="x",expand="true") + f = open(a, "w") + f2 = tkinter.Frame(bg="#CCCCFF") + f2.pack(fill="both", expand="true") + l1 = tkinter.Label(f2, text="Make An Entry:\n\nExample: Item1 Rs amount\nItem2 Rs amount", + bg="#FFFFFF", fg="#680000", relief="groove", anchor="n", pady=50, font=25) + l1.pack(fill="x", expand="true") TextArea = tkinter.Text(f2) - ScrollBar = tkinter.Scrollbar(f2,bg="white") + ScrollBar = tkinter.Scrollbar(f2, bg="white") ScrollBar.config(command=TextArea.yview) TextArea.config(yscrollcommand=ScrollBar.set) ScrollBar.pack(side="right", fill="y") TextArea.pack(fill="x") - b1=tkinter.Button(f2,text="Submit",bg="#FFFFFF",fg="blue",relief="groove",command=sub1) - b1.pack() + b1 = tkinter.Button(f2, text="Submit", bg="#FFFFFF", + fg="blue", relief="groove", command=sub1) + b1.pack() frame.destroy() - f1=tkinter.Frame(bg="#CCCCFF") - f1.pack(fill="both",expand="true") - l1=tkinter.Label(f1,text="Welcome To Expense Manager",bg="#330033",fg="#FFFFFF",relief="groove",pady=30,font=16) - l1.pack(fill="x",expand="true",anchor="n") - l1=tkinter.Label(f1,text="Enter Date:",bg="#330033",fg="#FFFFFF",relief="groove",font=9,padx=50) - l1.place(relx=0.35,rely=0.5) - e=tkinter.Entry(f1) - e.place(relx=0.52,rely=0.5) - b1=tkinter.Button(f1,text="Make Entry",bg="#9999FF",fg="#660099",relief="groove",command=sub_create,height=2,width=10) - b1.place(relx=0.45,rely=0.56) + f1 = tkinter.Frame(bg="#CCCCFF") + f1.pack(fill="both", expand="true") + l1 = tkinter.Label(f1, text="Welcome To Expense Manager", + bg="#330033", fg="#FFFFFF", relief="groove", pady=30, font=16) + l1.pack(fill="x", expand="true", anchor="n") + l1 = tkinter.Label(f1, text="Enter Date:", bg="#330033", + fg="#FFFFFF", relief="groove", font=9, padx=50) + l1.place(relx=0.35, rely=0.5) + e = tkinter.Entry(f1) + e.place(relx=0.52, rely=0.5) + b1 = tkinter.Button(f1, text="Make Entry", bg="#9999FF", fg="#660099", + relief="groove", command=sub_create, height=2, width=10) + b1.place(relx=0.45, rely=0.56) -#Defining the get function: +# Defining the get function: def get(): def sub_get(): def sub2(): - f2.destroy() - a=e.get() - a=a.upper() + f2.destroy() + a = e.get() + a = a.upper() f1.destroy() - f=open(a,'r') - f2=tkinter.Frame() - f2.pack(fill="both",expand="true") - l1=tkinter.Label(f2,text="Your Entries For The Date "+a+" Are: ",bg="#FFFFFF",fg="#680000",relief="groove",anchor="center",pady=50) - l1.pack(fill="x",expand="true") + f = open(a, 'r') + f2 = tkinter.Frame() + f2.pack(fill="both", expand="true") + l1 = tkinter.Label(f2, text="Your Entries For The Date "+a+" Are: ", + bg="#FFFFFF", fg="#680000", relief="groove", anchor="center", pady=50) + l1.pack(fill="x", expand="true") TextArea = tkinter.Text(f2) ScrollBar = tkinter.Scrollbar(f2) ScrollBar.config(command=TextArea.yview) ScrollBar.pack(side="right", fill="y") - TextArea.insert('insert',f.read()) - TextArea.config(yscrollcommand=ScrollBar.set,state="disabled") - TextArea.pack(fill="both",expand="true") - b1=tkinter.Button(f2,text="Return To MainMenu",bg="#FFFFFF",fg="blue",relief="groove",command=combine_funcs(sub2,start),height=2,width=25) + TextArea.insert('insert', f.read()) + TextArea.config(yscrollcommand=ScrollBar.set, state="disabled") + TextArea.pack(fill="both", expand="true") + b1 = tkinter.Button(f2, text="Return To MainMenu", bg="#FFFFFF", fg="blue", + relief="groove", command=combine_funcs(sub2, start), height=2, width=25) b1.pack(side="right") frame.destroy() - f1=tkinter.Frame(bg="#CCCCFF") - f1.pack(fill="both",expand="true") - l1=tkinter.Label(f1,text="Welcome To Expense Manager",bg="#330033",fg="#FFFFFF",relief="groove",pady=30,font=16) - l1.pack(fill="x",expand="true",anchor="n") - l1=tkinter.Label(f1,text="Enter Date:",bg="#330033",fg="#FFFFFF",relief="groove",font=9,padx=50) - l1.place(relx=0.35,rely=0.5) - e=tkinter.Entry(f1) - e.place(relx=0.52,rely=0.5) - b1=tkinter.Button(f1,text="Get Entry",bg="#9999FF",fg="#660099",relief="groove",command=sub_get,height=2,width=10) - b1.place(relx=0.45,rely=0.56) - -#Defining the get entry by month function: + f1 = tkinter.Frame(bg="#CCCCFF") + f1.pack(fill="both", expand="true") + l1 = tkinter.Label(f1, text="Welcome To Expense Manager", + bg="#330033", fg="#FFFFFF", relief="groove", pady=30, font=16) + l1.pack(fill="x", expand="true", anchor="n") + l1 = tkinter.Label(f1, text="Enter Date:", bg="#330033", + fg="#FFFFFF", relief="groove", font=9, padx=50) + l1.place(relx=0.35, rely=0.5) + e = tkinter.Entry(f1) + e.place(relx=0.52, rely=0.5) + b1 = tkinter.Button(f1, text="Get Entry", bg="#9999FF", fg="#660099", + relief="groove", command=sub_get, height=2, width=10) + b1.place(relx=0.45, rely=0.56) + +# Defining the get entry by month function: + def getm(): def sub_getm(): def sub2(): - f2.destroy() - a=e.get() - a=a.upper() + f2.destroy() + a = e.get() + a = a.upper() f1.destroy() - f2=tkinter.Frame() - f2.pack(fill="both",expand="true") - l1=tkinter.Label(f2,text="Your Entries For The Month Are: ",bg="#FFFFFF",fg="#680000",relief="groove",anchor="center",pady=50) - l1.pack(fill="x",expand="true") + f2 = tkinter.Frame() + f2.pack(fill="both", expand="true") + l1 = tkinter.Label(f2, text="Your Entries For The Month Are: ", + bg="#FFFFFF", fg="#680000", relief="groove", anchor="center", pady=50) + l1.pack(fill="x", expand="true") TextArea = tkinter.Text(f2) ScrollBar = tkinter.Scrollbar(f2) ScrollBar.config(command=TextArea.yview) ScrollBar.pack(side="right", fill="y") - for i in range(1,32): + for i in range(1, 32): try: - f=open(str(i)+' '+a,'r') + f = open(str(i)+' '+a, 'r') except IOError: - continue - TextArea.insert('insert',"\n"+str(i)+' '+a+": \n\n"+f.read()) - TextArea.config(yscrollcommand=ScrollBar.set,state="disabled") - TextArea.pack(fill="both",expand="true") - b1=tkinter.Button(f2,text="Return To MainMenu",bg="#FFFFFF",fg="blue",relief="groove",command=combine_funcs(sub2,start),height=2,width=25) + continue + TextArea.insert('insert', "\n"+str(i)+' '+a+": \n\n"+f.read()) + TextArea.config(yscrollcommand=ScrollBar.set, state="disabled") + TextArea.pack(fill="both", expand="true") + b1 = tkinter.Button(f2, text="Return To MainMenu", bg="#FFFFFF", fg="blue", + relief="groove", command=combine_funcs(sub2, start), height=2, width=25) b1.pack(side="right") frame.destroy() - f1=tkinter.Frame(bg="#CCCCFF") - f1.pack(fill="both",expand="true") - l1=tkinter.Label(f1,text="Welcome To Expense Manager",bg="#330033",fg="#FFFFFF",relief="groove",pady=30,font=16) - l1.pack(fill="x",expand="true",anchor="n") - l1=tkinter.Label(f1,text="Enter Month And Year:",bg="#330033",fg="#FFFFFF",relief="groove",font=9,padx=50) - l1.place(relx=0.3,rely=0.5) - e=tkinter.Entry(f1) - e.place(relx=0.52,rely=0.5) - b1=tkinter.Button(f1,text="Get Entry",bg="#9999FF",fg="#660099",relief="groove",command=sub_getm,height=2,width=10) - b1.place(relx=0.47,rely=0.56) - - + f1 = tkinter.Frame(bg="#CCCCFF") + f1.pack(fill="both", expand="true") + l1 = tkinter.Label(f1, text="Welcome To Expense Manager", + bg="#330033", fg="#FFFFFF", relief="groove", pady=30, font=16) + l1.pack(fill="x", expand="true", anchor="n") + l1 = tkinter.Label(f1, text="Enter Month And Year:", bg="#330033", + fg="#FFFFFF", relief="groove", font=9, padx=50) + l1.place(relx=0.3, rely=0.5) + e = tkinter.Entry(f1) + e.place(relx=0.52, rely=0.5) + b1 = tkinter.Button(f1, text="Get Entry", bg="#9999FF", fg="#660099", + relief="groove", command=sub_getm, height=2, width=10) + b1.place(relx=0.47, rely=0.56) -#Get Total Expense By Date: +# Get Total Expense By Date: def Sum(): def sub_Sum(): def sub2(): - f2.destroy() - t=e.get() - t=t.upper() + f2.destroy() + t = e.get() + t = t.upper() try: - f=open(t,'r') - a=f.readlines() - c=0 - for i in range(0,len(a)): - b='' - for j in range(len(a[i])-1,0,-1): - if(a[i][j]!=' ' and a[i][j]>='0' and a[i][j]<='9'): - b=b+a[i][j] - if(a[i][j]>='9'): + f = open(t, 'r') + a = f.readlines() + c = 0 + for i in range(0, len(a)): + b = '' + for j in range(len(a[i])-1, 0, -1): + if(a[i][j] != ' ' and a[i][j] >= '0' and a[i][j] <= '9'): + b = b+a[i][j] + if(a[i][j] >= '9'): break - if(b!=''): - c=c+int(b[::-1]) + if(b != ''): + c = c+int(b[::-1]) f1.destroy() - f2=tkinter.Frame() - f2.pack(fill="both",expand="true") - l1=tkinter.Label(f2,text="Total Expenses On "+t+" Are: \nRs "+str(c),bg="#FFFFFF",fg="#680000",relief="groove",anchor="center",pady=50,font=50) - l1.pack(fill="both",expand="true") + f2 = tkinter.Frame() + f2.pack(fill="both", expand="true") + l1 = tkinter.Label(f2, text="Total Expenses On "+t+" Are: \nRs "+str( + c), bg="#FFFFFF", fg="#680000", relief="groove", anchor="center", pady=50, font=50) + l1.pack(fill="both", expand="true") except IOError: - l1=tkinter.Label(f2,text="No Such Entry Is Made "+t+" Are: \nRs "+str(c),bg="#FFFFFF",fg="#680000",relief="groove",anchor="center",pady=50,font=50) - l1.pack(fill="both",expand="true") - b1=tkinter.Button(f2,text="Return To MainMenu",bg="#FFFFFF",fg="blue",relief="groove",command=combine_funcs(sub2,start),height=2,width=25) + l1 = tkinter.Label(f2, text="No Such Entry Is Made "+t+" Are: \nRs "+str( + c), bg="#FFFFFF", fg="#680000", relief="groove", anchor="center", pady=50, font=50) + l1.pack(fill="both", expand="true") + b1 = tkinter.Button(f2, text="Return To MainMenu", bg="#FFFFFF", fg="blue", + relief="groove", command=combine_funcs(sub2, start), height=2, width=25) b1.pack(side="right") frame.destroy() - f1=tkinter.Frame(bg="#CCCCFF") - f1.pack(fill="both",expand="true") - l1=tkinter.Label(f1,text="Welcome To Expense Manager",bg="#330033",fg="#FFFFFF",relief="groove",pady=30,font=16) - l1.pack(fill="x",expand="true",anchor="n") - l1=tkinter.Label(f1,text="Enter Date:",bg="#330033",fg="#FFFFFF",relief="groove",font=9,padx=50) - l1.place(relx=0.35,rely=0.5) - e=tkinter.Entry(f1) - e.place(relx=0.52,rely=0.5) - b1=tkinter.Button(f1,text="Get Expenses",bg="#9999FF",fg="#660099",relief="groove",command=sub_Sum,height=2,width=10) - b1.place(relx=0.47,rely=0.56) - -#Defining Get total expense in a month: + f1 = tkinter.Frame(bg="#CCCCFF") + f1.pack(fill="both", expand="true") + l1 = tkinter.Label(f1, text="Welcome To Expense Manager", + bg="#330033", fg="#FFFFFF", relief="groove", pady=30, font=16) + l1.pack(fill="x", expand="true", anchor="n") + l1 = tkinter.Label(f1, text="Enter Date:", bg="#330033", + fg="#FFFFFF", relief="groove", font=9, padx=50) + l1.place(relx=0.35, rely=0.5) + e = tkinter.Entry(f1) + e.place(relx=0.52, rely=0.5) + b1 = tkinter.Button(f1, text="Get Expenses", bg="#9999FF", fg="#660099", + relief="groove", command=sub_Sum, height=2, width=10) + b1.place(relx=0.47, rely=0.56) + +# Defining Get total expense in a month: + def Summ(): def sub_Summ(): def sub2(): - f2.destroy() - a=e.get() - a=a.upper() - c=0 - for i in range(1,32): + f2.destroy() + a = e.get() + a = a.upper() + c = 0 + for i in range(1, 32): try: - f=open(str(i)+' '+a,'r') - t=f.readlines() - for i in range(0,len(t)): - b='' - for j in range(len(t[i])-1,0,-1): - if(t[i][j]!=' ' and t[i][j]>='0' and t[i][j]<='9'): - b=b+t[i][j] - if(b!=''): - c=c+int(b[::-1]) + f = open(str(i)+' '+a, 'r') + t = f.readlines() + for i in range(0, len(t)): + b = '' + for j in range(len(t[i])-1, 0, -1): + if(t[i][j] != ' ' and t[i][j] >= '0' and t[i][j] <= '9'): + b = b+t[i][j] + if(b != ''): + c = c+int(b[::-1]) except IOError: continue f1.destroy() - f2=tkinter.Frame() - f2.pack(fill="both",expand="true") - l1=tkinter.Label(f2,text="Total Expenses In "+a+" Are: \nRs "+str(c),bg="#FFFFFF",fg="#680000",relief="groove",anchor="center",pady=50,font=50) - l1.pack(fill="both",expand="true") - b1=tkinter.Button(f2,text="Return To MainMenu",bg="#FFFFFF",fg="blue",relief="groove",command=combine_funcs(sub2,start),height=2,width=25) + f2 = tkinter.Frame() + f2.pack(fill="both", expand="true") + l1 = tkinter.Label(f2, text="Total Expenses In "+a+" Are: \nRs "+str( + c), bg="#FFFFFF", fg="#680000", relief="groove", anchor="center", pady=50, font=50) + l1.pack(fill="both", expand="true") + b1 = tkinter.Button(f2, text="Return To MainMenu", bg="#FFFFFF", fg="blue", + relief="groove", command=combine_funcs(sub2, start), height=2, width=25) b1.pack(side="right") frame.destroy() - f1=tkinter.Frame(bg="#CCCCFF") - f1.pack(fill="both",expand="true") - l1=tkinter.Label(f1,text="Welcome To Expense Manager",bg="#330033",fg="#FFFFFF",relief="groove",pady=30,font=16) - l1.pack(fill="x",expand="true",anchor="n") - l1=tkinter.Label(f1,text="Enter Month And Year:",bg="#330033",fg="#FFFFFF",relief="groove",font=9,padx=50) - l1.place(relx=0.3,rely=0.5) - e=tkinter.Entry(f1) - e.place(relx=0.52,rely=0.5) - b1=tkinter.Button(f1,text="Get Expenses",bg="#9999FF",fg="#660099",relief="groove",command=sub_Summ,height=2,width=10) - b1.place(relx=0.47,rely=0.56) - + f1 = tkinter.Frame(bg="#CCCCFF") + f1.pack(fill="both", expand="true") + l1 = tkinter.Label(f1, text="Welcome To Expense Manager", + bg="#330033", fg="#FFFFFF", relief="groove", pady=30, font=16) + l1.pack(fill="x", expand="true", anchor="n") + l1 = tkinter.Label(f1, text="Enter Month And Year:", bg="#330033", + fg="#FFFFFF", relief="groove", font=9, padx=50) + l1.place(relx=0.3, rely=0.5) + e = tkinter.Entry(f1) + e.place(relx=0.52, rely=0.5) + b1 = tkinter.Button(f1, text="Get Expenses", bg="#9999FF", fg="#660099", + relief="groove", command=sub_Summ, height=2, width=10) + b1.place(relx=0.47, rely=0.56) # Defining Add to entry: @@ -226,115 +261,143 @@ def sub_add(): def sub1(): def sub2(): f1.destroy() - b=TextArea.get("1.0",'end') - if(b!='0'): + b = TextArea.get("1.0", 'end') + if(b != '0'): f.write(b) f.write("\n") f2.destroy() - f1=tkinter.Frame(bg="#CCCCFF") - f1.pack(fill="both",expand="true") - l1=tkinter.Label(f1,text="Congratulations! Your Entry Is Made.",bg="#330033",fg="#FFFFFF",relief="groove",pady=30,font=16) - l1.pack(fill="x",expand="true") - b1=tkinter.Button(f1,text="Return To MainMenu",bg="#FFFFFF",fg="blue",relief="groove",command=combine_funcs(sub2,start),height=2,width=25) - b1.pack(side="right") - a=e.get() - a=a.upper() + f1 = tkinter.Frame(bg="#CCCCFF") + f1.pack(fill="both", expand="true") + l1 = tkinter.Label(f1, text="Congratulations! Your Entry Is Made.", + bg="#330033", fg="#FFFFFF", relief="groove", pady=30, font=16) + l1.pack(fill="x", expand="true") + b1 = tkinter.Button(f1, text="Return To MainMenu", bg="#FFFFFF", fg="blue", + relief="groove", command=combine_funcs(sub2, start), height=2, width=25) + b1.pack(side="right") + a = e.get() + a = a.upper() f1.destroy() - f=open(a,"a") - f2=tkinter.Frame(bg="#CCCCFF") - f2.pack(fill="both",expand="true") - l1=tkinter.Label(f2,text="Make An Entry:\n\nExample: Item1 Rs amount\nItem2 Rs amount",bg="#FFFFFF",fg="#680000",relief="groove",anchor="n",pady=50,font=25) - l1.pack(fill="x",expand="true") + f = open(a, "a") + f2 = tkinter.Frame(bg="#CCCCFF") + f2.pack(fill="both", expand="true") + l1 = tkinter.Label(f2, text="Make An Entry:\n\nExample: Item1 Rs amount\nItem2 Rs amount", + bg="#FFFFFF", fg="#680000", relief="groove", anchor="n", pady=50, font=25) + l1.pack(fill="x", expand="true") TextArea = tkinter.Text(f2) - ScrollBar = tkinter.Scrollbar(f2,bg="white") + ScrollBar = tkinter.Scrollbar(f2, bg="white") ScrollBar.config(command=TextArea.yview) TextArea.config(yscrollcommand=ScrollBar.set) ScrollBar.pack(side="right", fill="y") TextArea.pack(fill="x") - b1=tkinter.Button(f2,text="Submit",bg="#FFFFFF",fg="blue",relief="groove",command=sub1) - b1.pack() + b1 = tkinter.Button(f2, text="Submit", bg="#FFFFFF", + fg="blue", relief="groove", command=sub1) + b1.pack() frame.destroy() - f1=tkinter.Frame(bg="#CCCCFF") - f1.pack(fill="both",expand="true") - l1=tkinter.Label(f1,text="Welcome To Expense Manager",bg="#330033",fg="#FFFFFF",relief="groove",pady=30,font=16) - l1.pack(fill="x",expand="true",anchor="n") - l1=tkinter.Label(f1,text="Enter Date:",bg="#330033",fg="#FFFFFF",relief="groove",font=9,padx=50) - l1.place(relx=0.35,rely=0.5) - e=tkinter.Entry(f1) - e.place(relx=0.52,rely=0.5) - b1=tkinter.Button(f1,text="Make Entry",bg="#9999FF",fg="#660099",relief="groove",command=sub_add,height=2,width=10) - b1.place(relx=0.45,rely=0.56) + f1 = tkinter.Frame(bg="#CCCCFF") + f1.pack(fill="both", expand="true") + l1 = tkinter.Label(f1, text="Welcome To Expense Manager", + bg="#330033", fg="#FFFFFF", relief="groove", pady=30, font=16) + l1.pack(fill="x", expand="true", anchor="n") + l1 = tkinter.Label(f1, text="Enter Date:", bg="#330033", + fg="#FFFFFF", relief="groove", font=9, padx=50) + l1.place(relx=0.35, rely=0.5) + e = tkinter.Entry(f1) + e.place(relx=0.52, rely=0.5) + b1 = tkinter.Button(f1, text="Make Entry", bg="#9999FF", fg="#660099", + relief="groove", command=sub_add, height=2, width=10) + b1.place(relx=0.45, rely=0.56) # Defining Delete Existing Entry: + def delete(): - import os - delete=lambda x:os.remove(x) + + def delete(x): return os.remove(x) + def sub_delete(): def sub2(): - f2.destroy() - a=e.get() - a=a.upper() + f2.destroy() + a = e.get() + a = a.upper() delete(a) f1.destroy() - f2=tkinter.Frame(bg="#CCCCFF") - f2.pack(fill="both",expand="true") - l1=tkinter.Label(f2,text="Congratulations! Your Entry Is Deleted.",bg="#330033",fg="#FFFFFF",relief="groove",pady=30,font=16) - l1.pack(fill="x",expand="true") - b1=tkinter.Button(f2,text="Return To MainMenu",bg="#FFFFFF",fg="blue",relief="groove",command=combine_funcs(sub2,start),height=2,width=25) + f2 = tkinter.Frame(bg="#CCCCFF") + f2.pack(fill="both", expand="true") + l1 = tkinter.Label(f2, text="Congratulations! Your Entry Is Deleted.", + bg="#330033", fg="#FFFFFF", relief="groove", pady=30, font=16) + l1.pack(fill="x", expand="true") + b1 = tkinter.Button(f2, text="Return To MainMenu", bg="#FFFFFF", fg="blue", + relief="groove", command=combine_funcs(sub2, start), height=2, width=25) b1.pack(side="right") frame.destroy() - f1=tkinter.Frame(bg="#CCCCFF") - f1.pack(fill="both",expand="true") - l1=tkinter.Label(f1,text="Welcome To Expense Manager",bg="#330033",fg="#FFFFFF",relief="groove",pady=30,font=16) - l1.pack(fill="x",expand="true",anchor="n") - l1=tkinter.Label(f1,text="Enter Date:",bg="#330033",fg="#FFFFFF",relief="groove",font=9,padx=50) - l1.place(relx=0.35,rely=0.5) - e=tkinter.Entry(f1) - e.place(relx=0.52,rely=0.5) - b1=tkinter.Button(f1,text="Delete",bg="#9999FF",fg="#660099",relief="groove",command=sub_delete,height=2,width=10) - b1.place(relx=0.47,rely=0.56) - - - -import tkinter -root=tkinter.Tk() -root.geometry('1250x700') + f1 = tkinter.Frame(bg="#CCCCFF") + f1.pack(fill="both", expand="true") + l1 = tkinter.Label(f1, text="Welcome To Expense Manager", + bg="#330033", fg="#FFFFFF", relief="groove", pady=30, font=16) + l1.pack(fill="x", expand="true", anchor="n") + l1 = tkinter.Label(f1, text="Enter Date:", bg="#330033", + fg="#FFFFFF", relief="groove", font=9, padx=50) + l1.place(relx=0.35, rely=0.5) + e = tkinter.Entry(f1) + e.place(relx=0.52, rely=0.5) + b1 = tkinter.Button(f1, text="Delete", bg="#9999FF", fg="#660099", + relief="groove", command=sub_delete, height=2, width=10) + b1.place(relx=0.47, rely=0.56) + + def start(): global frame - frame=tkinter.Frame(bg="#CCCCFF") - frame.pack(fill="both",expand="true",) - l1=tkinter.Label(frame,text="Welcome To Expense Manager",bg="#330033",fg="#FFFFFF",relief="groove",pady=30,font=16) - l1.pack(fill="x",expand="true",anchor="n") - l1=tkinter.Label(frame,text="Press To Create A new Entry",bg="#330066",fg="#66FFFF",relief="groove",pady=15,font=16,padx=16) - l1.place(relx=0.2,rely=0.2,anchor="n") - b1=tkinter.Button(frame,text="Create Entry Sheet",bg="#9999FF",fg="#660099",relief="solid",command=create,font=11,pady=16,cursor="dot") - b1.place(relx=0.2,rely=0.3,anchor="n") - l1=tkinter.Label(frame,text="Press To Get Entry By Date",bg="#330066",fg="#66FFFF",relief="groove",pady=15,font=16,padx=16) - l1.place(relx=0.4,rely=0.2,anchor="n") - b1=tkinter.Button(frame,text="Get Entry Sheet",bg="#9999FF",fg="#660099",relief="solid",command=get,font=11,pady=16,cursor="dot") - b1.place(relx=0.4,rely=0.3,anchor="n") - l1=tkinter.Label(frame,text="Press To Get Entry By Month",bg="#330066",fg="#66FFFF",relief="groove",pady=15,font=16,padx=7) - l1.place(relx=0.6,rely=0.2,anchor="n") - b1=tkinter.Button(frame,text="Get Monthly Entry Sheet",bg="#9999FF",fg="#660099",relief="solid",command=getm,font=11,pady=16,cursor="dot") - b1.place(relx=0.6,rely=0.3,anchor="n") - l1=tkinter.Label(frame,text="Press To Get Total Expense On Date",bg="#330066",fg="#66FFFF",relief="groove",pady=15,font=16) - l1.place(relx=0.8,rely=0.2,anchor="n") - b1=tkinter.Button(frame,text="Get Total Expense On Date",bg="#9999FF",fg="#660099",relief="solid",command=Sum,font=11,pady=16,cursor="dot") - b1.place(relx=0.8,rely=0.3,anchor="n") - l1=tkinter.Label(frame,text="Press To Get Total Expense In A Month",bg="#330066",fg="#66FFFF",relief="groove",pady=15,font=16) - l1.place(relx=0.3,rely=0.5,anchor="n") - b1=tkinter.Button(frame,text="Get Total Expense",bg="#9999FF",fg="#660099",relief="solid",command=Summ,font=11,pady=16,cursor="dot") - b1.place(relx=0.3,rely=0.6,anchor="n") - l1=tkinter.Label(frame,text="Press To Add To Existing Entry",bg="#330066",fg="#66FFFF",relief="groove",pady=15,font=16) - l1.place(relx=0.51,rely=0.5,anchor="n") - b1=tkinter.Button(frame,text="Add To Entry",bg="#9999FF",fg="#660099",relief="solid",command=add,font=11,pady=16,cursor="dot") - b1.place(relx=0.51,rely=0.6,anchor="n") - l1=tkinter.Label(frame,text="Press To Delete Existing Entry",bg="#330066",fg="#66FFFF",relief="groove",pady=15,font=16) - l1.place(relx=0.7,rely=0.5,anchor="n") - b1=tkinter.Button(frame,text="Delete Entry",bg="#9999FF",fg="#660099",relief="solid",command=delete,font=11,pady=16,cursor="dot") - b1.place(relx=0.7,rely=0.6,anchor="n") - l1=tkinter.Label(frame,text="\u00a9"+" copyright 2016\t\t\t\t\t\t\t\t\t\t\t\t"+"Developed By: Akshit Grover",bg="#330033",fg="#FFFFFF",relief="groove",pady=30,font=16) - l1.pack(fill="x",expand="true",anchor="s") + frame = tkinter.Frame(bg="#CCCCFF") + frame.pack(fill="both", expand="true",) + l1 = tkinter.Label(frame, text="Welcome To Expense Manager", + bg="#330033", fg="#FFFFFF", relief="groove", pady=30, font=16) + l1.pack(fill="x", expand="true", anchor="n") + l1 = tkinter.Label(frame, text="Press To Create A new Entry", bg="#330066", + fg="#66FFFF", relief="groove", pady=15, font=16, padx=16) + l1.place(relx=0.2, rely=0.2, anchor="n") + b1 = tkinter.Button(frame, text="Create Entry Sheet", bg="#9999FF", fg="#660099", + relief="solid", command=create, font=11, pady=16, cursor="dot") + b1.place(relx=0.2, rely=0.3, anchor="n") + l1 = tkinter.Label(frame, text="Press To Get Entry By Date", bg="#330066", + fg="#66FFFF", relief="groove", pady=15, font=16, padx=16) + l1.place(relx=0.4, rely=0.2, anchor="n") + b1 = tkinter.Button(frame, text="Get Entry Sheet", bg="#9999FF", fg="#660099", + relief="solid", command=get, font=11, pady=16, cursor="dot") + b1.place(relx=0.4, rely=0.3, anchor="n") + l1 = tkinter.Label(frame, text="Press To Get Entry By Month", bg="#330066", + fg="#66FFFF", relief="groove", pady=15, font=16, padx=7) + l1.place(relx=0.6, rely=0.2, anchor="n") + b1 = tkinter.Button(frame, text="Get Monthly Entry Sheet", bg="#9999FF", + fg="#660099", relief="solid", command=getm, font=11, pady=16, cursor="dot") + b1.place(relx=0.6, rely=0.3, anchor="n") + l1 = tkinter.Label(frame, text="Press To Get Total Expense On Date", + bg="#330066", fg="#66FFFF", relief="groove", pady=15, font=16) + l1.place(relx=0.8, rely=0.2, anchor="n") + b1 = tkinter.Button(frame, text="Get Total Expense On Date", bg="#9999FF", + fg="#660099", relief="solid", command=Sum, font=11, pady=16, cursor="dot") + b1.place(relx=0.8, rely=0.3, anchor="n") + l1 = tkinter.Label(frame, text="Press To Get Total Expense In A Month", + bg="#330066", fg="#66FFFF", relief="groove", pady=15, font=16) + l1.place(relx=0.3, rely=0.5, anchor="n") + b1 = tkinter.Button(frame, text="Get Total Expense", bg="#9999FF", fg="#660099", + relief="solid", command=Summ, font=11, pady=16, cursor="dot") + b1.place(relx=0.3, rely=0.6, anchor="n") + l1 = tkinter.Label(frame, text="Press To Add To Existing Entry", + bg="#330066", fg="#66FFFF", relief="groove", pady=15, font=16) + l1.place(relx=0.51, rely=0.5, anchor="n") + b1 = tkinter.Button(frame, text="Add To Entry", bg="#9999FF", fg="#660099", + relief="solid", command=add, font=11, pady=16, cursor="dot") + b1.place(relx=0.51, rely=0.6, anchor="n") + l1 = tkinter.Label(frame, text="Press To Delete Existing Entry", + bg="#330066", fg="#66FFFF", relief="groove", pady=15, font=16) + l1.place(relx=0.7, rely=0.5, anchor="n") + b1 = tkinter.Button(frame, text="Delete Entry", bg="#9999FF", fg="#660099", + relief="solid", command=delete, font=11, pady=16, cursor="dot") + b1.place(relx=0.7, rely=0.6, anchor="n") + l1 = tkinter.Label(frame, text="\u00a9"+" copyright 2016\t\t\t\t\t\t\t\t\t\t\t\t" + + "Developed By: Akshit Grover", bg="#330033", fg="#FFFFFF", relief="groove", pady=30, font=16) + l1.pack(fill="x", expand="true", anchor="s") root.mainloop() + + start() diff --git a/bin/facebook-auto-post.py b/bin/facebook-auto-post.py index 8f02a23..419dd06 100644 --- a/bin/facebook-auto-post.py +++ b/bin/facebook-auto-post.py @@ -1,7 +1,6 @@ from selenium import webdriver from selenium.webdriver.common.keys import Keys -from time import sleep -from selenium.common.exceptions import TimeoutException +from time import sleepfrom selenium.common.exceptions import TimeoutException from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.ui import Select from selenium.webdriver.common.by import By @@ -18,7 +17,7 @@ email = driver.find_element_by_xpath("//input[@id='email' or @name='email']") email.send_keys(Email) print("Email Id entered...") -password1=getpass.getpass("Enter your Facebook password: ") +password1 = getpass.getpass("Enter your Facebook password: ") password = driver.find_element_by_xpath("//input[@id='pass']") password.send_keys(password1) print("Password entered...") @@ -38,4 +37,4 @@ time.sleep(10) driver.close() -#Thank You Stackoverflow and Jio for help +# Thank You Stackoverflow and Jio for help diff --git a/bin/fetch_html.py b/bin/fetch_html.py new file mode 100644 index 0000000..d864f19 --- /dev/null +++ b/bin/fetch_html.py @@ -0,0 +1,14 @@ +import urllib.request +import sys +from lxml import html + +if len(sys.argv) < 2: + print('Usage example: python fetch_html.py https://github.com') + sys.exit(1) + +url = sys.argv[1] +response = urllib.request.urlopen(url) +html_text = response.read().decode('UTF-8') +text = html.fromstring(html_text).text_content() + +print(text) diff --git a/bin/ftp_download_file.py b/bin/ftp_download_file.py index 8dbdee4..e6161d2 100644 --- a/bin/ftp_download_file.py +++ b/bin/ftp_download_file.py @@ -2,6 +2,7 @@ import os from ftplib import FTP + def parse_args(): ''' parse and check command line arguments ''' ap = argparse.ArgumentParser(description="FTP Utility") @@ -13,15 +14,16 @@ def parse_args(): ap.add_argument(dest='files', help="File names", nargs='+') return ap.parse_args() + def is_empty(file): - file_size = os.stat(file).st_size - if file_size == 0: - print('The file {} is empty'.format(file)) - return True - return False + file_size = os.stat(file).st_size + if file_size == 0: + print('The file {} is empty'.format(file)) + return True + return False -args=parse_args() +args = parse_args() host = args.host username = args.username @@ -35,15 +37,15 @@ def is_empty(file): ftp.cwd(remote_dir) for file in files: - try: - local_filename = os.path.join(local_dir, file) - print('Getting filename: ' + file) - ftp.retrbinary('RETR %s' % file, open(local_filename, 'wb').write) - print('Saving at %s' % local_filename) - except Exception as err: - print(err) - if (is_empty(local_filename)): - os.remove(local_filename) - continue + try: + local_filename = os.path.join(local_dir, file) + print('Getting filename: ' + file) + ftp.retrbinary('RETR %s' % file, open(local_filename, 'wb').write) + print('Saving at %s' % local_filename) + except Exception as err: + print(err) + if (is_empty(local_filename)): + os.remove(local_filename) + continue ftp.quit() diff --git a/bin/getExternalIp.py b/bin/getExternalIp.py new file mode 100644 index 0000000..9aaba61 --- /dev/null +++ b/bin/getExternalIp.py @@ -0,0 +1,11 @@ +import requests +import re + +try: + res = requests.get("http://whatismyip.org") + myIp = re.compile('(\d{1,3}\.){3}\d{1,3}').search(res.text).group() + if myIp != "": + print(myIp) +except: + print('N/A') + pass diff --git a/bin/group_file_by_type b/bin/group_file_by_type new file mode 100644 index 0000000..260072e --- /dev/null +++ b/bin/group_file_by_type @@ -0,0 +1,31 @@ +import os +import shutil +import sys + +if sys.argv[1] != None: + path = sys.argv[1] +else: + path = '.' + +# Get list of files +files = [f for f in os.listdir(path) if os.path.isfile(path + '\\' + f)] + + +# Get list of extensions and remove duplicated +extensions = set([f.split('.')[-1].lower() for f in files]) + + +# Create folder for each extension +try: + for ext in extensions: + os.makedirs(path+'\\'+ext) +except Exception: + print('Moving to existing folder with same name', Exception) + +# Move files to their folder with extension name +for f in files: + try: + shutil.move(path+'\\'+f, path+'\\'+f.split('.') + [-1].lower() + '\\' + f) + except Exception: + print('Unable to move file', path+'\\'+f) diff --git a/bin/highcharts_loader.py b/bin/highcharts_loader.py new file mode 100644 index 0000000..f0ead7d --- /dev/null +++ b/bin/highcharts_loader.py @@ -0,0 +1,56 @@ +import json +from base64 import b64encode + +import requests + + +class EmptyParams(Exception): + pass + + +class ToManyParams(Exception): + pass + + +class Options: + data = {} + + def __init__(self, *, from_file=None, from_dict=None): + if not from_file and not from_dict: + raise EmptyParams('You should pass "from_file" or "from_dict" param.') + if from_file and from_dict: + raise ToManyParams('You should pass only one param: "from_file" or "from_dict".') + + self.data = json.loads(open(from_file).read()) if from_file else from_dict + + +class ChartLoader: + raw_chart_data = None + url = 'http://export.highcharts.com/' + image_type = None + + def __init__(self, options: Options, image_type='image/png'): + self.image_type = image_type + response = requests.post(self.url, data={ + 'type': image_type, + 'options': json.dumps(options.data) + }) + if response.status_code == requests.codes.ok: + self.raw_chart_data = response.content + else: + response.raise_for_status() + + def _decoded_chart(self): + return b64encode(self.raw_chart_data).decode() + + def get_data_image(self): + return 'data:image/{0};charset=utf-8;base64,{1}'.format(self.image_type, + self._decoded_chart()) + + def get_raw_data(self): + return self.raw_chart_data + + def save_to_file(self, path): + f = open(path, 'wb+') + f.write(self.raw_chart_data) + f.close() diff --git a/bin/highcharts_loader_requirements.txt b/bin/highcharts_loader_requirements.txt new file mode 100644 index 0000000..3cb65d1 --- /dev/null +++ b/bin/highcharts_loader_requirements.txt @@ -0,0 +1 @@ +requests==2.20.0 \ No newline at end of file diff --git a/bin/image_encoder.py b/bin/image_encoder.py index 552372c..ec88abd 100644 --- a/bin/image_encoder.py +++ b/bin/image_encoder.py @@ -2,24 +2,27 @@ import json import time + def b64_encode(source_filepath): - with open(source_filepath, 'rb') as f: - data = f.read() - dest = open('ImageData/encodeData.json','r') - flag = json.loads(dest.read()) - key = (str(int(time.time()))).decode('utf-8') - d = {"data":base64.b64encode(data).decode('utf-8'),"ext":source_filepath[source_filepath.index('.'):]} - flag[key] = d - dest.close() - dest = open('ImageData/encodeData.json','w') - json.dump(flag,dest) - return key + with open(source_filepath, 'rb') as f: + data = f.read() + dest = open('ImageData/encodeData.json', 'r') + flag = json.loads(dest.read()) + key = (str(int(time.time()))).decode('utf-8') + d = {"data": base64.b64encode(data).decode( + 'utf-8'), "ext": source_filepath[source_filepath.index('.'):]} + flag[key] = d + dest.close() + dest = open('ImageData/encodeData.json', 'w') + json.dump(flag, dest) + return key + -def b64_decode(key,dest_path): - source = open('ImageData/encodeData.json','r') - flag = json.loads(source.read()) - name = key+str(flag[key]["ext"]) - dest = open(dest_path+name,'wb') - dest.write(base64.b64decode((flag[key]["data"]).encode('utf-8'))) - dest.close() - return dest_path+name +def b64_decode(key, dest_path): + source = open('ImageData/encodeData.json', 'r') + flag = json.loads(source.read()) + name = key+str(flag[key]["ext"]) + dest = open(dest_path+name, 'wb') + dest.write(base64.b64decode((flag[key]["data"]).encode('utf-8'))) + dest.close() + return dest_path+name diff --git a/bin/integrate-graph.py b/bin/integrate-graph.py index 218ed66..0fff738 100644 --- a/bin/integrate-graph.py +++ b/bin/integrate-graph.py @@ -4,42 +4,44 @@ import matplotlib.pyplot as plt from matplotlib import animation + def f(order, coefficients, x): s = sum([coefficients[i]*(x**(order-i)) for i in range(order+1)]) return s + class Integrate(object): def __init__(self): self.N = None self.I = None - + def graph(self, order, coefficients, low, high, interval, ans): - fig=plt.figure() + fig = plt.figure() plt.axes(xlim=(low-5, high+5)) lines = [plt.plot([], [], color='r')[0] for i in range(30)] - plt.title('Trapezoid Method\nRequired area is %0.2f units' %(ans)) + plt.title('Trapezoid Method\nRequired area is %0.2f units' % (ans)) plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.axhline(y=0, color='k') plt.axvline(x=0, color='k') - x=np.linspace(low, high, 500) - y=f(order, coefficients, x) - s='' + x = np.linspace(low, high, 500) + y = f(order, coefficients, x) + s = '' for i in range(order+1): - if coefficients[i]>=0: - s=s+(' +'+str(coefficients[i])+'x^'+str(order-i)) + if coefficients[i] >= 0: + s = s+(' +'+str(coefficients[i])+'x^'+str(order-i)) else: - s=s+(' '+str(coefficients[i])+'x^'+str(order-i)) - s=s+' = 0' + s = s+(' '+str(coefficients[i])+'x^'+str(order-i)) + s = s+' = 0' plt.plot(x, y, 'darkslateblue', label=s) - + def init(): for line in lines: line.set_data([], []) return lines - + def animate(i): - if i<2: + if i < 2: for j in range(30): lines[j].set_data([], []) else: @@ -51,14 +53,16 @@ def animate(i): for j in range(i, 29): lines[j].set_data([], []) return lines - - animation.FuncAnimation(fig, animate, init_func=init, frames=30, interval=500, blit=True) + + animation.FuncAnimation( + fig, animate, init_func=init, frames=30, interval=500, blit=True) plt.legend(loc='upper right', numpoints=1) plt.show() - + def Trapezoid(self, order, coefficients, low, high, interval): self.N = (high - low)/interval - self.I = sum([2*f(order, coefficients, low + (i*interval)) for i in range(1, int(self.N))]) + self.I = sum([2*f(order, coefficients, low + (i*interval)) + for i in range(1, int(self.N))]) self.I += (f(order, coefficients, low) + f(order, coefficients, high)) ans = (self.I*(high - low))/(2*self.N) self.graph(order, coefficients, low, high, interval, ans) @@ -66,17 +70,19 @@ def Trapezoid(self, order, coefficients, low, high, interval): def Simpson(self, order, coefficients, low, high, interval): self.N = (high - low)/(2*interval) - self.I = sum([4*f(order, coefficients, low + (i*interval)) if i%2==1 else 2*f(order, coefficients, low + (i*interval)) for i in range(1, int(2*self.N))]) + self.I = sum([4*f(order, coefficients, low + (i*interval)) if i % 2 == 1 else 2 * + f(order, coefficients, low + (i*interval)) for i in range(1, int(2*self.N))]) self.I += (f(order, coefficients, low) + f(order, coefficients, high)) return (self.I*(high - low))/(6*self.N) - - def solve(self, order, coefficients, low, high, method, interval = 1e-3): + + def solve(self, order, coefficients, low, high, method, interval=1e-3): if method == 'trapezoid': return self.Trapezoid(order, coefficients, low, high, interval) elif method == 'simpson': return self.Simpson(order, coefficients, low, high, interval) + igr = Integrate() -for method in ['trapezoid'] : +for method in ['trapezoid']: solution = igr.solve(3, [7, 3, -6, 10], -50, 65, method=method) - print (solution) + print(solution) diff --git a/bin/memedensity.py b/bin/memedensity.py index 1ad7a15..3a6b4b8 100644 --- a/bin/memedensity.py +++ b/bin/memedensity.py @@ -1,4 +1,14 @@ +import os +import argparse +import requests +import six +from selenium import webdriver +from selenium.webdriver.common.keys import Keys +from time import sleep +from getpass import getpass +from argparse import RawTextHelpFormatter + ASCII = """ __ __ _____ _ _ | \/ | | __ \ (_) | @@ -16,37 +26,29 @@ - Provides memes in newsfeed urls """ -import os -import argparse -import requests -import six -from selenium import webdriver -from selenium.webdriver.common.keys import Keys -from time import sleep -from getpass import getpass -from argparse import RawTextHelpFormatter - if six.PY2: - input = raw_input + input = raw_input else: - pass + pass + def _login_fb(): - email = input('> Email or Phone: ') - password = getpass('> Password: ') + email = input('> Email or Phone: ') + password = getpass('> Password: ') + + return email, password - return email,password def _xkcd(): - r = requests.get('http://xkcd.com/info.0.json').json() - return r['img'] + r = requests.get('http://xkcd.com/info.0.json').json() + return r['img'] -def _execute_script(email, password, count): +def _execute_script(email, password, count): - print("\nLoading..\nCheck out today's xkcd comic till then : %s \n\n" %(_xkcd())) + print("\nLoading..\nCheck out today's xkcd comic till then : %s \n\n" % (_xkcd())) driver = webdriver.PhantomJS() driver.get('https://www.facebook.com') @@ -54,23 +56,24 @@ def _execute_script(email, password, count): email_ID = driver.find_element_by_id('email') pass_ID = driver.find_element_by_id('pass') - email_ID.send_keys(email) pass_ID.send_keys(password) pass_ID.send_keys(Keys.ENTER) sleep(5) - for i in range(0,count): - driver.execute_script("window.scrollBy(0, document.body.scrollHeight);") + for i in range(0, count): + driver.execute_script( + "window.scrollBy(0, document.body.scrollHeight);") sleep(1) - + sleep(5) - driver_tags = driver.execute_script('return document.getElementsByClassName("scaledImageFitWidth img")') + driver_tags = driver.execute_script( + 'return document.getElementsByClassName("scaledImageFitWidth img")') driver_img_list = { - 'src' : [x.get_attribute('src') for x in driver_tags], - 'alt' : [x.get_attribute('alt') for x in driver_tags], + 'src': [x.get_attribute('src') for x in driver_tags], + 'alt': [x.get_attribute('alt') for x in driver_tags], } driver.quit() @@ -80,21 +83,21 @@ def _execute_script(email, password, count): def _check_memes(driver_img_list, verbose): - alt_list = driver_img_list['alt'] - if len(alt_list) == 0: - print("Error getting newsfeed. Possibly username or password was incorrect") - return + alt_list = driver_img_list['alt'] + if len(alt_list) == 0: + print("Error getting newsfeed. Possibly username or password was incorrect") + return - output = "\n{} memes in your newsfeed.\n{} total images in your newsfeed.\n{}% memes in newsfeed.\n" - count = 0 + output = "\n{} memes in your newsfeed.\n{} total images in your newsfeed.\n{}% memes in newsfeed.\n" + count = 0 - for key,alt in enumerate(alt_list): - if "text" in alt or "meme" in alt : - count += 1 - if verbose: - print(driver_img_list['src'][key]) + for key, alt in enumerate(alt_list): + if "text" in alt or "meme" in alt: + count += 1 + if verbose: + print(driver_img_list['src'][key]) - print(output.format(count,len(alt_list),round(count*100/len(alt_list),2))) + print(output.format(count, len(alt_list), round(count*100/len(alt_list), 2))) def main(): @@ -102,13 +105,13 @@ def main(): print('\n') parser = argparse.ArgumentParser( - description='\n{}\n{}\n'.format(ASCII,DESC), formatter_class=RawTextHelpFormatter) + description='\n{}\n{}\n'.format(ASCII, DESC), formatter_class=RawTextHelpFormatter) parser.add_argument('-C', '--count', action='store', dest='count', help='How many times to scroll newsfeed (default = 5)') parser.add_argument('-L', '--login', action='store_true', help='Input login credentials') parser.add_argument('-v', '--verbose', action='store_true', - help='Shows meme urls') + help='Shows meme urls') args = parser.parse_args() count = int(args.count or '5') @@ -116,14 +119,14 @@ def main(): verbose_bool = args.verbose if login_bool: - email,password = _login_fb() + email, password = _login_fb() else: - try: - email=os.environ['fb_email'] - password=os.environ['fb_pass'] - except KeyError: - print("Couldn't find fb_email and fb_pass in environment variables") - email,password = _login_fb() + try: + email = os.environ['fb_email'] + password = os.environ['fb_pass'] + except KeyError: + print("Couldn't find fb_email and fb_pass in environment variables") + email, password = _login_fb() driver_img_list = _execute_script(email, password, count) _check_memes(driver_img_list, verbose_bool) @@ -131,4 +134,4 @@ def main(): if __name__ == '__main__': - main() + main() diff --git a/bin/mi-community-bot.py b/bin/mi-community-bot.py index d509f17..9364a0e 100644 --- a/bin/mi-community-bot.py +++ b/bin/mi-community-bot.py @@ -16,7 +16,8 @@ signin = driver.find_element_by_css_selector(".sign-action > a:nth-child(1)") signin.click() time.sleep(10) -email = driver.find_element_by_xpath("//input[@id='username' or @name='email']") +email = driver.find_element_by_xpath( + "//input[@id='username' or @name='email']") email.send_keys('Email id') print("Email Id entered...") password = driver.find_element_by_xpath("//input[@id='pwd']") @@ -27,7 +28,8 @@ button.click() print('login successfully') time.sleep(7) -threadbutton = driver.find_element_by_css_selector(".thread-box > h4:nth-child(1) > a:nth-child(2)") +threadbutton = driver.find_element_by_css_selector( + ".thread-box > h4:nth-child(1) > a:nth-child(2)") threadbutton.click() print("clicked on new thread button") time.sleep(2) @@ -42,7 +44,7 @@ title = driver.find_element_by_css_selector("#subject") title.send_keys('Bot Typing Here....') -print('Title Entered waiting for your contant' ) +print('Title Entered waiting for your contant') time.sleep(10) submit = driver.find_element_by_css_selector(".btn-orange") submit.click() diff --git a/bin/missionaries_and_cannibals_problem.py b/bin/missionaries_and_cannibals_problem.py index 674622c..e1ffc97 100644 --- a/bin/missionaries_and_cannibals_problem.py +++ b/bin/missionaries_and_cannibals_problem.py @@ -1,19 +1,25 @@ -shore = {1:['m1','m2','m3','c1','c2','c3'],2:[]} -boat = {1:True,2:False} +shore = {1: ['m1', 'm2', 'm3', 'c1', 'c2', 'c3'], 2: []} +boat = {1: True, 2: False} boat_cap = 0 boat_hold = [] choice = 'y' count = 0 glob = 1 + + def pick(): print("Pick a person to put on boat/or press enter") return input() -def check(person,flag,avail_p): + + +def check(person, flag, avail_p): if(person in shore[flag] or person == "" or person in boat_hold): return True else: return False -def check_conditions(shore,flag,cflag,boatf): + + +def check_conditions(shore, flag, cflag, boatf): num_m = 0 num_c = 0 true = 0 @@ -37,17 +43,19 @@ def check_conditions(shore,flag,cflag,boatf): return False elif(true == 1): return true + + while(choice == 'Y' or choice == 'y'): count = 0 win = 0 while(count <= 25): - def again(shore,boat_hold): - print("People On Shore "+str(flag)+ " are: ") + def again(shore, boat_hold): + print("People On Shore "+str(flag) + " are: ") print() print(shore[flag] + boat_hold) shore[flag] = shore[flag] + boat_hold avail_p = shore[flag] + boat_hold - boat_hold =[] + boat_hold = [] for i in range(2): print("For Person " + str(i+1)) print() @@ -63,7 +71,7 @@ def again(shore,boat_hold): elif(person not in avail_p and not person == ""): print("Invalid Choice") person = pick() - while(not check(person,flag,avail_p)): + while(not check(person, flag, avail_p)): person = pick() if(person == ""): break @@ -76,12 +84,12 @@ def again(shore,boat_hold): flag = 2 cflag = 1 if(glob == 1): - boat_hold = again(shore,boat_hold) - while(not check_conditions(shore,flag,cflag,boat_hold)): + boat_hold = again(shore, boat_hold) + while(not check_conditions(shore, flag, cflag, boat_hold)): print() print("** Invalid Move,Try Again **") print() - boat_hold = again(shore,boat_hold) + boat_hold = again(shore, boat_hold) print("Sending Boat") print() avail_p = shore[cflag] + boat_hold @@ -97,7 +105,5 @@ def again(shore,boat_hold): print() print("*** Sorry, Number of moves exceeeded ***") print() - print("Do You Want To Replay? Y/N",end=" ") + print("Do You Want To Replay? Y/N", end=" ") choice = input() - - diff --git a/bin/password-strength-checker.py b/bin/password-strength-checker.py index e12c7ea..3923fd2 100644 --- a/bin/password-strength-checker.py +++ b/bin/password-strength-checker.py @@ -1,19 +1,32 @@ +import string + def checkx(): - email = raw_input('Enter the email:') + pass + email = input('Enter the email:') if '@' in email and '.' in email: pass1() - else : - print ('Check you email') + else: + print('Check you email') checkx() + def pass1(): - password = raw_input('Enter the password ') - special = '!@#$%^&*()?' - if len(password) >= 8 and not password.islower() and not password.isupper() and not password.isalpha() and not password.isdigit() and any((c in special) for c in password): - print ('Strong Password') - return 1 - else: - print ('Weak Password') - pass1() + invalidcharacters=set(string.punctuation) + while True: + password = input('Enter the password of atleast 10 characters length \n ') + if len(password) < 10 : + print(" your password is less than 10 characters") + + if len(password)>= 10 : + if (any(x.isdigit() for x in password)) and (any(x.islower() for x in password)) and any(char in invalidcharacters for char in password) and (any(x.isupper() for x in password)) : + print('Good! You have created a strong password ') + break + else: + print("Please enter Atleast, an upper case , lowercase , special character !@#$%^&*()? and digit") + + + + -checkx() +if __name__== '__main__': + checkx() diff --git a/bin/pi.py b/bin/pi.py index 2b8672b..1051d94 100644 --- a/bin/pi.py +++ b/bin/pi.py @@ -1,15 +1,17 @@ import numpy as np from numba import jit + @jit def aprox_pi(N): - points = 2 * np.random.rand(N, 2) - 1 - M = 0 + points = 2 * np.random.rand(N, 2) - 1 + M = 0 + + for k in range(N): + if points[k, 0]**2 + points[k, 1]**2 < 1.: + M += 1 - for k in range(N): - if points[k,0]**2 + points[k,1]**2 < 1.: - M += 1 + return 4.*M/N - return 4.*M/N print(aprox_pi(1e8)) diff --git a/bin/reveal-md.py b/bin/reveal-md.py new file mode 100644 index 0000000..a0a5775 --- /dev/null +++ b/bin/reveal-md.py @@ -0,0 +1,67 @@ +# Generating presentation from markdown + +import json +import argparse +from os import listdir +from os.path import isfile, join, isdir + +# Parsing command line args +parser = argparse.ArgumentParser( + description='Convert your markdown to presentation') + +parser.add_argument('-dir', metavar='-d', type=str, + nargs='+', help='Directory of your markdown files') +parser.add_argument('-config', metavar='-c', type=str, + nargs='+', help='Config file') + +args = parser.parse_args() +config = json.load(open('reveal.default.config.json')) + +# Replacing default config with user defined config +if args.config: + try: + config = json.load(open(args.config[0])) + except: + print('Please check if config file exist or it is a json') + +# Read all files in the directory +if args.dir: + if isdir(args.dir[0]): + file_names = [file for file in listdir( + args.dir[0]) if isfile(join(args.dir[0], file))] + + all_file_content = "" + html = """ + + + + + + +
+
""" + + for file in file_names: + with open(join(args.dir[0], file)) as f: + data = f.read() + + all_file_content = '
' + + html += all_file_content + + html += """
+
+ + + + + """ + + html_file = open('output.html', 'w') + html_file.write(html) + html_file.close() + else: + print('Please make sure directory exist or if it is a directory') diff --git a/bin/reveal.default.config.json b/bin/reveal.default.config.json new file mode 100644 index 0000000..d057b83 --- /dev/null +++ b/bin/reveal.default.config.json @@ -0,0 +1,14 @@ +{ + "controls": true, + "controlsLayout": "bottom-right", + "controlsBackArrows": "faded", + "progress": true, + "slideNumber": true, + "history": true, + "keyboard": true, + "overview": true, + "center": true, + "touch": true, + "mouseWheel": true, + "hideAddressBar": true +} \ No newline at end of file diff --git a/bin/server.txt b/bin/server.txt index 32eab29..be92aa2 100644 --- a/bin/server.txt +++ b/bin/server.txt @@ -1 +1 @@ -dddvdvkegivmk \ No newline at end of file +krpherbc udglr \ No newline at end of file diff --git a/bin/server_client/client.py b/bin/server_client/client.py index 83ef666..eb47676 100644 --- a/bin/server_client/client.py +++ b/bin/server_client/client.py @@ -1,16 +1,17 @@ import sys from socket import socket, AF_INET, SOCK_DGRAM, SOL_SOCKET, SO_REUSEADDR -SERVER_IP = '127.0.0.1' +SERVER_IP = '127.0.0.1' PORT_NUMBER = 5000 SIZE = 1024 -print ("Test client sending packets to IP {0}, via port {1}\n".format(SERVER_IP,PORT_NUMBER)) +print("Test client sending packets to IP {0}, via port {1}\n".format( + SERVER_IP, PORT_NUMBER)) -mySocket = socket( SOCK_DGRAM ) -mySocket.connect((SERVER_IP,PORT_NUMBER)) +mySocket = socket(SOCK_DGRAM) +mySocket.connect((SERVER_IP, PORT_NUMBER)) while True: - data = mySocket.recv(SIZE) - print(data) + data = mySocket.recv(SIZE) + print(data) sys.exit() mySocket.close() diff --git a/bin/server_client/server.py b/bin/server_client/server.py index 0ff2ccc..adb89ae 100644 --- a/bin/server_client/server.py +++ b/bin/server_client/server.py @@ -3,9 +3,9 @@ PORT_NUMBER = 5000 SIZE = 1024 -hostName = gethostbyname( 'localhost' ) +hostName = gethostbyname('localhost') -mySocket = socket( SOCK_DGRAM ) +mySocket = socket(SOCK_DGRAM) mySocket.bind((hostName, PORT_NUMBER)) mySocket.listen(1) while True: diff --git a/bin/shortener.py b/bin/shortener.py index ad55e51..3a86cc4 100644 --- a/bin/shortener.py +++ b/bin/shortener.py @@ -1,24 +1,27 @@ from __future__ import with_statement import contextlib try: - from urllib.parse import urlencode + from urllib.parse import urlencode except ImportError: - from urllib import urlencode + from urllib import urlencode try: - from urllib.request import urlopen + from urllib.request import urlopen except ImportError: - from urllib2 import urlopen + from urllib2 import urlopen import sys + def make_tiny(url): - request_url = ('http://tinyurl.com/api-create.php?' + - urlencode({'url':url})) - with contextlib.closing(urlopen(request_url)) as response: - return response.read().decode('utf-8') + request_url = ('http://tinyurl.com/api-create.php?' + + urlencode({'url': url})) + with contextlib.closing(urlopen(request_url)) as response: + return response.read().decode('utf-8') + def main(): - for tinyurl in map(make_tiny, sys.argv[1:]): - print(tinyurl) + for tinyurl in map(make_tiny, sys.argv[1:]): + print(tinyurl) + if __name__ == '__main__': - main() + main() diff --git a/bin/tweetload.py b/bin/tweetload.py index bea1cce..444e058 100644 --- a/bin/tweetload.py +++ b/bin/tweetload.py @@ -15,9 +15,9 @@ def init_twitter(): data = json.load(data_file) api = twitter.Api(consumer_key=data["consumer_key"], - consumer_secret=data["consumer_secret"], - access_token_key=data["access_token_key"], - access_token_secret=data["access_token_secret"]) + consumer_secret=data["consumer_secret"], + access_token_key=data["access_token_key"], + access_token_secret=data["access_token_secret"]) return api @@ -33,7 +33,8 @@ def main(): tweets = api.GetUserTimeline(screen_name=user, count=200) curr_id = tweets[-1].id for i in range(19): - tweets = tweets + api.GetUserTimeline(screen_name=user, count=200, max_id=curr_id) + tweets = tweets + \ + api.GetUserTimeline(screen_name=user, count=200, max_id=curr_id) curr_id = tweets[-1].id print("Tweets: " + str(len(tweets))) @@ -53,7 +54,5 @@ def main(): file_o.write(tweet_cont + '\n') - - if __name__ == "__main__": main() diff --git a/bin/twitter sentiment analysis.ipynb b/bin/twitter sentiment analysis.ipynb new file mode 100644 index 0000000..06dcb11 --- /dev/null +++ b/bin/twitter sentiment analysis.ipynb @@ -0,0 +1,187 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "consumer_key = '*******'\n", + "consumer_secret = '********'\n", + "access_token = '******'\n", + "access_token_secret = '*******'" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "\"\"\"Twitter retweet bot\"\"\"\n", + "\"\"\" Before running this make sure your twitter developer account has read and write acess \"\"\"\n", + "import tweepy # This is a Twitter API helper library.\n", + "import time\n", + "\n", + "\n", + "auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n", + "auth.set_access_token(access_token, access_token_secret)\n", + "api = tweepy.API(auth)\n", + "\n", + "\n", + "def retweet_bot():\n", + " pass\n", + " for tweet in tweepy.Cursor(api.search, q='#IoT').items(100000000):\n", + " try:\n", + " print('Twitter user: ' + '@' + tweet.user.screen_name)\n", + " tweet.retweet()\n", + " print('\\nDone')\n", + " # You can remove the time module, if you want the program to continuously retweet\n", + " time.sleep(5)\n", + " except tweepy.error.TweepError:\n", + " pass\n", + " \n", + "\n", + "if __name__ == '__main__':\n", + " retweet_bot()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "\"\"\"Code to know the twitter sentiment \"\"\"\n", + "import re \n", + "import tweepy \n", + "from tweepy import OAuthHandler \n", + "from textblob import TextBlob \n", + " \n", + "class TwitterClient(object): \n", + " ''' \n", + " Generic Twitter Class for sentiment analysis. \n", + " '''\n", + " def __init__(self): \n", + " self.auth = OAuthHandler(consumer_key, consumer_secret)\n", + " self.auth.set_access_token(access_token, access_token_secret) \n", + " self.api = tweepy.API(self.auth) \n", + " \n", + " def clean_tweet(self, tweet):#renoving the special characters\n", + " \n", + " return ' '.join(re.sub(\"(@[A-Za-z0-9]+)|([^0-9A-Za-z \\t]) |(\\w+:\\/\\/\\S+)\", \" \", tweet).split()) \n", + " \n", + " def get_tweet_sentiment(self, tweet): \n", + " # create TextBlob object of passed tweet text \n", + " analysis = TextBlob(self.clean_tweet(tweet)) \n", + " # set sentiment \n", + " if analysis.sentiment.polarity > 0: \n", + " return 'positive'\n", + " elif analysis.sentiment.polarity == 0: \n", + " return 'neutral'\n", + " else: \n", + " return 'negative'\n", + " \n", + " def get_tweets(self, query, count = 10): \n", + " \n", + " tweets = [] \n", + " \n", + " try: \n", + " # call twitter api to fetch tweets \n", + " fetched_tweets = self.api.search(q = query, count = count) \n", + " \n", + " for tweet in fetched_tweets: \n", + " parsed_tweet = {} \n", + " \n", + " parsed_tweet['text'] = tweet.text \n", + " parsed_tweet['sentiment'] = self.get_tweet_sentiment(tweet.text) \n", + " \n", + " if tweet.retweet_count > 0: \n", + " if parsed_tweet not in tweets: \n", + " tweets.append(parsed_tweet) \n", + " else: \n", + " tweets.append(parsed_tweet) \n", + " \n", + " return tweets \n", + " \n", + " except tweepy.TweepError as e: \n", + " \n", + " print(\"Error : \" + str(e)) \n", + " \n", + "\n", + " \n", + "\n", + " \n", + " \n", + "if __name__ == \"__main__\":\n", + " count=0\n", + " totalp=0\n", + " totaln=0\n", + " totalnu=0\n", + " api = TwitterClient()\n", + " \n", + " topic=input(\"Enter the topic to analyse the sentiment \\n\")\n", + " \n", + " while True:\n", + " \n", + " count=count+1 \n", + " tweets = api.get_tweets(query = topic , count = 300) \n", + "\n", + " ptweets = [tweet for tweet in tweets if tweet['sentiment'] == 'positive'] \n", + "\n", + " pos=(len(ptweets)/len(tweets)) \n", + "\n", + " ntweets = [tweet for tweet in tweets if tweet['sentiment'] == 'negative'] \n", + "\n", + "\n", + " neg=(len(ntweets)/len(tweets)) \n", + "\n", + "\n", + " neu=((len(tweets) -(len( ntweets )+len( ptweets)))/len(tweets))\n", + "\n", + " totalp=totalp+pos\n", + " print(\"Average positive for \",count ,\" run is \", (totalp/count)*100 )\n", + "\n", + " totaln=totaln+neg\n", + " print(\"Average negative for \",count ,\" run is \", (totaln/count)*100 )\n", + " \n", + " totalnu=totalnu+neu\n", + " print(\"Average neutral for \",count ,\" run is \", (totalnu/count)*100 )\n", + " \n", + " print(\"\\n\\nPositive tweets:\") \n", + " for tweet in ptweets[:10]: \n", + " print(tweet['text']) \n", + "\n", + " print(\"\\n\\nNegative tweets:\") \n", + " for tweet in ntweets[:10]: \n", + " print(tweet['text']) \n", + "\n", + " \n", + " y=input(\" enter y to continue for more run \")\n", + " if y!='y':\n", + " break" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/bin/twitter_retweet_bot.py b/bin/twitter_retweet_bot.py index 9d80be4..9e71e13 100644 --- a/bin/twitter_retweet_bot.py +++ b/bin/twitter_retweet_bot.py @@ -22,7 +22,8 @@ def retweet_bot(): print('Twitter user: ' + '@' + tweet.user.screen_name) tweet.retweet() print('\nDone') - time.sleep(5) # You can remove the time module, if you want the program to continuously retweet + # You can remove the time module, if you want the program to continuously retweet + time.sleep(5) except tweepy.error.TweepError: pass diff --git a/bin/youtube-bot-linux.py b/bin/youtube-bot-linux.py index ba107d4..78b2e8c 100644 --- a/bin/youtube-bot-linux.py +++ b/bin/youtube-bot-linux.py @@ -1,4 +1,6 @@ -import time,webbrowser,os +import time +import webbrowser +import os url = str(input("Enter your video url in ->\"url here \"<- : ")) n = input("Enter refresh rate(seconds) : ") diff --git a/bin/youtube-bot-windows.py b/bin/youtube-bot-windows.py index a459292..aa33ec5 100644 --- a/bin/youtube-bot-windows.py +++ b/bin/youtube-bot-windows.py @@ -1,4 +1,6 @@ -import time,webbrowser,os +import time +import webbrowser +import os url = str(input("Enter your video url in ->\"url here \"<- : ")) n = input("Enter refresh rate(seconds) : ") diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..fb269f3 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,3 @@ +# python_scripts_page +This Repo Git page for [python_scripts](https://github.com/Logan1x/Python-Scripts). +This repo was built in couple of minutes so it really could use some help to improve further. diff --git a/docs/_config.yml b/docs/_config.yml new file mode 100644 index 0000000..c741881 --- /dev/null +++ b/docs/_config.yml @@ -0,0 +1 @@ +theme: jekyll-theme-slate \ No newline at end of file diff --git a/docs/about.html b/docs/about.html new file mode 100644 index 0000000..66d1d96 --- /dev/null +++ b/docs/about.html @@ -0,0 +1,44 @@ + + + + + + + FAQ + + + + + +
+ Python Scripts +
+ +
+
+

## What is this all about ?

+

+ Python is an awesome language that comes with many built in libraries and an awesome community.
+ Python has a package for everything (almost). Which also means people have written many small scripts that does + incredible things from automating simple things for everyday usage to really complex ones. + This repo is collection of awesome scrips by awesome people so that someone might find usefull + here someday or just use it for fun. If you are bored and have time to kill or have some awesome python + scripts please consider contributing to this repo. +

+
+ +
+

## Contributors

+ +
+ + ayrusmelionaspzinuzoiddgupta777chiraag-jainniharikakrishnanahadalikhushboopaddiyarHarshvardhan58pr0meabhinavralhanSouldivszepnapotSuryaThiruapuayushishank011ValentinChCloudMadhavBahlMDvigov5RodolfoFerrotoonarmycaptainharsha7890Pradhvanehnydeelshivamp123vis2797SharanpaikalbhorRafi993iyanuashiriakshitgroverKayvanMazaheriLogan1x + +

* If you have given a pull request to this repo add your image here too after reducing its size to 50x50

+
+ +
+
+ + + \ No newline at end of file diff --git a/docs/data.json b/docs/data.json new file mode 100644 index 0000000..40dce07 --- /dev/null +++ b/docs/data.json @@ -0,0 +1,161 @@ +[{ + + "name": "Air Quality Script", + "description": "
  • This script renders the air quality from the location of the user
  • The location is fetched using the user's IP address
  • This script requires a key from WAQI
  • It is free and can be fetched from http://aqicn.org/data-platform/token/#/
Release History
0.0.1 - Work in progress", + "usage": "python air-quality.py token", + "type": "data" +},{ + "name": "A* Pathfinding Algorithm with GUI", + "description": "It will find the shortes distance between two nodes, and it's implemented with a GUI.", + "usage": "cd A-Star-GUI -> python AStarGUI.py ", + "type": "data" +},{ + "name": "Approximating pi", + "description": "This script is useful to show a way to approximate the value of pi using a Monte Carlo method. It is also optimized using the @jit (just-in-time) decorator from the numba library.", + "type": "data" +},{ + "name": "Blog Reader", + "description": "Blog Reader is the terminal reader that scrapes the article from planet dgplug and displays it on the terminal.It seprates the content accrding to the screen size.", + "usage": "python Blog_reader.py", + "type": "social" +},{ + "name": "Bulk add users to Twitter list", + "description": "Simple script helps you mass add users to your twitter list to follow (Ex: Bitcoin/Altcoins official account, news, traders...)
  • Prepare list screen names
  • Setup your app and get an access token
", + "usage": "pip install twitter
python bulk_add_twitter_list.py", + "type": "social" +},{ + "name": "Caesar Cipher", + "description": "Encrypts or Decrypts any message you want, simply enter the message and the rotation number", + "usage": "python caesar_cipher.py", + "type": "crypto" +},{ + "name": "Contributor list", + "description": "For a given repo generate contribute.md with images in same size like the one in this README.md. you may need to install packages like PIL@1.1.7 and requests if not installed", + "usage": "python contributors.py https://github.com/Logan1x/Python-Scripts/", + "type": "FOSS" +},{ + "name": "End To End Encryption", + "description": "It is a simple program to implement and understand the basic of end_to_end encryption. Here i am using caesar cipher to encrpt nbut in reality they Use algotihms lile SHA-1, RSA etc.", + "usage": "python end_to_end.py", + "type": "crypto" +},{ + "name": "Expense Manager", + "description": "Simple GUI program which helps you calculate your expenses, monitor them just through mouse clicks. All you have to do is run the script and choose an option from the menu which will displayed when you run the script. Enter Your Expenses as eg: 'Biscuits Rs 15' ' rs ' ignore the quotes.", + "usage": "python expense_manger.py", + "type": "$" +},{ + "name": "Facebook Auto Post", + "description": "This is python script that log in into facebook and post the status.You can see live execution of this script here.", + "usage": "pip install -r facebook-auto-post.requirements.txt
python facebook-auto-post.py", + "type": "social" +},{ + "name": "Find Large Files", + "description": "Searches a file location and subdirectories for files larger than a given size. Useful for phones which might hide files in FileExplorer, but allow use as flash memory. Directly prints results if run directly. May also be imported, yielding results one by one.", + "type": "util" +},{ + "name": "FTP Download File", + "description": "A simple application to download a file via FTP with the given remote and local path Parameters:
  • hh hostname
  • u username
  • p password
  • rd remote directory
  • ld local directory
    • ", + "usage": "python ftp_download_file.py
      ## This script fetch html response from the provided url and parse xml tag to get only text content and print out.
      python fetch_html.py https://github.com", + "type": "util" +},{ + "name": "Get External IP", + "description": "Gets the external ip-address from the current machine and prints it to the console", + "usage": "python getExternalIp.py", + "type": "util" +},{ + "name": "Group files by type", + "description": "
      • Group files by their extensions
      • Files are moved into folders with extension names
        • ", + "usage": "python group_file_by_type.py 'C:\\test\\products'", + "type": "util" +},{ + "name": "Handy offline dictionary", + "description": "A tiny offline dictionary app based on nltk wordnet and pyqt5", + "usage": "cd dictionary
          python app.py", + "type": "util" +},{ + "name": "Highcharts loader", + "description": "It is a simple program that can load charts from highcharts.After loading chart you can save it to file or embed it into your html page in base64 format.Don't forget install requests library from highcharts_loader_requirements.txt", + "usage": "from highcharts_loader import ChartLoader, Options
          options = Options(from_file='options.json')
          chart = ChartLoader(options)
          chart.save_to_file('result.png')
          // options.json example:", + "json": "{'chart': {'type': 'bar'},'title': {'text': 'Which channels are driving engagement?'},'xAxis': {'categories': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun','Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']},'series': [{'data': [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]}]}", + "type": "data" +},{ + "name": "Image Encoder", + "description": "It is a simple program to encode and decode images, which helps to reduce and handle images on server, as it is convertedto base64 address.", + "usage": "python image_encoder.py", + "type": "images" +},{ + "name": "Integrate to find area of a graph", + "description": "The script takes a given graph along with the range within which the area is to be calculated. It then calculates the area using two methods, the Simpson method and the Trapezoid method and displays the results on a graph.", + "usage": "python integrate-graph.py", + "type": "data" +},{ + "name": "Locate Me", + "description": "Run this script and it will locate you.
          This will tell you your
          • City
          • Region
          • Country
          • Latitude & Longitude
          • Your Internet Service Provider
          This uses Checkip and ipinfo.io.", + "usage": "python locate-me.py", + "type": "util" +},{ + "name": "Meme Density", + "description": "This script tells you the amount of memes in your facebook feed", + "usage": "pip install memedensity
          memedensity", + "type": "social" +},{ + "name": "Mi Community Bot", + "description": "This python script uses selenium module in python to automate the thread posting.
          You can see live execution of this script here.
          If you want to understand this code you can visit here.", + "usage": "pip install -r mi-community-bot.requirements.txt
          python mi-community-bot.py", + "type": "social" +},{ + "name": "Missionaires And Cannibals Problem", + "description": "It is a simple program to mimic Missionaries And Cannibals River Crossing Problem.", + "usage": "python missionaries_and_cannibals_problem.py", + "type": "misc" +},{ + "name": "Password Strength Checker", + "description": "This code checks for your password strength. For the right password, password must contain mixture of an upper case letters, an digit (including 0-9), and a special characters with lower case letters.", + "usage": "python password-strength-checker.py", + "type": "util" +},{ + "name": "Plotting a function", + "description": "This script contains an example of plotting a function using matplotlib. Feel free to modify the value of y to obtain different functions that depend on x.", + "type": "data" +},{ + "name": "Server And Client", + "description": "It is simple client server communication script, will add more functionality in future.", + "usage": "cd server_client
          python client.py
          python server.py", + "type": "misc" +},{ + "name": "Tweetload", + "description": "Download latest tweets (default: up to 4000) from a specific twitter user. The script will create a file with one tweet per line, stripped from mentions, hashtags and links. For that to work, create a json file with your twitter credentials (see source) and define the twitter user in source code.", + "usage": "python3 tweetload.py", + "type": "social" +},{ + "name": "Twitter_retweet_bot", + "description": "It is a simple script that retweets any hashtag provided in it.", + "usage": "python twitter_retweet_bot.py", + "type": "social" +},{ + "name": "Twitter Sentiment Analysis", + "description": "A python script that goes through the twitter feeds and calculates the sentiment of the users on the topic of Demonetization in India. Sentiments are calculated to be positive, negative or neutral. Various other analyses are represented using graphs.", + "usage": "pip install -r analyseTweets-requirements.txt
          python analyseTweets.py", + "type": "social" +},{ + "name": "URL Shortener", + "description": "This is python script that shortens any URL provided to it.", + "usage": "# Takes multiple inputs and returns shortened URL for both
          python shortener.py url1 url2
          #Stores shortened URLs in a file
          python shortener.py url1 url2 > file.txt", + "type": "util" +},{ + "name": "Video-downloader v1.1", + "description": "This file allows the user to download videos off of the web. as of version 1 the user is able to download highquality videos as a playlist or single file as well as audio files from the supported websites given here are supported.More features will be added in the future iterations of the project. a simple video downloader using youtube-dl Library, a starter script for making use of youtube-dl.
          Requirements
          • You will need to install youtube_dl
            • This can be installed using pip on windows
            • if you do not know how to use pip please read the installation instructions
          • requests library
            • can be downloaded using pip on windows and respective package managers on different operating systems
          • ffmpeg in order to convert the downloaded files to the right format
            • Installation: clone this repo and run python vid.py script! assuming you already have the other requirements", + "type": "util" +},{ + "name": "YouTube Bot", + "description": "This is a simple python script that increases your video count/ views. Log out from all google accounts and run this.", + "usage": "# For Linux Users
              python youtube-bot-linux.py
              # For Windows Users
              python youtube-bot-windows.py", + "note": "In case your browser stoped working delete/comment the following line in the script.
              Linux
              os.system(' killall -9 ' + brow)
              Windows
              os.system('TASKKILL /F /IM ' + brow + '.exe')", + "type": "social" +},{ + "name": "Markdown to presentation", + "description": "You can convert markdown in a directory into a **.html** file for presentation using reveal.js", + "usage": "python reveal-md.py -d folder_name -c config", + "note": "the config is optional. You can specify with keys as here https://github.com/hakimel/reveal.js/#configuration in a json file. Reveal.js cdn link is included in generated html you may need to download them if you want to use the presentation offline", + "type": "util" + }] diff --git a/docs/images/79974586_280549466424880_5856738100331003205_n.jpg b/docs/images/79974586_280549466424880_5856738100331003205_n.jpg new file mode 100644 index 0000000..8508e49 Binary files /dev/null and b/docs/images/79974586_280549466424880_5856738100331003205_n.jpg differ diff --git a/docs/images/Harshvardhan58.png b/docs/images/Harshvardhan58.png new file mode 100644 index 0000000..758a68b Binary files /dev/null and b/docs/images/Harshvardhan58.png differ diff --git a/docs/images/KayvanMazaheri.png b/docs/images/KayvanMazaheri.png new file mode 100644 index 0000000..42ab768 Binary files /dev/null and b/docs/images/KayvanMazaheri.png differ diff --git a/docs/images/Logan1x.png b/docs/images/Logan1x.png new file mode 100644 index 0000000..d3b08d1 Binary files /dev/null and b/docs/images/Logan1x.png differ diff --git a/docs/images/MadhavBahlMD.png b/docs/images/MadhavBahlMD.png new file mode 100644 index 0000000..6de00cc Binary files /dev/null and b/docs/images/MadhavBahlMD.png differ diff --git a/docs/images/Pradhvan.png b/docs/images/Pradhvan.png new file mode 100644 index 0000000..20bb7cd Binary files /dev/null and b/docs/images/Pradhvan.png differ diff --git a/docs/images/Rafi993.png b/docs/images/Rafi993.png new file mode 100644 index 0000000..7c98446 Binary files /dev/null and b/docs/images/Rafi993.png differ diff --git a/docs/images/RodolfoFerro.png b/docs/images/RodolfoFerro.png new file mode 100644 index 0000000..5b3e37b Binary files /dev/null and b/docs/images/RodolfoFerro.png differ diff --git a/docs/images/Sharanpai.png b/docs/images/Sharanpai.png new file mode 100644 index 0000000..0b4cb28 Binary files /dev/null and b/docs/images/Sharanpai.png differ diff --git a/docs/images/Souldiv.png b/docs/images/Souldiv.png new file mode 100644 index 0000000..1bc604a Binary files /dev/null and b/docs/images/Souldiv.png differ diff --git a/docs/images/SuryaThiru.png b/docs/images/SuryaThiru.png new file mode 100644 index 0000000..6abcb9f Binary files /dev/null and b/docs/images/SuryaThiru.png differ diff --git a/docs/images/ValentinChCloud.png b/docs/images/ValentinChCloud.png new file mode 100644 index 0000000..233e5af Binary files /dev/null and b/docs/images/ValentinChCloud.png differ diff --git a/docs/images/abhinavralhan.png b/docs/images/abhinavralhan.png new file mode 100644 index 0000000..4f8f228 Binary files /dev/null and b/docs/images/abhinavralhan.png differ diff --git a/docs/images/ahadali.png b/docs/images/ahadali.png new file mode 100644 index 0000000..7f9aa6b Binary files /dev/null and b/docs/images/ahadali.png differ diff --git a/docs/images/akshitgrover.png b/docs/images/akshitgrover.png new file mode 100644 index 0000000..2dd160e Binary files /dev/null and b/docs/images/akshitgrover.png differ diff --git a/docs/images/apuayush.png b/docs/images/apuayush.png new file mode 100644 index 0000000..c04f818 Binary files /dev/null and b/docs/images/apuayush.png differ diff --git a/docs/images/ayrusme.png b/docs/images/ayrusme.png new file mode 100644 index 0000000..9c0a36f Binary files /dev/null and b/docs/images/ayrusme.png differ diff --git a/docs/images/chiraag-jain.png b/docs/images/chiraag-jain.png new file mode 100644 index 0000000..0dc0f24 Binary files /dev/null and b/docs/images/chiraag-jain.png differ diff --git a/docs/images/dgupta777.png b/docs/images/dgupta777.png new file mode 100644 index 0000000..6ce8628 Binary files /dev/null and b/docs/images/dgupta777.png differ diff --git a/docs/images/ehnydeel.png b/docs/images/ehnydeel.png new file mode 100644 index 0000000..f3a6cf3 Binary files /dev/null and b/docs/images/ehnydeel.png differ diff --git a/docs/images/harsha7890.png b/docs/images/harsha7890.png new file mode 100644 index 0000000..75141c2 Binary files /dev/null and b/docs/images/harsha7890.png differ diff --git a/docs/images/ishank011.png b/docs/images/ishank011.png new file mode 100644 index 0000000..37a89f1 Binary files /dev/null and b/docs/images/ishank011.png differ diff --git a/docs/images/iyanuashiri.png b/docs/images/iyanuashiri.png new file mode 100644 index 0000000..5305175 Binary files /dev/null and b/docs/images/iyanuashiri.png differ diff --git a/docs/images/kalbhor.png b/docs/images/kalbhor.png new file mode 100644 index 0000000..d5e35f9 Binary files /dev/null and b/docs/images/kalbhor.png differ diff --git a/docs/images/khushboopaddiyar.png b/docs/images/khushboopaddiyar.png new file mode 100644 index 0000000..92ce279 Binary files /dev/null and b/docs/images/khushboopaddiyar.png differ diff --git a/docs/images/lionasp.png b/docs/images/lionasp.png new file mode 100644 index 0000000..2c39eef Binary files /dev/null and b/docs/images/lionasp.png differ diff --git a/docs/images/niharikakrishnan.png b/docs/images/niharikakrishnan.png new file mode 100644 index 0000000..c0ce171 Binary files /dev/null and b/docs/images/niharikakrishnan.png differ diff --git a/docs/images/pr0me.png b/docs/images/pr0me.png new file mode 100644 index 0000000..a037219 Binary files /dev/null and b/docs/images/pr0me.png differ diff --git a/docs/images/shivamp123.png b/docs/images/shivamp123.png new file mode 100644 index 0000000..cdfb1bd Binary files /dev/null and b/docs/images/shivamp123.png differ diff --git a/docs/images/szepnapot.png b/docs/images/szepnapot.png new file mode 100644 index 0000000..6f3c6e4 Binary files /dev/null and b/docs/images/szepnapot.png differ diff --git a/docs/images/temp.png b/docs/images/temp.png new file mode 100644 index 0000000..76fb41d Binary files /dev/null and b/docs/images/temp.png differ diff --git a/docs/images/toonarmycaptain.png b/docs/images/toonarmycaptain.png new file mode 100644 index 0000000..4731975 Binary files /dev/null and b/docs/images/toonarmycaptain.png differ diff --git a/docs/images/vigov5.png b/docs/images/vigov5.png new file mode 100644 index 0000000..b85895f Binary files /dev/null and b/docs/images/vigov5.png differ diff --git a/docs/images/vis2797.png b/docs/images/vis2797.png new file mode 100644 index 0000000..27c207d Binary files /dev/null and b/docs/images/vis2797.png differ diff --git a/docs/images/zinuzoid.png b/docs/images/zinuzoid.png new file mode 100644 index 0000000..924ad90 Binary files /dev/null and b/docs/images/zinuzoid.png differ diff --git a/docs/index.css b/docs/index.css new file mode 100644 index 0000000..819727e --- /dev/null +++ b/docs/index.css @@ -0,0 +1,239 @@ +body{ + font-family: sans-serif; + letter-spacing: 0.3rem; +} + +input::-webkit-input-placeholder{ + font-family: sans-serif; + letter-spacing: 0.3rem; + font-size: 12px; +} + +input::-moz-placeholder{ + font-family: sans-serif; + letter-spacing: 0.3rem; + font-size: 12px; +} +input:-ms-input-placeholder{ + font-family: sans-serif; + letter-spacing: 0.3rem; + font-size: 12px; +} +input:-moz-placeholder{ + font-family: sans-serif; + letter-spacing: 0.3rem; + font-size: 12px; +} + + +header{ + background:#263238; + min-height: 50px; + position: fixed; + right: 0px; + left: 0px; +} + +.title, .sub_title{ + color: #fff; + display: inline-block; + font-weight: 300; + padding-top: 15px; + padding-left: 15px; + text-decoration: none; + transition: all 0.5s; +} + +.title:hover, .sub_title:hover{ + transition: all 0.5s; + color: #546E7A; +} + +.sub_title{ + font-size: 12px; + padding-top: 20px; +} + +.pull-right{ + float: right; + padding-right: 10px; +} + +.container{ + padding:0px 20px; + padding-top: 30px; +} + +.container-fluid{ + margin: 0px; +} + +.sidebar{ + width: 300px; + border: 1px solid #f2f2f2; + display: inline-block; + position: fixed; + top: 50px; + bottom: 0px; +} +.details{ + display: inline-block; + margin-top: 52px; + /* height: 20vh; */ + width: 77%; + margin-left: 300px; + margin-bottom: 15px; +} + +.search{ + padding: 15px 10px; + padding-bottom: 0px; + width: 238px; + position: relative; +} + +.search input{ + width: 100%; + padding: 5px; + border: none; + outline: none; + border-bottom: 1px solid #ccc; + padding-left: 5px; +} + +.search input:focus, .search input:hover{ + border-bottom: 1px solid #263238; +} + +.search img{ + height: 13px; + position: absolute; + right: 14px; + top: 22px; +} + +p{ + line-height: 1.7rem; +} + +.content-block{ + margin-bottom: 50px; +} + +.contribs img{ + cursor: pointer; + padding: 5px; + border: 6px solid #fff; + border-radius: 50%; + transition: all 0.5s; +} + +.contribs img:hover{ + transition: all 0.5s; + border: 6px solid #263238; +} + +.scripts-list{ + padding-left: 0px; + height: calc(100vh - 112px); + overflow: auto; + margin: 0px; + margin-top: 15px; +} + +.scripts-list li{ + padding-left: 15px; + padding-right: 15px; + padding-top: 10px; + padding-bottom: 10px; + font-size: 13px; + letter-spacing: 0.1rem; + width: 88%; +} + +.scripts-list li a { + color: #263238; +} + +.scripts-list li:hover a{ + color: #fff +} + +.scripts-list li:hover{ + transition: all 0.1s; + background: #263238; + color: #fff +} + +.scripts-list li span.tag{ + float: right; + background: #263238; + color: #fff; + padding: 5px; + position: relative; + top: -3px; +} + +.scripts-list li:hover > span.tag{ + background: #fff; + color: #263238; + cursor: pointer; +} + +.scripts-list li span.searchText{ + display: inline-block; + width: 70%; + cursor: pointer; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +/* Utils */ +@media screen and (max-width: 480px){ + .hidden-xs{ + display: none; + } +} + +@media screen and (max-width: 480px){ + .details{ + margin-left: 0px; + } +} + +.contentDiv{ + padding-left: 20px; + padding-top: 15px; +} + +.contentDiv h3{ + margin: 0px; + padding-bottom: 20px; + cursor: pointer; +} + +.contentDiv p{ + letter-spacing: 0.1rem; +} + +.contentDiv code{ + background: #f2f2f2; + padding: 2px 5px; + border-radius: 2px; +} + +.contentDiv a{ + color: #546E7A; +} + +.contentDiv a:hover{ + color: #000000; +} + +.usage{ + display: block; + padding: 15px 22px; + letter-spacing: 0.1px; + line-height: 20px; +} \ No newline at end of file diff --git a/docs/index.html b/docs/index.html new file mode 100644 index 0000000..d71eeb7 --- /dev/null +++ b/docs/index.html @@ -0,0 +1,39 @@ + + + + + + + Python-Scripts + + + +
              + Python Scripts + + +
              + +
              + +
              +
              + + + + + + + \ No newline at end of file diff --git a/docs/index.js b/docs/index.js new file mode 100644 index 0000000..eb5a1b2 --- /dev/null +++ b/docs/index.js @@ -0,0 +1,112 @@ +console.log('If you like to contribute to this project check out the repo') + +const populateSearch = data =>{ + let ul = document.getElementById('searchList') + data.forEach((element, i) => { + let li = document.createElement('li') + + let a = document.createElement('a') + // a.href = '#'+ i + '_details' + // a.onclick = scrollTo('#'+ i + '_details', ) + a.addEventListener('click', ()=>{ + let elem = document.getElementById(i + '_details').offsetTop - 52 + scrollTo(document.documentElement, elem, 500) + }) + + let type = document.createElement('span') + let searchText = document.createElement('span') + + + ul.appendChild(li) + li.appendChild(a) + + type.innerText = element.type + type.className = 'tag' + + searchText.className = 'searchText' + searchText.innerText = element.name + + a.appendChild(searchText) + a.appendChild(type) + + }); +} + +const populateDetails = data =>{ + let details = document.getElementById('details'); + data.forEach((elem, i)=>{ + + let contentDiv = document.createElement('div'); + contentDiv.className = 'contentDiv' + contentDiv.id = i + '_details' + + let heading = document.createElement('h3') + heading.innerText = '## '+ elem.name + + let description = document.createElement('p') + description.innerHTML = elem.description + + details.appendChild(contentDiv) + contentDiv.appendChild(heading) + contentDiv.appendChild(description) + + + if(elem.usage !== undefined){ + let usage = document.createElement('code') + usage.className = 'usage' + usage.innerHTML = elem.usage + contentDiv.appendChild(usage) + } + }) + +} + + +const scrollTo = (element, to, duration)=> { + if (duration <= 0) return; + const difference = to - element.scrollTop; + const perTick = difference / duration * 10; + + setTimeout(()=> { + element.scrollTop = element.scrollTop + perTick; + if (element.scrollTop === to) return; + scrollTo(element, to, duration - 10); + }, 10); +} + +document.onreadystatechange = () => { + // document ready + if (document.readyState === 'complete') { + + fetch('data.json') + .then(response => response.json()) + .then(data=>{ + window.data = data; + populateSearch(data) + populateDetails(data) + }) + + // Filter li as user types in search box + let e = document.getElementById('search'); + e.oninput = e=>{ + let ul = document.getElementById('searchList') + let li = ul.getElementsByTagName("li"); + let filter = document.getElementById('search').value.toLowerCase(); + // Hide elements that does not match search term + Array.from(li).forEach(elem=>{ + const text = elem.getElementsByClassName("searchText")[0].innerHTML.toLowerCase(); + const tag = elem.getElementsByClassName("tag")[0].innerHTML.toLowerCase(); + + if (text.indexOf(filter) > -1 || + tag.indexOf(filter) > -1) { + elem.style.display = ""; + } else { + elem.style.display = "none"; + } + + }) + + } + + } + }; \ No newline at end of file diff --git a/docs/search.svg b/docs/search.svg new file mode 100644 index 0000000..3fd7b88 --- /dev/null +++ b/docs/search.svg @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/images/79974586_280549466424880_5856738100331003205_n.jpg b/images/79974586_280549466424880_5856738100331003205_n.jpg new file mode 100644 index 0000000..8508e49 Binary files /dev/null and b/images/79974586_280549466424880_5856738100331003205_n.jpg differ diff --git a/images/Harshvardhan58.png b/images/Harshvardhan58.png new file mode 100644 index 0000000..758a68b Binary files /dev/null and b/images/Harshvardhan58.png differ diff --git a/images/KayvanMazaheri.png b/images/KayvanMazaheri.png new file mode 100644 index 0000000..42ab768 Binary files /dev/null and b/images/KayvanMazaheri.png differ diff --git a/images/Logan1x.png b/images/Logan1x.png new file mode 100644 index 0000000..d3b08d1 Binary files /dev/null and b/images/Logan1x.png differ diff --git a/images/MadhavBahlMD.png b/images/MadhavBahlMD.png new file mode 100644 index 0000000..6de00cc Binary files /dev/null and b/images/MadhavBahlMD.png differ diff --git a/images/Pradhvan.png b/images/Pradhvan.png new file mode 100644 index 0000000..20bb7cd Binary files /dev/null and b/images/Pradhvan.png differ diff --git a/images/Rafi993.png b/images/Rafi993.png new file mode 100644 index 0000000..7c98446 Binary files /dev/null and b/images/Rafi993.png differ diff --git a/images/RodolfoFerro.png b/images/RodolfoFerro.png new file mode 100644 index 0000000..5b3e37b Binary files /dev/null and b/images/RodolfoFerro.png differ diff --git a/images/Sharanpai.png b/images/Sharanpai.png new file mode 100644 index 0000000..0b4cb28 Binary files /dev/null and b/images/Sharanpai.png differ diff --git a/images/Souldiv.png b/images/Souldiv.png new file mode 100644 index 0000000..1bc604a Binary files /dev/null and b/images/Souldiv.png differ diff --git a/images/SuryaThiru.png b/images/SuryaThiru.png new file mode 100644 index 0000000..6abcb9f Binary files /dev/null and b/images/SuryaThiru.png differ diff --git a/images/ValentinChCloud.png b/images/ValentinChCloud.png new file mode 100644 index 0000000..233e5af Binary files /dev/null and b/images/ValentinChCloud.png differ diff --git a/images/abhinavralhan.png b/images/abhinavralhan.png new file mode 100644 index 0000000..4f8f228 Binary files /dev/null and b/images/abhinavralhan.png differ diff --git a/images/ahadali.png b/images/ahadali.png new file mode 100644 index 0000000..7f9aa6b Binary files /dev/null and b/images/ahadali.png differ diff --git a/images/akshitgrover.png b/images/akshitgrover.png new file mode 100644 index 0000000..2dd160e Binary files /dev/null and b/images/akshitgrover.png differ diff --git a/images/apuayush.png b/images/apuayush.png new file mode 100644 index 0000000..c04f818 Binary files /dev/null and b/images/apuayush.png differ diff --git a/images/ayrusme.png b/images/ayrusme.png new file mode 100644 index 0000000..9c0a36f Binary files /dev/null and b/images/ayrusme.png differ diff --git a/images/chiraag-jain.png b/images/chiraag-jain.png new file mode 100644 index 0000000..0dc0f24 Binary files /dev/null and b/images/chiraag-jain.png differ diff --git a/images/dgupta777.png b/images/dgupta777.png new file mode 100644 index 0000000..6ce8628 Binary files /dev/null and b/images/dgupta777.png differ diff --git a/images/ehnydeel.png b/images/ehnydeel.png new file mode 100644 index 0000000..f3a6cf3 Binary files /dev/null and b/images/ehnydeel.png differ diff --git a/images/harsha7890.png b/images/harsha7890.png new file mode 100644 index 0000000..75141c2 Binary files /dev/null and b/images/harsha7890.png differ diff --git a/images/ishank011.png b/images/ishank011.png new file mode 100644 index 0000000..37a89f1 Binary files /dev/null and b/images/ishank011.png differ diff --git a/images/iyanuashiri.png b/images/iyanuashiri.png new file mode 100644 index 0000000..5305175 Binary files /dev/null and b/images/iyanuashiri.png differ diff --git a/images/kalbhor.png b/images/kalbhor.png new file mode 100644 index 0000000..d5e35f9 Binary files /dev/null and b/images/kalbhor.png differ diff --git a/images/khushboopaddiyar.png b/images/khushboopaddiyar.png new file mode 100644 index 0000000..92ce279 Binary files /dev/null and b/images/khushboopaddiyar.png differ diff --git a/images/lionasp.png b/images/lionasp.png new file mode 100644 index 0000000..2c39eef Binary files /dev/null and b/images/lionasp.png differ diff --git a/images/mohitpeshwani.png b/images/mohitpeshwani.png new file mode 100644 index 0000000..addccba Binary files /dev/null and b/images/mohitpeshwani.png differ diff --git a/images/niharikakrishnan.png b/images/niharikakrishnan.png new file mode 100644 index 0000000..c0ce171 Binary files /dev/null and b/images/niharikakrishnan.png differ diff --git a/images/pr0me.png b/images/pr0me.png new file mode 100644 index 0000000..a037219 Binary files /dev/null and b/images/pr0me.png differ diff --git a/images/shivamp123.png b/images/shivamp123.png new file mode 100644 index 0000000..cdfb1bd Binary files /dev/null and b/images/shivamp123.png differ diff --git a/images/szepnapot.png b/images/szepnapot.png new file mode 100644 index 0000000..6f3c6e4 Binary files /dev/null and b/images/szepnapot.png differ diff --git a/images/temp.png b/images/temp.png new file mode 100644 index 0000000..76fb41d Binary files /dev/null and b/images/temp.png differ diff --git a/images/toonarmycaptain.png b/images/toonarmycaptain.png new file mode 100644 index 0000000..4731975 Binary files /dev/null and b/images/toonarmycaptain.png differ diff --git a/images/vigov5.png b/images/vigov5.png new file mode 100644 index 0000000..b85895f Binary files /dev/null and b/images/vigov5.png differ diff --git a/images/vis2797.png b/images/vis2797.png new file mode 100644 index 0000000..27c207d Binary files /dev/null and b/images/vis2797.png differ diff --git a/images/zinuzoid.png b/images/zinuzoid.png new file mode 100644 index 0000000..924ad90 Binary files /dev/null and b/images/zinuzoid.png differ diff --git a/requirement.txt b/requirement.txt new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/requirement.txt @@ -0,0 +1 @@ +